qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
194,077
|
<p>I've just recently setup a custom replication for my subscriber database, as described in <a href="https://stackoverflow.com/questions/161890/how-do-you-track-the-time-of-replicated-rows-for-subscribers-in-sql-server-2005">another post here</a>. Basically, when the publisher pushes a new record to the subscribers, the stored procedure will also insert a replicated time into an extra column in the table, and insert a new record to a log table.</p>
<p>My problem occurs when trying to replicate the log table back to the main publication database. This is what I did:</p>
<ol>
<li>In the database where the log table is located, I setup a new transactional replication, and set it to create a snapshot.</li>
<li>Once the publication is created, I create a new push subscription, and set it to initialize immediately.</li>
<li>Once the subscription is created, I checked the synchronization status and confirm that the snapshot is applied successfully.</li>
</ol>
<p>Now here's the weird part: if I manually add a record to the log table using the SQL Server Management Studio, the record will be replicated fine. If the record is added by the custom replication stored procedure, it will not. The status will always display "No replicated transactions are available".</p>
<p>I have no clue why the publication is behaving this way: I really don't see how it is treating the data inserted by the custom replication stored procedure differently.</p>
<p>Can someone explain what may I've done wrong?</p>
<p><strong>UPDATE:</strong> I finally have an answer for this problem a few months ago, just that I never got around to update this question. We have to log a support call to Microsoft, but we got a working solution.</p>
<p><hr>
<strong>ANSWER:</strong> To resolve the problem, when adding a subscription,
you need to run the script like below:</p>
<pre><code>sp_addsubscription @publication = 'TEST', ..., @loopback_detection = 'false'
</code></pre>
<p>The key to the solution is the last parameter shown above. By default, the generated subscription script will not have this parameter. </p>
|
[
{
"answer_id": 649814,
"author": "alextansc",
"author_id": 19582,
"author_profile": "https://Stackoverflow.com/users/19582",
"pm_score": 2,
"selected": true,
"text": "sp_addsubscription @publication = 'TEST', ..., @loopback_detection = 'false'\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194077",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19582/"
] |
194,089
|
<p>Say I've got a string which contains a number. I want to check if this number is an integer.</p>
<h3>Examples</h3>
<pre><code>IsInteger("sss") => false
IsInteger("123") => true
IsInterger("123.45") =>false
</code></pre>
|
[
{
"answer_id": 194091,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 4,
"selected": false,
"text": " int val;\nif(int.TryParse(inputString, out val))\n{\n //dosomething\n}\n"
},
{
"answer_id": 194097,
"author": "Alex McBride",
"author_id": 27059,
"author_profile": "https://Stackoverflow.com/users/27059",
"pm_score": 2,
"selected": false,
"text": "string str = \"10\";\nint number = 0;\nif (int.TryParse(str, out number))\n{\n // True\n}\nelse\n{\n // False\n}\n"
},
{
"answer_id": 194105,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 3,
"selected": false,
"text": "int res;\nConsole.WriteLine(int.TryParse(\"sss\", out res));\nConsole.WriteLine(int.TryParse(\"123\", out res));\nConsole.WriteLine(int.TryParse(\"123.45\", out res));\nConsole.WriteLine(int.TryParse(\"123a\", out res));\n False\nTrue\nFalse\nFalse\n Regex pattern = new Regex(\"^-?[0-9]+$\", RegexOptions.Singleline);\nConsole.WriteLine(pattern.Match(\"sss\").Success);\nConsole.WriteLine(pattern.Match(\"123\").Success);\nConsole.WriteLine(pattern.Match(\"123.45\").Success);\nConsole.WriteLine(pattern.Match(\"123a\").Success);\n False\nTrue\nFalse\nFalse\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,101
|
<p>I'd like to track changes in inputs in a form via javascript. My intent is (but not limited) to</p>
<ul>
<li>enable "save" button only when something has changed</li>
<li>alert if the user wants to close the page and something is not saved</li>
</ul>
<p>Ideas?</p>
|
[
{
"answer_id": 194110,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": true,
"text": "onchange $(\"#myForm\")\n .on(\"input\", function() {\n // do whatever you need to do when something's changed.\n // perhaps set up an onExit function on the window\n $('#saveButton').show();\n })\n;\n"
},
{
"answer_id": 194112,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 4,
"selected": false,
"text": ".value .defaultValue function formChanged(form) {\n for (var i = 0; i < form.elements.length; i++) {\n if(form.elements[i].value != form.elements[i].defaultValue) return(true);\n }\n return(false);\n}\n element.checked != element.defaultChecked <select /> select.options selected == defaultSelected onchange formChanged() enabled beforeunload"
},
{
"answer_id": 194119,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 1,
"selected": false,
"text": "window.onbeforeunload = function() {\n return \"You are about to lose your form data.\";\n};\n"
},
{
"answer_id": 194347,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "$(document).observe('dom:loaded', function(e) {\n var browser = {\n trident: !!document.all && !window.opera,\n webkit: (!(!!document.all && !window.opera) && !document.doctype) ||\n (!!window.devicePixelRatio && !!window.getMatchedCSSRules)\n };\n\n // Select form elements that won't bubble up delegated events (eg. onchange)\n var inputs = $('form_id').select('select, input[type=\"radio\"], input[type=\"checkbox\"]');\n\n $('form_id').observe('submit', function(e) {\n // Don't bother submitting if form not modified\n if(!$('form_id').hasClassName('modified')) {\n e.stop();\n return false;\n }\n $('form_id').addClassName('saving');\n });\n\n var change = function(e) {\n // Paste event fires before content has been pasted\n if(e && e.type && e.type == 'paste') {\n arguments.callee.defer();\n return false;\n }\n\n // Check if event actually results in changed data\n if(!e || e.type != 'change') {\n var modified = false;\n $('form_id').getElements().each(function(element) {\n if(element.tagName.match(/^textarea$/i)) {\n if($F(element) != element.defaultValue) {\n modified = true;\n }\n return;\n } else if(element.tagName.match(/^input$/i)) {\n if(element.type.match(/^(text|hidden)$/i) && $F(element) != element.defaultValue) {\n modified = true;\n } else if(element.type.match(/^(checkbox|radio)$/i) && element.checked != element.defaultChecked) {\n modified = true;\n }\n }\n });\n if(!modified) {\n return false;\n }\n }\n\n // Mark form as modified\n $('form_id').addClassName('modified');\n\n // Enable submit/reset buttons\n $('reset_button_id').removeAttribute('disabled');\n $('submit_button_id').removeAttribute('disabled');\n\n // Remove event handlers as they're no longer needed\n if(browser.trident) {\n $('form_id').stopObserving('keyup', change);\n $('form_id').stopObserving('paste', change);\n } else {\n $('form_id').stopObserving('input', change);\n }\n if(browser.webkit) {\n $$('#form_id textarea').invoke('stopObserving', 'keyup', change);\n $$('#form_id textarea').invoke('stopObserving', 'paste', change);\n }\n inputs.invoke('stopObserving', 'change', arguments.callee);\n };\n\n $('form_id').observe('reset', function(e) {\n // Unset form modified, restart modified check...\n $('reset_button_id').writeAttribute('disabled', true);\n $('submit_button_id').writeAttribute('disabled', true);\n $('form_id').removeClassName('modified');\n startObservers();\n });\n\n var startObservers = (function(e) {\n if(browser.trident) {\n $('form_id').observe('keyup', change);\n $('form_id').observe('paste', change);\n } else {\n $('form_id').observe('input', change);\n }\n // Webkit apparently doesn't fire oninput in textareas\n if(browser.webkit) {\n $$('#form_id textarea').invoke('observe', 'keyup', change);\n $$('#form_id textarea').invoke('observe', 'paste', change);\n }\n inputs.invoke('observe', 'change', change);\n return arguments.callee;\n })();\n\n window.onbeforeunload = function(e) {\n if($('form_id').hasClassName('modified') && !$('form_id').hasClassName('saving')) {\n return 'You have unsaved content, would you really like to leave the page? All your changes will be lost.';\n }\n };\n\n});\n"
},
{
"answer_id": 194381,
"author": "Jared",
"author_id": 1980,
"author_profile": "https://Stackoverflow.com/users/1980",
"pm_score": 1,
"selected": false,
"text": "// this example uses the prototype library\n// also, it's not very efficient, I just threw it together\nvar valuesAtLoad = [];\nvar valuesOnCheck = [];\nvar isDirty = false;\nvar names = [];\nEvent.observe(window, 'load', function() {\n $$('.field').each(function(i) {\n valuesAtLoad.push($F(i));\n });\n});\n\nvar checkValues = function() {\n var changes = [];\n valuesOnCheck = [];\n $$('.field').each(function(i) {\n valuesOnCheck.push($F(i));\n });\n\n for(var i = 0; i <= valuesOnCheck.length - 1; i++ ) {\n var source = valuesOnCheck[i];\n var compare = valuesAtLoad[i];\n if( source !== compare ) {\n changes.push($$('.field')[i]);\n }\n }\n\n return changes.length > 0 ? changes : [];\n};\n\nsetInterval(function() { names = checkValues().pluck('id'); isDirty = names.length > 0; }, 100);\n\n// notify the user when they exit\nEvent.observe(window, 'beforeunload', function(e) {\n e.returnValue = isDirty ? \"you have changed the following fields: \\r\\n\" + names + \"\\r\\n these changes will be lost if you exit. Are you sure you want to continue?\" : true;\n});\n"
},
{
"answer_id": 194412,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 0,
"selected": false,
"text": "default"
},
{
"answer_id": 17548306,
"author": "Nikita Makarov",
"author_id": 2564525,
"author_profile": "https://Stackoverflow.com/users/2564525",
"pm_score": 3,
"selected": false,
"text": "function isModifiedForm(form){\n var __clone = $(form).clone();\n __clone[0].reset();\n return $(form).serialize() == $(__clone).serialize();\n}\n"
},
{
"answer_id": 19526123,
"author": "skibulk",
"author_id": 1017480,
"author_profile": "https://Stackoverflow.com/users/1017480",
"pm_score": 3,
"selected": false,
"text": "function formUnloadPrompt(formSelector) {\n var formA = $(formSelector).serialize(), formB, formSubmit = false;\n\n // Detect Form Submit\n $(formSelector).submit( function(){\n formSubmit = true;\n });\n\n // Handle Form Unload \n window.onbeforeunload = function(){\n if (formSubmit) return;\n formB = $(formSelector).serialize();\n if (formA != formB) return \"Your changes have not been saved.\";\n };\n\n // Enable & Disable Submit Button\n var formToggleSubmit = function(){\n formB = $(formSelector).serialize();\n $(formSelector+' [type=\"submit\"]').attr( \"disabled\", formA == formB);\n };\n\n formToggleSubmit();\n $(formSelector).change(formToggleSubmit);\n $(formSelector).keyup(formToggleSubmit);\n}\n\n\n\n// Call function on DOM Ready:\n\n$(function(){\n formUnloadPrompt('form');\n});\n"
},
{
"answer_id": 20137132,
"author": "Savaratkar",
"author_id": 942301,
"author_profile": "https://Stackoverflow.com/users/942301",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\" id=\"MonitorChangeFramework\">\n// MONITOR CHANGE FRAMEWORK\n// ALL ELEMENTS WITH CLASS \".monitorChange\" WILL BE REGISTERED FOR CHANGE\n// ON CHANGE IT WILL RAISE A FLAG\nvar hasChanged;\n\nfunction MonitorChange() {\n hasChanged = false;\n $(\".monitorChange\").change(function () {\n hasChanged = true;\n });\n}\n <textarea class=\"monitorChange\" rows=\"5\" cols=\"10\" id=\"testArea\"></textarea></br>\n <div id=\"divDrinks\">\n <input type=\"checkbox\" class=\"chb monitorChange\" value=\"Tea\" />Tea </br>\n <input type=\"checkbox\" class=\"chb monitorChange\" value=\"Milk\" checked='checked' />Milk</br>\n <input type=\"checkbox\" class=\"chb monitorChange\" value=\"Coffee\" />Coffee </br>\n </div>\n <select id=\"comboCar\" class=\"monitorChange\">\n <option value=\"volvo\">Volvo</option>\n <option value=\"saab\">Saab</option>\n <option value=\"mercedes\">Mercedes</option>\n <option value=\"audi\">Audi</option>\n </select>\n <button id=\"testButton\">\n test</button><a onclick=\"NavigateTo()\">next >>> </a>\n"
},
{
"answer_id": 29946158,
"author": "Bijan",
"author_id": 306478,
"author_profile": "https://Stackoverflow.com/users/306478",
"pm_score": 1,
"selected": false,
"text": "<form onchange=\"validate()\">\n...\n</form>\n <form onkeydown=\"validate()\">\n ...\n <input type=\"checkbox\" onchange=\"validate()\">\n</form>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
194,102
|
<p>We have a web service that is deployed on 2 separate machines in different locations. Is it possible to monitor the url that a person used to call our webservice using java code? We have a 3DNS url set up and we want all clients to use this url as oppossed hitting the boxes directly with the correct port numbers in the url.</p>
<p>Thanks
Damien</p>
|
[
{
"answer_id": 1861830,
"author": "monksy",
"author_id": 80701,
"author_profile": "https://Stackoverflow.com/users/80701",
"pm_score": 3,
"selected": true,
"text": "@Resource\nWebServiceContext wsContext;\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11612/"
] |
194,104
|
<p>I am writing a script that powers on a system via network. And then i need to run a few commands on the other host. How do I know whether the system has powered on?</p>
<p>My programming language is Perl and the target host is RHEL5.</p>
<p>Is there any kernel interrupt or network boot information that indicates the system has powered on and the os has loaded?</p>
<p>[In a different scenario] I was also wondering just in case if i just switch on my Machine manually. when is it exactly said to have powered on. and when is the OS is supposed to have booted completely for a network related operation such as executing a network command there. What if the system is on DHCP how would a remote system then search for this machine [i guess it is possible via mac address. but if i am wrong ].</p>
<p>If I have missed out any info please feel free to ask me. If you have any suggestions to make the task easier please surface them :) </p>
<p>thanx
imkin</p>
|
[
{
"answer_id": 194139,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "@reboot man 5 crontab"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2577336/"
] |
194,121
|
<p>At the team with which I work, we have an old codebase using PHP's ibase_* functions all over the code to communicate with database. We created a wrapper to it that would do something else beside just calling the original function and I did a mass search-replace in the entire code to make sure that wrapper is used instead.</p>
<p>Now, how do we prevent usage of ibase_* functions in the future?</p>
<p>Preferably, I'd like to still have them available, but make it throw a NOTICE or WARNING when it is used.</p>
<p>A solution in pure PHP (not needing to compile a custom version of PHP) is preferred.</p>
|
[
{
"answer_id": 194129,
"author": "unexist",
"author_id": 18179,
"author_profile": "https://Stackoverflow.com/users/18179",
"pm_score": 3,
"selected": false,
"text": "<?php\nclass Foo\n{ \n public function __construct()\n {\n trigger_error('Use Bar instead', E_USER_NOTICE);\n }\n}\n\n$foo = new Foo()\n Notice: Use Bar instead in /home/unexist/projects/ingame/svn/foo.php on line 6\n"
},
{
"answer_id": 194135,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "function my_deprecated_function() {\n trigger_error(\"Deprecated function called.\", E_USER_NOTICE);\n // do stuff.\n}\n"
},
{
"answer_id": 45348092,
"author": "Francesco Casula",
"author_id": 828366,
"author_profile": "https://Stackoverflow.com/users/828366",
"pm_score": 5,
"selected": false,
"text": "/**\n * @deprecated\n *\n * @return $this\n */\npublic function oldMethod()\n{\n trigger_error('Method ' . __METHOD__ . ' is deprecated', E_USER_DEPRECATED);\n\n return $this;\n}\n @deprecated E_USER_DEPRECATED E_DEPRECATED"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194121",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14690/"
] |
194,133
|
<p>I'm working on a Win32 control. There could be hundreds of "items" on this control. Those are not windows, but internal objects (eg: rectangles). Depending on the mouse position I want to change the mouse cursor. That is fine, I can use WM_SETCURSOR.</p>
<p>At the same time based on mouse move I want to display a status bar which shows details about the object currently under the mouse. For that I can use WM_MOUSEMOVE.</p>
<p>Because there could be hundreds of items, traveling all of them to find one under the mouse, well it's not efficient, especially two times (one for set cursor, one for mouse move).</p>
<p>To make it short, do you know if WM_SETCURSOR and WM_MOUSEMOVE are <strong>ALWAYS</strong> in pair? In that case I can calculate what I want during WM_SETCURSOR. The other option would be to set the mouse cursor during WM_MOUSEMOVE, but as far as I know that it's not a good solution (will flicker).</p>
<p>Thanks</p>
|
[
{
"answer_id": 5579715,
"author": "T800",
"author_id": 696612,
"author_profile": "https://Stackoverflow.com/users/696612",
"pm_score": 2,
"selected": false,
"text": "GetMessagePos() MapWindowPoints()"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,150
|
<p>How to check reliably if a SoundChannel is still playing a sound? </p>
<p>For example,</p>
<pre><code>[Embed(source="song.mp3")]
var Song: Class;
var s: Song = new Song();
var ch: SoundChannel = s.play();
// how to check if ch is playing?
</code></pre>
|
[
{
"answer_id": 194653,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 5,
"selected": true,
"text": "\npackage\n{\n import flash.events.Event;\n import flash.media.Sound;\n import flash.media.SoundChannel;\n\n public class SoundPlayer\n {\n [Embed(source=\"song.mp3\")]\n private var Song:Class;\n\n private var s:Song;\n private var ch:SoundChannel;\n private var isSoundPlaying:Boolean;\n\n public function SoundPlayer()\n {\n s = new Song();\n play();\n }\n\n public function play():void\n {\n if(!isPlaying)\n {\n ch = s.play();\n ch.addEventListener(\n Event.SOUND_COMPLETE,\n handleSoundComplete);\n isSoundPlaying = true;\n }\n }\n\n public function stop():void\n {\n if(isPlaying)\n {\n ch.stop();\n isSoundPlaying = false;\n }\n }\n\n private function handleSoundComplete(ev:Event):void\n {\n isSoundPlaying = false;\n }\n }\n}\n"
},
{
"answer_id": 12762031,
"author": "Vesper",
"author_id": 1627055,
"author_profile": "https://Stackoverflow.com/users/1627055",
"pm_score": 1,
"selected": false,
"text": "private var oldPosition:Number;\nfunction onEnterFrame(e:Event):void {\n var stillPlaying:Boolean;\n var newPosition=soundChannel.position;\n if (newPosition-oldPosition>1) stillPlaying=true; else stillPlaying=false;\n oldPosition=newPosition;\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11238/"
] |
194,157
|
<p>I'm using:</p>
<pre><code>FileInfo(
System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles)
+ @"\MyInstalledApp"
</code></pre>
<p>In order to determine if a program is detected on a users machine (it's not ideal, but the program I'm looking for is a right old kludge of a MS-DOS application, and I couldn't think of another method).</p>
<p>On Windows XP and 32-bit versions of Windows Vista this works fine. However, on x64 Windows Vista the code returns the x64 Program Files folder, whereas the application is installed in Program Files x86. Is there a way to programatically return the path to Program Files x86 without hard wiring "C:\Program Files (x86)"?</p>
|
[
{
"answer_id": 194163,
"author": "tomasr",
"author_id": 10292,
"author_profile": "https://Stackoverflow.com/users/10292",
"pm_score": 3,
"selected": false,
"text": "String x86folder = Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\");\n"
},
{
"answer_id": 194191,
"author": "chadmyers",
"author_id": 10862,
"author_profile": "https://Stackoverflow.com/users/10862",
"pm_score": 4,
"selected": false,
"text": "ProgramFiles(x86) ProgramFiles"
},
{
"answer_id": 194223,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 9,
"selected": true,
"text": "Program Files static string ProgramFilesx86()\n{\n if( 8 == IntPtr.Size \n || (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable(\"PROCESSOR_ARCHITEW6432\"))))\n {\n return Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\");\n }\n\n return Environment.GetEnvironmentVariable(\"ProgramFiles\");\n}\n"
},
{
"answer_id": 4442467,
"author": "Carl Hörberg",
"author_id": 80589,
"author_profile": "https://Stackoverflow.com/users/80589",
"pm_score": 5,
"selected": false,
"text": "Environment.GetEnvironmentVariable(\"PROGRAMFILES(X86)\") ?? Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)\n"
},
{
"answer_id": 4514110,
"author": "Nathan",
"author_id": 506520,
"author_profile": "https://Stackoverflow.com/users/506520",
"pm_score": 7,
"selected": false,
"text": "Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)\n"
},
{
"answer_id": 5140124,
"author": "Samir",
"author_id": 637418,
"author_profile": "https://Stackoverflow.com/users/637418",
"pm_score": 3,
"selected": false,
"text": "Environment.GetEnvironmentVariable(\"PROGRAMFILES\")\n"
},
{
"answer_id": 50842101,
"author": "Red John",
"author_id": 3721646,
"author_profile": "https://Stackoverflow.com/users/3721646",
"pm_score": 0,
"selected": false,
"text": "Environment.Is64BitOperatingSystem ? Environment.GetEnvironmentVariable(\"ProgramFiles(x86)\") : Environment.GetEnvironmentVariable(\"ProgramFiles\"))"
},
{
"answer_id": 59478187,
"author": "Clint",
"author_id": 4686729,
"author_profile": "https://Stackoverflow.com/users/4686729",
"pm_score": 0,
"selected": false,
"text": "Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) Go to Visual Studio > Project Properties > Build > Uncheck \"Prefer 32 bit\"\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1293123/"
] |
194,165
|
<p>I'm using the standard <code>ConsoleHandler</code> from <code>java.util.logging</code> and by default the console output is directed to the error stream (i.e. <code>System.err</code>).</p>
<p>How do I change the console output to the output stream (i.e. <code>System.out</code>)?</p>
|
[
{
"answer_id": 194202,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 2,
"selected": false,
"text": "Handler fh = new FileHandler(FILENAME);\nLogger.getLogger(LOGGER_NAME).addHandler(fh);\n"
},
{
"answer_id": 194851,
"author": "Obediah Stane",
"author_id": 23120,
"author_profile": "https://Stackoverflow.com/users/23120",
"pm_score": 3,
"selected": false,
"text": "setUseParentHandlers(false);\n setOutputStream(System.out);\n"
},
{
"answer_id": 2906222,
"author": "Jeremiah Jahn",
"author_id": 350068,
"author_profile": "https://Stackoverflow.com/users/350068",
"pm_score": 3,
"selected": false,
"text": "Handler consoleHandler = new Handler(){\n @Override\n public void publish(LogRecord record)\n {\n if (getFormatter() == null)\n {\n setFormatter(new SimpleFormatter());\n }\n\n try {\n String message = getFormatter().format(record);\n if (record.getLevel().intValue() >= Level.WARNING.intValue())\n {\n System.err.write(message.getBytes()); \n }\n else\n {\n System.out.write(message.getBytes());\n }\n } catch (Exception exception) {\n reportError(null, exception, ErrorManager.FORMAT_FAILURE);\n }\n\n }\n\n @Override\n public void close() throws SecurityException {}\n @Override\n public void flush(){}\n };\n"
},
{
"answer_id": 4738963,
"author": "Frank Vlach",
"author_id": 581895,
"author_profile": "https://Stackoverflow.com/users/581895",
"pm_score": 4,
"selected": false,
"text": " SimpleFormatter fmt = new SimpleFormatter();\n StreamHandler sh = new StreamHandler(System.out, fmt);\n logger.addHandler(sh);\n"
},
{
"answer_id": 5357588,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 4,
"selected": false,
"text": "public class StdoutConsoleHandler extends ConsoleHandler {\n protected void setOutputStream(OutputStream out) throws SecurityException {\n super.setOutputStream(System.out); // kitten killed here :-(\n }\n}\n"
},
{
"answer_id": 10213202,
"author": "Kai",
"author_id": 1341872,
"author_profile": "https://Stackoverflow.com/users/1341872",
"pm_score": 2,
"selected": false,
"text": "package helper;\n\n/**\n * The only difference to the standard StreamHandler is \n * that a MAXLEVEL can be defined (which then is not published)\n * \n * @author Kai Goergen\n */\n\nimport java.io.PrintStream;\nimport java.util.logging.Formatter;\nimport java.util.logging.Level;\nimport java.util.logging.LogRecord;\nimport java.util.logging.StreamHandler;\n\npublic class MaxlevelStreamHandler extends StreamHandler {\n\n private Level maxlevel = Level.SEVERE; // by default, put out everything\n\n /**\n * The only method we really change to check whether the message\n * is smaller than maxlevel.\n * We also flush here to make sure that the message is shown immediately.\n */\n @Override\n public synchronized void publish(LogRecord record) {\n if (record.getLevel().intValue() > this.maxlevel.intValue()) {\n // do nothing if the level is above maxlevel\n } else {\n // if we arrived here, do what we always do\n super.publish(record);\n super.flush();\n }\n }\n\n /**\n * getter for maxlevel\n * @return\n */\n public Level getMaxlevel() {\n return maxlevel;\n }\n\n /**\n * Setter for maxlevel. \n * If a logging event is larger than this level, it won't be displayed\n * @param maxlevel\n */\n public void setMaxlevel(Level maxlevel) {\n this.maxlevel = maxlevel;\n }\n\n /** Constructor forwarding */\n public MaxlevelStreamHandler(PrintStream out, Formatter formatter) {\n super(out, formatter);\n }\n\n /** Constructor forwarding */\n public MaxlevelStreamHandler() {\n super();\n }\n}\n // setup all logs that are smaller than WARNINGS to stdout\nMaxlevelStreamHandler outSh = new MaxlevelStreamHandler(System.out, formatter);\noutSh.setLevel(Level.ALL);\noutSh.setMaxlevel(Level.INFO);\nlogger.addHandler(outSh);\n\n// setup all warnings to stdout & warnings and higher to stderr\nStreamHandler errSh = new StreamHandler(System.err, formatter);\nerrSh.setLevel(Level.WARNING);\nlogger.addHandler(errSh);\n\n// remove default console logger\nlogger.setUseParentHandlers(false);\n\nlogger.info(\"info\");\nlogger.warning(\"warning\");\nlogger.severe(\"severe\");\n"
},
{
"answer_id": 23717493,
"author": "ocarlsen",
"author_id": 1007631,
"author_profile": "https://Stackoverflow.com/users/1007631",
"pm_score": 3,
"selected": false,
"text": "System.out System.err public class DualConsoleHandler extends StreamHandler {\n\n private final ConsoleHandler stderrHandler = new ConsoleHandler();\n\n public DualConsoleHandler() {\n super(System.out, new SimpleFormatter());\n }\n\n @Override\n public void publish(LogRecord record) {\n if (record.getLevel().intValue() <= Level.INFO.intValue()) {\n super.publish(record);\n super.flush();\n } else {\n stderrHandler.publish(record);\n stderrHandler.flush();\n }\n }\n}\n Level.INFO System.err"
},
{
"answer_id": 35919737,
"author": "jmehrens",
"author_id": 2428802,
"author_profile": "https://Stackoverflow.com/users/2428802",
"pm_score": 2,
"selected": false,
"text": "System.err ConsoleHandler h = null;\nfinal PrintStream err = System.err;\nSystem.setErr(System.out);\ntry {\n h = new ConsoleHandler(); //Snapshot of System.err\n} finally {\n System.setErr(err);\n}\n"
},
{
"answer_id": 42458416,
"author": "Virendra Singh",
"author_id": 7622140,
"author_profile": "https://Stackoverflow.com/users/7622140",
"pm_score": 2,
"selected": false,
"text": "ConsoleHandler consoleHandler = new ConsoleHandler (){\n @Override\n protected synchronized void setOutputStream(OutputStream out) throws SecurityException {\n super.setOutputStream(System.out);\n }\n };\n"
},
{
"answer_id": 62165188,
"author": "Hari Krishna",
"author_id": 3302424,
"author_profile": "https://Stackoverflow.com/users/3302424",
"pm_score": 3,
"selected": false,
"text": "log.setUseParentHandlers(false);\n log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));\n import java.io.IOException;\nimport java.util.logging.Logger;\nimport java.util.logging.SimpleFormatter;\nimport java.util.logging.StreamHandler;\n\npublic class App {\n\n static final Logger log = Logger.getLogger(\"com.sample.app.App\");\n\n static void processData() {\n log.info(\"Started Processing Data\");\n log.info(\"Finished processing data\");\n }\n\n public static void main(String args[]) throws IOException {\n log.setUseParentHandlers(false);\n\n log.addHandler(new StreamHandler(System.out, new SimpleFormatter()));\n\n processData();\n }\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194165",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
194,168
|
<p>I asked before about pixel-pushing, and have now managed to get far enough to get noise to show up on the screen. Here's how I init:</p>
<pre><code>CGDataProviderRef provider;
bitmap = malloc(320*480*4);
provider = CGDataProviderCreateWithData(NULL, bitmap, 320*480*4, NULL);
CGColorSpaceRef colorSpaceRef;
colorSpaceRef = CGColorSpaceCreateDeviceRGB();
ir = CGImageCreate(
320,
480,
8,
32,
4 * 320,
colorSpaceRef,
kCGImageAlphaNoneSkipLast,
provider,
NULL,
NO,
kCGRenderingIntentDefault
);
</code></pre>
<p>Here's how I render each frame:</p>
<pre><code>for (int i=0; i<320*480*4; i++) {
bitmap[i] = rand()%256;
}
CGRect rect = CGRectMake(0, 0, 320, 480);
CGContextDrawImage(context, rect, ir);
</code></pre>
<p>Problem is this is awfully awfully slow, around 5fps. I think my path to publish the buffer must be wrong. Is it even possible to do full-screen pixel-based graphics that I could update at 30fps, without using the 3D chip?</p>
|
[
{
"answer_id": 194216,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "320*480*4"
},
{
"answer_id": 1948932,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 1,
"selected": false,
"text": "CGContextDrawImage CGImageRef -[CALayer setContents:] [[view layer] setContents:(id)ir];\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8005/"
] |
194,192
|
<p>I need to know when the user finishes editing a cell in an NSTableView. The table contains all of the user's calendars (obtained from the CalCalendarStore), so in order for the user's changes to be saved I need to inform the CalCalendarStore of the changes. However, I can't find anything that gets called after the user finishes their editing - I would guess that there would be a method in the table's delegate, but I only saw one that gets called when editing starts, not when editing ends.</p>
|
[
{
"answer_id": 12132442,
"author": "Milly",
"author_id": 1608447,
"author_profile": "https://Stackoverflow.com/users/1608447",
"pm_score": 4,
"selected": false,
"text": "NSTableView NSNotificationCenter NSControl delegate NSTableView - (void)controlTextDidEndEditing:(NSNotification *)obj { ... }\n NSTableView delegate NSControl delegate NSNotificationCenter // where you instantiate the table view\n[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(editingDidEnd:)\n name:NSControlTextDidEndEditingNotification object:nil];\n\n// somewhere else in the .m file\n- (void)editingDidEnd:(NSNotification *)notification { ... }\n\n// remove the observer in the dealloc\n- (void)dealloc {\n [[NSNotificationCenter defaultCenter] removeObserver:self\n name:NSControlTextDidEndEditingNotification object:nil];\n [super dealloc]\n}\n"
},
{
"answer_id": 46102084,
"author": "J.beenie",
"author_id": 7289621,
"author_profile": "https://Stackoverflow.com/users/7289621",
"pm_score": 0,
"selected": false,
"text": "// Setup editing completion notifications\nNotificationCenter.default.addObserver(self, selector: #selector(editingDidEnd(_:)), name: NSNotification.Name.NSControlTextDidEndEditing, object: nil)\n func editingDidEnd(_ obj: Notification) {\n guard let newName = (obj.object as? NSTextField)?.stringValue else {\n return\n }\n\n // post editing logic goes here\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3857/"
] |
194,194
|
<p>I have a large collection of data in an excel file (and csv files). The data needs to be placed into a database (mysql). However, before it goes into the database it needs to be processed..for example if columns 1 is less than column 3 add 4 to column 2. There are quite a few rules that must be followed before the information is persisted.</p>
<p>What would be a good design to follow to accomplish this task? (using java)</p>
<p><strong>Additional notes</strong></p>
<p>The process needs to be automated. In the sense that I don't have to manually go in and alter the data. We're talking about thousands of lines of data with 15 columns of information per line.</p>
<p>Currently, I have a sort of chain of responsibility design set up. One class(Java) for each rule. When one rule is done, it calls the following rule.</p>
<p><strong>More Info</strong></p>
<p>Typically there are about 5000 rows per data sheet. Speed isn't a huge concern because
this large input doesn't happen often.</p>
<p>I've considered drools, however I wasn't sure the task was complicated enough for drols. </p>
<p>Example rules:</p>
<ol>
<li><p>All currency (data in specific columns) must not contain currency symbols.</p></li>
<li><p>Category names must be uniform (e.g. book case = bookcase)</p></li>
<li><p>Entry dates can not be future dates</p></li>
<li><p>Text input can only contain [A-Z 0-9 \s]</p></li>
</ol>
<p>etc..<br>
Additionally if any column of information is invalid it needs to be reported when
processing is complete
(or maybe stop processing).</p>
<p>My current solution works. However I think there is room for improvement so I'm looking
for ideals as to how it can be improved and or how other people have handled similar
situations.</p>
<p>I've considered (very briefly) using drools but I wasn't sure the work was complicated enough to take advantage of drools.</p>
|
[
{
"answer_id": 194205,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 0,
"selected": false,
"text": "public class ALine {\n private int col1;\n private int col2;\n private int coln;\n // ...\n\n public ALine(string line) {\n // read row into private variables\n // ...\n\n this.Process();\n this.Insert();\n }\n\n public void Process() {\n // do all your rules here working with the local variables\n }\n\n public void Insert() {\n // write to DB\n }\n}\n\nforeach line in csv\n new ALine(line);\n"
},
{
"answer_id": 194679,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": true,
"text": "interface IFilter {\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n }\n}\n\nclass PredicateFilter : IFilter {\n public PredicateFilter(Predicate<string> predicate) { }\n\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n foreach (string s in file) {\n if (this.Predicate(s)) {\n yield return s;\n }\n }\n }\n}\n\nclass ActionFilter : IFilter {\n public ActionFilter(Action<string> action) { }\n\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n foreach (string s in file) {\n this.Action(s);\n yield return s;\n }\n }\n}\n\nclass ReplaceFilter : IFilter {\n public ReplaceFilter(Func<string, string> replace) { }\n\n public IEnumerable<string> Filter(IEnumerable<string> file) {\n foreach (string s in file) {\n yield return this.Replace(s);\n }\n }\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17337/"
] |
194,208
|
<p>I'm using the following code within the JCProperty class to retrieve data from a DAL: </p>
<pre><code>Dim x As JCProperty
x = JCPropertyDB.GetProperty(PropertyID)
If Not x Is Nothing Then
Me.PropertyID = x.PropertyID
Me.AddressLine1 = x.AddressLine1
Me.AddressLine2 = x.AddressLine2
Me.AddressLine3 = x.AddressLine3
Me.AddressCity = x.AddressCity
Me.AddressCounty = x.AddressCounty
Me.AddressPostcode = x.AddressPostcode
Me.TelNo = x.TelNo
Me.UpdatedOn = x.UpdatedOn
Me.CreatedOn = x.CreatedOn
Me.Description = x.Description
Me.GUID = x.GUID
End If
</code></pre>
<p>This works fine but requires that the DAL object (JCPropertyDB) is aware of the business object (JCProperty) and I effectively create and populate the same object twice (once in the DAL to return to the BL and then again within the BL object to populate itself). </p>
<p>I'm missing something here, I know there must be a better way! </p>
<p>Effectively I need to assign 'Me = x' which is not allowed. Can someone put me straight?</p>
|
[
{
"answer_id": 194270,
"author": "Ron Savage",
"author_id": 12476,
"author_profile": "https://Stackoverflow.com/users/12476",
"pm_score": 2,
"selected": true,
"text": "class JCProperty : inherits JCPropertyDB\n {\n\n New()\n {\n MyBase.New()\n\n GetProperty(PropertyID)\n\n }\n }\n"
},
{
"answer_id": 1543355,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class Person : IBusinessObject<Person>\n{\n protected IDataLayer<T> dataLayer;\n\n Person Load() { this.dataLayer.Load(this); }\n\n}\n public class PersonMapper : IDataLayer<Person> \n{\n Person Load(Person person) {\n ...get DB stuff...map to person...decorate object...\n return person;\n }\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20048/"
] |
194,241
|
<p>In Visual Studio if I define a class to implement an interface e.g.</p>
<pre><code>class MyObject : ISerializable {}
</code></pre>
<p>I am able to right click on ISerializable, select "<em>Implement Interface</em>" from the context menu and see the appropriate methods appear in my class definition.</p>
<pre><code>class MyObject : ISerializable {
#region ISerializable Members
public void GetObjectData(SerializationInfo info,
StreamingContext context)
{
throw new NotImplementedException();
}
#endregion
}
</code></pre>
<p>Is there anything anything like this functionality available in Xcode on the Mac? I would like to be able to automatically implement Protocols in this way. Maybe with the optional methods generated but commented out.</p>
|
[
{
"answer_id": 3952028,
"author": "bithavoc",
"author_id": 146032,
"author_profile": "https://Stackoverflow.com/users/146032",
"pm_score": 1,
"selected": false,
"text": "@protocol PosterousWebsitesDelegate <NSObject>\n- (void)PosterousWebsitesLoadSuccess:(PosterousWebsites*)websites;\n@end\n -(void)Poste (...press ESC...)\n"
},
{
"answer_id": 5359534,
"author": "Clay",
"author_id": 16429,
"author_profile": "https://Stackoverflow.com/users/16429",
"pm_score": 5,
"selected": false,
"text": "@interface FooAppDelegate : NSObject <NSApplicationDelegate, \n NSTableViewDelegate> {\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1403/"
] |
194,247
|
<p>I have a 2 dimensional array, like so:</p>
<pre><code>char[,] str = new char[2,50];
</code></pre>
<p>Now, after I've stored contents in both str[0] and str[1], how do I store it in a </p>
<pre><code>string[] s = new string[2];
</code></pre>
<p>?</p>
<p>I tried </p>
<pre><code>s[0] = str[0].ToString();
</code></pre>
<p>but that seems to be an error: VC# expects 'two' indices within the braces, which means I can convert only a character from the array. Is there a way to convert the entire str[0] to a string? Or is changing it to a jagged array the only solution?</p>
|
[
{
"answer_id": 194252,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 2,
"selected": false,
"text": "char[,] str = new char[2,50];\n\n// populate str somehow\n\n// chose which of the strings we want (the 'row' index)\nint strIndex = 0;\n// create a temporary array (faster and less wasteful than using a StringBuilder)\nchar[] chars = new chars[50];\nfor (int i = 0; i < 50; i++)\n chars[i] = str[strIndex, i];\nstring s = new string[chars];\n char[][] str = new char[2][];\n string s = new string(characters[0]);\n"
},
{
"answer_id": 194259,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 3,
"selected": true,
"text": "// For the multi-dimentional array\nStringBuilder sb = new StringBuilder();\nfor (int stringIndex = 0; stringIndex < s.Length; stringIndex++)\n{\n sb.Clear();\n for (int charIndex = 0; charIndex < str.UpperBound(1); charIndex++)\n sb.Append(str[stringIndex,charIndex]);\n s[stringIndex] = sb.ToString();\n}\n\n// For the jagged array\nfor (int index = 0; index < s.Length; index++)\n s[index] = new string(str[index]);\n"
},
{
"answer_id": 194280,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "static T[][] InitJaggedArray<T>(int dimension1, int dimension2)\n{\n T[][] array = new T[dimension1][];\n for (int i = 0; i < dimension1; i += 1)\n {\n array[i] = new T[dimension2];\n }\n return array;\n}\n char[,] str = new char[2,50];\n char[][] str = ArrayHelper.InitJaggedArray<char>(2, 50);\n str[0, 10] = 'a';\n string s = new string(str[0]);\n"
},
{
"answer_id": 11493521,
"author": "John Rayner",
"author_id": 46473,
"author_profile": "https://Stackoverflow.com/users/46473",
"pm_score": 0,
"selected": false,
"text": "string[] Convert(char[,] chars)\n{\n return Enumerable.Range(0, chars.GetLength(1))\n .Select(i => Enumerable.Range(0, chars.GetLength(0))\n .Select(j => chars[j, i]))\n .Select(chars => new string(chars.ToArray());\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194247",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8127/"
] |
194,261
|
<p>I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/finally clauses to be sure that, should something wrong happen, the Buffer Streams would be closed (and thus, my OS ressources freed) before quiting the function.</p>
<p>I trimmed down the function to show the pattern:</p>
<pre><code>public static void copyFile(FileOutputStream oDStream, FileInputStream oSStream) throw etc...
{
BufferedInputStream oSBuffer = new BufferedInputStream(oSStream, 4096);
BufferedOutputStream oDBuffer = new BufferedOutputStream(oDStream, 4096);
try
{
try
{
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
}
finally
{
oDBuffer.close(); // could throw a IOException
}
}
finally
{
oSBuffer.close(); // could throw a IOException
}
}
</code></pre>
<p>As far as I understand it, I cannot put the two <code>close()</code> in the finally clause because the first <code>close()</code> could well throw, and then, the second would not be executed.</p>
<p>I know C# has the <em>Dispose</em> pattern that would have handled this with the <code>using</code> keyword.</p>
<p>I even know better a C++ code would have been something like (using a Java-like API):</p>
<pre><code>void copyFile(FileOutputStream & oDStream, FileInputStream & oSStream)
{
BufferedInputStream oSBuffer(oSStream, 4096);
BufferedOutputStream oDBuffer(oDStream, 4096);
int c;
while((c = oSBuffer.read()) != -1) // could throw a IOException
{
oDBuffer.write(c); // could throw a IOException
}
// I don't care about resources, as RAII handle them for me
}
</code></pre>
<p>I am missing something, or do I really have to produce ugly and bloated code in Java just to handle exceptions in the <code>close()</code> method of a Buffered Stream?</p>
<p>(Please, tell me I'm wrong somewhere...)</p>
<p><strong>EDIT: Is it me, or when updating this page, I saw both the question and all the answers decreased by one point in a couple of minutes? Is someone enjoying himself too much while remaning anonymous?</strong></p>
<p>EDIT 2: <strong>McDowell</strong> offered a very interesting link I felt I had to mention here:
<a href="http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html" rel="noreferrer">http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-stream.html</a></p>
<p>EDIT 3: Following McDowell's link, I tumbled upon a proposal for Java 7 of a pattern similar to the C# using pattern: <a href="http://tech.puredanger.com/java7/#resourceblock" rel="noreferrer">http://tech.puredanger.com/java7/#resourceblock</a> . My problem is explicitly described. Apparently, even with the Java 7 <code>do</code>, the problems remain.</p>
|
[
{
"answer_id": 194288,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": true,
"text": "/** transcodes text file from one encoding to another */\npublic static void transcode(File source, Charset srcEncoding,\n File target, Charset tgtEncoding)\n throws IOException {\n try (InputStream in = new FileInputStream(source);\n Reader reader = new InputStreamReader(in, srcEncoding);\n OutputStream out = new FileOutputStream(target);\n Writer writer = new OutputStreamWriter(out, tgtEncoding)) {\n char[] buffer = new char[1024];\n int r;\n while ((r = reader.read(buffer)) != -1) {\n writer.write(buffer, 0, r);\n }\n }\n}\n AutoCloseable public class Foo {\n public static void main(String[] args) {\n class CloseTest implements AutoCloseable {\n public void close() {\n System.out.println(\"Close\");\n }\n }\n try (CloseTest closeable = new CloseTest()) {}\n }\n}\n"
},
{
"answer_id": 194292,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "public static void copy(\n InputStream in, OutputStream out\n) throw IOException {\n byte[] buff = new byte[8192];\n for (;;) {\n int len = in.read(buff);\n if (len == -1) {\n break;\n }\n out.write(buff, 0, len);\n }\n}\n private"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14089/"
] |
194,278
|
<p>In a <a href="https://stackoverflow.com/questions/194272">related question</a>, my team is about to (hopefully) start using LINQ, and I'd like to take advantage of anonymous types. What is the best way to mix VB.NET's Option Strict (which we've been using through the life of the project) and the new Option Infer directives?</p>
|
[
{
"answer_id": 54266943,
"author": "jmoreno",
"author_id": 234954,
"author_profile": "https://Stackoverflow.com/users/234954",
"pm_score": 0,
"selected": false,
"text": "txtBox.Text = If(str=\"\", Nothing, CDate(str))\n txtBox.Text = CStr(If(str=\"\", Nothing, CType(CDate(str), Object)))\n txtBox.Text = Cstr(If(str=\"\", CDate(Nothing), CType(CDate(str), Object)))\n txtBox.Text = Cstr(If(str=\"\", Nothing, CDate(str)))\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194278",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6897/"
] |
194,304
|
<p>I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range. </p>
<p>Here's an example:</p>
<pre><code>IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
</code></pre>
|
[
{
"answer_id": 195920,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "class Range<T> where T: IComparable<T>\n{\n public T From { get; set; }\n public T To { get; set; }\n\n public Range(T from, T to) { this.From = from; this.To = to; }\n\n public IEnumerable<T> Enumerate(Func<T, T> next)\n {\n for (T t = this.From; t.CompareTo(this.To) < 0; t = next(t))\n {\n yield return t;\n }\n }\n\n static void Example()\n {\n new Range<int> (0, 100).Enumerate(i => i+1)\n }\n}\n"
},
{
"answer_id": 195921,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 0,
"selected": false,
"text": "class EnumerableRange<T> : Range<T>, IEnumerable<T>\n where T : IComparable<T>\n{\n readonly Func<T, T> _next;\n public EnumerableRange(T from, T to, Func<T, T> next)\n : base(from, to)\n {\n this._next = next;\n }\n\n public IEnumerator<T> GetEnumerator()\n {\n return Enumerate(this._next).GetEnumerator();\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n}\n"
},
{
"answer_id": 195924,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 3,
"selected": false,
"text": "public static IEnumerable<int> To(this int start, int end)\n{\n return start.To(end, i => i + 1);\n}\n\npublic static IEnumerable<int> To(this int start, int end, Func<int, int> next)\n{\n int current = start;\n while (current < end)\n {\n yield return current;\n current = next(current);\n }\n}\n 1.To(100)\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5314/"
] |
194,328
|
<p>I know we can use tools like JProfiler etc.
Is there any tutorial on how to configure it to display the memory usage just by remote monitoring?</p>
<p>Any idea?</p>
|
[
{
"answer_id": 194351,
"author": "MatthieuGD",
"author_id": 3109,
"author_profile": "https://Stackoverflow.com/users/3109",
"pm_score": 3,
"selected": false,
"text": "JAVA_HOME/bin/jstatd -J-Djava.security.policy=jstatd.all.policy\n grant codebase \"file:${java.home}/../lib/tools.jar\" { \npermission java.security.AllPermission;\n};\n visualgc the_pid@remote_machine_address\n"
},
{
"answer_id": 229091,
"author": "Peter",
"author_id": 26483,
"author_profile": "https://Stackoverflow.com/users/26483",
"pm_score": 2,
"selected": false,
"text": "-agentlib:jprofilerti=port=25000"
},
{
"answer_id": 229161,
"author": "joejag",
"author_id": 2257098,
"author_profile": "https://Stackoverflow.com/users/2257098",
"pm_score": 3,
"selected": false,
"text": "JAVA_OPTS=\"-Djava.awt.headless=true -agentlib:yjpagent -Xrunyjpagent:sessionname=Tomcat\"\n LD_LIBRARY_PATH=$LD_LIBRARY_PATH:~/yourkit/yjp-6.0.16/bin/linux-x86-32\n"
},
{
"answer_id": 8417604,
"author": "Madhu Cheepati",
"author_id": 1085899,
"author_profile": "https://Stackoverflow.com/users/1085899",
"pm_score": 1,
"selected": false,
"text": ".bash_profile /root .bash_profile file\nexport LD_LIBRARY_PATH=/dsvol/jprofiler6/bin/linux-x86\n catalena.sh bin catelana.sh export JPROFILER_HOME\nJAVA_OPTS=\"-Xms768m -Xmx1024m -XX:PermSize=256m -XX:MaxPermSize=256m -Dfile.encoding=UTF8 -agentpath:/opt/Performance/jprofiler7/bin/linux-x86/libjprofilerti.so=port=8849 $CATALINA_OPTS\"\n starup.sh"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25368/"
] |
194,331
|
<p>I have a domain class containing a couple of fields. I can access them from my .gsps. I want to add a method to the domain class, which I can call from the .gsps (this method is a kind of virtual field; it's data is not coming directly from the database).</p>
<p>How do I add the method and how can I then call it from the .gsps?</p>
|
[
{
"answer_id": 194348,
"author": "Hates_",
"author_id": 3410,
"author_profile": "https://Stackoverflow.com/users/3410",
"pm_score": 5,
"selected": true,
"text": "def someMethod() {\n return \"Hello.\"\n}\n ${myObject.someMethod()}\n"
},
{
"answer_id": 18535117,
"author": "Ramesh",
"author_id": 2729165,
"author_profile": "https://Stackoverflow.com/users/2729165",
"pm_score": 2,
"selected": false,
"text": "String jobTitle\nString jobType\nString jobLocation\nString state\n\n\n\nstatic constraints = {\n\n jobTitle nullable : false,size: 0..200\n jobType nullable : false,size: 0..200\n jobLocation nullable : false,size: 0..200\n state nullable : false\n\n\n}\n\n\n\ndef jsonMap () {\n [\n 'jobTitle':\"some job title\",\n 'jobType':\"some jobType\",\n 'jobLocation':\"some location\",\n 'state':\"some state\"\n ]\n }\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3506/"
] |
194,339
|
<p>I have several python projects that share common modules. Until now, I've been ... ahem ... keeping multiple copies of the common code and synchronizing by hand. But I'd clearly prefer to do something else.</p>
<p>It looks to me now, as if zc.Buildout maybe what I need. I guess that what I should be doing is putting each reusable component of my system into a separate egg, and then using buildout to assemble them into projects.</p>
<p>I'm also thinking that for any particular module, I should put the unit-tests into a separate package or egg, so that I'm not also installing copies of the component's unit-tests in every project. I only want to unit-test in a place where my library is developed, not where it's just being used.</p>
<p>So maybe I want something like this</p>
<pre><code>projects
lib1
tests
code
lib2
tests
code
app1
tests
appcode
app2
tests
appcode
</code></pre>
<p>etc.</p>
<p>Where both app1 and app2 are independent applications with their own code and tests, but are also including and using both lib1 and lib2. And lib1/test, lib1/code, lib2/test, lib2code, app1, app2 are separate eggs. Does this sound right?</p>
<p>However, I now get confused. I assume that when I develop app1, I want buildout to pull copies of lib1, lib2 and app1 into a separate working directory rather than put copies of these libraries under app1 directly. But how does this work with my SVN source-control? If the working directory is dynamically constructed with buildout, it can't be a live SVN directory from which I can check the changes back into the repository?</p>
<p>Have I misunderstood how buildout is meant to be used? Would I be better going for a completely different approach? How do you mix source-control with module-reuse between projects?</p>
<p>Update : thanks to the two people who've currently answered this question. I'm experimenting more with this.</p>
|
[
{
"answer_id": 194472,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "sys.path lib/site-packages .pth PYTHONPATH setup.py svn up python setup.py install PYTHONPATH projects/lib1 projects/lib2 PYTHONPATH"
},
{
"answer_id": 195102,
"author": "Kozyarchuk",
"author_id": 52490,
"author_profile": "https://Stackoverflow.com/users/52490",
"pm_score": 2,
"selected": false,
"text": "Lib1/\n branches/\n tags/\n trunk/\n lib1/\n tests/\n setup.py\nLib2\n branches/\n tags/\n trunk/\n lib2/\n tests/\n setup.py\nApp1\n branches/\n tags/\n trunk/\n app1/\n tests/\n setup.py\nApp2\n branches/\n tags/\n trunk/\n app2/\n tests/\n setup.py\n Lib1/\n lib1/\n tests/\n setup.py\nLib2/\n lib2/\n tests/\n setup.py\nApp1/\n app1/\n tests/\n setup.py\nApp2/\n app2/\n tests/\n setup.py\n App1/\n lib1-1.1.0-py2.5.egg/\n lib2-1.1.0-py2.5.egg/\n app1/\n sitecustomize.py\n\nApp2/\n lib1-1.2.0-py2.5.egg/\n lib2-1.2.0-py2.5.egg/\n app2/\n sitecustomize.py\n"
},
{
"answer_id": 421758,
"author": "elarson",
"author_id": 5434,
"author_profile": "https://Stackoverflow.com/users/5434",
"pm_score": 1,
"selected": false,
"text": "mkvirtualenv lib1-dev\n workon lib1-dev\n virtualenv --no-site-packages some-env\n"
},
{
"answer_id": 7620767,
"author": "Martijn Pieters",
"author_id": 100297,
"author_profile": "https://Stackoverflow.com/users/100297",
"pm_score": 3,
"selected": false,
"text": "buildout.cfg bootstrap.py zc.recipe.testrunner sources.cfg checkouts.cfg testing.cfg"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8482/"
] |
194,346
|
<p>I have an HTML page (say welcome.html) which contains an iframe to a page I have no control over (say app.html). The user performs some actions using the app within the iframe and clicks submit. Once they do this, they are taken to a new page (say thanks.jsp), which loads within the iframe. Is there a way in which I can force thanks.jsp to load in the full frame and not the iframe once submit is clicked? Remember, I have no control over the logic behind that Submit button or app.html. I do however have control over welcome.html and thanks.jsp. If possible, I would like to stick with HTML and/or JavaScript. Thank you in advance.</p>
|
[
{
"answer_id": 194363,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 4,
"selected": true,
"text": "thanks.jsp <script type=\"text/javascript\">\n if (self != top) { top.location.replace(location); }\n</script>\n <base target=\"_top\">"
},
{
"answer_id": 194365,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "thanks.jsp // Parent window not the same as this one\nif (self !=top) \n{\n top.location.href = self.location.href;\n} \n thanks.jsp thanks.jsp thanks.jsp thanks.jsp"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78/"
] |
194,349
|
<p>Where do you store <em>user-specific</em> and <em>machine-specific</em> <strong>runtime</strong> configuration data for J2SE application?</p>
<p>(For example, <em>C:\Users\USERNAME\AppData\Roaming</em> on Windows and /home/username</em> on Unix)</p>
<p>How do you get these locations in the filesystem in platform-independent way?</p>
|
[
{
"answer_id": 194371,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": false,
"text": "Preferences userPrefs = Preferences.getUserNodeForPackage(MyClass.class); // Gets user preferences node for MyClass\nPreferences systemPrefs = Preferences.getSysteNodeForPackage(MyClass.class); // Gets system preferences node for MyClass\nPreferences userPrefsRoot = Preferences.getUserRoot(); // Gets user preferences root node\nPreferences systemPrefsRoot = Preferences.getSystemRoot(); // Gets system preferences root node\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1764/"
] |
194,358
|
<p>I have an unmanaged C dll I call from a C# class library that encrypts a string value into an encrypted string that contains non-ascii characters. I need to take the data and write its binary values to a file, but C# treats text as <code>string</code> rather than a <code>byte[]</code>. </p>
<p>The encrypted value commonly contains special characters (<code>\r</code>, <code>\O</code>, etc). When I do this converting the returned string to C# using some type of codeset (ascii, utf-7, utf-16) it writes the special character values as the Windows interpreted values instead their actual binary representation. </p>
<p>My question is how can I pull the data from the unmanaged dll into a <code>byte[]</code> rather than a string so I can write that to file using the <code>BinaryWriter</code>?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 194425,
"author": "Stephen Edmonds",
"author_id": 17349,
"author_profile": "https://Stackoverflow.com/users/17349",
"pm_score": 2,
"selected": false,
"text": "ASCIIEncoding ascii = new ASCIIEncoding();\nByte[] encodedBytes = ascii.GetBytes(unicodeString);\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,382
|
<p>What is the difference between applying the visitor design pattern to your code and the following approach:</p>
<pre><code>interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s) {
this.s = s;
}
public void setInterface(Dointerface d) {
this.d = d;
}
public void perform() {
d.perform(this);
}
public static void main(String[] args) {
T t = new T("Geonline");
t.setInterface(new Dointerface() {
public void perform(Object o) {
T a = (T)o;
System.out.println(a.getS());
}
});
t.perform();
}
}
</code></pre>
<p>I assume that by using interfaces, we're not really separating the algorithm.</p>
|
[
{
"answer_id": 194452,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 3,
"selected": true,
"text": "perfom setInterface perfom accept setInterface"
},
{
"answer_id": 217105,
"author": "Martin Brown",
"author_id": 20553,
"author_profile": "https://Stackoverflow.com/users/20553",
"pm_score": 2,
"selected": false,
"text": " public void visit(Object o) {\n if (o instanceof File)\n visitFile((File)o);\n else if (o instanceof Directory)\n visitDirectory((Directory)o);\n else if (o instanceof X)\n // ...\n }\n @Override\n public void accept(FileSystemVisitor v) {\n v.visitFile(this);\n }\n public class VisitorSample {\n //\n public abstract class FileSystemItem {\n public abstract String getName();\n public abstract int getSize();\n public abstract void accept(FileSystemVisitor v);\n }\n // \n public abstract class FileSystemItemContainer extends FileSystemItem {\n protected java.util.ArrayList<FileSystemItem> _list = new java.util.ArrayList<FileSystemItem>();\n // \n public void addItem(FileSystemItem item)\n {\n _list.add(item);\n }\n //\n public FileSystemItem getItem(int i)\n {\n return _list.get(i);\n }\n // \n public int getCount() {\n return _list.size();\n }\n // \n public abstract void accept(FileSystemVisitor v);\n public abstract String getName();\n public abstract int getSize();\n }\n // \n public class File extends FileSystemItem {\n //\n public String _name;\n public int _size;\n // \n public File(String name, int size) {\n _name = name;\n _size = size;\n }\n // \n @Override\n public void accept(FileSystemVisitor v) {\n v.visitFile(this);\n }\n //\n @Override\n public String getName() {\n return _name;\n }\n //\n @Override\n public int getSize() {\n return _size;\n }\n }\n // \n public class Directory extends FileSystemItemContainer {\n //\n private String _name;\n // \n public Directory(String name) {\n _name = name;\n }\n // \n @Override\n public void accept(FileSystemVisitor v) {\n v.visitDirectory(this);\n }\n //\n @Override\n public String getName() {\n return _name;\n }\n //\n @Override\n public int getSize() {\n int size = 0;\n for (int i = 0; i < _list.size(); i++)\n {\n size += _list.get(i).getSize();\n }\n return size;\n } \n }\n // \n public abstract class FileSystemVisitor {\n // \n public void visitFile(File f) { }\n public void visitDirectory(Directory d) { }\n //\n public void vistChildren(FileSystemItemContainer c) {\n for (int i = 0; i < c.getCount(); i++)\n {\n c.getItem(i).accept(this);\n }\n }\n }\n // \n public class ListingVisitor extends FileSystemVisitor {\n // \n private int _indent = 0;\n // \n @Override\n public void visitFile(File f) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.print(\"~\");\n System.out.print(f.getName());\n System.out.print(\":\");\n System.out.println(f.getSize());\n }\n // \n @Override\n public void visitDirectory(Directory d) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \"); \n System.out.print(\"\\\\\");\n System.out.print(d.getName());\n System.out.println(\"\\\\\");\n // \n _indent += 3;\n vistChildren(d);\n _indent -= 3;\n }\n }\n // \n public class XmlVisitor extends FileSystemVisitor {\n // \n private int _indent = 0;\n // \n @Override\n public void visitFile(File f) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.print(\"<file name=\\\"\");\n System.out.print(f.getName());\n System.out.print(\"\\\" size=\\\"\");\n System.out.print(f.getSize());\n System.out.println(\"\\\" />\");\n }\n // \n @Override\n public void visitDirectory(Directory d) {\n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.print(\"<directory name=\\\"\");\n System.out.print(d.getName());\n System.out.print(\"\\\" size=\\\"\");\n System.out.print(d.getSize());\n System.out.println(\"\\\">\");\n // \n _indent += 4;\n vistChildren(d);\n _indent -= 4;\n // \n for (int i = 0; i < _indent; i++)\n System.out.print(\" \");\n System.out.println(\"</directory>\");\n }\n }\n // \n public static void main(String[] args) {\n VisitorSample s = new VisitorSample();\n // \n Directory root = s.new Directory(\"root\");\n root.addItem(s.new File(\"FileA\", 163));\n root.addItem(s.new File(\"FileB\", 760));\n Directory sub = s.new Directory(\"sub\");\n root.addItem(sub);\n sub.addItem(s.new File(\"FileC\", 401));\n sub.addItem(s.new File(\"FileD\", 543));\n Directory subB = s.new Directory(\"subB\");\n root.addItem(subB);\n subB.addItem(s.new File(\"FileE\", 928));\n subB.addItem(s.new File(\"FileF\", 238));\n // \n XmlVisitor xmlVisitor = s.new XmlVisitor();\n root.accept(xmlVisitor);\n // \n ListingVisitor listing = s.new ListingVisitor();\n root.accept(listing);\n }\n }\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11234/"
] |
194,384
|
<p>(sorry for my English)
For example, in my DAL,I have an AuthorDB object, that has a Name
and a BookDB object, that has a Title and an IdAuthor. </p>
<p>Now, if I want to show all the books with their corresponding author's name, I have to get a collection of all the Books, and for each of them, with the IdAuthor attribute, find the Author's name. This makes a lot of queries to the database, and obviously, a simple JOIN could be used. </p>
<p>What are my options? Creating a 'custom' object that contains the author's name and the title of the book? If so, the maintenance could become awful.</p>
<p>So, what are the options?
Thank you!</p>
|
[
{
"answer_id": 194588,
"author": "Thomas Eyde",
"author_id": 3282,
"author_profile": "https://Stackoverflow.com/users/3282",
"pm_score": 0,
"selected": false,
"text": "public IEnumerable<Book> AllBooks()\n{\n return from book in db.Books\n join author in db.Authors on book.AuthorId equals author.Id\n select new Book() \n { \n Title = book.Title, \n Author = author.Name,\n };\n}\n public IEnumerable<Book> AllBooks()\n{\n DataTable booksAndAuthors = QueryAllBooksAndAuthors(); // encapsulates the sql query\n\n foreach (DataRow row in booksAndAuthors.Rows)\n {\n Book book = new Book();\n book.Title = row[\"Title\"];\n book.Author = row[\"AuthorName\"];\n yield return book;\n }\n}\n"
},
{
"answer_id": 196223,
"author": "Thomas Eyde",
"author_id": 3282,
"author_profile": "https://Stackoverflow.com/users/3282",
"pm_score": 0,
"selected": false,
"text": "var books = new BookRepository().GetAllBooks();\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,388
|
<p>The existing application is in C#. During startup the application calls a virtual method to make changes to the database (for example a new revision may need to calculate a new field or something). An open OleDb connection is passed into the method. </p>
<p>I need to change a field width. The ALTER TABLE statement is working fine. But I would like to avoid executing the ALTER TABLE statement if the field is already the appropriate size. Is there a way to determine the size of an MS Access field using the same OleDb connection?</p>
|
[
{
"answer_id": 195048,
"author": "Andy",
"author_id": 27096,
"author_profile": "https://Stackoverflow.com/users/27096",
"pm_score": 1,
"selected": false,
"text": "var command = new OleDbCommand(\"SELECT FIELD FROM TABLE\", connection); \nvar reader = command.ExecuteReader(CommandBehavior.SchemaOnly); \nvar schema = reader.GetSchemaTable(); \nvar size = Convert.ToInt32(table.Rows[0][\"ColumnSize\"]);\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27096/"
] |
194,395
|
<p>Given a heapdump or a running VM, how do I discover what the contents of the permanent generation is ? I know about 'jmap -permstat' but that's not available on Windows.</p>
|
[
{
"answer_id": 8600342,
"author": "David Tinker",
"author_id": 159434,
"author_profile": "https://Stackoverflow.com/users/159434",
"pm_score": 1,
"selected": false,
"text": " MemoryUsage usage = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();\n long nonHeapFree = usage.getMax() - usage.getUsed();\n long nonHeapTotal = usage.getMax();\n"
},
{
"answer_id": 32832221,
"author": "Bobby",
"author_id": 162980,
"author_profile": "https://Stackoverflow.com/users/162980",
"pm_score": 0,
"selected": false,
"text": "-verbose:class"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22850/"
] |
194,397
|
<p>I want to make a JavaScript application that's not open source, and thus I wish to learn how to can obfuscate my JS code? Is this possible?</p>
|
[
{
"answer_id": 194399,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 10,
"selected": true,
"text": "UPDATE: This question was originally asked on 2008, and The mentioned technologies are deprecated. you can use:"
},
{
"answer_id": 3541517,
"author": "Andreas Bonini",
"author_id": 95135,
"author_profile": "https://Stackoverflow.com/users/95135",
"pm_score": 4,
"selected": false,
"text": "a = [1,2,3,];"
},
{
"answer_id": 8692272,
"author": "Matt",
"author_id": 1124926,
"author_profile": "https://Stackoverflow.com/users/1124926",
"pm_score": 2,
"selected": false,
"text": "sort _sUserPreferredNickName a"
},
{
"answer_id": 17468822,
"author": "cocco",
"author_id": 2450730,
"author_profile": "https://Stackoverflow.com/users/2450730",
"pm_score": 5,
"selected": false,
"text": "var ajax=function(a,b,d,c,e,f){\n e=new FormData();\n for(f in d){e.append(f,d[f]);};\n c=new XMLHttpRequest();\n c.open('POST',a);\n c.setRequestHeader(\"Troll1\",\"lol\");\n c.onload=b;\n c.send(e);\n};\nwindow.onload=function(){\n ajax('Troll.php',function(){\n (new Function(atob(this.response)))()\n },{'Troll2':'lol'});\n}\n (new Function(atob('dmFyIGFqYXg9ZnVuY3Rpb24oYSxiLGQsYyxlLGYpe2U9bmV3IEZvcm1EYXRhKCk7Zm9yKGYgaW4gZCl7ZS5hcHBlbmQoZixkW2ZdKTt9O2M9bmV3IFhNTEh0dHBSZXF1ZXN0KCk7Yy5vcGVuKCdQT1NUJyxhKTtjLnNldFJlcXVlc3RIZWFkZXIoIlRyb2xsMSIsImxvbCIpO2Mub25sb2FkPWI7Yy5zZW5kKGUpO307d2luZG93Lm9ubG9hZD1mdW5jdGlvbigpe2FqYXgoJ1Ryb2xsLnBocCcsZnVuY3Rpb24oKXsgKG5ldyBGdW5jdGlvbihhdG9iKHRoaXMucmVzcG9uc2UpKSkoKX0seydUcm9sbDInOidsb2wnfSk7fQ==')))()\n <?php\n$t1=apache_request_headers();\nif(base64_encode($_SERVER['HTTP_REFERER'])=='aHR0cDovL2hlcmUuaXMvbXkvbGF1bmNoZXIuaHRtbA=='&&$_POST['Troll2']=='lol'&&$t1['Troll1']='lol'){\n echo 'ZG9jdW1lbnQuYm9keS5hcHBlbmRDaGlsZChkb2N1bWVudC5jcmVhdGVFbGVtZW50KCdkaXYnKSkuaW5uZXJUZXh0PSdBd2Vzb21lJzsNCg==';//here is the SECRET javascript code\n}else{\n echo 'd2luZG93Lm9wZW4oJycsICdfc2VsZicsICcnKTt3aW5kb3cuY2xvc2UoKTs=';\n};\n?>\n http://here.is/my/launcher.html document.body.appendChild(document.createElement('div')).innerText='Awesome'; window.open('', '_self', '');window.close(); document.body.appendChild(document.createElement('div')).innerText='Awesome'; <!doctype html><html><head><meta charset=\"utf-8\"><title></title><script src=\"data:application/javascript;base64,KG5ldyBGdW5jdGlvbihhdG9iKCdkbUZ5SUdGcVlYZzlablZ1WTNScGIyNG9ZU3hpTEdRc1l5eGxMR1lwZTJVOWJtVjNJRVp2Y20xRVlYUmhLQ2s3Wm05eUtHWWdhVzRnWkNsN1pTNWhjSEJsYm1Rb1ppeGtXMlpkS1R0OU8yTTlibVYzSUZoTlRFaDBkSEJTWlhGMVpYTjBLQ2s3WXk1dmNHVnVLQ2RRVDFOVUp5eGhLVHRqTG5ObGRGSmxjWFZsYzNSSVpXRmtaWElvSWxSeWIyeHNNU0lzSW14dmJDSXBPMk11YjI1c2IyRmtQV0k3WXk1elpXNWtLR1VwTzMwN2QybHVaRzkzTG05dWJHOWhaRDFtZFc1amRHbHZiaWdwZTJGcVlYZ29KMVJ5YjJ4c0xuQm9jQ2NzWm5WdVkzUnBiMjRvS1hzZ0tHNWxkeUJHZFc1amRHbHZiaWhoZEc5aUtIUm9hWE11Y21WemNHOXVjMlVwS1Nrb0tYMHNleWRVY205c2JESW5PaWRzYjJ3bmZTazdmUT09JykpKSgp\"></script></head><body></body></html>\n <?php $t1=apache_request_headers();if(/*base64_encode($_SERVER['HTTP_REFERER'])=='PUT THE LAUNCHER REFERER HERE'&&*/$_POST['Troll2']=='lol'&&$t1['Troll1']='lol'){echo 'ZG9jdW1lbnQuYm9keS5hcHBlbmRDaGlsZChkb2N1bWVudC5jcmVhdGVFbGVtZW50KCdkaXYnKSkuaW5uZXJUZXh0PSdBd2Vzb21lJzsNCg==';}else{echo 'd2luZG93Lm9wZW4oJycsICdfc2VsZicsICcnKTt3aW5kb3cuY2xvc2UoKTs=';}; ?>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
194,418
|
<p>I'm looking for some help and it goes like this:
I'm a fairly green software developer, and focus mainly on the web (python/PHP) but am pretty well experienced with Java applications and as an electrical engineering student, looking forward to dive into some c/c++. I've pretty much grown up on Windows machine, but hate .net with a passion and dont really have a need to develop on Windows - besides the fact that i'm used to it.</p>
<p>I'm looking to switch to Ubuntu as my development machine entirely (without having WinXP on another partition) as I'm quite fedup with Windows, but am tempted to go back to it everytime i'm stuck with countless driver issues (be it headphone drivers, or dual monitor setup, etc). I'm looking for a comprehensive resource that will help this transition and doesn't assume you know alien linux shell keywords.</p>
<p>Cheers.</p>
|
[
{
"answer_id": 194636,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 2,
"selected": false,
"text": ".gnome"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11110/"
] |
194,428
|
<p>How can i release the memory that I used for a variable (e.g. a long string) in C?</p>
|
[
{
"answer_id": 194432,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 5,
"selected": true,
"text": "malloc free"
},
{
"answer_id": 194444,
"author": "Svet",
"author_id": 8934,
"author_profile": "https://Stackoverflow.com/users/8934",
"pm_score": 1,
"selected": false,
"text": "for (int i=0;i<10;i++) {\n int k=i;\n //do stuff\n}\n int* intArray;\nmalloc(200 * sizeof(int));\n"
},
{
"answer_id": 194447,
"author": "PhirePhly",
"author_id": 20082,
"author_profile": "https://Stackoverflow.com/users/20082",
"pm_score": 1,
"selected": false,
"text": "char array[100];\n int reallylongfunction() {\n // Do a lot of stuff\n {\n char stringbuffer[100];\n // Do stuff with the buffer...\n // Ok, we're done with the buffer, and don't want it anymore\n }\n // Do a lot more stuff\n return;\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25017/"
] |
194,430
|
<p>I'm experimenting with internationalization by making a Hello World program that uses properties files + ResourceBundle to get different strings.</p>
<p>Specifically, I have a file "messages_en_US.properties" that stores "hello.world=Hello World!", which works fine of course.</p>
<p>I then have a file "messages_ja_JP.properties" which I've tried all sorts of things with, but it always appears as some type of garbled string when printed to the console or in Swing. The problem is obviously with the reading of the content into a Java string, as a Java string in Japanese typed directly into the source can print fine.</p>
<p>Things I've tried:</p>
<ul>
<li>The .properties file in UTF-8 encoding with the Japanese string as-is for the value. Something I read indicates that Java expects a properties file to be in the native encoding of the system...? It didn't work either way.</li>
<li>The file in default encoding (ISO-8859-1) and the value stored as escaped Unicode created by the native2ascii program included with Java. Tried with a source file in various Japanese encodings... SHIFT-JIS, EUC-JP, ISO-2022-JP.</li>
</ul>
<p><strong>Edit:</strong></p>
<p>I actually figured this out while I was typing this, but I figured I'd post it anyway and answer it in case it helps anyone.</p>
|
[
{
"answer_id": 194794,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 2,
"selected": false,
"text": "String realProp = new String(prop.getBytes(\"ISO-8859-1\"), \"UTF-8\");\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13792/"
] |
194,443
|
<p>I want to post an xml document to an <strong>asp</strong> page from an <strong>asp.net</strong> page. If I use WebRequest with content/type text/xml the document never gets to the asp page. How can I do this ?</p>
|
[
{
"answer_id": 197728,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<data id='10'>value</data>"
},
{
"answer_id": 315438,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 2,
"selected": false,
"text": "HttpWebRequest request = (HttpWebRequest)WebRequest.Create(targetUri);\nstring sendString = formParameterName + \"=\" + HttpUtility.UrlEncode(xmlData);\nbyte[] byteStream;\nbyteStream = System.Text.Encoding.UTF8.GetBytes(sendString);\n\nrequest.Method = POST;\nrequest.ContentType = \"application/x-www-form-urlencoded\";\nrequest.ContentLength = byteStream.LongLength;\n\nusing(Stream writer = request.GetRequestStream())\n{\n writer.Write(byteStream, 0, (int)request.ContentLength);\n writer.Flush();\n}\n\nHttpWebResponse resp = (HttpWebResponse)request.GetResponse();\n\n//read the response\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,445
|
<p>the question I am having is: when running my app with a launch code other than sysAppLaunchCmdNormalLaunch, I can not use code outside the default code segment - but could I use a shared library that is multi-segmented, thus circumventing this problem?</p>
<p>A bit of background information: I am evaluating the possibility of porting an existing mobile application to PalmOS. A core part of this app is that it is doing some network communication in the background every 10 minutes or so, or when it receives incoming data (via a network/socket callback). During this time, I do not have access to globals and hence not to any code segments in my application other than the default one.</p>
<p>The problem now is that the actions involved in the communication (protocol, data handling, etc) require a lot of code that just does not fit into one segment. Apart from the question whether it makes sense to have that much code run in the 'background', the obvious problem is: how would I run it in the first place? Hence the question, whether putting the code in a shared (multi-segment) library would help.</p>
<p>Looking forward to your insights.</p>
|
[
{
"answer_id": 912886,
"author": "PhrkOnLsh",
"author_id": 112613,
"author_profile": "https://Stackoverflow.com/users/112613",
"pm_score": 1,
"selected": false,
"text": "__STANDALONE_CODE_RESOURCE__ //segment 1000\n\nUInt32 foobar( char* hi )\n{\n return 12;\n}\n\n// functions.c\ntypedef (UInt32)(*fooPtr)( char* ); // this is now a type representing a pointer to your function.\nUInt32 foobar( char* hi )\n{\n LocalID id; UInt16 cn; SysCurAppDatabase(&cn,&id);\n DmOpenRef ref = DmOpenDatabase (cn, id, dmModeReadOnly );\n MemHandle H = DmGetResource('code',1000);\n fooPtr code = MemHandleLock(H);\n UInt32 result = (*fooPtr)( hi);\n\n return result;\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27101/"
] |
194,450
|
<p>I'm looking for an easiest way how to implement the "suggest" feature for a text entry field in a Rails application. The idea is to complete names stored in a database column, giving the user a drop-down menu of possible matches as he types.</p>
<p>Thanks for any suggestions!</p>
|
[
{
"answer_id": 199771,
"author": "JasonOng",
"author_id": 6048,
"author_profile": "https://Stackoverflow.com/users/6048",
"pm_score": 1,
"selected": false,
"text": "# your_view.rhtml\n\n<%= text_field 'contact', 'name', :id => 'suggest' %>\n<div id='dropdown' style='display:none; z-index: 100; background: #FFFFFF'></div>\n\n<script>\n new Ajax.Autocompleter('suggest', 'dropdown', \"<%= url_for :controller => 'contacts', :action => 'suggest_name' %>\") \n</script>\n\n# contacts_controller.rb\n\ndef suggest_name\n query_string = params[:contact][:name]\n @contacts = Contact.find.all :conditions => ['name ilike ?', \"%#{query_string}%\"]\n render :partial => 'name_suggestions'\nend\n\n# contacts/_name_suggestions.rhtml\n\n<ul>\n<% for contact in @contacts %>\n <li><%= contact.name %></li>\n<% end %>\n</ul>\n"
},
{
"answer_id": 201380,
"author": "Olly",
"author_id": 1174,
"author_profile": "https://Stackoverflow.com/users/1174",
"pm_score": 3,
"selected": false,
"text": "text_field_with_auto_complete ActionView::Helpers::JavaScriptMacrosHelper Post title text_field_tag f.text_field text_field_with_auto_complete <%= text_field_with_auto_complete :post, :title %>\n PostsController class PostsController < ApplicationController\n auto_complete_for :post, :title\nend\n auto_complete_for_[object]_[method] auto_complete_for_post_title find Post.find(:all, ...) Post auto_complete_for_[object]_[method]"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,464
|
<p>Everyone (at least everyone who uses a compiled language) has faced compilation errors but how many times do you get to actually crash the compiler? </p>
<p>I've had my fair share of <strong>"internal compiler errors"</strong> but most went away just by re-compiling. Do you have a (minimal) piece of code that crashes the compiler?</p>
|
[
{
"answer_id": 194599,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "switch(on_some_variable)\n{\n}\n"
},
{
"answer_id": 194630,
"author": "ejgottl",
"author_id": 9808,
"author_profile": "https://Stackoverflow.com/users/9808",
"pm_score": 5,
"selected": false,
"text": "// -*- C++ -*-\n\ntemplate <int n>\nclass Foo : public Foo<n+1>\n{\n\n};\n\nint main(int, char*[])\n{\n Foo<0> x;\n return 0;\n};\n\n\nejgottl@luna:~/tmp$ g++ -ftemplate-depth-1000000 -Wall foo.cpp -o foo\ng++: Internal error: Segmentation fault (program cc1plus)\nPlease submit a full bug report.\nSee `<URL:http://gcc.gnu.org/bugs.html>` for instructions.\nFor Debian GNU/Linux specific bug reporting instructions, see\n`<URL:file:///usr/share/doc/gcc-4.2/README.Bugs>`.\n"
},
{
"answer_id": 194757,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "struct MyClass\n{\n MyClass operator->() { return *this; }\n};\n\n\nint main(int argc, char* argv[])\n{\n MyClass A;\n A->x;\n}\n"
},
{
"answer_id": 194942,
"author": "ephemient",
"author_id": 20713,
"author_profile": "https://Stackoverflow.com/users/20713",
"pm_score": 4,
"selected": false,
"text": "My brain just exploded.\nI can't handle pattern bindings for existentially-quantified constructors.\n"
},
{
"answer_id": 195062,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 0,
"selected": false,
"text": "//wierd japanese characters here %^$$\\\nswitch(n)\n{\ncase 0:\n .....\nbreak;\ncase 1:\n .....\nbreak;\n}\n"
},
{
"answer_id": 195880,
"author": "friol",
"author_id": 23034,
"author_profile": "https://Stackoverflow.com/users/23034",
"pm_score": 2,
"selected": false,
"text": "PRINT 0 + \"\" +- 0\n"
},
{
"answer_id": 196485,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "------ Build started: Project: pdfp, Configuration: Debug Win32 ------\nCompiling...\nreader.cpp\nxref.cpp\nc:\\projects\\pdfp\\xref.cpp(52) : fatal error C1001: An internal error has occurred in the compiler.\n(compiler file 'f:\\dd\\vctools\\compiler\\cxxfe\\sl\\p1\\c\\toil.c', line 8569)\n To work around this problem, try simplifying or changing the program near the locations listed above.\nPlease choose the Technical Support command on the Visual C++ \n Help menu, or open the Technical Support help file for more information\nGenerating Code...\nBuild log was saved at \"file://c:\\Projects\\pdfp\\Debug\\BuildLog.htm\"\npdfp - 1 error(s), 0 warning(s)\n========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========\n"
},
{
"answer_id": 225172,
"author": "Motti",
"author_id": 3848,
"author_profile": "https://Stackoverflow.com/users/3848",
"pm_score": 1,
"selected": false,
"text": " template<typename Res, typename T>\n Res operator_cast(const T& t)\n {\n return t.operator Res();\n }\n\n int main()\n {\n return operator_cast<int>(0);\n }\n"
},
{
"answer_id": 339529,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 2,
"selected": false,
"text": "typdef struct kGUIColor GameColor;\n\nc:\\source\\kgui\\samples\\space\\space.cpp(35) : fatal error C1001: INTERNAL COMPILER ERROR\n (compiler file 'msc1.cpp', line 2708) \n Please choose the Technical Support command on the Visual C++ \n Help menu, or open the Technical Support help file for more information\n"
},
{
"answer_id": 2610539,
"author": "Synetech",
"author_id": 119540,
"author_profile": "https://Stackoverflow.com/users/119540",
"pm_score": 2,
"selected": false,
"text": "struct PATTERN {\n …\n};\n typedef int SOMETHINGOROTHER;\n struct SOMETHINGOROTHER {};\n > fatal error C1001: INTERNAL COMPILER ERROR > (compiler file 'msc1.cpp', line 2708) … struct SOMETHINGOROTHER {};\n typedef int SOMETHINGOROTHER;\n > 'SOMETHINGOROTHER' : redefinition; different basic types"
},
{
"answer_id": 2610688,
"author": "Earlz",
"author_id": 69742,
"author_profile": "https://Stackoverflow.com/users/69742",
"pm_score": 1,
"selected": false,
"text": "struct{\n char myvalue:1;\n}mystruct;\n"
},
{
"answer_id": 3773171,
"author": "natskvi",
"author_id": 455495,
"author_profile": "https://Stackoverflow.com/users/455495",
"pm_score": 2,
"selected": false,
"text": "typedef map<int,int> Tmap;\nprivate: Tmap; * m_map;\n Tmap m_map"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3848/"
] |
194,465
|
<p>What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of <a href="http://en.cppreference.com/w/cpp/string/byte/atoi" rel="noreferrer">returning zero</a>).</p>
|
[
{
"answer_id": 194478,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 3,
"selected": false,
"text": "int str2int (const string &str) {\n stringstream ss(str);\n int num;\n ss >> num;\n return num;\n}\n"
},
{
"answer_id": 194487,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 4,
"selected": false,
"text": "lexical_cast lexical_cast<Target>(Source) bad_lexical_cast"
},
{
"answer_id": 194512,
"author": "Luka Marinko",
"author_id": 19814,
"author_profile": "https://Stackoverflow.com/users/19814",
"pm_score": 6,
"selected": false,
"text": "const char* str = \"123\";\nint i;\n\nif(sscanf(str, \"%d\", &i) == EOF )\n{\n /* error */\n}\n int str2int (const string &str) {\n stringstream ss(str);\n int num;\n if((ss >> num).fail())\n { \n //ERROR \n }\n return num;\n}\n #include <boost/lexical_cast.hpp>\n#include <string>\n\ntry\n{\n std::string str = \"123\";\n int number = boost::lexical_cast< int >( str );\n}\ncatch( const boost::bad_lexical_cast & )\n{\n // Error\n}\n"
},
{
"answer_id": 194518,
"author": "jk.",
"author_id": 21284,
"author_profile": "https://Stackoverflow.com/users/21284",
"pm_score": 4,
"selected": false,
"text": "stringstream ss(str);\nint x;\nss >> x;\n\nif(ss) { // <-- error handling\n // use x\n} else {\n // not a number\n}\n"
},
{
"answer_id": 1350601,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "static const std::size_t digit_table_symbol_count = 256;\nstatic const unsigned char digit_table[digit_table_symbol_count] = {\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xFF - 0x07\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x08 - 0x0F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x10 - 0x17\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x18 - 0x1F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x20 - 0x27\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x28 - 0x2F\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 0x30 - 0x37\n 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x38 - 0x3F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x40 - 0x47\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x48 - 0x4F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x50 - 0x57\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x58 - 0x5F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x60 - 0x67\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x68 - 0x6F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x70 - 0x77\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x78 - 0x7F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x80 - 0x87\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x88 - 0x8F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x90 - 0x97\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0x98 - 0x9F\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA0 - 0xA7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xA8 - 0xAF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB0 - 0xB7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xB8 - 0xBF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC0 - 0xC7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xC8 - 0xCF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD0 - 0xD7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xD8 - 0xDF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE0 - 0xE7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xE8 - 0xEF\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 0xF0 - 0xF7\n 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 0xF8 - 0xFF\n };\n\ntemplate<typename InputIterator, typename T>\ninline bool string_to_signed_type_converter_impl_itr(InputIterator begin, InputIterator end, T& v)\n{\n if (0 == std::distance(begin,end))\n return false;\n v = 0;\n InputIterator it = begin;\n bool negative = false;\n if ('+' == *it)\n ++it;\n else if ('-' == *it)\n {\n ++it;\n negative = true;\n }\n if (end == it)\n return false;\n while(end != it)\n {\n const T digit = static_cast<T>(digit_table[static_cast<unsigned int>(*it++)]);\n if (0xFF == digit)\n return false;\n v = (10 * v) + digit;\n }\n if (negative)\n v *= -1;\n return true;\n}\n"
},
{
"answer_id": 4328610,
"author": "caa",
"author_id": 527010,
"author_profile": "https://Stackoverflow.com/users/527010",
"pm_score": 3,
"selected": false,
"text": "ex.: generate(ptr_char, int_, integer_number);\n int naive_char_2_int(const char *p) {\n int x = 0;\n bool neg = false;\n if (*p == '-') {\n neg = true;\n ++p;\n }\n while (*p >= '0' && *p <= '9') {\n x = (x*10) + (*p - '0');\n ++p;\n }\n if (neg) {\n x = -x;\n }\n return x;\n}\n"
},
{
"answer_id": 6154614,
"author": "Dan Moulding",
"author_id": 95706,
"author_profile": "https://Stackoverflow.com/users/95706",
"pm_score": 8,
"selected": false,
"text": "bool str2int (int &i, char const *s)\n{\n std::stringstream ss(s);\n ss >> i;\n if (ss.fail()) {\n // not an integer\n return false;\n }\n return true;\n}\n str2int(i, \"1337h4x0r\") true i 1337 stringstream bool str2int (int &i, char const *s)\n{\n char c;\n std::stringstream ss(s);\n ss >> i;\n if (ss.fail() || ss.get(c)) {\n // not an integer\n return false;\n }\n return true;\n}\n ss << std::hex int int stringstream stringstream lexical_cast lexical_cast stringstream stringstream lexical_cast lexical_cast stringstream stringstream strtol enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };\n\nSTR2INT_ERROR str2int (int &i, char const *s, int base = 0)\n{\n char *end;\n long l;\n errno = 0;\n l = strtol(s, &end, base);\n if ((errno == ERANGE && l == LONG_MAX) || l > INT_MAX) {\n return OVERFLOW;\n }\n if ((errno == ERANGE && l == LONG_MIN) || l < INT_MIN) {\n return UNDERFLOW;\n }\n if (*s == '\\0' || *end != '\\0') {\n return INCONVERTIBLE;\n }\n i = l;\n return SUCCESS;\n}\n base strtol"
},
{
"answer_id": 11354496,
"author": "CC.",
"author_id": 195527,
"author_profile": "https://Stackoverflow.com/users/195527",
"pm_score": 9,
"selected": true,
"text": "int myNr = std::stoi(myString);\n"
},
{
"answer_id": 17998820,
"author": "fuzzyTew",
"author_id": 129550,
"author_profile": "https://Stackoverflow.com/users/129550",
"pm_score": 3,
"selected": false,
"text": "<string> stoi stol stoul stoll stoull strto*"
},
{
"answer_id": 17999031,
"author": "BlackMamba",
"author_id": 2223579,
"author_profile": "https://Stackoverflow.com/users/2223579",
"pm_score": -1,
"selected": false,
"text": "int atoi (const char * str)"
},
{
"answer_id": 25223180,
"author": "user3925906",
"author_id": 3925906,
"author_profile": "https://Stackoverflow.com/users/3925906",
"pm_score": 2,
"selected": false,
"text": "#include <cstdlib>\n#include <cerrno>\n#include <climits>\n#include <stdexcept>\n\nint to_int(const std::string &s, int base = 0)\n{\n char *end;\n errno = 0;\n long result = std::strtol(s.c_str(), &end, base);\n if (errno == ERANGE || result > INT_MAX || result < INT_MIN)\n throw std::out_of_range(\"toint: string is out of range\");\n if (s.length() == 0 || *end != '\\0')\n throw std::invalid_argument(\"toint: invalid string\");\n return result;\n}\n to_int(\"0x7b\") to_int(\"0173\") to_int(\"01111011\", 2) to_int(\"0000007B\", 16) to_int(\"11120\", 3) to_int(\"3L\", 34); std::stoi std::stoi boost::lexical_cast stringstream to_int(\" 123\") to_int(\"123 \")"
},
{
"answer_id": 27724349,
"author": "Boris",
"author_id": 4403456,
"author_profile": "https://Stackoverflow.com/users/4403456",
"pm_score": 0,
"selected": false,
"text": "#define toInt(x) {atoi(x.c_str())};\n int main()\n{\nstring test = \"46\", test2 = \"56\";\nint a = toInt(test);\nint b = toInt(test2);\ncout<<a+b<<endl;\n}\n"
},
{
"answer_id": 31196698,
"author": "DreamWarrior",
"author_id": 4995485,
"author_profile": "https://Stackoverflow.com/users/4995485",
"pm_score": 0,
"selected": false,
"text": "#include <cstdlib>\n#include <cerrno>\n#include <limits>\n#include <stdexcept>\n#include <sstream>\n\nstatic const int DefaultBase = 10;\n\ntemplate<typename T>\nstatic inline T CstrtoxllWrapper(const char *str, int base = DefaultBase)\n{\n while (isspace(*str)) str++; // remove leading spaces; verify there's data\n if (*str == '\\0') { throw std::invalid_argument(\"str; no data\"); } // nothing to convert\n\n // NOTE: for some reason strtoull allows a negative sign, we don't; if\n // converting to an unsigned then it must always be positive!\n if (!std::numeric_limits<T>::is_signed && *str == '-')\n { throw std::invalid_argument(\"str; negative\"); }\n\n // reset errno and call fn (either strtoll or strtoull)\n errno = 0;\n char *ePtr;\n T tmp = std::numeric_limits<T>::is_signed ? strtoll(str, &ePtr, base)\n : strtoull(str, &ePtr, base);\n\n // check for any C errors -- note these are range errors on T, which may\n // still be out of the range of the actual type we're using; the caller\n // may need to perform additional range checks.\n if (errno != 0) \n {\n if (errno == ERANGE) { throw std::range_error(\"str; out of range\"); }\n else if (errno == EINVAL) { throw std::invalid_argument(\"str; EINVAL\"); }\n else { throw std::invalid_argument(\"str; unknown errno\"); }\n }\n\n // verify everything converted -- extraneous spaces are allowed\n if (ePtr != NULL)\n {\n while (isspace(*ePtr)) ePtr++;\n if (*ePtr != '\\0') { throw std::invalid_argument(\"str; bad data\"); }\n }\n\n return tmp;\n}\n\ntemplate<typename T>\nT StringToSigned(const char *str, int base = DefaultBase)\n{\n static const long long max = std::numeric_limits<T>::max();\n static const long long min = std::numeric_limits<T>::min();\n\n long long tmp = CstrtoxllWrapper<typeof(tmp)>(str, base); // use largest type\n\n // final range check -- only needed if not long long type; a smart compiler\n // should optimize this whole thing out\n if (sizeof(T) == sizeof(tmp)) { return tmp; }\n\n if (tmp < min || tmp > max)\n {\n std::ostringstream err;\n err << \"str; value \" << tmp << \" out of \" << sizeof(T) * 8\n << \"-bit signed range (\";\n if (sizeof(T) != 1) err << min << \"..\" << max;\n else err << (int) min << \"..\" << (int) max; // don't print garbage chars\n err << \")\";\n throw std::range_error(err.str());\n }\n\n return tmp;\n}\n\ntemplate<typename T>\nT StringToUnsigned(const char *str, int base = DefaultBase)\n{\n static const unsigned long long max = std::numeric_limits<T>::max();\n\n unsigned long long tmp = CstrtoxllWrapper<typeof(tmp)>(str, base); // use largest type\n\n // final range check -- only needed if not long long type; a smart compiler\n // should optimize this whole thing out\n if (sizeof(T) == sizeof(tmp)) { return tmp; }\n\n if (tmp > max)\n {\n std::ostringstream err;\n err << \"str; value \" << tmp << \" out of \" << sizeof(T) * 8\n << \"-bit unsigned range (0..\";\n if (sizeof(T) != 1) err << max;\n else err << (int) max; // don't print garbage chars\n err << \")\";\n throw std::range_error(err.str());\n }\n\n return tmp;\n}\n\ntemplate<typename T>\ninline T\nStringToDecimal(const char *str, int base = DefaultBase)\n{\n return std::numeric_limits<T>::is_signed ? StringToSigned<T>(str, base)\n : StringToUnsigned<T>(str, base);\n}\n\ntemplate<typename T>\ninline T\nStringToDecimal(T &out_convertedVal, const char *str, int base = DefaultBase)\n{\n return out_convertedVal = StringToDecimal<T>(str, base);\n}\n\n/*============================== [ Test Strap ] ==============================*/ \n\n#include <inttypes.h>\n#include <iostream>\n\nstatic bool _g_anyFailed = false;\n\ntemplate<typename T>\nvoid TestIt(const char *tName,\n const char *s, int base,\n bool successExpected = false, T expectedValue = 0)\n{\n #define FAIL(s) { _g_anyFailed = true; std::cout << s; }\n\n T x;\n std::cout << \"converting<\" << tName << \">b:\" << base << \" [\" << s << \"]\";\n try\n {\n StringToDecimal<T>(x, s, base);\n // get here on success only\n if (!successExpected)\n {\n FAIL(\" -- TEST FAILED; SUCCESS NOT EXPECTED!\" << std::endl);\n }\n else\n {\n std::cout << \" -> \";\n if (sizeof(T) != 1) std::cout << x;\n else std::cout << (int) x; // don't print garbage chars\n if (x != expectedValue)\n {\n FAIL(\"; FAILED (expected value:\" << expectedValue << \")!\");\n }\n std::cout << std::endl;\n }\n }\n catch (std::exception &e)\n {\n if (successExpected)\n {\n FAIL( \" -- TEST FAILED; EXPECTED SUCCESS!\"\n << \" (got:\" << e.what() << \")\" << std::endl);\n }\n else\n {\n std::cout << \"; expected exception encounterd: [\" << e.what() << \"]\" << std::endl;\n }\n }\n}\n\n#define TEST(t, s, ...) \\\n TestIt<t>(#t, s, __VA_ARGS__);\n\nint main()\n{\n std::cout << \"============ variable base tests ============\" << std::endl;\n TEST(int, \"-0xF\", 0, true, -0xF);\n TEST(int, \"+0xF\", 0, true, 0xF);\n TEST(int, \"0xF\", 0, true, 0xF);\n TEST(int, \"-010\", 0, true, -010);\n TEST(int, \"+010\", 0, true, 010);\n TEST(int, \"010\", 0, true, 010);\n TEST(int, \"-10\", 0, true, -10);\n TEST(int, \"+10\", 0, true, 10);\n TEST(int, \"10\", 0, true, 10);\n\n std::cout << \"============ base-10 tests ============\" << std::endl;\n TEST(int, \"-010\", 10, true, -10);\n TEST(int, \"+010\", 10, true, 10);\n TEST(int, \"010\", 10, true, 10);\n TEST(int, \"-10\", 10, true, -10);\n TEST(int, \"+10\", 10, true, 10);\n TEST(int, \"10\", 10, true, 10);\n TEST(int, \"00010\", 10, true, 10);\n\n std::cout << \"============ base-8 tests ============\" << std::endl;\n TEST(int, \"777\", 8, true, 0777);\n TEST(int, \"-0111 \", 8, true, -0111);\n TEST(int, \"+0010 \", 8, true, 010);\n\n std::cout << \"============ base-16 tests ============\" << std::endl;\n TEST(int, \"DEAD\", 16, true, 0xDEAD);\n TEST(int, \"-BEEF\", 16, true, -0xBEEF);\n TEST(int, \"+C30\", 16, true, 0xC30);\n\n std::cout << \"============ base-2 tests ============\" << std::endl;\n TEST(int, \"-10011001\", 2, true, -153);\n TEST(int, \"10011001\", 2, true, 153);\n\n std::cout << \"============ irregular base tests ============\" << std::endl;\n TEST(int, \"Z\", 36, true, 35);\n TEST(int, \"ZZTOP\", 36, true, 60457993);\n TEST(int, \"G\", 17, true, 16);\n TEST(int, \"H\", 17);\n\n std::cout << \"============ space deliminated tests ============\" << std::endl;\n TEST(int, \"1337 \", 10, true, 1337);\n TEST(int, \" FEAD\", 16, true, 0xFEAD);\n TEST(int, \" 0711 \", 0, true, 0711);\n\n std::cout << \"============ bad data tests ============\" << std::endl;\n TEST(int, \"FEAD\", 10);\n TEST(int, \"1234 asdfklj\", 10);\n TEST(int, \"-0xF\", 10);\n TEST(int, \"+0xF\", 10);\n TEST(int, \"0xF\", 10);\n TEST(int, \"-F\", 10);\n TEST(int, \"+F\", 10);\n TEST(int, \"12.4\", 10);\n TEST(int, \"ABG\", 16);\n TEST(int, \"10011002\", 2);\n\n std::cout << \"============ int8_t range tests ============\" << std::endl;\n TEST(int8_t, \"7F\", 16, true, std::numeric_limits<int8_t>::max());\n TEST(int8_t, \"80\", 16);\n TEST(int8_t, \"-80\", 16, true, std::numeric_limits<int8_t>::min());\n TEST(int8_t, \"-81\", 16);\n TEST(int8_t, \"FF\", 16);\n TEST(int8_t, \"100\", 16);\n\n std::cout << \"============ uint8_t range tests ============\" << std::endl;\n TEST(uint8_t, \"7F\", 16, true, std::numeric_limits<int8_t>::max());\n TEST(uint8_t, \"80\", 16, true, std::numeric_limits<int8_t>::max()+1);\n TEST(uint8_t, \"-80\", 16);\n TEST(uint8_t, \"-81\", 16);\n TEST(uint8_t, \"FF\", 16, true, std::numeric_limits<uint8_t>::max());\n TEST(uint8_t, \"100\", 16);\n\n std::cout << \"============ int16_t range tests ============\" << std::endl;\n TEST(int16_t, \"7FFF\", 16, true, std::numeric_limits<int16_t>::max());\n TEST(int16_t, \"8000\", 16);\n TEST(int16_t, \"-8000\", 16, true, std::numeric_limits<int16_t>::min());\n TEST(int16_t, \"-8001\", 16);\n TEST(int16_t, \"FFFF\", 16);\n TEST(int16_t, \"10000\", 16);\n\n std::cout << \"============ uint16_t range tests ============\" << std::endl;\n TEST(uint16_t, \"7FFF\", 16, true, std::numeric_limits<int16_t>::max());\n TEST(uint16_t, \"8000\", 16, true, std::numeric_limits<int16_t>::max()+1);\n TEST(uint16_t, \"-8000\", 16);\n TEST(uint16_t, \"-8001\", 16);\n TEST(uint16_t, \"FFFF\", 16, true, std::numeric_limits<uint16_t>::max());\n TEST(uint16_t, \"10000\", 16);\n\n std::cout << \"============ int32_t range tests ============\" << std::endl;\n TEST(int32_t, \"7FFFFFFF\", 16, true, std::numeric_limits<int32_t>::max());\n TEST(int32_t, \"80000000\", 16);\n TEST(int32_t, \"-80000000\", 16, true, std::numeric_limits<int32_t>::min());\n TEST(int32_t, \"-80000001\", 16);\n TEST(int32_t, \"FFFFFFFF\", 16);\n TEST(int32_t, \"100000000\", 16);\n\n std::cout << \"============ uint32_t range tests ============\" << std::endl;\n TEST(uint32_t, \"7FFFFFFF\", 16, true, std::numeric_limits<int32_t>::max());\n TEST(uint32_t, \"80000000\", 16, true, std::numeric_limits<int32_t>::max()+1);\n TEST(uint32_t, \"-80000000\", 16);\n TEST(uint32_t, \"-80000001\", 16);\n TEST(uint32_t, \"FFFFFFFF\", 16, true, std::numeric_limits<uint32_t>::max());\n TEST(uint32_t, \"100000000\", 16);\n\n std::cout << \"============ int64_t range tests ============\" << std::endl;\n TEST(int64_t, \"7FFFFFFFFFFFFFFF\", 16, true, std::numeric_limits<int64_t>::max());\n TEST(int64_t, \"8000000000000000\", 16);\n TEST(int64_t, \"-8000000000000000\", 16, true, std::numeric_limits<int64_t>::min());\n TEST(int64_t, \"-8000000000000001\", 16);\n TEST(int64_t, \"FFFFFFFFFFFFFFFF\", 16);\n TEST(int64_t, \"10000000000000000\", 16);\n\n std::cout << \"============ uint64_t range tests ============\" << std::endl;\n TEST(uint64_t, \"7FFFFFFFFFFFFFFF\", 16, true, std::numeric_limits<int64_t>::max());\n TEST(uint64_t, \"8000000000000000\", 16, true, std::numeric_limits<int64_t>::max()+1);\n TEST(uint64_t, \"-8000000000000000\", 16);\n TEST(uint64_t, \"-8000000000000001\", 16);\n TEST(uint64_t, \"FFFFFFFFFFFFFFFF\", 16, true, std::numeric_limits<uint64_t>::max());\n TEST(uint64_t, \"10000000000000000\", 16);\n\n std::cout << std::endl << std::endl\n << (_g_anyFailed ? \"!! SOME TESTS FAILED !!\" : \"ALL TESTS PASSED\")\n << std::endl;\n\n return _g_anyFailed;\n}\n StringToDecimal int a; a = StringToDecimal<int>(\"100\");\n int a; StringToDecimal(a, \"100\");\n int a; a = StringToDecimal(\"100\");\n CstrtoxllWrapper strtoull strtoll CstrtoxllWrapper StringToSigned StringToUnsigned StringToSigned StringToUnsigned StringToDecimal"
},
{
"answer_id": 35204010,
"author": "pellucide",
"author_id": 892771,
"author_profile": "https://Stackoverflow.com/users/892771",
"pm_score": 1,
"selected": false,
"text": " while (isspace(*end)) {\n end++;\n }\n if ((errno != 0) || (s == end)) {\n return INCONVERTIBLE;\n }\n #include <cstdlib>\n#include <cerrno>\n#include <climits>\n#include <stdexcept>\n\nenum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };\n\nSTR2INT_ERROR str2long (long &l, char const *s, int base = 0)\n{\n char *end = (char *)s;\n errno = 0;\n\n l = strtol(s, &end, base);\n\n if ((errno == ERANGE) && (l == LONG_MAX)) {\n return OVERFLOW;\n }\n if ((errno == ERANGE) && (l == LONG_MIN)) {\n return UNDERFLOW;\n }\n if ((errno != 0) || (s == end)) {\n return INCONVERTIBLE;\n } \n while (isspace((unsigned char)*end)) {\n end++;\n }\n\n if (*s == '\\0' || *end != '\\0') {\n return INCONVERTIBLE;\n }\n\n return SUCCESS;\n}\n"
},
{
"answer_id": 44275053,
"author": "Iqra.",
"author_id": 7596696,
"author_profile": "https://Stackoverflow.com/users/7596696",
"pm_score": 2,
"selected": false,
"text": "std::string s1 = \"4533\";\nstd::string s2 = \"3.010101\";\nstd::string s3 = \"31337 with some string\";\n\nint myint1 = std::stoi(s1);\nint myint2 = std::stoi(s2);\nint myint3 = std::stoi(s3);\n\nstd::cout << s1 <<\"=\" << myint1 << '\\n';\nstd::cout << s2 <<\"=\" << myint2 << '\\n';\nstd::cout << s3 <<\"=\" << myint3 << '\\n';\n #include <string.h>\n#include <sstream>\n#include <iostream>\n#include <cstring>\nusing namespace std;\n\n\nint StringToInteger(string NumberAsString)\n{\n int NumberAsInteger;\n stringstream ss;\n ss << NumberAsString;\n ss >> NumberAsInteger;\n return NumberAsInteger;\n}\nint main()\n{\n string NumberAsString;\n cin >> NumberAsString;\n cout << StringToInteger(NumberAsString) << endl;\n return 0;\n} \n std::string str4 = \"453\";\nint i = 0, in=0; // 453 as on\nfor ( i = 0; i < str4.length(); i++)\n{\n\n in = str4[i];\n cout <<in-48 ;\n\n}\n"
},
{
"answer_id": 48917248,
"author": "Pharap",
"author_id": 1377706,
"author_profile": "https://Stackoverflow.com/users/1377706",
"pm_score": 4,
"selected": false,
"text": "std::from_chars <charconv> #include <iostream>\n#include <charconv>\n#include <array>\n\nint main()\n{\n char const * str = \"42\";\n int value = 0;\n\n std::from_chars_result result = std::from_chars(std::begin(str), std::end(str), value);\n\n if(result.error == std::errc::invalid_argument)\n {\n std::cout << \"Error, invalid format\";\n }\n else if(result.error == std::errc::result_out_of_range)\n {\n std::cout << \"Error, value too big for int range\";\n }\n else\n {\n std::cout << \"Success: \" << result;\n }\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3827/"
] |
194,468
|
<p>I'm trying to write a faster user switching app for Windows. Win+L and selecting users is very cumbersome. If I start Task Manager as administrator, it shows active users and I can select one and "Connect" (if I enter their password).</p>
<p>How do I get the list of all users (or all active users)? </p>
<p>I'm using C# (Visual Studio Express).</p>
|
[
{
"answer_id": 732654,
"author": "Dan Ports",
"author_id": 88885,
"author_profile": "https://Stackoverflow.com/users/88885",
"pm_score": 2,
"selected": false,
"text": "using Cassia;\n\nforeach (ITerminalServicesSession session in new TerminalServicesManager().GetSessions())\n{\n if (!string.IsNullOrEmpty(session.UserName))\n {\n Console.WriteLine(\"Session {0} (User {1})\", session.SessionId, session.UserName);\n }\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21352/"
] |
194,484
|
<p>I collect a few corner cases and <a href="http://www.yoda.arachsys.com/csharp/teasers.html" rel="nofollow noreferrer">brain teasers</a> and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:</p>
<pre><code>string x = new string(new char[0]);
string y = new string(new char[0]);
Console.WriteLine(object.ReferenceEquals(x, y));
</code></pre>
<p>I'd expect that to print False - after all, "new" (with a reference type) <em>always</em> creates a new object, doesn't it? The specs for both C# and the CLI indicate that it should. Well, not in this particular case. It prints True, and has done on every version of the framework I've tested it with. (I haven't tried it on Mono, admittedly...)</p>
<p>Just to be clear, this is only an example of the kind of thing I'm looking for - I wasn't particularly looking for discussion/explanation of this oddity. (It's not the same as normal string interning; in particular, string interning doesn't normally happen when a constructor is called.) I was really asking for similar odd behaviour.</p>
<p>Any other gems lurking out there?</p>
|
[
{
"answer_id": 194671,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 10,
"selected": true,
"text": " static void Foo<T>() where T : new()\n {\n T t = new T();\n Console.WriteLine(t.ToString()); // works fine\n Console.WriteLine(t.GetHashCode()); // works fine\n Console.WriteLine(t.Equals(t)); // works fine\n\n // so it looks like an object and smells like an object...\n\n // but this throws a NullReferenceException...\n Console.WriteLine(t.GetType());\n }\n Nullable<T> int? where T : class, new() private static void Main() {\n CanThisHappen<MyFunnyType>();\n}\n\npublic static void CanThisHappen<T>() where T : class, new() {\n var instance = new T(); // new() on a ref-type; should be non-null, then\n Debug.Assert(instance != null, \"How did we break the CLR?\");\n}\n class MyFunnyProxyAttribute : ProxyAttribute {\n public override MarshalByRefObject CreateInstance(Type serverType) {\n return null;\n }\n}\n[MyFunnyProxy]\nclass MyFunnyType : ContextBoundObject { }\n new() MyFunnyProxyAttribute null"
},
{
"answer_id": 194685,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 3,
"selected": false,
"text": "Public Class Item\n Public ID As Guid\n Public Text As String\n\n Public Sub New(ByVal id As Guid, ByVal name As String)\n Me.ID = id\n Me.Text = name\n End Sub\nEnd Class\n\nPublic Sub Load(sender As Object, e As EventArgs) Handles Me.Load\n Dim box As New ComboBox\n Me.Controls.Add(box) 'Sorry I forgot this line the first time.'\n Dim h As IntPtr = box.Handle 'Im not sure you need this but you might.'\n Try\n box.Items.Add(New Item(Guid.Empty, Nothing))\n Catch ex As Exception\n MsgBox(ex.ToString())\n End Try\nEnd Sub\n"
},
{
"answer_id": 195143,
"author": "Samuel Kim",
"author_id": 437435,
"author_profile": "https://Stackoverflow.com/users/437435",
"pm_score": 8,
"selected": false,
"text": "Math.Round(-0.5) == 0\nMath.Round(0.5) == 0\nMath.Round(1.5) == 2\nMath.Round(2.5) == 2\netc...\n"
},
{
"answer_id": 195636,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 4,
"selected": false,
"text": "newobj var method = new DynamicMethod(\"Test\", null, null);\nvar il = method.GetILGenerator();\n\nil.Emit(OpCodes.Ldc_I4_0);\nil.Emit(OpCodes.Newarr, typeof(char));\nil.Emit(OpCodes.Newobj, typeof(string).GetConstructor(new[] { typeof(char[]) }));\n\nil.Emit(OpCodes.Ldc_I4_0);\nil.Emit(OpCodes.Newarr, typeof(char));\nil.Emit(OpCodes.Newobj, typeof(string).GetConstructor(new[] { typeof(char[]) }));\n\nil.Emit(OpCodes.Call, typeof(object).GetMethod(\"ReferenceEquals\"));\nil.Emit(OpCodes.Box, typeof(bool));\nil.Emit(OpCodes.Call, typeof(Console).GetMethod(\"WriteLine\", new[] { typeof(object) }));\n\nil.Emit(OpCodes.Ret);\n\nmethod.Invoke(null, null);\n true string.Empty"
},
{
"answer_id": 195824,
"author": "Greg Beech",
"author_id": 13552,
"author_profile": "https://Stackoverflow.com/users/13552",
"pm_score": 7,
"selected": false,
"text": "Rec(0) static void Rec(int i)\n{\n Console.WriteLine(i);\n if (i < int.MaxValue)\n {\n Rec(i + 1);\n }\n}\n"
},
{
"answer_id": 241451,
"author": "Craig Eddy",
"author_id": 5557,
"author_profile": "https://Stackoverflow.com/users/5557",
"pm_score": -1,
"selected": false,
"text": "Console.WriteLine(\"{0}\", yep(int.MaxValue ));\n\n\nprivate bool yep( int val )\n{\n return ( 0 < val * 2);\n}\n"
},
{
"answer_id": 241491,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": -1,
"selected": false,
"text": "using System;\nusing System.Collections;\nusing System.Windows.Forms;\n\nnamespace WindowsApplication6\n{\n public class Bar\n {\n public Bar()\n {\n }\n }\n\n public class Foo\n {\n private Bar m_Bar = new Bar();\n private DateTime m_DateTime = DateTime.Now;\n\n public Foo()\n {\n }\n\n public Bar Bar\n {\n get\n {\n return m_Bar;\n }\n set\n {\n m_Bar = value;\n }\n }\n\n public DateTime DateTime\n {\n get\n {\n return m_DateTime;\n }\n set\n {\n m_DateTime = value;\n }\n }\n }\n\n public class TestBugControl : UserControl\n {\n public TestBugControl()\n {\n InitializeComponent();\n }\n\n public void InitializeData(IList types)\n {\n this.cBoxType.DataSource = types;\n }\n\n public void BindFoo(Foo foo)\n {\n this.cBoxType.DataBindings.Add(\"SelectedItem\", foo, \"Bar\");\n this.dtStart.DataBindings.Add(\"Value\", foo, \"DateTime\");\n }\n\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Component Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.checkBox1 = new System.Windows.Forms.CheckBox();\n this.cBoxType = new System.Windows.Forms.ComboBox();\n this.dtStart = new System.Windows.Forms.DateTimePicker();\n this.SuspendLayout();\n //\n // checkBox1\n //\n this.checkBox1.AutoSize = true;\n this.checkBox1.Location = new System.Drawing.Point(14, 5);\n this.checkBox1.Name = \"checkBox1\";\n this.checkBox1.Size = new System.Drawing.Size(97, 20);\n this.checkBox1.TabIndex = 0;\n this.checkBox1.Text = \"checkBox1\";\n this.checkBox1.UseVisualStyleBackColor = true;\n //\n // cBoxType\n //\n this.cBoxType.FormattingEnabled = true;\n this.cBoxType.Location = new System.Drawing.Point(117, 3);\n this.cBoxType.Name = \"cBoxType\";\n this.cBoxType.Size = new System.Drawing.Size(165, 24);\n this.cBoxType.TabIndex = 1;\n //\n // dtStart\n //\n this.dtStart.Location = new System.Drawing.Point(117, 40);\n this.dtStart.Name = \"dtStart\";\n this.dtStart.Size = new System.Drawing.Size(165, 23);\n this.dtStart.TabIndex = 2;\n this.dtStart.Visible = false;\n //\n // TestBugControl\n //\n this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.Controls.Add(this.dtStart);\n this.Controls.Add(this.cBoxType);\n this.Controls.Add(this.checkBox1);\n this.Font = new System.Drawing.Font(\"Verdana\", 9.75F,\n System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point,\n ((byte)(0)));\n this.Margin = new System.Windows.Forms.Padding(4);\n this.Name = \"TestBugControl\";\n this.Size = new System.Drawing.Size(285, 66);\n this.ResumeLayout(false);\n this.PerformLayout();\n\n }\n\n #endregion\n\n private System.Windows.Forms.CheckBox checkBox1;\n private System.Windows.Forms.ComboBox cBoxType;\n private System.Windows.Forms.DateTimePicker dtStart;\n }\n\n public class Form1 : Form\n {\n public Form1()\n {\n InitializeComponent();\n this.Load += new EventHandler(Form1_Load);\n }\n\n void Form1_Load(object sender, EventArgs e)\n {\n InitializeControl();\n }\n\n public void InitializeControl()\n {\n TestBugControl control = new TestBugControl();\n IList list = new ArrayList();\n for (int i = 0; i < 10; i++)\n {\n list.Add(new Bar());\n }\n control.InitializeData(list);\n control.BindFoo(new Foo());\n this.Controls.Add(control);\n }\n\n /// <summary>\n /// Required designer variable.\n /// </summary>\n private System.ComponentModel.IContainer components = null;\n\n /// <summary>\n /// Clean up any resources being used.\n /// </summary>\n /// <param name=\"disposing\">true if managed resources should be disposed; otherwise, false.</param>\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n #region Windows Form Designer generated code\n\n /// <summary>\n /// Required method for Designer support - do not modify\n /// the contents of this method with the code editor.\n /// </summary>\n private void InitializeComponent()\n {\n this.components = new System.ComponentModel.Container();\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.Text = \"Form1\";\n }\n\n #endregion\n }\n\n static class Program\n {\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n }\n}\n"
},
{
"answer_id": 242503,
"author": "heijp06",
"author_id": 1793417,
"author_profile": "https://Stackoverflow.com/users/1793417",
"pm_score": 4,
"selected": false,
"text": "object[] oArray = new string[] { \"one\", \"two\", \"three\" };\nstring[] sArray = (string[])oArray;\n\n// Also works for IList (and IEnumerable, ICollection)\nIList<string> sList = (IList<string>)oArray;\nIList<object> oList = new string[] { \"one\", \"two\", \"three\" };\n object[] oArray2 = new int[] { 1, 2, 3 }; // Error: Cannot implicitly convert type 'int[]' to 'object[]'\nint[] iArray = (int[])oArray2; // Error: Cannot convert type 'object[]' to 'int[]'\n"
},
{
"answer_id": 311831,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 6,
"selected": false,
"text": "enum MyEnum\n{\n Red,\n Blue,\n}\n enum MyEnum\n{\n Black,\n Red,\n Blue,\n}\n"
},
{
"answer_id": 530988,
"author": "cbp",
"author_id": 21966,
"author_profile": "https://Stackoverflow.com/users/21966",
"pm_score": 4,
"selected": false,
"text": " [Test]\n public void Test()\n {\n var bar = new MyClass\n {\n Foo = 500\n };\n bar.Foo += 500;\n\n Assert.That(bar.Foo.Value.Amount, Is.EqualTo(1000));\n }\n\n private class MyClass\n {\n public MyStruct? Foo { get; set; }\n }\n\n private struct MyStruct\n {\n public decimal Amount { get; private set; }\n\n public MyStruct(decimal amount) : this()\n {\n Amount = amount;\n }\n\n public static MyStruct operator +(MyStruct x, MyStruct y)\n {\n return new MyStruct(x.Amount + y.Amount);\n }\n\n public static MyStruct operator +(MyStruct x, decimal y)\n {\n return new MyStruct(x.Amount + y);\n }\n\n public static implicit operator MyStruct(int value)\n {\n return new MyStruct(value);\n }\n\n public static implicit operator MyStruct(decimal value)\n {\n return new MyStruct(value);\n }\n }\n"
},
{
"answer_id": 840352,
"author": "Jarek Kardas",
"author_id": 1515181,
"author_profile": "https://Stackoverflow.com/users/1515181",
"pm_score": 7,
"selected": false,
"text": "double d = 13.6;\n\nint i1 = Convert.ToInt32(d);\nint i2 = (int)d;\n i1 == 14\ni2 == 13\n int i1 = Convert.ToInt32( Math.Ceiling(d) );\nint i2 = (int) Math.Ceiling(d);\n"
},
{
"answer_id": 847353,
"author": "Michael Buen",
"author_id": 11432,
"author_profile": "https://Stackoverflow.com/users/11432",
"pm_score": 6,
"selected": false,
"text": "namespace Craft\n{\n enum Symbol { Alpha = 1, Beta = 2, Gamma = 3, Delta = 4 };\n\n\n class Mate\n {\n static void Main(string[] args)\n {\n\n JustTest(Symbol.Alpha); // enum\n JustTest(0); // why enum\n JustTest((int)0); // why still enum\n\n int i = 0;\n\n JustTest(Convert.ToInt32(0)); // have to use Convert.ToInt32 to convince the compiler to make the call site use the object version\n\n JustTest(i); // it's ok from down here and below\n JustTest(1);\n JustTest(\"string\");\n JustTest(Guid.NewGuid());\n JustTest(new DataTable());\n\n Console.ReadLine();\n }\n\n static void JustTest(Symbol a)\n {\n Console.WriteLine(\"Enum\");\n }\n\n static void JustTest(object o)\n {\n Console.WriteLine(\"Object\");\n }\n }\n}\n"
},
{
"answer_id": 1047948,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 2,
"selected": false,
"text": "if (true)\n{\n OleDbCommand command = SQLServer.CreateCommand();\n}\n\nOleDbCommand command = SQLServer.CreateCommand();\n"
},
{
"answer_id": 1281522,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "interface IFoo\n{\n string Message {get;}\n}\n...\nIFoo obj = new IFoo(\"abc\");\nConsole.WriteLine(obj.Message);\n IFoo using IFoo"
},
{
"answer_id": 1332344,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 6,
"selected": false,
"text": "public class Turtle<T> where T : Turtle<T>\n{\n}\n"
},
{
"answer_id": 1481604,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 5,
"selected": false,
"text": "stringvariable1.Equals(stringvariable2, StringComparison.InvariantCultureIgnoreCase);\n if (assemblyfilename.EndsWith(\"someparticular.dll\", StringComparison.InvariantCultureIgnoreCase))\n{\n assemblyfilename = \"someparticular_modified.dll\";\n}\n"
},
{
"answer_id": 1672628,
"author": "Heinzi",
"author_id": 87698,
"author_profile": "https://Stackoverflow.com/users/87698",
"pm_score": 5,
"selected": false,
"text": "Dim i As Integer? = If(True, Nothing, 5)\n i Nothing 0 Nothing null Nothing null default(T) T If Integer Nothing 5 Nothing 0"
},
{
"answer_id": 1799153,
"author": "Anders Ivner",
"author_id": 218858,
"author_profile": "https://Stackoverflow.com/users/218858",
"pm_score": 3,
"selected": false,
"text": "enumProperty.SetValue(obj, 1, null); //works\nnullableIntProperty.SetValue(obj, 1, null); //works\nnullableEnumProperty.SetValue(obj, MyEnum.Foo, null); //works\nnullableEnumProperty.SetValue(obj, 1, null); // throws an exception !!!\n"
},
{
"answer_id": 1800162,
"author": "Omer Mor",
"author_id": 61061,
"author_profile": "https://Stackoverflow.com/users/61061",
"pm_score": 7,
"selected": false,
"text": " public void Foo()\n {\n this = new Teaser();\n }\n string cheat = @\"\n public void Foo()\n {\n this = new Teaser();\n }\n\";\n public struct Teaser\n{\n public void Foo()\n {\n this = new Teaser();\n }\n}\n this"
},
{
"answer_id": 2203280,
"author": "Dynami Le Savard",
"author_id": 208917,
"author_profile": "https://Stackoverflow.com/users/208917",
"pm_score": 3,
"selected": false,
"text": "class Program\n{\n static void Main(string[] args)\n {\n Derived d = new Derived();\n d.Property = \"AWESOME\";\n }\n}\n\nclass Base\n{\n string _baseProp;\n public virtual string Property \n { \n get \n {\n return \"BASE_\" + _baseProp;\n }\n set\n {\n _baseProp = value;\n //do work with the base property which might \n //not be exposed to derived types\n //here\n Console.Out.WriteLine(\"_baseProp is BASE_\" + value.ToString());\n }\n }\n}\n\nclass Derived : Base\n{\n string _prop;\n public override string Property \n {\n get { return _prop; }\n set \n { \n _prop = value; \n base.Property = value;\n } //<- put a breakpoint here then mouse over BaseProperty, \n // and then mouse over the base.Property call inside it.\n }\n\n public string BaseProperty { get { return base.Property; } private set { } }\n}\n Derived base.Property base.Property Derived this base ((TestProject1.Base)(d))\n public string BaseProperty { get { return ((TestProject1.Base)(d)).Property; } private set { } }\n \"AWESOME\" \"BASE_AWESOME\" call callvirt Derived.BaseProperty \"BASE_AWESOME\" Base"
},
{
"answer_id": 2309473,
"author": "Spencer Ruport",
"author_id": 52551,
"author_profile": "https://Stackoverflow.com/users/52551",
"pm_score": 3,
"selected": false,
"text": "string filename = @\"c:\\program files\\my folder\\test.txt\";\nSystem.IO.File.WriteAllText(filename, \"Hello world.\");\nbool exists = System.IO.File.Exists(filename); // returns true;\nstring text = System.IO.File.ReadAllText(filename); // Returns \"Hello world.\"\n C:\\Users\\<username>\\Virtual Store\\Program Files\\my folder\\test.txt"
},
{
"answer_id": 2354325,
"author": "Sam Harwell",
"author_id": 138304,
"author_profile": "https://Stackoverflow.com/users/138304",
"pm_score": 4,
"selected": false,
"text": "public class DummyObject\n{\n public override string ToString()\n {\n return null;\n }\n}\n DummyObject obj = new DummyObject();\nConsole.WriteLine(\"The text: \" + obj.GetType() + \" is \" + obj);\n NullReferenceException String.Concat(object[]) object obj2 = args[i];\nstring text = (obj2 != null) ? obj2.ToString() : string.Empty;\n// if obj2 is non-null, but obj2.ToString() returns null, then text==null\nint length = text.Length;\n string null ToString object ToString null"
},
{
"answer_id": 2485589,
"author": "MPelletier",
"author_id": 210916,
"author_profile": "https://Stackoverflow.com/users/210916",
"pm_score": 2,
"selected": false,
"text": "Bool aBoolValue;\n aBoolValue Byte aByteValue = aBoolValue ? 1 : 0;\n Int anIntValue = aBoolValue ? 1 : 0;\n"
},
{
"answer_id": 2602423,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 3,
"selected": false,
"text": "TypeLoadException interface I<T> {\n T M(T p);\n}\nabstract class A<T> : I<T> {\n public abstract T M(T p);\n}\nabstract class B<T> : A<T>, I<int> {\n public override T M(T p) { return p; }\n public int M(int p) { return p * 2; }\n}\nclass C : B<int> { }\n\nclass Program {\n static void Main(string[] args) {\n Console.WriteLine(new C().M(42));\n }\n}\n C:\\Temp>type Program.cs\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1 {\n\n interface I<T> {\n T M(T p);\n }\n abstract class A<T> : I<T> {\n public abstract T M(T p);\n }\n abstract class B<T> : A<T>, I<int> {\n public override T M(T p) { return p; }\n public int M(int p) { return p * 2; }\n }\n class C : B<int> { }\n\n class Program {\n static void Main(string[] args) {\n Console.WriteLine(new C().M(11));\n }\n }\n\n}\nC:\\Temp>csc Program.cs\nMicrosoft (R) Visual C# 2008 Compiler version 3.5.30729.1\nfor Microsoft (R) .NET Framework version 3.5\nCopyright (C) Microsoft Corporation. All rights reserved.\n\n\nC:\\Temp>Program\n\nUnhandled Exception: System.TypeLoadException: Could not load type 'ConsoleAppli\ncation1.C' from assembly 'Program, Version=0.0.0.0, Culture=neutral, PublicKeyTo\nken=null'.\n at ConsoleApplication1.Program.Main(String[] args)\n\nC:\\Temp>peverify Program.exe\n\nMicrosoft (R) .NET Framework PE Verifier. Version 3.5.30729.1\nCopyright (c) Microsoft Corporation. All rights reserved.\n\n[token 0x02000005] Type load failed.\n[IL]: Error: [C:\\Temp\\Program.exe : ConsoleApplication1.Program::Main][offset 0x\n00000001] Unable to resolve token.\n2 Error(s) Verifying Program.exe\n\nC:\\Temp>ver\n\nMicrosoft Windows XP [Version 5.1.2600]\n"
},
{
"answer_id": 2915346,
"author": "tclem",
"author_id": 19688,
"author_profile": "https://Stackoverflow.com/users/19688",
"pm_score": 3,
"selected": false,
"text": "Get() class TwoWayRelationship<T1, T2>\n{\n public T2 Get(T1 key) { /* ... */ }\n public T1 Get(T2 key) { /* ... */ }\n}\n T1 T2 var r1 = new TwoWayRelationship<int, string>();\nr1.Get(1);\nr1.Get(\"a\");\n T1 T2 var r2 = new TwoWayRelationship<int, int>();\nr2.Get(1); // \"The call is ambiguous...\"\n"
},
{
"answer_id": 3077238,
"author": "Tor Livar",
"author_id": 367665,
"author_profile": "https://Stackoverflow.com/users/367665",
"pm_score": 3,
"selected": false,
"text": "Equals() true null return test != null ? test : GetDefault();\n if (test == null)\n return GetDefault();\nreturn test;\n GetDefault() null return test ?? GetDefault();\n null null operator= Equals()"
},
{
"answer_id": 3450711,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 2,
"selected": false,
"text": "if (something)\n doit();\nelse\n var v = 1 + 2;\n if (something)\n doit();\nelse {\n var v = 1 + 2;\n}\n"
},
{
"answer_id": 3451958,
"author": "Omer Mor",
"author_id": 61061,
"author_profile": "https://Stackoverflow.com/users/61061",
"pm_score": 3,
"selected": false,
"text": "public class Derived : Base\n{\n public int BrokenAccess()\n {\n return base.m_basePrivateField;\n }\n}\n private int m_basePrivateField = 0;\n Derived Base public class Base\n{\n private int m_basePrivateField = 0;\n\n public class Derived : Base\n {\n public int BrokenAccess()\n {\n return base.m_basePrivateField;\n }\n }\n}\n"
},
{
"answer_id": 3535490,
"author": "Lasse Espeholt",
"author_id": 174574,
"author_profile": "https://Stackoverflow.com/users/174574",
"pm_score": 1,
"selected": false,
"text": "public static bool? ToBoolean(this string s)\n{\n bool result;\n\n if (bool.TryParse(s, out result))\n return result;\n else\n return null;\n}\n string nullStr = null;\nvar res = nullStr.ToBoolean();\n HelperClass.ToBoolean(null)"
},
{
"answer_id": 3934725,
"author": "Rune FS",
"author_id": 112407,
"author_profile": "https://Stackoverflow.com/users/112407",
"pm_score": 2,
"selected": false,
"text": " public bool ReturnsFalse()\n {\n //The default value is not defined!\n return Enum.IsDefined(typeof (NoZero), default(NoZero));\n }\n internal sealed class Strange\n{\n public void Foo()\n {\n Console.WriteLine(this == null);\n }\n}\n public class Program\n{\n [STAThread()]\n public static void Main(string[] args)\n {\n Strange bar = null;\n var hello = new DynamicMethod(\"ThisIsNull\",\n typeof(void), new[] { typeof(Strange) },\n typeof(Strange).Module);\n ILGenerator il = hello.GetILGenerator(256);\n il.Emit(OpCodes.Ldarg_0);\n var foo = typeof(Strange).GetMethod(\"Foo\");\n il.Emit(OpCodes.Call, foo);\n il.Emit(OpCodes.Ret);\n var print = (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));\n print(bar);\n Console.ReadLine();\n }\n}\n"
},
{
"answer_id": 4604818,
"author": "Jordão",
"author_id": 31158,
"author_profile": "https://Stackoverflow.com/users/31158",
"pm_score": 3,
"selected": false,
"text": "public interface MyInterface {\n void Method();\n}\npublic class Base {\n public void Method() { }\n}\npublic class Derived : Base, MyInterface { }\n Base Derived Base::Method Base Base Derived Derived Derived MyInterface::Method Base::Method"
},
{
"answer_id": 4723038,
"author": "TDaver",
"author_id": 571536,
"author_profile": "https://Stackoverflow.com/users/571536",
"pm_score": 3,
"selected": false,
"text": "public class Base\n{\n public virtual void Initialize(dynamic stuff) { \n //...\n }\n}\npublic class Derived:Base\n{\n public override void Initialize(dynamic stuff) {\n base.Initialize(stuff);\n //...\n }\n}\n"
},
{
"answer_id": 4941012,
"author": "Andrew Sevastian",
"author_id": 589340,
"author_profile": "https://Stackoverflow.com/users/589340",
"pm_score": 2,
"selected": false,
"text": "static int x = 0;\n\npublic static void Foo()\n{\n try { return; }\n finally { x = 1; }\n}\n\nstatic void Main() { Foo(); }\n"
},
{
"answer_id": 5113304,
"author": "Steve",
"author_id": 468666,
"author_profile": "https://Stackoverflow.com/users/468666",
"pm_score": 3,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.Remoting.Proxies;\nusing System.Reflection;\nusing System.Runtime.Remoting.Messaging;\n\nnamespace BrokenProxy\n{\n class NotAnIAsyncResult\n {\n public string SomeProperty { get; set; }\n }\n\n class BrokenProxy : RealProxy\n {\n private void HackFlags()\n {\n var flagsField = typeof(RealProxy).GetField(\"_flags\", BindingFlags.NonPublic | BindingFlags.Instance);\n int val = (int)flagsField.GetValue(this);\n val |= 1; // 1 = RemotingProxy, check out System.Runtime.Remoting.Proxies.RealProxyFlags\n flagsField.SetValue(this, val);\n }\n\n public BrokenProxy(Type t)\n : base(t)\n {\n HackFlags();\n }\n\n public override IMessage Invoke(IMessage msg)\n {\n var naiar = new NotAnIAsyncResult();\n naiar.SomeProperty = \"o noes\";\n return new ReturnMessage(naiar, null, 0, null, (IMethodCallMessage)msg);\n }\n }\n\n interface IRandomInterface\n {\n int DoSomething();\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n BrokenProxy bp = new BrokenProxy(typeof(IRandomInterface));\n var instance = (IRandomInterface)bp.GetTransparentProxy();\n Func<int> doSomethingDelegate = instance.DoSomething;\n IAsyncResult notAnIAsyncResult = doSomethingDelegate.BeginInvoke(null, null);\n\n var interfaces = notAnIAsyncResult.GetType().GetInterfaces();\n Console.WriteLine(!interfaces.Any() ? \"No interfaces on notAnIAsyncResult\" : \"Interfaces\");\n Console.WriteLine(notAnIAsyncResult is IAsyncResult); // Should be false, is it?!\n Console.WriteLine(((NotAnIAsyncResult)notAnIAsyncResult).SomeProperty);\n Console.WriteLine(((IAsyncResult)notAnIAsyncResult).IsCompleted); // No way this works.\n }\n }\n}\n No interfaces on notAnIAsyncResult\nTrue\no noes\n\nUnhandled Exception: System.EntryPointNotFoundException: Entry point was not found.\n at System.IAsyncResult.get_IsCompleted()\n at BrokenProxy.Program.Main(String[] args) \n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194484",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22656/"
] |
194,485
|
<p>I'm building few command-line utilities in Xcode (plain C, no Cocoa). I want all of them to use my customized version of libpng, and I want to save space by sharing one copy of the library among all executables (I don't mind re-distributing <code>.dylib</code> with them).</p>
<p>Do I need to do some magic to get libpng export symbols?</p>
<p>Does <em>"Link Binary With Libraries"</em> build phase link statically? </p>
<p>Apple's docs mention loading of libraries at run time with <code>dlopen</code>, but how I can make Xcode create executable without complaining about missing symbols?</p>
<hr>
<p>I think I've figured it out:</p>
<ul>
<li><p>libpng wasn't linking properly, because I've built 32/64-bit executables and 32-bit library. Build settings of the library and executables must match.</p></li>
<li><p>libpng's config.h needs to have tons of defines like <code>#define FEATURE_XXX_SUPPORTED</code></p></li>
<li><p><em>"Link Binary With Libraries"</em> build phase handles dynamic libraries just fine, and <code>DYLD_FALLBACK_LIBRARY_PATH</code> environmental variable is neccessary for loading <code>.dylib</code>s from application bundle.</p></li>
</ul>
|
[
{
"answer_id": 195030,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 4,
"selected": true,
"text": "DYLD_FALLBACK_LIBRARY_PATH dyld(1)"
},
{
"answer_id": 515966,
"author": "denis",
"author_id": 86643,
"author_profile": "https://Stackoverflow.com/users/86643",
"pm_score": 6,
"selected": false,
"text": "mymod.c:\n #include <stdio.h>\n void mymod( int x )\n {\n printf( \"mymod: %d\\n\", x );\n }\ngcc -c mymod.c # -> mymod.o\ngcc -dynamiclib -current_version 1.0 mymod.o -o libmylib.dylib\n # calls libtool with many options -- see man libtool\n # -compatibility_version is used by dyld, see also cmpdylib\n\nfile libmylib.dylib # Mach-O dynamically linked shared library ppc\notool -L libmylib.dylib # versions, refs /usr/lib/libgcc_s.1.dylib\n callmymod.c:\n extern void mymod( int x );\n int main( int argc, char** argv )\n {\n mymod( 42 );\n }\ngcc -c callmymod.c\ngcc -v callmymod.o ./libmylib.dylib -o callmymod\n # == gcc callmymod.o -dynamic -L. -lmylib\notool -L callmymod # refs libmylib.dylib\nnm -gpv callmymod # U undef _mymod: just a reference, not mymod itself\n export DYLD_PRINT_LIBRARIES=1 # see what dyld does, for ALL programs\n./callmymod\n dyld: loaded: libmylib.dylib ...\n mymod: 42\n\nmv libmylib.dylib /tmp\nexport DYLD_LIBRARY_PATH=/tmp # dir:dir:...\n./callmymod\n dyld: loaded: /tmp/libmylib.dylib ...\n mymod: 42\n\nunset DYLD_PRINT_LIBRARIES\nunset DYLD_LIBRARY_PATH\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27009/"
] |
194,492
|
<p>In visual C++, I can do things like this:</p>
<pre><code>template <class T>
class A{
protected:
T i;
};
template <class T>
class B : public A<T>{
T geti() {return i;}
};
</code></pre>
<p>If I try to compile this in g++, I get an error. I have to do this:</p>
<pre><code>template <class T>
class B : public A<T>{
T geti() {return A<T>::i;}
};
</code></pre>
<p>Am I not supposed to do the former in standard C++? Or is something misconfigured with gcc that's giving me errors?</p>
|
[
{
"answer_id": 194640,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": true,
"text": " template <typename T> struct B {\n int m;\n int n;\n int f ();\n int g ();\n };\n int n;\n int g ();\n template <typename T> struct C : B<T> {\n void h ()\n {\n m = 0; // error\n f (); // error\n n = 0; // ::n is modified\n g (); // ::g is called\n }\n };\n template <typename T> void C<T>::h ()\n {\n this->m = 0;\n this->f ();\n this->n = 0\n this->g ();\n }\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194492",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
194,496
|
<p>In a language where both are available, would you prefer to see an instance constructor or a static method that returns an instance?</p>
<p>For example, if you're creating a <code>String</code> from a <code>char[]</code>:</p>
<ol>
<li><p><code>String.FromCharacters(chars);</code></p></li>
<li><p><code>new String(chars);</code></p></li>
</ol>
|
[
{
"answer_id": 194540,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 5,
"selected": false,
"text": "public class Foo\n{\n private Foo() { }\n\n private static List<Foo> FooList = new List<Foo>();\n public static Foo CreateFoo()\n {\n Foo f = new Foo();\n FooList.Add(f);\n return f;\n }\n}\n Foo f = Foo.CreateFoo();\nBar b = new Bar();\n"
},
{
"answer_id": 195115,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 2,
"selected": false,
"text": "Foo.new* Foo.create* Foo.of* Foo.for*"
},
{
"answer_id": 54407350,
"author": "Sumanth Varada",
"author_id": 4044987,
"author_profile": "https://Stackoverflow.com/users/4044987",
"pm_score": 1,
"selected": false,
"text": "getInstance()"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23427/"
] |
194,520
|
<p>Is there an easy way to create standalone .exe files from Lua scripts? Basically this would involve linking the Lua interpreter and the scripts.</p>
<p>I believe it is possible (PLT Scheme allows the creation of standalone executables in the same way), but how, exactly?</p>
|
[
{
"answer_id": 194605,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "copy interpreter.exe+script.lua script.exe\n"
},
{
"answer_id": 1150047,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "luac script.lua -o script.luac\nbin2c script.luac > code.c\n cl /I \"./\" /I \"$(LUA_DIR)\\include\" /D \"_CRT_SECURE_NO_DEPRECATE\" /D \"_MBCS\" /GF /FD /EHsc /MD /Gy /TC /c main.c\nld /SUBSYSTEM:CONSOLE /RELEASE /ENTRY:\"mainCRTStartup\" /MACHINE:X86 /MANIFEST $(LUA_DIR)\\lib\\lua5.1.lib main.obj /out:script.exe\nmt -manifest $script.manifest -outputresource:script.exe;1\n #include <stdlib.h>\n#include <stdio.h>\n#include \"lua.h\"\n#include \"lauxlib.h\"\n#include \"lualib.h\"\n\nint main(int argc, char *argv[]) {\n int i;\n lua_State *L = luaL_newstate();\n luaL_openlibs(L);\n lua_newtable(L);\n for (i = 0; i < argc; i++) {\n lua_pushnumber(L, i);\n lua_pushstring(L, argv[i]);\n lua_rawset(L, -3);\n }\n lua_setglobal(L, \"arg\");\n#include \"code.c\"\n lua_close(L);\n return 0;\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21048/"
] |
194,528
|
<p>I have a ASP.Net page using ADO to query MS access database and as a learning exercise i would like to incorporate LINQ. I have one simple table called Quotes.</p>
<p>The fields are: QuoteID, QuoteDescription, QuoteAuthor, QuoteDate. I would like to run simple queries like, "Give me all quotes after 1995". </p>
<p>How would i incorporate LINQ into this ASP.Net site (C#)</p>
<p>Basically, my question is does LINQ work for MS Access ??</p>
|
[
{
"answer_id": 194651,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": true,
"text": "var year = 1995; // you can pass the year into a method so you can filter on any year\nvar results = from row in dsQuotes\n where row.QuoteDate > year\n select row;\n SELECT * FROM Quotes WHERE Year(QuoteDate) > @Year\n SELECT * FROM Quotes WHERE Year(QuoteDate) > ?\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4653/"
] |
194,534
|
<p>I have been looking at various dependency injection frameworks for .NET as I feel the project I am working on would greatly benefit from it. While I think I have a good grasp of the <em>capabilities</em> of these frameworks, I am still a little unclear on how best to introduce them into a large system. Most demos (understandably) tend to be of quite simple classes that have one or two dependencies. </p>
<p>I have three questions...</p>
<p><strong>First</strong>, how do you deal with those common but uninteresting dependencies, e.g. ILog, IApplicationSettings, IPermissions, IAudit. It seems overkill for every class to have these as parameters in their constructor. Would it be better to use a static instance of the DI container to get these when they are needed?</p>
<pre><code>MyClass(ILog log, IAudit audit, IPermissions permissions, IApplicationSettings settings)
// ... versus ...
ILog log = DIContainer.Get<ILog>();
</code></pre>
<p><strong>Second</strong>, how do you approach dependencies that <em>might</em> be used, but may be expensive to create. Example - a class might have a dependency on an ICDBurner interface but not want the concrete implementation to be created unless the CD Burning feature was actually used. Do you pass in interfaces to factories (e.g. ICDBurnerFactory) in the constructor, or do you again go with some static way of getting directly to the DI Container and ask for it at the point it is needed?</p>
<p><strong>Third</strong>, suppose you have a large Windows Forms application, in which the top level GUI component (e.g. MainForm) is the parent of potentially hundreds of sub-panels or modal forms, each of which may have several dependencies. Does this mean that MainForm should be set up to have as dependencies the superset of all the dependencies of its children? And if you did so, wouldn't this end up creating a huge self-inflating monster that constructs every single class it could ever need the moment you create MainForm, wasting time and memory in the process?</p>
|
[
{
"answer_id": 198911,
"author": "Maurice",
"author_id": 19676,
"author_profile": "https://Stackoverflow.com/users/19676",
"pm_score": 4,
"selected": true,
"text": "IUnityContainer container = new UnityContainer();\ncontainer.RegisterInstance<IUnityContainer>(container);\n"
},
{
"answer_id": 200401,
"author": "Mark Heath",
"author_id": 7532,
"author_profile": "https://Stackoverflow.com/users/7532",
"pm_score": 0,
"selected": false,
"text": "var container = new Container(r =>\n{\n r.FillAllPropertiesOfType<ILogger>().TheDefault.Is\n .ConstructedBy(context => new Logger(context.ParentType));\n});\n public class ClassWithLogger\n{\n public ILogger Logger { get; set; }\n}\n\npublic class ClassWithLogger2\n{\n public ILogger Logger { get; set; }\n}\n container.GetInstance<ClassWithLogger>();\n"
},
{
"answer_id": 1589582,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "public SomeService(ICDBurner burner)\n{\n}\n public SomeService(IServiceFactory<ICDBurner> burnerFactory)\n{\n}\n\nICDBurner burner = burnerFactory.Create();\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing LVK.IoC.Interfaces;\nusing System.Diagnostics;\n\nnamespace LVK.IoC\n{\n /// <summary>\n /// This class is used to implement <see cref=\"IServiceFactory{T}\"/> for all\n /// services automatically.\n /// </summary>\n [DebuggerDisplay(\"AutoServiceFactory (Type={typeof(T)}, Policy={Policy})\")]\n internal class AutoServiceFactory<T> : ServiceBase, IServiceFactory<T>\n {\n #region Private Fields\n\n [DebuggerBrowsable(DebuggerBrowsableState.Never)]\n private readonly String _Policy;\n\n #endregion\n\n #region Construction & Destruction\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"AutoServiceFactory<T>\"/> class.\n /// </summary>\n /// <param name=\"serviceContainer\">The service container involved.</param>\n /// <param name=\"policy\">The policy to use when resolving the service.</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"serviceContainer\"/> is <c>null</c>.</exception>\n public AutoServiceFactory(IServiceContainer serviceContainer, String policy)\n : base(serviceContainer)\n {\n _Policy = policy;\n }\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"AutoServiceFactory<T>\"/> class.\n /// </summary>\n /// <param name=\"serviceContainer\">The service container involved.</param>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"serviceContainer\"/> is <c>null</c>.</exception>\n public AutoServiceFactory(IServiceContainer serviceContainer)\n : this(serviceContainer, null)\n {\n // Do nothing here\n }\n\n #endregion\n\n #region Public Properties\n\n /// <summary>\n /// Gets the policy that will be used when the service is resolved.\n /// </summary>\n public String Policy\n {\n get\n {\n return _Policy;\n }\n }\n\n #endregion\n\n #region IServiceFactory<T> Members\n\n /// <summary>\n /// Constructs a new service of the correct type and returns it.\n /// </summary>\n /// <returns>The created service.</returns>\n public IService<T> Create()\n {\n return MyServiceContainer.Resolve<T>(_Policy);\n }\n\n #endregion\n }\n}\n var builder = new ServiceContainerBuilder();\nbuilder.Register<ISomeService>()\n .From.ConcreteType<SomeService>();\n\nusing (var container = builder.Build())\n{\n using (var factory = container.Resolve<IServiceFactory<ISomeService>>())\n {\n using (var service = factory.Instance.Create())\n {\n service.Instance.DoSomethingAwesomeHere();\n }\n }\n}\n var builder = new ServiceContainerBuilder();\nbuilder.Register<ICDBurner>()\n .From.ConcreteType<CDBurner>();\nbuilder.Register<ISomeService>()\n .From.ConcreteType<SomeService>(); // constructor used in the top of answer\n\nusing (var container = builder.Build())\n{\n using (var service = container.Resolve<ISomeService>())\n {\n service.Instance.DoSomethingHere();\n }\n}\n using (var service1 = container.Resolve<ISomeService>())\nusing (var service2 = container.Resolve<ISomeService>())\n{\n service1.Instance.DoSomethingHere();\n service2.Instance.DoSomethingHere();\n}\n using (var service = container.Resolve<ISomeService>())\n{\n service.Instance.DoSomethingHere();\n}\nusing (var service = container.Resolve<ISomeService>())\n{\n service.Instance.DoSomethingElseHere();\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7532/"
] |
194,565
|
<p>I have to implement the VinPower application. They offer a Java version, a C dll and an ActiveX dll, if anyone has an idea on where I could begin, I'd appreciate it.</p>
|
[
{
"answer_id": 194911,
"author": "Peter Boughton",
"author_id": 9360,
"author_profile": "https://Stackoverflow.com/users/9360",
"pm_score": 2,
"selected": true,
"text": "<cfset vp = createObject(\"java\",\"com.pki.vp4j.VinPower\") />\n\n<cfset rc = vp.decodeVIN(\"JTEDP21A650046919\") />\n\n<cfif rc>\n <cfoutput>#vp.getAsXML()#</cfoutput>\n</cfif>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26121/"
] |
194,574
|
<p>I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:</p>
<pre><code><list>
<activity>swimming</activity>
<activity>running</activity>
<list>
</code></pre>
<p>Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new elements, and a php page which will insert the data into the XML file. Here's the code for index.php:</p>
<pre><code><html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml', LIBXML_NOBLANKS);
$activities = = $xmldoc->firstChild->firstChild;
if($activities!=null){
while(activities!=null){
echo $activities->textContent.'<br/>';
activities = activities->nextSibling.
}
}
?>
<form name='input' action='insert.php' method='post'>
insert activity:
<input type='text' name='activity'/>
<input type='submit' value='send'/>
</form>
</body>
</html
</code></pre>
<p>and here's the code for insert.php:</p>
<pre><code><?php
header('Location:index.php');
$xmldoc = new DOMDocument();
$xmldoc->load('sample.xml');
$newAct = $_POST['activity'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$xmldoc->save('sample.xml');
?>
</code></pre>
<p>The user is to access index.php, where he would see a list of the current activities present in the XML file, and a text field below where he can insert new activities. Upon clicking the send button, the page would call insert.php, which contains a code that opens the XML file in a DOM tree, inserts a new node under the root node and calls back the index.php page, where the user should be able to see the list of activities, his new activity there under the others. It is not working. When i click on the button to submit a new entry, the pages refreshes and apparently nothing happens, the XML is the same as before. What did i do wrong? Also, i'd like to know if there's a better way of doing it.</p>
|
[
{
"answer_id": 194637,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<form name='input' action'insert.php' method='post'> // should be:\n<form name=\"input\" action=\"insert.php\" method=\"post\">\n action \"insert.php\" print 'I wrote '.$xmldoc->save('sample.xml').' bytes of data';\n"
},
{
"answer_id": 676025,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<?xml-stylesheet type=\"text/xsl\" href=\"sample.xsl\" ?> <?xml:stylesheet type=\"text/xsl\" href=\"sample.xsl\" ?>\n"
},
{
"answer_id": 1585440,
"author": "wicho",
"author_id": 192066,
"author_profile": "https://Stackoverflow.com/users/192066",
"pm_score": 2,
"selected": false,
"text": "<html>\n<head><title>test</title></head>\n</head>\n\n<?php\n $xmldoc = new DOMDocument();\n $xmldoc->load('sample.xml', LIBXML_NOBLANKS);\n\n $activities = $xmldoc->firstChild->firstChild;\n if($activities!=null){\n while($activities!=null){\n echo $activities->textContent.'<br/>';\n $activities = $activities->nextSibling;\n }\n }\n?>\n\n<form name='input' action='insert.php' method='post'>\n insert activity:\n <input type='text' name='activity'/>\n <input type='submit' value='send'/>\n</form>\n</body>\n</html>\n\n\n\n\ninsert.php\n\n\n<?php\n header('Location:index.php');\n $xmldoc = new DOMDocument();\n $xmldoc->load('sample.xml');\n\n $newAct = $_POST['activity'];\n\n $root = $xmldoc->firstChild;\n\n $newElement = $xmldoc->createElement('activity');\n $root->appendChild($newElement);\n $newText = $xmldoc->createTextNode($newAct);\n $newElement->appendChild($newText);\n\n $xmldoc->save('sample.xml');\n?>\n <list>\n <activity>swimming</activity> \n <activity>running</activity> \n</list>\n"
},
{
"answer_id": 1965053,
"author": "Amdad Hossain",
"author_id": 239045,
"author_profile": "https://Stackoverflow.com/users/239045",
"pm_score": 3,
"selected": false,
"text": "<list>\n <activity>swimming</activity>\n <activity>running</activity>\n <activity>Jogging</activity>\n <activity>Theatre</activity>\n <activity>Programming</activity>\n</list>\n <html>\n<head><title>test</title></head>\n</head>\n\n<?php\n $xmldoc = new DOMDocument();\n $xmldoc->load(\"sample.xml\", LIBXML_NOBLANKS);\n\n $activities = $xmldoc->firstChild->firstChild;\n if($activities!=null){\n while($activities!=null){\n echo $activities->textContent.\"<br/>\";\n $activities = $activities->nextSibling;\n }\n }\n?>\n\n<form name=\"input\" action=\"insert.php\" method=\"post\">\n insert activity:\n <input type=\"text\" name=\"activity\"/>\n <input type=\"submit\" value=\"send\"/>\n</form>\n</body>\n</html>\n <?php\n header('Location:index.php');\n $xmldoc = new DOMDocument();\n $xmldoc->load('sample.xml');\n\n $newAct = $_POST['activity'];\n\n $root = $xmldoc->firstChild;\n\n $newElement = $xmldoc->createElement('activity');\n $root->appendChild($newElement);\n $newText = $xmldoc->createTextNode($newAct);\n $newElement->appendChild($newText);\n\n $xmldoc->save('sample.xml');\n?>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27090/"
] |
194,579
|
<p>I've got a php page which handles requets for file downloads. I need to be able to detect when a file has been downloaded successfully. How can this be done? Perhaps there's some means of detecting this client-side then sending a confirmation down to the server.</p>
<p>Thanks.</p>
<p>Edit:
By handle, I mean that the page is doing something like this:</p>
<pre><code>$file = '/var/www/html/file-to-download.xyz';
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($file));
header('Content-Disposition: attachment; filename=' . basename($file));
readfile($file);
</code></pre>
|
[
{
"answer_id": 194618,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 5,
"selected": true,
"text": "readfile($file);"
},
{
"answer_id": 196246,
"author": "Willem",
"author_id": 15447,
"author_profile": "https://Stackoverflow.com/users/15447",
"pm_score": 2,
"selected": false,
"text": "flush()"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19467/"
] |
194,584
|
<p>Other than standard OO concepts, what are some other strategies that allow for producing good, clean PHP code when a framework is not being used?</p>
|
[
{
"answer_id": 195378,
"author": "Javier",
"author_id": 11649,
"author_profile": "https://Stackoverflow.com/users/11649",
"pm_score": 6,
"selected": true,
"text": "?> <?php"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
194,616
|
<p>I have an application installed on my computer. How do I find out if it was compiled in DEBUG mode or not?</p>
<p>I've tried to use <a href="http://en.wikipedia.org/wiki/.NET_Reflector" rel="noreferrer">.NET Reflector</a>, but it does not show anything specific. Here is what I see:</p>
<pre><code>// Assembly APPLICATION_NAME, Version 8.0.0.15072
Location: C:\APPLICATION_FOLDER\APPLICATION_NAME.exe
Name: APPLICATION_NAME, Version=8.0.0.15072, Culture=neutral, PublicKeyToken=null
Type: Windows Application
</code></pre>
|
[
{
"answer_id": 194625,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 5,
"selected": false,
"text": "private void testfile(string file)\n{\n if(isAssemblyDebugBuild(file))\n {\n MessageBox.Show(String.Format(\"{0} seems to be a debug build\",file));\n }\n else\n {\n MessageBox.Show(String.Format(\"{0} seems to be a release build\",file));\n }\n} \n\nprivate bool isAssemblyDebugBuild(string filename)\n{\n return isAssemblyDebugBuild(System.Reflection.Assembly.LoadFile(filename)); \n} \n\nprivate bool isAssemblyDebugBuild(System.Reflection.Assembly assemb)\n{\n bool retVal = false;\n foreach(object att in assemb.GetCustomAttributes(false))\n {\n if(att.GetType() == System.Type.GetType(\"System.Diagnostics.DebuggableAttribute\"))\n {\n retVal = ((System.Diagnostics.DebuggableAttribute)att).IsJITTrackingEnabled;\n }\n }\n return retVal;\n}\n"
},
{
"answer_id": 194635,
"author": "Joe Basirico",
"author_id": 20795,
"author_profile": "https://Stackoverflow.com/users/20795",
"pm_score": 3,
"selected": false,
"text": "[assembly: Debuggable(...)]\n"
},
{
"answer_id": 5316442,
"author": "Dave Black",
"author_id": 251267,
"author_profile": "https://Stackoverflow.com/users/251267",
"pm_score": 5,
"selected": false,
"text": "System.Diagnostics.Conditional()"
},
{
"answer_id": 14160090,
"author": "Max",
"author_id": 1057961,
"author_profile": "https://Stackoverflow.com/users/1057961",
"pm_score": 2,
"selected": false,
"text": "Public Shared Function IsDebug(Assem As [Assembly]) As Boolean\n For Each attrib In Assem.GetCustomAttributes(False)\n If TypeOf attrib Is System.Diagnostics.DebuggableAttribute Then\n Return DirectCast(attrib, System.Diagnostics.DebuggableAttribute).IsJITTrackingEnabled\n End If\n Next\n\n Return False\nEnd Function\n\nPublic Shared Function IsThisAssemblyDebug() As Boolean\n Return IsDebug([Assembly].GetCallingAssembly)\nEnd Function\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,621
|
<p>I know there are a few different <a href="http://en.wikipedia.org/wiki/Traveling_salesman_problem" rel="nofollow noreferrer">Traveling Salesman</a> projects out there and I've played with <a href="http://www.akira.ruc.dk/~keld/research/LKH/" rel="nofollow noreferrer">LKH</a> a bit, but I was wondering if anyone had any recommendations on any other ones?</p>
<p>My project is GPL'ed so I would need something that is compatible with that license.</p>
<p><img src="https://i.stack.imgur.com/6WnwE.gif" alt="Input"> <img src="https://i.stack.imgur.com/lAUwq.gif" alt="Output"></p>
|
[
{
"answer_id": 197110,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 2,
"selected": false,
"text": "(defvar *grid-width* 100000)\n(defvar *grid-heigth* 100000)\n(defvar *max-number-of-points* 1000)\n(defvar *search-area-width* (* 2 *grid-width*))\n(defvar *search-area-heigth* (* 2 *grid-heigth*))\n\n(defun make-random-point (max-x max-y)\n \"makes a point in a random position of the grid\"\n (complex\n (/ (random (* max-x 1000)) 1000)\n (/ (random (* max-y 1000)) 1000)))\n\n\n(defun make-random-point-list (max-len)\n \"makes a list of random points up to max-len length\"\n (let ((value ())) ; Make a set of random points\n (dotimes (n (random max-len) value)\n (setq value\n (cons (make-random-point *grid-width* *grid-heigth*) value)))))\n\n(defun get-printable-point-position (point)\n \"Gets a rounded-off point that can be used to make a dot on a visual grid\"\n (complex\n (round (realpart point))\n (round (imagpart point))))\n\n(defun euclid (point-a point-b)\n \"calculates the euclidean distance in between two points\"\n (let* ((p (- point-a point-b)))\n (sqrt\n (+ (expt (realpart p) 2)\n (expt (imagpart p) 2)))))\n\n(defstruct triangle\n \"A triangle consists of 3 points.\n Complex numbers are used to construct the points,\n the real part signifying the X axis,\n and the imaginary part signifying the Y axis.\"\n a b c)\n\n(defun avg (&rest numbers)\n \"Gets the average of the numbers provided\"\n (if\n (null numbers)\n 1 ; prevents divide by 0\n (/ (apply #'+ numbers) (length numbers)))) ;/\n\n(defun get-triangle-centre (triangle)\n \"Gets the centre of a triangle\"\n (avg (triangle-a triangle)\n (triangle-b triangle)\n (triangle-c triangle)))\n\n(defstruct (triangle-list\n (:include triangle))\n point-list)\n\n(defun triangle-split (triangle)\n \"Splits a triangle in two according to the rule:\n { a0->c1; b0->a1,c2; c0->a2; avg(c0,a0)->b1,b2 }\"\n (let* ((old-a-point (triangle-a triangle))\n (old-b-point (triangle-b triangle))\n (old-c-point (triangle-c triangle))\n (new-b-point (avg old-a-point old-c-point)))\n (list\n (make-triangle-list :a old-b-point :b new-b-point :c old-a-point)\n (make-triangle-list :a old-c-point :b new-b-point :c old-b-point))))\n\n(defun triangle-list-split (triangle-list)\n \"Split a triangle list and acomodate all the points in their right places\"\n (let* ((triangles (triangle-split triangle-list))\n (triangle-a (car triangles))\n (triangle-b (cadr triangles))\n (centre-a (get-triangle-centre triangle-a))\n (centre-b (get-triangle-centre triangle-b)))\n (dolist (point (triangle-list-point-list triangle-list))\n (if (< (euclid point centre-a) (euclid point centre-b))\n (setf (triangle-list-point-list triangle-a)\n (cons point (triangle-list-point-list triangle-a)))\n (setf (triangle-list-point-list triangle-b)\n (cons point (triangle-list-point-list triangle-b)))))\n (let ((list-a (triangle-list-point-list triangle-a))\n (list-b (triangle-list-point-list triangle-b)))\n (if (= 1 (length list-a))\n (setf (triangle-list-point-list triangle-a) (car list-a)))\n (if (= 1 (length list-b))\n (setf (triangle-list-point-list triangle-b) (car list-b))))\n (list triangle-a triangle-b)))\n\n(defun print-point (out point &rest args)\n \"Utility function - Pretty-prints a point\"\n (format out \"(X:~F, Y:~F)\"\n (realpart point)\n (imagpart point))\n args)\n\n(defun pprint-triangle-list (out triangle-list &rest args)\n \"Utility function - Pretty-prints a triangle-list object\"\n (format out \" TRIANGLE{\n A:~/print-point/\n B:~/print-point/\n C:~/print-point/\n CENTRE:~/print-point/\n POINTS:{~{~/print-point/~^,~% ~}}~& }\"\n (triangle-a triangle-list)\n (triangle-b triangle-list)\n (triangle-c triangle-list)\n (get-triangle-centre triangle-list)\n (let ((points (triangle-list-point-list triangle-list)))\n (cond\n ((null points) ())\n ((listp points) points)\n (t (list points)))))\n args)\n\n(defun print-list-of-triangle-list (lst)\n \"Pretty-prints a list of triangle-list objects\"\n (format t \"(~{~/pprint-triangle-list/~^,~% ~}~&)\" lst))\n\n(defun explode (lst)\n \"explodes a triangle-list list and gets all\n the points in the order they should be\"\n (let ((l (flatten lst)))\n (cond\n ((null l) ())\n ((triangle-list-p l) (explode (triangle-list-split l)))\n ((null (triangle-list-point-list (car l)))\n (explode (cdr l)))\n ((atom (triangle-list-point-list (car l)))\n (cons (car l) (explode (cdr l))))\n (t (explode (append (triangle-list-split (car l)) (cdr l)))))))\n\n\n(defun flatten (lst)\n \"Flattens a list (removes nesting and nulls)\"\n (cond\n ((atom lst) lst)\n ((listp (car lst))\n (append (flatten (car lst)) (flatten (cdr lst))))\n (t (append (list (car lst)) (flatten (cdr lst))))))\n\n(let ((triangle (make-triangle-list\n :a (complex 0 *search-area-heigth*)\n :b 0\n :c *search-area-width*\n :point-list (make-random-point-list *max-number-of-points*))))\n (print-list-of-triangle-list (explode triangle)))\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
194,628
|
<p>IOKit and the DiskArbitration framework can tell me a lot of things about mounted volumes on a mac, but they don't seem to be able to differentiate between HFS+ and HFS Standard volumes. </p>
<p>The IOKit/DA keys <code>Content</code>, <code>DAVolumeKind</code> and <code>DAMediaContent</code> are always Apple_HFS and hfs for both HFS Standard and HFS+ volumes.</p>
<p>diskutil and DiskUtility.app <em>can</em> tell the difference, but I they don't seem to have been open sourced by Apple. </p>
<p>p.s. statfs (2) does not differentiate</p>
|
[
{
"answer_id": 194722,
"author": "Brian Webster",
"author_id": 23324,
"author_profile": "https://Stackoverflow.com/users/23324",
"pm_score": 4,
"selected": true,
"text": "getattrlist() ATTR_VOL_SIGNATURE signature getattrlist getattrlist"
},
{
"answer_id": 550570,
"author": "mouviciel",
"author_id": 45249,
"author_profile": "https://Stackoverflow.com/users/45249",
"pm_score": 1,
"selected": false,
"text": "FSGetVolumeInfo() FSVolumeInfo signature filesystemID -getFileSystemInfoForPath: NSWorkspace hfs msdos"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22147/"
] |
194,634
|
<p>I have read several places that the difference between <code>c_str()</code> and <code>data()</code> (in STL and other implementations) is that <code>c_str()</code> is always null terminated while <code>data()</code> is not.
As far as I have seen in actual implementations, they either do the same or <code>data()</code> calls <code>c_str()</code>.</p>
<p>What am I missing here?
Which one is more correct to use in which scenarios?</p>
|
[
{
"answer_id": 194638,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 7,
"selected": false,
"text": "c_str() data() c_str() data() data() c_str() data"
},
{
"answer_id": 194654,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 4,
"selected": false,
"text": "//Example 1\n//Plain text:\nstd::string s1;\ns1 = \"abc\";\n\n//Example 2\n//Arbitrary binary data:\nstd::string s2;\ns2.append(\"a\\0b\\0b\\0\", 6);\n std::string s;\ns = \"abc\"; \nchar sz[512]; \nstrcpy(sz, s.data());//This could crash depending on the implementation of .data()\n"
},
{
"answer_id": 7661733,
"author": "Mihran Hovsepyan",
"author_id": 509233,
"author_profile": "https://Stackoverflow.com/users/509233",
"pm_score": 2,
"selected": false,
"text": "ANSI ISO IEC 14882 2003 21.3.6 basic_string string operations [lib.string.ops]\n\n const charT* c_str() const;\n\n Returns: A pointer to the initial element of an array of length size() + 1 whose first size() elements\nequal the corresponding elements of the string controlled by *this and whose last element is a\nnull character specified by charT().\n Requires: The program shall not alter any of the values stored in the array. Nor shall the program treat the\nreturned value as a valid pointer value after any subsequent call to a non-const member function of the\nclass basic_string that designates the same object as this.\n\n const charT* data() const;\n\n Returns: If size() is nonzero, the member returns a pointer to the initial element of an array whose first\nsize() elements equal the corresponding elements of the string controlled by *this. If size() is\nzero, the member returns a non-null pointer that is copyable and can have zero added to it.\n Requires: The program shall not alter any of the values stored in the character array. Nor shall the program\ntreat the returned value as a valid pointer value after any subsequent call to a non- const member\nfunction of basic_string that designates the same object as this.\n"
},
{
"answer_id": 11280444,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 2,
"selected": false,
"text": "std::string string string::substr c_str string::data c_str data"
},
{
"answer_id": 12399518,
"author": "mfazekas",
"author_id": 27048,
"author_profile": "https://Stackoverflow.com/users/27048",
"pm_score": 5,
"selected": false,
"text": "data() c_str() data() basic_string const charT* c_str() const noexcept; const charT* data() const noexcept; p + i == &operator[](i) i [0,size()] const_reference operator[](size_type pos) const noexcept; *(begin() + pos) if pos < size() charT();"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194634",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,650
|
<p>Simply put, is there a way to create a 2D javascript array using similar syntax to this?</p>
<pre><code>var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
</code></pre>
|
[
{
"answer_id": 194660,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<script>\nvar newArray = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]\n]\nalert(newArray[0][2]);\n</script>\n"
},
{
"answer_id": 194961,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": true,
"text": "<script>\n var newArray = [\n [0, 1, 2],\n [3, 4, 5],\n [6, 7, 8]\n ]\n var newArray3d =\n [[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],\n [[10, 11, 12],[13, 14, 15],[16, 17, 18]],\n [[20, 21, 22],[23, 24, 25],[26, 27, 28]]]\n alert(newArray[0]);\n alert(newArray[0][2]);\n alert(newArray3d[0]);\n alert(newArray3d[1][0]);\n alert(newArray3d[1][0][2]);\n</script>\n 0,1,2\n2\n0,1,2,3,4,5,6,7,8\n10,11,12\n12\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194650",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1384652/"
] |
194,652
|
<p>Is there any regular expression library written in T-SQL (no CLR, no extended <code>SP</code>, pure T-SQL) for SQL Server, and that should work with shared hosting?</p>
<p>Edit:</p>
<ul>
<li>Thanks, I know about <code>PATINDEX</code>, <code>LIKE</code>, <code>xp_</code> <code>sps</code> and CLR solutions</li>
<li>I also know it is not the best place for regex, the question is theoretical :)</li>
<li>Reduced functionality is also accepted</li>
</ul>
|
[
{
"answer_id": 198986,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 6,
"selected": false,
"text": "Wildcard Meaning \n% Any string of zero or more characters.\n\n_ Any single character.\n\n[ ] Any single character within the specified range \n (for example, [a-f]) or set (for example, [abcdef]).\n\n[^] Any single character not within the specified range \n (for example, [^a - f]) or set (for example, [^abcdef]).\n"
},
{
"answer_id": 12903070,
"author": "James Poulose",
"author_id": 249097,
"author_profile": "https://Stackoverflow.com/users/249097",
"pm_score": 2,
"selected": false,
"text": "DECLARE @obj INT, @res INT, @match BIT;\nDECLARE @pattern varchar(255) = '<your regex pattern goes here>';\nDECLARE @matchstring varchar(8000) = '<string to search goes here>';\nSET @match = 0;\n\n-- Create a VB script component object\nEXEC @res = sp_OACreate 'VBScript.RegExp', @obj OUT;\n\n-- Apply/set the pattern to the RegEx object\nEXEC @res = sp_OASetProperty @obj, 'Pattern', @pattern;\n\n-- Set any other settings/properties here\nEXEC @res = sp_OASetProperty @obj, 'IgnoreCase', 1;\n\n-- Call the method 'Test' to find a match\nEXEC @res = sp_OAMethod @obj, 'Test', @match OUT, @matchstring;\n\n-- Don't forget to clean-up\nEXEC @res = sp_OADestroy @obj;\n SQL Server blocked access to procedure 'sys.sp_OACreate'... sp_reconfigure Ole Automation Procedures Test"
},
{
"answer_id": 30877281,
"author": "Matt Farguson",
"author_id": 4561434,
"author_profile": "https://Stackoverflow.com/users/4561434",
"pm_score": 4,
"selected": false,
"text": "// default using statements above\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Text.RegularExpressions;\n\nnamespace CLR_Functions\n{ \n public class myFunctions\n {\n [SqlFunction]\n public static SqlInt16 RegexContain(SqlString text, SqlString pattern)\n { \n SqlInt16 returnVal = 0;\n try\n {\n string myText = text.ToString();\n string myPattern = pattern.ToString();\n MatchCollection mc = Regex.Matches(myText, myPattern);\n if (mc.Count > 0)\n {\n returnVal = 1;\n }\n }\n catch\n {\n returnVal = 0;\n }\n\n return returnVal;\n }\n }\n}\n CREATE FUNCTION RegexContain(@text NVARCHAR(50), @pattern NVARCHAR(50))\nRETURNS smallint \nAS\nEXTERNAL NAME CLR_Functions.[CLR_Functions.myFunctions].RegexContain\n SELECT * \nFROM \n(\n SELECT\n DailyLog.Date,\n DailyLog.Researcher,\n DailyLog.team,\n DailyLog.field,\n DailyLog.EntityID,\n DailyLog.[From],\n DailyLog.[To],\n dbo.RegexContain(Researcher, '[\\p{L}\\s]+') as 'is null values'\n FROM [DailyOps].[dbo].[DailyLog]\n) AS a\nWHERE a.[is null values] = 0\n"
},
{
"answer_id": 46536661,
"author": "Dave Mason",
"author_id": 2961160,
"author_profile": "https://Stackoverflow.com/users/2961160",
"pm_score": 3,
"selected": false,
"text": "sp_execute_external_script grep grepl [Application].[People] [WideWorldImporters] InputDataSet EXEC sp_execute_external_script \n @language = N'R',\n @script = N' RegexWithR <- InputDataSet;\nOutputDataSet <- RegexWithR[!grepl(\"([_a-z0-9-]+(\\\\.[_a-z0-9-]+)*@[a-z0-9-]+(\\\\.[a-z0-9-]+)*(\\\\.[a-z]{2,4}))\", RegexWithR$EmailAddress), ];',\n @input_data_1 = N'SELECT PersonID, FullName, EmailAddress FROM Application.People'\n WITH RESULT SETS (([PersonID] INT, [FullName] NVARCHAR(50), [EmailAddress] NVARCHAR(256)))\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2622295/"
] |
194,663
|
<p>I'm new to Flex SDK and trying to implement a simple project using <a href="http://dougmccune.com/blog/2007/11/19/flex-coverflow-performance-improvement-flex-carousel-component-and-vertical-coverflow/" rel="nofollow noreferrer">Doug Mccune's CoverFlow</a> widget. Most of the documentation out there on how to do this assumes that one is using Adobe's FlexBuilder product, which is a $250 Eclipse plug-in that I'd rather avoid buying. The problem I'm having is simply getting Doug's swc file, which is the binary version of his component lib, to be recognized by mxmlc, the Flex SDK project compiler. I keep getting error messages such as</p>
<blockquote>
<p>Error: Could not resolve to a component installation</p>
</blockquote>
<p>and</p>
<blockquote>
<p>Error: Type was not found or was not a compile-time constant: CoverFlow.</p>
</blockquote>
<p>I have also tried the type "VideoCoverFlow" as I am pretty sure that these types are defined in Doug's lib. Alas, I am stuck on figuring out where I've gone wrong.</p>
<p>The following is the full text for my mxml project file, called coverflow.mxml.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="*"
height="100%"
width="100%"
layout="absolute">
<local:CoverFlow
id="CoverFlow"
horizontalCenter="0"
verticalCenter="0"
borderThickness="10"
borderColor="#FFFFFF"
width="100%"/>
</mx:Application>
</code></pre>
<p>I am trying to compile it with the following command:</p>
<pre><code>c:\flex_sdk_3\bin\mxmlc.exe -compiler.source-path=lib coverflow.mxml
</code></pre>
<p>I have also tried moving the CoverFlow_lib.swc file into the same dir as the mxml file instead of using the source-path argument, but that does not seem to make a difference.</p>
<p>I would gladly go RTFM if somebody could be so kind as to point me in the direction of the proper docs. There are related Stack Overflow questions <a href="https://stackoverflow.com/questions/78230/compiling-mxml-files-with-ant-and-flex-sdk">here</a> and <a href="https://stackoverflow.com/questions/119947/using-flash-component-swc-file-in-flex">here</a>.</p>
<p>Thank you!</p>
<hr>
<p><strong>Update</strong>: I have changed my build command to the following:</p>
<pre><code>mxmlc -library-path+=lib coverflow.mxml
</code></pre>
<p>And I also tried the following:</p>
<pre><code>mxmlc -library-path+=CoverFlow_lib.swc coverflow.mxml
</code></pre>
<p>With the swc file in the same dir as the mxml file. However, I'm still getting the same errors.</p>
<p>There's also a <a href="http://www.adobe.com/products/flex/media/flexapp/" rel="nofollow noreferrer">video here</a> showing the same library that I'm trying to use, but in Flex Builder. Unfortunately, it doesn't show how to use mxmlc.</p>
<p>I've also tried stripping down my mxml to simply,</p>
<pre><code><mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:local="*" >
<local:VideoCoverFlow />
</mx:Application>
</code></pre>
|
[
{
"answer_id": 194682,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 4,
"selected": true,
"text": "mxmlc -help list library-path c:\\flex_sdk_3\\bin\\mxmlc.exe -library-path+=lib coverflow.mxml\n"
},
{
"answer_id": 194716,
"author": "Parappa",
"author_id": 9974,
"author_profile": "https://Stackoverflow.com/users/9974",
"pm_score": 0,
"selected": false,
"text": "mxmlc -library-path+=lib coverflow.mxml\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n\n<mx:Application\n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n xmlns:coverflow=\"com.dougmccune.coverflow.*\"\n xmlns:containers=\"com.dougmccune.containers.*\"\n xmlns:local=\"*\" >\n\n <containers:CoverFlowContainer id=\"flow\" />\n\n</mx:Application\n id=\"coverflow\""
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9974/"
] |
194,666
|
<p>Is there a way to suppress warnings in Xcode?</p>
<p>For example I am calling an undocumented method and since the method is not in the header I get a warning on compile. I know I can add it to my header to stop the warning, but I am wondering if there is a way other than adding it to the header (so I can keep the headers clean and standard) to suppress the warning? A pragma or something?</p>
|
[
{
"answer_id": 196781,
"author": "robottobor",
"author_id": 10184,
"author_profile": "https://Stackoverflow.com/users/10184",
"pm_score": 7,
"selected": false,
"text": "#pragma GCC diagnostic ignored \"-Wwarning-flag\"\n"
},
{
"answer_id": 1480048,
"author": "Mark Pauley",
"author_id": 146757,
"author_profile": "https://Stackoverflow.com/users/146757",
"pm_score": 3,
"selected": false,
"text": "@interface NSTheClass (MyUndocumentedMethodsForNSTheClass)\n\n-(id)theUndocumentedMethod;\n@end\n...\n\n@implementation myClass : mySuperclass\n\n-(void) myMethod {\n...\n [theObject theUndocumentedMethod];\n...\n}\n"
},
{
"answer_id": 7992423,
"author": "thesummersign",
"author_id": 751026,
"author_profile": "https://Stackoverflow.com/users/751026",
"pm_score": 6,
"selected": false,
"text": "#pragma unused(varname)\n User-Defined GCC_WARN_UNUSED_VARIABLE NO BOOL ok = YES;\nNSAssert1(ok, @\"Failed to calculate the first day the month based on %@\", self);\n ok BOOL ok = YES;\n#pragma unused(ok)\nNSAssert1(ok, @\"Failed to calculate the first day the month based on %@\", self);\n GCC_WARN_ABOUT_RETURN_TYPE YES/NO"
},
{
"answer_id": 25700438,
"author": "Inder Kumar Rathore",
"author_id": 468724,
"author_profile": "https://Stackoverflow.com/users/468724",
"pm_score": 5,
"selected": false,
"text": "#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Wshadow-ivar\"\n// your code\n#pragma GCC diagnostic pop\n [-Wshadow-ivar] #pragma clang diagnostic push\n#pragma clang diagnostic ignored \"-Wshadow-ivar\"\n// your code\n#pragma clang diagnostic pop\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26728/"
] |
194,698
|
<p>I was asked to build a java system that will have the ability to load new code (expansions) while running.
How do I re-load a jar file while my code is running? or how do I load a new jar?</p>
<p>Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does not complicate things too much).</p>
<p>What are the things I should look out for?
(think of it as two different questions - one regarding reloading classes at runtime, the other regarding adding new classes).</p>
|
[
{
"answer_id": 194708,
"author": "Amir Arad",
"author_id": 11813,
"author_profile": "https://Stackoverflow.com/users/11813",
"pm_score": 2,
"selected": false,
"text": "File file = getJarFileToLoadFrom(); \nString lcStr = getNameOfClassToLoad(); \nURL jarfile = new URL(\"jar\", \"\",\"file:\" + file.getAbsolutePath()+\"!/\"); \nURLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile }); \nClass loadedClass = cl.loadClass(lcStr); \n"
},
{
"answer_id": 194712,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 7,
"selected": true,
"text": "ClassLoader loader = URLClassLoader.newInstance(\n new URL[] { yourURL },\n getClass().getClassLoader()\n);\nClass<?> clazz = Class.forName(\"mypackage.MyClass\", true, loader);\nClass<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);\n// Avoid Class.newInstance, for it is evil.\nConstructor<? extends Runnable> ctor = runClass.getConstructor();\nRunnable doRun = ctor.newInstance();\ndoRun.run();\n java.beans URLClassLoader.addURL"
},
{
"answer_id": 673414,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "File file = new File(\"c:\\\\myjar.jar\");\n\nURL url = file.toURL(); \nURL[] urls = new URL[]{url};\n\nClassLoader cl = new URLClassLoader(urls);\nClass cls = cl.loadClass(\"com.mypackage.myclass\");\n"
},
{
"answer_id": 10715076,
"author": "Doan Huynh",
"author_id": 1411937,
"author_profile": "https://Stackoverflow.com/users/1411937",
"pm_score": 2,
"selected": false,
"text": "public LoadEngine() {\n Lookup ocrengineLookup;\n Collection<OCREngine> ocrengines;\n Template ocrengineTemplate;\n Result ocrengineResults;\n try {\n //ocrengineLookup = Lookup.getDefault(); this only load OCREngine in classpath of application\n ocrengineLookup = Lookups.metaInfServices(getClassLoaderForExtraModule());//this load the OCREngine in the extra module as well\n ocrengineTemplate = new Template(OCREngine.class);\n ocrengineResults = ocrengineLookup.lookup(ocrengineTemplate); \n ocrengines = ocrengineResults.allInstances();//all OCREngines must implement the defined interface in OCREngine. Reference to guideline of implement org.openide.util.Lookup for more information\n\n } catch (Exception ex) {\n }\n}\n\npublic ClassLoader getClassLoaderForExtraModule() throws IOException {\n\n List<URL> urls = new ArrayList<URL>(5);\n //foreach( filepath: external file *.JAR) with each external file *.JAR, do as follows\n File jar = new File(filepath);\n JarFile jf = new JarFile(jar);\n urls.add(jar.toURI().toURL());\n Manifest mf = jf.getManifest(); // If the jar has a class-path in it's manifest add it's entries\n if (mf\n != null) {\n String cp =\n mf.getMainAttributes().getValue(\"class-path\");\n if (cp\n != null) {\n for (String cpe : cp.split(\"\\\\s+\")) {\n File lib =\n new File(jar.getParentFile(), cpe);\n urls.add(lib.toURI().toURL());\n }\n }\n }\n ClassLoader cl = ClassLoader.getSystemClassLoader();\n if (urls.size() > 0) {\n cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());\n }\n return cl;\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11813/"
] |
194,725
|
<p>I am a heavy command line user and use the <code>find</code> command extensively in my build system scripts. However on Mac OS X when I am not concentrating I often get output like this:</p>
<pre><code>$ find -name \*.plist
find: illegal option -- n
find: illegal option -- a
find: illegal option -- m
find: illegal option -- e
find: *.plist: No such file or directory
</code></pre>
<p>Basically, I forgot to add the little dot:</p>
<pre><code>$ find . -name \*.plist
</code></pre>
<p>Because BSD <code>find</code> requires the path and GNU <code>find</code> doesn't (it assumes the current directory if you don't specify one). I use Linux, Mac OS X and Cygwin often all at the same time, so it's of great benefit to me to have all my tools behave the same. I tried writing a bash <code>find</code> function that added "./" if I forgot, but I failed. Thanks for your help. :)</p>
|
[
{
"answer_id": 194732,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 2,
"selected": false,
"text": "find ./ -name \"*.plist\"\n #!/bin/sh\n# remapping find!\nCMD=`echo $1 | cut -c 1`\nif [ $CMD = '-' ]\nthen\n# pwd search\n /usr/bin/find ./ $*\nelse\n# regular find\n /usr/bin/find $*\nfi\n"
},
{
"answer_id": 194737,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 1,
"selected": false,
"text": "alias find=\"find .\" findl"
},
{
"answer_id": 194738,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "sh bash"
},
{
"answer_id": 194756,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "alias find=/usr/bin/find\\ .\n alias find=find find"
},
{
"answer_id": 194883,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "find find findutils find cp bin cp file1 file2 find #!/bin/sh\n[ ! -d \"$1\" ] && set -- . \"$@\"\nexec /usr/bin/find \"$@\"\n ~/bin/find /non-existent/directory -name '*.plist' -print\n cp"
},
{
"answer_id": 15003450,
"author": "odinho - Velmont",
"author_id": 179978,
"author_profile": "https://Stackoverflow.com/users/179978",
"pm_score": 5,
"selected": false,
"text": "$ brew install findutils\n$ alias find=gfind\n"
},
{
"answer_id": 32616689,
"author": "Pysis",
"author_id": 1091943,
"author_profile": "https://Stackoverflow.com/users/1091943",
"pm_score": 1,
"selected": false,
"text": "findutils"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6444/"
] |
194,733
|
<p>If I have a method such as:</p>
<pre><code>private function testMethod(param:string):void
{
// Get the object that called this function
}
</code></pre>
<p>Inside the testMethod, can I work out what object called us? e.g.</p>
<pre><code>class A
{
doSomething()
{
var b:B = new B();
b.fooBar();
}
}
class B
{
fooBar()
{
// Can I tell that the calling object is type of class A?
}
}
</code></pre>
|
[
{
"answer_id": 194745,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 4,
"selected": true,
"text": "arguments caller \nvar stackTrace:String;\n\ntry { throw new Error(); }\ncatch (e:Error) { stackTrace = e.getStackTrace(); }\n\nvar lines:Array = stackTrace.split(\"\\n\");\nvar isDebug:Boolean = (lines[1] as String).indexOf('[') != -1;\n\nvar path:String;\nvar line:int = -1;\n\nif(isDebug)\n{\n var regex:RegExp = /at\\x20(.+?)\\[(.+?)\\]/i;\n var matches:Array = regex.exec(lines[2]);\n\n path = matches[1];\n\n //file:line = matches[2]\n //windows == 2 because of drive:\\\n line = matches[2].split(':')[2];\n}\nelse\n{\n path = (lines[2] as String).substring(4);\n}\n\ntrace(path + (line != -1 ? '[' + line.toString() + ']' : ''));\n"
},
{
"answer_id": 958720,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "Event e.currentTarget private function button_hover(e:Event):void\n{\n e.currentTarget.label=\"Hovering\";\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
194,742
|
<p>What is the best way to determine whether there is an available Internet connection for a WinForms app. (Programatically of course) I want to disable/hide certain functions if the user is not connected to the Internet.</p>
|
[
{
"answer_id": 194747,
"author": "QAZ",
"author_id": 14260,
"author_profile": "https://Stackoverflow.com/users/14260",
"pm_score": 3,
"selected": false,
"text": "bool IsInternetConnected( void )\n{\n DWORD dwConnectionFlags = 0;\n\n if( !InternetGetConnectedState( &dwConnectionFlags, 0 ) )\n return false;\n\n if( InternetAttemptConnect( 0 ) != ERROR_SUCCESS )\n return false;\n\n return true;\n}\n"
},
{
"answer_id": 194782,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 1,
"selected": false,
"text": "NetworkInterface.GetIsNetworkAvailable() NetworkChange System.Net.NetworkInformation"
},
{
"answer_id": 194789,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 5,
"selected": true,
"text": "NetworkInterface.GetIsNetworkAvailable() \n private static int ERROR_SUCCESS = 0;\npublic static bool IsInternetConnected() {\n long dwConnectionFlags = 0;\n if (!InternetGetConnectedState(dwConnectionFlags, 0))\n return false;\n\n if(InternetAttemptConnect(0) != ERROR_SUCCESS)\n return false;\n\n return true;\n}\n\n\n [DllImport(\"wininet.dll\", SetLastError=true)]\n public static extern int InternetAttemptConnect(uint res);\n\n\n [DllImport(\"wininet.dll\", SetLastError=true)]\n public static extern bool InternetGetConnectedState(out int flags,int reserved); \n"
},
{
"answer_id": 194799,
"author": "Stuart Helwig",
"author_id": 5019,
"author_profile": "https://Stackoverflow.com/users/5019",
"pm_score": 2,
"selected": false,
"text": "HttpWebRequest req;\nHttpWebResponse resp;\ntry\n{\n req = (HttpWebRequest)WebRequest.Create(\"http://www.google.com\");\n resp = (HttpWebResponse)req.GetResponse();\n\n if(resp.StatusCode.ToString().Equals(\"OK\"))\n {\n Console.WriteLine(\"its connected.\");\n }\n else\n {\n Console.WriteLine(\"its not connected.\");\n }\n}\ncatch(Exception exc)\n{\n Console.WriteLine(\"its not connected.\");\n}\n"
},
{
"answer_id": 194997,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "\n[DllImport(\"wininet.dll\", SetLastError=true)] \npublic static extern bool InternetGetConnectedState(out int flags,int reserved);\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5019/"
] |
194,754
|
<p>Is there any good tool or tool-chain that allows UML images in the .svg format to be created from a textual source file?
The reason for this question is that I want to automate the generation of these images to avoid having to manually create and update this set of images.</p>
|
[
{
"answer_id": 17568112,
"author": "Pranav 웃",
"author_id": 993915,
"author_profile": "https://Stackoverflow.com/users/993915",
"pm_score": 2,
"selected": false,
"text": "underscore.js Raphaël"
},
{
"answer_id": 21622594,
"author": "Jonathan Hartley",
"author_id": 10176,
"author_profile": "https://Stackoverflow.com/users/10176",
"pm_score": 1,
"selected": false,
"text": "# MSC for some fictional process\nmsc {\n hscale = \"2\";\n\n a,b,c;\n\n a->b [ label = \"ab()\" ] ;\n b->c [ label = \"bc(TRUE)\"];\n c=>c [ label = \"process(1)\" ];\n c=>c [ label = \"process(2)\" ];\n ...;\n c=>c [ label = \"process(n)\" ];\n c=>c [ label = \"process(END)\" ];\n a<<=c [ label = \"callback()\"];\n --- [ label = \"If more to run\", ID=\"*\" ];\n a->a [ label = \"next()\"];\n a->c [ label = \"ac1()\\nac2()\"];\n b<-c [ label = \"cb(TRUE)\"];\n b->b [ label = \"stalled(...)\"];\n a<-b [ label = \"ab() = FALSE\"];\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27134/"
] |
194,759
|
<p>I've got a client that, during testing, is giving me conflicting information. I don't think they are lying but more confused. So, I would like to setup some simple auditing in my ASP.Net application. Specifically, right when any page is called, I want to immediately insert the Querystring and/or form POST data into a log table. Just the raw values.</p>
<p>Querystring is easy. But there doesn't seem to be a way to get the raw form POST'ed data without using BinaryRead, and if I do that, then I screw myself out of using the Request.Form collection later on.</p>
<p>Does anyone know a way around this?</p>
<p>EDIT: tvanfosson suggested Request.Params. I was looking for something that was easier to use (like Request.Querystring, only for POST), but I guess I could just as easily loop through all params and build a string of name=value&, etc).</p>
|
[
{
"answer_id": 194910,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 2,
"selected": false,
"text": "public class CustomModule : IHttpModule \n{\n public void Init(HttpApplication context)\n {\n context.EndRequest += new EventHandler(context_BeginRequest);\n }\n\n private void context_BeginRequest(object sender, EventArgs e)\n {\n HttpContext context = ((HttpApplication)sender).Context;\n // you can use the context.Request here to send it to the database or a log file\n }\n}\n <httpModules>\n <add name=\"CustomModule\" type=\"CustomModule\"/>\n</httpModules>\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
194,765
|
<p>At the moment a default entry looks something like this:</p>
<pre><code>Oct 12, 2008 9:45:18 AM myClassInfoHere
INFO: MyLogMessageHere
</code></pre>
<p>How do I get it to do this?</p>
<pre><code>Oct 12, 2008 9:45:18 AM myClassInfoHere - INFO: MyLogMessageHere
</code></pre>
<p>Clarification I'm using java.util.logging</p>
|
[
{
"answer_id": 195147,
"author": "Obediah Stane",
"author_id": 23120,
"author_profile": "https://Stackoverflow.com/users/23120",
"pm_score": 3,
"selected": false,
"text": " public String format(LogRecord record) {\n return new java.util.Date() + \" \" + record.getLevel() + \" \" + record.getMessage() + \"\\r\\n\";\n }\n"
},
{
"answer_id": 197361,
"author": "Benno Richters",
"author_id": 3565,
"author_profile": "https://Stackoverflow.com/users/3565",
"pm_score": 5,
"selected": false,
"text": "format Formatter SimpleFormatter SimpleFormatter Date LogRecord Date Formatter LogRecord LogRecord Handler Logger LogRecord import java.io.PrintWriter;\nimport java.io.StringWriter;\nimport java.util.Date;\nimport java.util.logging.Formatter;\nimport java.util.logging.LogRecord;\n\npublic final class LogFormatter extends Formatter {\n\n private static final String LINE_SEPARATOR = System.getProperty(\"line.separator\");\n\n @Override\n public String format(LogRecord record) {\n StringBuilder sb = new StringBuilder();\n\n sb.append(new Date(record.getMillis()))\n .append(\" \")\n .append(record.getLevel().getLocalizedName())\n .append(\": \")\n .append(formatMessage(record))\n .append(LINE_SEPARATOR);\n\n if (record.getThrown() != null) {\n try {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n record.getThrown().printStackTrace(pw);\n pw.close();\n sb.append(sw.toString());\n } catch (Exception ex) {\n // ignore\n }\n }\n\n return sb.toString();\n }\n}\n"
},
{
"answer_id": 5937929,
"author": "Ondra Žižka",
"author_id": 145989,
"author_profile": "https://Stackoverflow.com/users/145989",
"pm_score": 6,
"selected": false,
"text": "-Djava.util.logging.SimpleFormatter.format java.util.Formatter -Djava.util.logging.SimpleFormatter.format=... \n -Djava.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n\n 2014-09-02 16:44:57 SEVERE org.jboss.windup.util.ZipUtil unzip: Failed to load: foo.zip\n java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-... <!-- Surefire -->\n<plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-surefire-plugin</artifactId>\n <version>2.17</version>\n <configuration>\n <systemPropertyVariables>\n <!-- Set JUL Formatting -->\n <java.util.logging.SimpleFormatter.format>%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n</java.util.logging.SimpleFormatter.format>\n </systemPropertyVariables>\n </configuration>\n</plugin>\n java.util.logging SingleLineFormatter public class SingleLineFormatter extends Formatter {\n\n Date dat = new Date();\n private final static String format = \"{0,date} {0,time}\";\n private MessageFormat formatter;\n private Object args[] = new Object[1];\n\n // Line separator string. This is the value of the line.separator\n // property at the moment that the SimpleFormatter was created.\n //private String lineSeparator = (String) java.security.AccessController.doPrivileged(\n // new sun.security.action.GetPropertyAction(\"line.separator\"));\n private String lineSeparator = \"\\n\";\n\n /**\n * Format the given LogRecord.\n * @param record the log record to be formatted.\n * @return a formatted log record\n */\n public synchronized String format(LogRecord record) {\n\n StringBuilder sb = new StringBuilder();\n\n // Minimize memory allocations here.\n dat.setTime(record.getMillis()); \n args[0] = dat;\n\n\n // Date and time \n StringBuffer text = new StringBuffer();\n if (formatter == null) {\n formatter = new MessageFormat(format);\n }\n formatter.format(args, text, null);\n sb.append(text);\n sb.append(\" \");\n\n\n // Class name \n if (record.getSourceClassName() != null) {\n sb.append(record.getSourceClassName());\n } else {\n sb.append(record.getLoggerName());\n }\n\n // Method name \n if (record.getSourceMethodName() != null) {\n sb.append(\" \");\n sb.append(record.getSourceMethodName());\n }\n sb.append(\" - \"); // lineSeparator\n\n\n\n String message = formatMessage(record);\n\n // Level\n sb.append(record.getLevel().getLocalizedName());\n sb.append(\": \");\n\n // Indent - the more serious, the more indented.\n //sb.append( String.format(\"% \"\"s\") );\n int iOffset = (1000 - record.getLevel().intValue()) / 100;\n for( int i = 0; i < iOffset; i++ ){\n sb.append(\" \");\n }\n\n\n sb.append(message);\n sb.append(lineSeparator);\n if (record.getThrown() != null) {\n try {\n StringWriter sw = new StringWriter();\n PrintWriter pw = new PrintWriter(sw);\n record.getThrown().printStackTrace(pw);\n pw.close();\n sb.append(sw.toString());\n } catch (Exception ex) {\n }\n }\n return sb.toString();\n }\n}\n"
},
{
"answer_id": 10706033,
"author": "Trevor Robinson",
"author_id": 123336,
"author_profile": "https://Stackoverflow.com/users/123336",
"pm_score": 7,
"selected": false,
"text": "-Djava.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'\n logger.properties java.util.logging.SimpleFormatter.format='%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$s %2$s %5$s%6$s%n'\n"
},
{
"answer_id": 34229629,
"author": "Guy L",
"author_id": 1344896,
"author_profile": "https://Stackoverflow.com/users/1344896",
"pm_score": 6,
"selected": false,
"text": " System.setProperty(\"java.util.logging.SimpleFormatter.format\", \n \"%1$tF %1$tT %4$s %2$s %5$s%6$s%n\");\n"
},
{
"answer_id": 39034822,
"author": "Jin Kwon",
"author_id": 330457,
"author_profile": "https://Stackoverflow.com/users/330457",
"pm_score": 4,
"selected": false,
"text": "public class VerySimpleFormatter extends Formatter {\n\n private static final String PATTERN = \"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\";\n\n @Override\n public String format(final LogRecord record) {\n return String.format(\n \"%1$s %2$-7s %3$s\\n\",\n new SimpleDateFormat(PATTERN).format(\n new Date(record.getMillis())),\n record.getLevel().getName(), formatMessage(record));\n }\n}\n 2016-08-19T17:43:14.295+09:00 INFO Hey~\n2016-08-19T17:43:16.068+09:00 SEVERE Seriously?\n2016-08-19T17:43:16.068+09:00 WARNING I'm warning you!!!\n"
},
{
"answer_id": 39827527,
"author": "Mohammad Irfan",
"author_id": 1927485,
"author_profile": "https://Stackoverflow.com/users/1927485",
"pm_score": -1,
"selected": false,
"text": "-Djava.util.logging.ConsoleHandler.formatter = org.apache.juli.OneLineFormatter\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23120/"
] |
194,803
|
<p>I'm currently developing a website and my client wants the text of various articles to overflow into two columns. Kind of like in a newspaper? So it would look like:</p>
<pre class="lang-none prettyprint-override"><code>Today in Wales, someone actually Nobody was harmed in
did something interesting. the incident, although one
Authorities are baffled by this elderly victim is receiving
development and have arrested the counselling.
perpetrator.
</code></pre>
<p>Is there a way I can do this with just CSS alone? I'd prefer not to have to use multiple divs. I'm open to using JavaScript too, but I'm <em>really</em> bad at that, so help would be appreciated. I was thinking maybe JavaScript could count how many <p>'s there are in the content div, and then move the second half of them to be floated right based on that?</p>
|
[
{
"answer_id": 194818,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 3,
"selected": false,
"text": "$content = \"Today in Wales, someone actually did something...\";\n// Find the literal halfway point, should be close to the textual halfway point\n$pos = int(strlen($content) / 2);\n// Find the end of the nearest word\nwhile ($content[$pos] != \" \") { $pos++; }\n// Split into columns based on the word ending.\n$column1 = substr($content, 0, $pos);\n$column2 = substr($content, $pos+1);\n"
},
{
"answer_id": 194825,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": false,
"text": "div.multi {\n column-count: 3\n column-gap: 10px;\n column-rule: 1px solid black; \n}\n"
},
{
"answer_id": 3736256,
"author": "tholane",
"author_id": 450688,
"author_profile": "https://Stackoverflow.com/users/450688",
"pm_score": -1,
"selected": false,
"text": "-moz-column-count"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12765/"
] |
194,821
|
<p>What is the most efficient way to go through and update every single node in a drupal site, to, for instance mechanically add tags? Drupal 6 has a shiny new batch API, but what to do in Drupal 5?</p>
<p>I started writing a script that keeps a pointer and then goes around all nodes on a cron, loads them and then saves them, but I wonder what else could be done.</p>
|
[
{
"answer_id": 194838,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 0,
"selected": false,
"text": "term_node term_node\n- nid\n- vid\n- tid\n term_data term_data\n- tid\n- name\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
194,828
|
<p>Is it possible to initialize an array of pointers to structs?
Something like:</p>
<pre><code>struct country_t *countries[] = {
{"United States of America", "America"},
{"England", "Europe"},
{"Ethiopia", "Africa"}
}
</code></pre>
<p>I want to do that in order to get the entities in not-contiguous memory, and the pointers to them in contiguous memory... But I can't use dynamic memory, so I wonder if it is possible without it.</p>
|
[
{
"answer_id": 194840,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": false,
"text": "static struct country_t us = { \"United States of America\", \"America\" };\nstatic struct country_t uk = { \"England\", \"Europe\" };\nstatic struct country_t et = { \"Ethiopia\", \"Africa\" };\n\nstruct country_t *countries[] = { &us, &uk, &et, };\n struct country_t *countries[] =\n{\n &(struct country_t) { \"United States of America\", \"America\" },\n &(struct country_t) { \"England\", \"Europe\" },\n &(struct country_t) { \"Ethiopia\", \"Africa\" },\n};\n struct country_t"
},
{
"answer_id": 194845,
"author": "James Fassett",
"author_id": 27081,
"author_profile": "https://Stackoverflow.com/users/27081",
"pm_score": 0,
"selected": false,
"text": "\nstruct country_t {\n char *fullname;\n char *shortname;\n};\n\nstruct country_t countries[] = {\n {\"United States of America\", \"America\"},\n {\"England\", \"Europe\"},\n {\"Ethiopia\", \"Africa\"}\n};\n\nint main(int argc, char *argv[])\n{\n return 0;\n}\n \nstruct country_t {\n char *fullname;\n char *shortname;\n} countries[] = {\n {\"United States of America\", \"America\"},\n {\"England\", \"Europe\"},\n {\"Ethiopia\", \"Africa\"}\n};\n\nint main(int argc, char *argv[])\n{\n return 0;\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,842
|
<p>Is it possible to make such buttons (<a href="http://img225.imageshack.us/img225/6452/buttonslw9.jpg" rel="nofollow noreferrer">http://img225.imageshack.us/img225/6452/buttonslw9.jpg</a>) using CSS? It should be Menu, and PHP would just feed the text to html/css and css should take care of the design. </p>
<p>Maybe I want too much out of CSS - especially with that red outline of the text.. ? Any ideas how i can achieve such results without doing those buttons manually in Graphical Editor?</p>
|
[
{
"answer_id": 194880,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": true,
"text": "text-shadow -webkit-text-stroke -webkit-gradient background-image"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
194,846
|
<p>Basically, I'm trying to create an object of unique objects, a set. I had the brilliant idea of just using a JavaScript object with objects for the property names. Such as,</p>
<pre><code>set[obj] = true;
</code></pre>
<p>This works, up to a point. It works great with string and numbers, but with other objects, they all seem to "hash" to the same value and access the same property. Is there some kind of way I can generate a unique hash value for an object? How do strings and numbers do it, can I override the same behavior?</p>
|
[
{
"answer_id": 194906,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 6,
"selected": true,
"text": "var ObjectReference = [];\nObjectReference.push(obj);\n\nset['ObjectReference.' + ObjectReference.indexOf(obj)] = true;\n"
},
{
"answer_id": 195222,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 3,
"selected": false,
"text": "myObject[myProperty] = ...;\n myObject[myProperty.toString()] = ...;\n myObject[\"someProperty\"]\n myObject.someProperty\n"
},
{
"answer_id": 885944,
"author": "Daniel X Moore",
"author_id": 68210,
"author_profile": "https://Stackoverflow.com/users/68210",
"pm_score": 5,
"selected": false,
"text": "toString (function() {\n var id = 0;\n\n /*global MyObject */\n MyObject = function() {\n this.objectId = '<#MyObject:' + (id++) + '>';\n this.toString= function() {\n return this.objectId;\n };\n };\n})();\n Hashtable equals() hashCode()"
},
{
"answer_id": 5790850,
"author": "theGecko",
"author_id": 39022,
"author_profile": "https://Stackoverflow.com/users/39022",
"pm_score": 4,
"selected": false,
"text": "Function.prototype.getHashCode = (function(id) {\n return function() {\n if (!this.hashCode) {\n this.hashCode = '<hash|#' + (id++) + '>';\n }\n return this.hashCode;\n }\n}(0));\n"
},
{
"answer_id": 8076436,
"author": "KimKha",
"author_id": 333214,
"author_profile": "https://Stackoverflow.com/users/333214",
"pm_score": 6,
"selected": false,
"text": "function hashCode(string){\n var hash = 0;\n for (var i = 0; i < string.length; i++) {\n var code = string.charCodeAt(i);\n hash = ((hash<<5)-hash)+code;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n}\n Math.abs()"
},
{
"answer_id": 8077416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "var wm1 = new WeakMap(),\n wm2 = new WeakMap();\nvar o1 = {},\n o2 = function(){},\n o3 = window;\n\nwm1.set(o1, 37);\nwm1.set(o2, \"azerty\");\nwm2.set(o1, o2); // A value can be anything, including an object or a function.\nwm2.set(o3, undefined);\nwm2.set(wm1, wm2); // Keys and values can be any objects. Even WeakMaps!\n\nwm1.get(o2); // \"azerty\"\nwm2.get(o2); // Undefined, because there is no value for o2 on wm2.\nwm2.get(o3); // Undefined, because that is the set value.\n\nwm1.has(o2); // True\nwm2.has(o2); // False\nwm2.has(o3); // True (even if the value itself is 'undefined').\n\nwm1.has(o1); // True\nwm1.delete(o1);\nwm1.has(o1); // False\n --harmony-weak-maps"
},
{
"answer_id": 11440965,
"author": "cburgmer",
"author_id": 575501,
"author_profile": "https://Stackoverflow.com/users/575501",
"pm_score": 0,
"selected": false,
"text": "var uniqueIdList = [];\nfunction getConstantUniqueIdFor(element) {\n // HACK, using a list results in O(n), but how do we hash e.g. a DOM node?\n if (uniqueIdList.indexOf(element) < 0) {\n uniqueIdList.push(element);\n }\n return uniqueIdList.indexOf(element);\n}\n"
},
{
"answer_id": 14469330,
"author": "darthmatch",
"author_id": 1872746,
"author_profile": "https://Stackoverflow.com/users/1872746",
"pm_score": 0,
"selected": false,
"text": "var hash = require('es-hash');\n\n// Save data in an object with an object as a key\nObject.prototype.toString = function () {\n return '[object Object #'+hash(this)+']';\n}\n\nvar foo = {};\n\nfoo[{bar: 'foo'}] = 'foo';\n\n/*\n * Output:\n * foo\n * undefined\n */\nconsole.log(foo[{bar: 'foo'}]);\nconsole.log(foo[{}]);\n"
},
{
"answer_id": 14953738,
"author": "Johnny",
"author_id": 459753,
"author_profile": "https://Stackoverflow.com/users/459753",
"pm_score": 1,
"selected": false,
"text": "Object (function() {\n var lastStorageId = 0;\n\n this.Object.hash = function(object) {\n var hash = object.__id;\n\n if (!hash)\n hash = object.__id = lastStorageId++;\n\n return '#' + hash;\n };\n}());\n"
},
{
"answer_id": 15868654,
"author": "Metalstorm",
"author_id": 524126,
"author_profile": "https://Stackoverflow.com/users/524126",
"pm_score": 4,
"selected": false,
"text": "Hashcode.value(\"stackoverflow\")\n// -2559914341\nHashcode.value({ 'site' : \"stackoverflow\" })\n// -3579752159\n"
},
{
"answer_id": 22330776,
"author": "ijmacd",
"author_id": 1228394,
"author_profile": "https://Stackoverflow.com/users/1228394",
"pm_score": 4,
"selected": false,
"text": "var hashtable = {};\n\nvar myObject = {a:0,b:1,c:2};\n\nvar hash = JSON.stringify(myObject);\n// '{\"a\":0,\"b\":1,\"c\":2}'\n\nhashtable[hash] = myObject;\n// {\n// '{\"a\":0,\"b\":1,\"c\":2}': myObject\n// }\n"
},
{
"answer_id": 27930322,
"author": "Daniel X Moore",
"author_id": 68210,
"author_profile": "https://Stackoverflow.com/users/68210",
"pm_score": 3,
"selected": false,
"text": "Set"
},
{
"answer_id": 40187493,
"author": "A1rPun",
"author_id": 1449624,
"author_profile": "https://Stackoverflow.com/users/1449624",
"pm_score": 0,
"selected": false,
"text": "var lookup = {};\n function getHashCode(obj) {\n var hashCode = '';\n if (typeof obj !== 'object')\n return hashCode + obj;\n for (var prop in obj) // No hasOwnProperty needed\n hashCode += prop + getHashCode(obj[prop]); // Add key + value to the result string\n return hashCode;\n}\n var key = getHashCode({ 1: 3, 3: 7 });\n// key = '1337'\nlookup[key] = true;\n var key = getHashCode([1, 3, 3, 7]);\n// key = '01132337'\nlookup[key] = true;\n var key = getHashCode('StackOverflow');\n// key = 'StackOverflow'\nlookup[key] = true;\n { 1337: true, 01132337: true, StackOverflow: true } getHashCode getHashCode([{},{},{}]);\n// '012'\ngetHashCode([[],[],[]]);\n// '012'\n getHashCode JSON"
},
{
"answer_id": 41925534,
"author": "Khalid Azam",
"author_id": 988976,
"author_profile": "https://Stackoverflow.com/users/988976",
"pm_score": 2,
"selected": false,
"text": "var obj = {};\n\nobj[Symbol('a')] = 'a';\nobj[Symbol.for('b')] = 'b';\nobj['c'] = 'c';\nobj.d = 'd';\n"
},
{
"answer_id": 43245290,
"author": "Timothy Perez",
"author_id": 904725,
"author_profile": "https://Stackoverflow.com/users/904725",
"pm_score": 2,
"selected": false,
"text": "function hashcode(obj) {\n var hc = 0;\n var chars = JSON.stringify(obj).replace(/\\{|\\\"|\\}|\\:|,/g, '');\n var len = chars.length;\n for (var i = 0; i < len; i++) {\n // Bump 7 to larger prime number to increase uniqueness\n hc += (chars.charCodeAt(i) * 7);\n }\n return hc;\n}\n"
},
{
"answer_id": 53905336,
"author": "jozsef morrissey",
"author_id": 7760485,
"author_profile": "https://Stackoverflow.com/users/7760485",
"pm_score": 1,
"selected": false,
"text": "exports.Hash = () => {\n let hashFunc;\n function stringHash(string, noType) {\n let hashString = string;\n if (!noType) {\n hashString = `string${string}`;\n }\n var hash = 0;\n for (var i = 0; i < hashString.length; i++) {\n var character = hashString.charCodeAt(i);\n hash = ((hash<<5)-hash)+character;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash;\n }\n\n function objectHash(obj, exclude) {\n if (exclude.indexOf(obj) > -1) {\n return undefined;\n }\n let hash = '';\n const keys = Object.keys(obj).sort();\n for (let index = 0; index < keys.length; index += 1) {\n const key = keys[index];\n const keyHash = hashFunc(key);\n const attrHash = hashFunc(obj[key], exclude);\n exclude.push(obj[key]);\n hash += stringHash(`object${keyHash}${attrHash}`, true);\n }\n return stringHash(hash, true);\n }\n\n function Hash(unkType, exclude) {\n let ex = exclude;\n if (ex === undefined) {\n ex = [];\n }\n if (!isNaN(unkType) && typeof unkType !== 'string') {\n return unkType;\n }\n switch (typeof unkType) {\n case 'object':\n return objectHash(unkType, ex);\n default:\n return stringHash(String(unkType));\n }\n }\n\n hashFunc = Hash;\n\n return Hash;\n};\n Hash('hello world'), Hash('hello world') == Hash('hello world')\nHash({hello: 'hello world'}), Hash({hello: 'hello world'}) == Hash({hello: 'hello world'})\nHash({hello: 'hello world', goodbye: 'adios amigos'}), Hash({hello: 'hello world', goodbye: 'adios amigos'}) == Hash({goodbye: 'adios amigos', hello: 'hello world'})\nHash(['hello world']), Hash(['hello world']) == Hash(['hello world'])\nHash(1), Hash(1) == Hash(1)\nHash('1'), Hash('1') == Hash('1')\n 432700947 true\n-411117486 true\n1725787021 true\n-1585332251 true\n1 true\n-1881759168 true\n ErrorSvc({id: 1, json: '{attr: \"not-valid\"}'}, 'Invalid Json Syntax - key not double quoted');\n ErrorSvc({id: 1, json: '{attr: \"not-valid\"}'});\n ['Invalid Json Syntax - key not double quoted']\n ErrorSvc({id: 1, json: '{\"attr\": \"not-valid\"}'});\n []\n"
},
{
"answer_id": 57385857,
"author": "NVRM",
"author_id": 2494754,
"author_profile": "https://Stackoverflow.com/users/2494754",
"pm_score": 3,
"selected": false,
"text": "async function H(m) {\n const msgUint8 = new TextEncoder().encode(m) \n const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8) \n const hashArray = Array.from(new Uint8Array(hashBuffer)) \n const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('')\n console.log(hashHex)\n}\n\n/* Examples ----------------------- */\nH(\"An obscure ....\")\nH(JSON.stringify( {\"hello\" : \"world\"} ))\nH(JSON.stringify( [54,51,54,47] )) bf1cf3fe6975fe382ab392ec1dd42009380614be03d489f23601c11413cfca2b\n93a23971a914e5eacbf0a8d25154cda309c3c1c72fbb9914d47c60f3cb681588\nd2f209e194045604a3b15bdfd7502898a0e848e4603c5a818bd01da69c00ad19\n SHA-1 (but don't use this in cryptographic applications)\nSHA-256\nSHA-384\nSHA-512\n"
},
{
"answer_id": 60344292,
"author": "Nikolay Makhonin",
"author_id": 5221762,
"author_profile": "https://Stackoverflow.com/users/5221762",
"pm_score": 0,
"selected": false,
"text": "defineProperty enumerable: false var nextObjectId = 1\nfunction getNextObjectId() {\n return nextObjectId++\n}\n\nvar UNIQUE_ID_PROPERTY_NAME = '458d576952bc489ab45e98ac7f296fd9'\nfunction getObjectUniqueId(object) {\n if (object == null) {\n return null\n }\n\n var id = object[UNIQUE_ID_PROPERTY_NAME]\n\n if (id != null) {\n return id\n }\n\n if (Object.isFrozen(object)) {\n return null\n }\n\n var uniqueId = getNextObjectId()\n Object.defineProperty(object, UNIQUE_ID_PROPERTY_NAME, {\n enumerable: false,\n configurable: false,\n writable: false,\n value: uniqueId,\n })\n\n return uniqueId\n}\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16492/"
] |
194,852
|
<p>Consider a database table holding names, with three rows:</p>
<pre><code>Peter
Paul
Mary
</code></pre>
<p>Is there an easy way to turn this into a single string of <code>Peter, Paul, Mary</code>?</p>
|
[
{
"answer_id": 194875,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 7,
"selected": false,
"text": "SELECT 1 AS a, GROUP_CONCAT(name ORDER BY name ASC SEPARATOR ', ') AS people \nFROM users \nWHERE id IN (1,2,3) \nGROUP BY a\n"
},
{
"answer_id": 194886,
"author": "Dana",
"author_id": 7856,
"author_profile": "https://Stackoverflow.com/users/7856",
"pm_score": 5,
"selected": false,
"text": "DECLARE @names VARCHAR(500)\n\nSELECT @names = @names + ' ' + Name\nFROM Names\n"
},
{
"answer_id": 194887,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 10,
"selected": false,
"text": "COALESCE DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(@Names + ', ', '') + Name \nFROM People\n @Names @Names DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(@Names + ', ', '') + Name\nFROM People\nWHERE Name IS NOT NULL\n DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(@Names + ', ', '') + \n ISNULL(Name, 'N/A')\nFROM People\n"
},
{
"answer_id": 198333,
"author": "gbn",
"author_id": 27535,
"author_profile": "https://Stackoverflow.com/users/27535",
"pm_score": 3,
"selected": false,
"text": "DECLARE @Names VARCHAR(8000)\nSELECT @name = ''\nSELECT @Names = @Names + ',' + Names FROM People\nSELECT SUBSTRING(2, @Names, 7998)\n"
},
{
"answer_id": 545672,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 12,
"selected": true,
"text": "XML PATH STUDENTS SubjectID StudentName\n---------- -------------\n1 Mary\n1 John\n1 Sam\n2 Alaina\n2 Edward\n SubjectID StudentName\n---------- -------------\n1 Mary, John, Sam\n2 Alaina, Edward\n T-SQL SELECT Main.SubjectID,\n LEFT(Main.Students,Len(Main.Students)-1) As \"Students\"\nFROM\n (\n SELECT DISTINCT ST2.SubjectID, \n (\n SELECT ST1.StudentName + ',' AS [text()]\n FROM dbo.Students ST1\n WHERE ST1.SubjectID = ST2.SubjectID\n ORDER BY ST1.SubjectID\n FOR XML PATH (''), TYPE\n ).value('text()[1]','nvarchar(max)') [Students]\n FROM dbo.Students ST2\n ) [Main]\n substring SELECT DISTINCT ST2.SubjectID, \n SUBSTRING(\n (\n SELECT ','+ST1.StudentName AS [text()]\n FROM dbo.Students ST1\n WHERE ST1.SubjectID = ST2.SubjectID\n ORDER BY ST1.SubjectID\n FOR XML PATH (''), TYPE\n ).value('text()[1]','nvarchar(max)'), 2, 1000) [Students]\nFROM dbo.Students ST2\n"
},
{
"answer_id": 3672860,
"author": "teamchong",
"author_id": 442938,
"author_profile": "https://Stackoverflow.com/users/442938",
"pm_score": 8,
"selected": false,
"text": "SELECT Stuff(\n (SELECT N', ' + Name FROM Names FOR XML PATH(''),TYPE)\n .value('text()[1]','nvarchar(max)'),1,2,N'')\n SELECT per.ID,\nEmails = JSON_VALUE(\n REPLACE(\n (SELECT _ = em.Email FROM Email em WHERE em.Person = per.ID FOR JSON PATH)\n ,'\"},{\"_\":\"',', '),'$[0]._'\n) \nFROM Person per\n Id Emails\n1 abc@gmail.com\n2 NULL\n3 def@gmail.com, xyz@gmail.com\n '\"},{\"_\":\"' '\"},{\"_\":\"', \"},{\\\"_\\\":\\\" ', '"
},
{
"answer_id": 5558670,
"author": "jens frandsen",
"author_id": 693784,
"author_profile": "https://Stackoverflow.com/users/693784",
"pm_score": 9,
"selected": false,
"text": "XML data() SELECT FName + ', ' AS 'data()'\nFROM NameList\nFOR XML PATH('')\n \"Peter, Paul, Mary, \"\n STUFF(REPLACE((SELECT '#!' + LTRIM(RTRIM(FName)) AS 'data()' FROM NameList\nFOR XML PATH('')),' #!',', '), 1, 2, '') as Brands\n"
},
{
"answer_id": 5580166,
"author": "Diwakar",
"author_id": 696690,
"author_profile": "https://Stackoverflow.com/users/696690",
"pm_score": 4,
"selected": false,
"text": "REPLACE(\n (select FName AS 'data()' from NameList for xml path(''))\n , ' ', ', ') \n"
},
{
"answer_id": 5834020,
"author": "Hans Bluh",
"author_id": 731334,
"author_profile": "https://Stackoverflow.com/users/731334",
"pm_score": 1,
"selected": false,
"text": "ISNULL(SUBSTRING(REPLACE((select ',' FName as 'data()' from NameList for xml path('')), ' ,',', '), 2, 300), '') 'MyList'\n"
},
{
"answer_id": 6231011,
"author": "user762952",
"author_id": 762952,
"author_profile": "https://Stackoverflow.com/users/762952",
"pm_score": 3,
"selected": false,
"text": "wm_concat"
},
{
"answer_id": 6592636,
"author": "Vladimir Nesterovsky",
"author_id": 831007,
"author_profile": "https://Stackoverflow.com/users/831007",
"pm_score": 3,
"selected": false,
"text": "with lines as \n( \n select \n row_number() over(order by id) id, -- id is a line id\n line -- line of text.\n from\n source -- line source\n), \nresult_lines as \n( \n select \n id, \n cast(line as nvarchar(max)) line \n from \n lines \n where \n id = 1 \n union all \n select \n l.id, \n cast(r.line + N', ' + l.line as nvarchar(max))\n from \n lines l \n inner join \n result_lines r \n on \n l.id = r.id + 1 \n) \nselect top 1 \n line\nfrom\n result_lines\norder by\n id desc\n"
},
{
"answer_id": 6596590,
"author": "Yogesh Bhadauirya",
"author_id": 831537,
"author_profile": "https://Stackoverflow.com/users/831537",
"pm_score": 5,
"selected": false,
"text": "DECLARE @t table\n(\n Id int,\n Name varchar(10)\n)\nINSERT INTO @t\nSELECT 1,'a' UNION ALL\nSELECT 1,'b' UNION ALL\nSELECT 2,'c' UNION ALL\nSELECT 2,'d' \n\nSELECT ID,\nstuff(\n(\n SELECT ','+ [Name] FROM @t WHERE Id = t.Id FOR XML PATH('')\n),1,1,'') \nFROM (SELECT DISTINCT ID FROM @t ) t\n"
},
{
"answer_id": 6850549,
"author": "Pramod",
"author_id": 249496,
"author_profile": "https://Stackoverflow.com/users/249496",
"pm_score": 3,
"selected": false,
"text": "DECLARE @Names VARCHAR(8000) \nSELECT @Names = COALESCE(COALESCE(@Names + ', ', '') + Name, @Names) FROM People\n"
},
{
"answer_id": 8206256,
"author": "Oleg Sakharov",
"author_id": 87057,
"author_profile": "https://Stackoverflow.com/users/87057",
"pm_score": 3,
"selected": false,
"text": "DECLARE @names VARCHAR(MAX)\nSET @names = ''\n\nSELECT @names = @names + ', ' + Name FROM Names\n\n-- Deleting last two symbols (', ')\nSET @sSql = LEFT(@sSql, LEN(@sSql) - 1)\n"
},
{
"answer_id": 9127273,
"author": "Daniel Reis",
"author_id": 959570,
"author_profile": "https://Stackoverflow.com/users/959570",
"pm_score": 4,
"selected": false,
"text": "select substring(\n (select ', '+Name AS 'data()' from Names for xml path(''))\n ,3, 255) as \"MyList\"\n"
},
{
"answer_id": 9621167,
"author": "Alex",
"author_id": 265877,
"author_profile": "https://Stackoverflow.com/users/265877",
"pm_score": 6,
"selected": false,
"text": "COLUMN employees FORMAT A50\n\nSELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees\nFROM emp\nGROUP BY deptno;\n\n DEPTNO EMPLOYEES\n---------- --------------------------------------------------\n 10 CLARK,KING,MILLER\n 20 ADAMS,FORD,JONES,SCOTT,SMITH\n 30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD\n\n3 rows selected.\n"
},
{
"answer_id": 11891963,
"author": "jmoreno",
"author_id": 234954,
"author_profile": "https://Stackoverflow.com/users/234954",
"pm_score": 5,
"selected": false,
"text": ";WITH basetable AS (\n SELECT\n id,\n CAST(name AS VARCHAR(MAX)) name,\n ROW_NUMBER() OVER (Partition BY id ORDER BY seq) rw,\n COUNT(*) OVER (Partition BY id) recs\n FROM (VALUES\n (1, 'Johnny', 1),\n (1, 'M', 2),\n (2, 'Bill', 1),\n (2, 'S.', 4),\n (2, 'Preston', 5),\n (2, 'Esq.', 6),\n (3, 'Ted', 1),\n (3, 'Theodore', 2),\n (3, 'Logan', 3),\n (4, 'Peter', 1),\n (4, 'Paul', 2),\n (4, 'Mary', 3)\n ) g (id, name, seq)\n),\nrCTE AS (\n SELECT recs, id, name, rw\n FROM basetable\n WHERE rw = 1\n\n UNION ALL\n\n SELECT b.recs, r.ID, r.name +', '+ b.name name, r.rw + 1\n FROM basetable b\n INNER JOIN rCTE r ON b.id = r.id AND b.rw = r.rw + 1\n)\nSELECT name\nFROM rCTE\nWHERE recs = rw AND ID=4\nOPTION (MAXRECURSION 101)\n"
},
{
"answer_id": 11892100,
"author": "hgmnz",
"author_id": 165452,
"author_profile": "https://Stackoverflow.com/users/165452",
"pm_score": 6,
"selected": false,
"text": "postgres=# \\c test\nYou are now connected to database \"test\" as user \"hgimenez\".\ntest=# create table names (name text);\nCREATE TABLE\ntest=# insert into names (name) values ('Peter'), ('Paul'), ('Mary');\nINSERT 0 3\ntest=# select * from names;\n name\n-------\n Peter\n Paul\n Mary\n(3 rows)\n test=# select array_agg(name) from names;\n array_agg\n-------------------\n {Peter,Paul,Mary}\n(1 row)\n test=# select array_to_string(array_agg(name), ', ') from names;\n array_to_string\n-------------------\n Peter, Paul, Mary\n(1 row)\n select string_agg(name, ',') \nfrom names;\n"
},
{
"answer_id": 12647157,
"author": "Priti Getkewar Joshi",
"author_id": 1653179,
"author_profile": "https://Stackoverflow.com/users/1653179",
"pm_score": 2,
"selected": false,
"text": " create table name\n (first_name varchar2(30));\n\n insert into name values ('Peter');\n insert into name values ('Paul');\n insert into name values ('Mary');\n select substr(max(sys_connect_by_path (first_name, ',')),2) from (select rownum r, first_name from name ) n start with r=1 connect by prior r+1=r\n o/p=> Peter,Paul,Mary\n select rtrim(xmlagg (xmlelement (e, first_name || ',')).extract ('//text()'), ',') first_name from name\n o/p=> Peter,Paul,Mary\n"
},
{
"answer_id": 16526394,
"author": "ZeroK",
"author_id": 1535863,
"author_profile": "https://Stackoverflow.com/users/1535863",
"pm_score": 3,
"selected": false,
"text": "SELECT question_id,\n LISTAGG(element_id, ',') WITHIN GROUP (ORDER BY element_id)\nFROM YOUR_TABLE;\nGROUP BY question_id\n"
},
{
"answer_id": 19584555,
"author": "endo64",
"author_id": 333153,
"author_profile": "https://Stackoverflow.com/users/333153",
"pm_score": 3,
"selected": false,
"text": "create table #test (id int,name varchar(10))\n--use separate inserts on older versions of SQL Server\ninsert into #test values (1,'Peter'), (1,'Paul'), (1,'Mary'), (2,'Alex'), (3,'Jack')\n\nDECLARE @t VARCHAR(255)\nSELECT @t = ISNULL(@t + ',' + name, name) FROM #test WHERE id = 1\nselect @t\ndrop table #test\n Peter,Paul,Mary\n"
},
{
"answer_id": 20009988,
"author": "topchef",
"author_id": 59470,
"author_profile": "https://Stackoverflow.com/users/59470",
"pm_score": 2,
"selected": false,
"text": "SubjectID StudentName\n---------- -------------\n1 Mary\n1 John\n1 Sam\n2 Alaina\n2 Edward\n SELECT * FROM npath(\n ON Students\n PARTITION BY SubjectID\n ORDER BY StudentName\n MODE(nonoverlapping)\n PATTERN('A*')\n SYMBOLS(\n 'true' as A\n )\n RESULT(\n FIRST(SubjectID of A) as SubjectID,\n ACCUMULATE(StudentName of A) as StudentName\n )\n);\n SubjectID StudentName\n---------- -------------\n1 [John, Mary, Sam]\n2 [Alaina, Edward]\n"
},
{
"answer_id": 20324790,
"author": "Max Tkachenko",
"author_id": 1393791,
"author_profile": "https://Stackoverflow.com/users/1393791",
"pm_score": 1,
"selected": false,
"text": "Students name declare @rowsCount INT\ndeclare @i INT = 1\ndeclare @names varchar(max) = ''\n\nDECLARE @MyTable TABLE\n(\n Id int identity,\n Name varchar(500)\n)\ninsert into @MyTable select name from Students\nset @rowsCount = (select COUNT(Id) from @MyTable)\n\nwhile @i < @rowsCount\nbegin\n set @names = @names + ', ' + (select name from @MyTable where Id = @i)\n set @i = @i + 1\nend\nselect @names\n"
},
{
"answer_id": 28476945,
"author": "Rapunzo",
"author_id": 141800,
"author_profile": "https://Stackoverflow.com/users/141800",
"pm_score": 3,
"selected": false,
"text": "DECLARE @names VARCHAR(500)\nSELECT @names = CONCAT(@names, ' ', name) \nFROM Names\nselect @names\n"
},
{
"answer_id": 29740361,
"author": "Hamid Bahmanabady",
"author_id": 1527921,
"author_profile": "https://Stackoverflow.com/users/1527921",
"pm_score": -1,
"selected": false,
"text": " declare @phone varchar(max)='' \n select @phone=@phone + mobileno +',' from members\n select @phone\n"
},
{
"answer_id": 30114419,
"author": "Nizam",
"author_id": 358614,
"author_profile": "https://Stackoverflow.com/users/358614",
"pm_score": 3,
"selected": false,
"text": "EXEC sp_configure 'show advanced options', 1\nRECONFIGURE;\nEXEC sp_configure 'clr strict security', 1;\nRECONFIGURE;\n\nCREATE Assembly concat_assembly\n AUTHORIZATION dbo\n FROM '<PATH TO Concat.dll IN SERVER>'\n WITH PERMISSION_SET = SAFE;\nGO\n\nCREATE AGGREGATE dbo.concat (\n\n @Value NVARCHAR(MAX)\n , @Delimiter NVARCHAR(4000)\n\n) RETURNS NVARCHAR(MAX)\nEXTERNAL Name concat_assembly.[Concat.Concat];\nGO\n\nsp_configure 'clr enabled', 1;\nRECONFIGURE\n SELECT dbo.Concat(field1, ',')\nFROM Table1\n"
},
{
"answer_id": 31557028,
"author": "user1767754",
"author_id": 1767754,
"author_profile": "https://Stackoverflow.com/users/1767754",
"pm_score": 3,
"selected": false,
"text": "___________________________\n| id | rowList |\n|-------------------------|\n| 0 | 6, 9 |\n| 1 | 1,2,3,4,5,7,8,1 |\n|_________________________|\n CREATE TABLE `Data` (\n `id` int(11) NOT NULL,\n `user_id` int(11) NOT NULL\n) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;\n\n\nINSERT INTO `Data` (`id`, `user_id`) VALUES\n(1, 1),\n(2, 1),\n(3, 1),\n(4, 1),\n(5, 1),\n(6, 0),\n(7, 1),\n(8, 1),\n(9, 0),\n(10, 1);\n\n\nCREATE TABLE `User` (\n `id` int(11) NOT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n\n\nINSERT INTO `User` (`id`) VALUES\n(0),\n(1);\n SELECT User.id, GROUP_CONCAT(Data.id ORDER BY Data.id) AS rowList FROM User LEFT JOIN Data ON User.id = Data.user_id GROUP BY User.id\n"
},
{
"answer_id": 36419425,
"author": "Pedram",
"author_id": 1156018,
"author_profile": "https://Stackoverflow.com/users/1156018",
"pm_score": 6,
"selected": false,
"text": "Declare @Numbers AS Nvarchar(MAX) -- It must not be MAX if you have few numbers\nSELECT @Numbers = COALESCE(@Numbers + ',', '') + Number\nFROM TableName where Number IS NOT NULL\n\nSELECT @Numbers\n 102,103,104\n"
},
{
"answer_id": 37036438,
"author": "Mike Barlow - BarDev",
"author_id": 92166,
"author_profile": "https://Stackoverflow.com/users/92166",
"pm_score": 4,
"selected": false,
"text": "SELECT\n Table_Name\n ,STUFF((\n SELECT ',' + Column_Name\n FROM INFORMATION_SCHEMA.Columns Columns\n WHERE Tables.Table_Name = Columns.Table_Name\n ORDER BY Column_Name\n FOR XML PATH ('')), 1, 1, ''\n )Columns\nFROM INFORMATION_SCHEMA.Columns Tables\nGROUP BY TABLE_NAME \n"
},
{
"answer_id": 37459266,
"author": "Muhammad Bilal",
"author_id": 1415927,
"author_profile": "https://Stackoverflow.com/users/1415927",
"pm_score": 2,
"selected": false,
"text": "SELECT PageContent = Stuff(\n ( SELECT PageContent\n FROM dbo.InfoGuide\n WHERE CategoryId = @CategoryId\n AND SubCategoryId = @SubCategoryId\n for xml path(''), type\n ).value('.[1]','nvarchar(max)'),\n 1, 1, '')\nFROM dbo.InfoGuide info\n"
},
{
"answer_id": 37578420,
"author": "Graeme",
"author_id": 832552,
"author_profile": "https://Stackoverflow.com/users/832552",
"pm_score": 3,
"selected": false,
"text": "CREATE TABLE dbo.Students\n(\n StudentId INT\n , Name VARCHAR(50)\n , CONSTRAINT PK_Students PRIMARY KEY (StudentId)\n);\n\nCREATE TABLE dbo.Subjects\n(\n SubjectId INT\n , Name VARCHAR(50)\n , CONSTRAINT PK_Subjects PRIMARY KEY (SubjectId)\n);\n\nCREATE TABLE dbo.Schedules\n(\n StudentId INT\n , SubjectId INT\n , CONSTRAINT PK__Schedule PRIMARY KEY (StudentId, SubjectId)\n , CONSTRAINT FK_Schedule_Students FOREIGN KEY (StudentId) REFERENCES dbo.Students (StudentId)\n , CONSTRAINT FK_Schedule_Subjects FOREIGN KEY (SubjectId) REFERENCES dbo.Subjects (SubjectId)\n);\n\nINSERT dbo.Students (StudentId, Name) VALUES\n (1, 'Mary')\n , (2, 'John')\n , (3, 'Sam')\n , (4, 'Alaina')\n , (5, 'Edward')\n;\n\nINSERT dbo.Subjects (SubjectId, Name) VALUES\n (1, 'Physics')\n , (2, 'Geography')\n , (3, 'French')\n , (4, 'Gymnastics')\n;\n\nINSERT dbo.Schedules (StudentId, SubjectId) VALUES\n (1, 1) --Mary, Physics\n , (2, 1) --John, Physics\n , (3, 1) --Sam, Physics\n , (4, 2) --Alaina, Geography\n , (5, 2) --Edward, Geography\n;\n\nSELECT\n sub.SubjectId\n , sub.Name AS [SubjectName]\n , ISNULL( x.Students, '') AS Students\nFROM\n dbo.Subjects sub\n OUTER APPLY\n (\n SELECT\n CASE ROW_NUMBER() OVER (ORDER BY stu.Name) WHEN 1 THEN '' ELSE ', ' END\n + stu.Name\n FROM\n dbo.Students stu\n INNER JOIN dbo.Schedules sch\n ON stu.StudentId = sch.StudentId\n WHERE\n sch.SubjectId = sub.SubjectId\n ORDER BY\n stu.Name\n FOR XML PATH('')\n ) x (Students)\n;\n"
},
{
"answer_id": 37738837,
"author": "Glen",
"author_id": 1828277,
"author_profile": "https://Stackoverflow.com/users/1828277",
"pm_score": 2,
"selected": false,
"text": "DECLARE @MyList VARCHAR(1000), @Delimiter CHAR(2) = ', '\nSELECT @MyList = CASE WHEN @MyList > '' THEN @MyList + @Delimiter ELSE '' END + FieldToConcatenate FROM MyData\n"
},
{
"answer_id": 40619710,
"author": "Tigerjz32",
"author_id": 1556242,
"author_profile": "https://Stackoverflow.com/users/1556242",
"pm_score": 5,
"selected": false,
"text": "DECLARE @char VARCHAR(MAX);\n\nSELECT @char = COALESCE(@char + ', ' + [column], [column]) \nFROM [table];\n\nPRINT @char;\n"
},
{
"answer_id": 42778050,
"author": "Mathieu Renda",
"author_id": 3506362,
"author_profile": "https://Stackoverflow.com/users/3506362",
"pm_score": 10,
"selected": false,
"text": "SELECT STRING_AGG(Name, ', ') AS Departments\nFROM HumanResources.Department;\n SELECT GroupName, STRING_AGG(Name, ', ') AS Departments\nFROM HumanResources.Department\nGROUP BY GroupName;\n SELECT GroupName, STRING_AGG(Name, ', ') WITHIN GROUP (ORDER BY Name ASC) AS Departments\nFROM HumanResources.Department\nGROUP BY GroupName;\n"
},
{
"answer_id": 47700428,
"author": "Shahbaz",
"author_id": 3273603,
"author_profile": "https://Stackoverflow.com/users/3273603",
"pm_score": 2,
"selected": false,
"text": "SELECT t1.id,\n GROUP_CONCAT(t1.id) ids\n FROM table t1 JOIN table t2 ON (t1.id = t2.id)\n GROUP BY t1.id\n"
},
{
"answer_id": 48435921,
"author": "Max Szczurek",
"author_id": 1208034,
"author_profile": "https://Stackoverflow.com/users/1208034",
"pm_score": 4,
"selected": false,
"text": "SELECT STUFF((SELECT ', ' + name FROM [table] FOR XML PATH('')), 1, 2, '')\n DECLARE @t TABLE (name VARCHAR(10))\nINSERT INTO @t VALUES ('Peter'), ('Paul'), ('Mary')\nSELECT STUFF((SELECT ', ' + name FROM @t FOR XML PATH('')), 1, 2, '')\n--Peter, Paul, Mary\n"
},
{
"answer_id": 48803931,
"author": "Pooja Bhat",
"author_id": 5906392,
"author_profile": "https://Stackoverflow.com/users/5906392",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE \"NAMES\" (\"NAME\" VARCHAR2(10 BYTE))) ;\n INSERT INTO NAMES VALUES('PETER');\nINSERT INTO NAMES VALUES('PAUL');\nINSERT INTO NAMES VALUES('MARY');\n DECLARE \n\nMAXNUM INTEGER;\nCNTR INTEGER := 1;\nC_NAME NAMES.NAME%TYPE;\nNSTR VARCHAR2(50);\n\nBEGIN\n\nSELECT MAX(ROWNUM) INTO MAXNUM FROM NAMES;\n\nLOOP\n\nSELECT NAME INTO C_NAME FROM \n(SELECT ROWNUM RW, NAME FROM NAMES ) P WHERE P.RW = CNTR;\n\nNSTR := NSTR ||','||C_NAME;\nCNTR := CNTR + 1;\nEXIT WHEN CNTR > MAXNUM;\n\nEND LOOP;\n\ndbms_output.put_line(SUBSTR(NSTR,2));\n\nEND;\n PETER,PAUL,MARY\n"
},
{
"answer_id": 49611871,
"author": "Ravi Pipaliya",
"author_id": 5608331,
"author_profile": "https://Stackoverflow.com/users/5608331",
"pm_score": 2,
"selected": false,
"text": "-- Table Creation\nCREATE TABLE Tbl\n( CustomerCode VARCHAR(50)\n, CustomerName VARCHAR(50)\n, Type VARCHAR(50)\n,Items VARCHAR(50)\n)\n\ninsert into Tbl\nSELECT 'C0001','Thomas','BREAKFAST','Milk'\nunion SELECT 'C0001','Thomas','BREAKFAST','Bread'\nunion SELECT 'C0001','Thomas','BREAKFAST','Egg'\nunion SELECT 'C0001','Thomas','LUNCH','Rice'\nunion SELECT 'C0001','Thomas','LUNCH','Fish Curry'\nunion SELECT 'C0001','Thomas','LUNCH','Lessy'\nunion SELECT 'C0002','JOSEPH','BREAKFAST','Bread'\nunion SELECT 'C0002','JOSEPH','BREAKFAST','Jam'\nunion SELECT 'C0002','JOSEPH','BREAKFAST','Tea'\nunion SELECT 'C0002','JOSEPH','Supper','Tea'\nunion SELECT 'C0002','JOSEPH','Brunch','Roti'\n\n-- function creation\nGO\nCREATE FUNCTION [dbo].[fn_GetItemsByType]\n( \n @CustomerCode VARCHAR(50)\n ,@Type VARCHAR(50)\n)\nRETURNS @ItemType TABLE ( Items VARCHAR(5000) )\nAS\nBEGIN\n\n INSERT INTO @ItemType(Items)\n SELECT STUFF((SELECT distinct ',' + [Items]\n FROM Tbl \n WHERE CustomerCode = @CustomerCode\n AND Type=@Type\n FOR XML PATH(''))\n ,1,1,'') as Items\n\n\n\n RETURN \nEND\n\nGO\n\n-- fianl Query\nDECLARE @cols AS NVARCHAR(MAX),\n @query AS NVARCHAR(MAX)\n\nselect @cols = STUFF((SELECT distinct ',' + QUOTENAME(Type) \n from Tbl\n FOR XML PATH(''), TYPE\n ).value('.', 'NVARCHAR(MAX)') \n ,1,1,'')\n\nset @query = 'SELECT CustomerCode,CustomerName,' + @cols + '\n from \n (\n select \n distinct CustomerCode\n ,CustomerName\n ,Type\n ,F.Items\n FROM Tbl T\n CROSS APPLY [fn_GetItemsByType] (T.CustomerCode,T.Type) F\n ) x\n pivot \n (\n max(Items)\n for Type in (' + @cols + ')\n ) p '\n\nexecute(@query) \n"
},
{
"answer_id": 51606514,
"author": "Esperento57",
"author_id": 3735690,
"author_profile": "https://Stackoverflow.com/users/3735690",
"pm_score": 1,
"selected": false,
"text": "-- Create example table\nCREATE TABLE tmptable (NAME VARCHAR(30)) ;\n\n-- Insert example data\nINSERT INTO tmptable VALUES('PETER');\nINSERT INTO tmptable VALUES('PAUL');\nINSERT INTO tmptable VALUES('MARY');\n\n-- Recurse query\nwith tblwithrank as (\nselect * , row_number() over(order by name) rang , count(*) over() NbRow\nfrom tmptable\n),\ntmpRecursive as (\nselect *, cast(name as varchar(2000)) as AllName from tblwithrank where rang=1\nunion all\nselect f0.*, cast(f0.name + ',' + f1.AllName as varchar(2000)) as AllName \nfrom tblwithrank f0 inner join tmpRecursive f1 on f0.rang=f1.rang +1 \n)\nselect AllName from tmpRecursive\nwhere rang=NbRow\n"
},
{
"answer_id": 55816724,
"author": "Kemal AL GAZZAH",
"author_id": 6774506,
"author_profile": "https://Stackoverflow.com/users/6774506",
"pm_score": 0,
"selected": false,
"text": "declare @mytable as table(id int identity(1,1), str nvarchar(100))\ninsert into @mytable values('Peter'),('Paul'),('Mary')\n\ndeclare @myresult as table(id int,str nvarchar(max),ind int, R# int)\n\n;with cte as(select id,cast(str as nvarchar(100)) as str, cast(0 as int) ind from @mytable\nunion all\nselect t2.id,cast(t1.str+',' +t2.str as nvarchar(100)) ,t1.ind+1 from cte t1 inner join @mytable t2 on t2.id=t1.id+1)\ninsert into @myresult select *,row_number() over(order by ind) R# from cte\n\nselect top 1 str from @myresult order by R# desc\n"
},
{
"answer_id": 57517612,
"author": "asmgx",
"author_id": 1492229,
"author_profile": "https://Stackoverflow.com/users/1492229",
"pm_score": 3,
"selected": false,
"text": "Tom\nAli\nJohn\nAli\nTom\nMike\n Tom,Ali,John,Ali,Tom,Mike Tom,Ali,John,Mike DECLARE @Names VARCHAR(8000)\nSELECT DISTINCT @Names = COALESCE(@Names + ',', '') + Name\nFROM People\nWHERE Name IS NOT NULL\nSELECT @Names\n"
},
{
"answer_id": 57956819,
"author": "Arash.Zandi",
"author_id": 3046588,
"author_profile": "https://Stackoverflow.com/users/3046588",
"pm_score": 4,
"selected": false,
"text": "SELECT CarNamesString = STUFF((\n SELECT ',' + [Name]\n FROM tbl_cars\n FOR XML PATH('')\n ), 1, 1, '')\n SELECT [Name],\n GROUP_CONCAT(DISTINCT [Name] SEPARATOR ',')\n FROM tbl_cars\n"
},
{
"answer_id": 64820174,
"author": "Amirreza mohammadi",
"author_id": 8508960,
"author_profile": "https://Stackoverflow.com/users/8508960",
"pm_score": 0,
"selected": false,
"text": " Go\n declare @temp table(\n title nvarchar(50)\n )\n insert into @temp(title)\n select p.Title from dbo.person p\n --\n declare @mainString nvarchar(max)\n set @mainString = '';\n --\n while ((select count(*) from @temp) != 0)\n begin\n declare @itemTitle nvarchar(50)\n set @itemTitle = (select top(1) t.Title from @temp t)\n \n if @mainString = ''\n begin\n set @mainString = @itemTitle\n end\n else\n begin\n set @mainString = concat(@mainString,',',@itemTitle)\n end\n \n delete top(1) from @temp\n \n end\n print @mainString\n"
},
{
"answer_id": 65716131,
"author": "panser",
"author_id": 3554624,
"author_profile": "https://Stackoverflow.com/users/3554624",
"pm_score": 2,
"selected": false,
"text": "SELECT array_to_string(array_agg(DISTINCT rolname), ',') FROM pg_catalog.pg_roles;\n SELECT STRING_AGG(rolname::text,',') FROM pg_catalog.pg_roles;\n"
},
{
"answer_id": 66944063,
"author": "sameer Ahmed",
"author_id": 4796661,
"author_profile": "https://Stackoverflow.com/users/4796661",
"pm_score": 5,
"selected": false,
"text": "SELECT\n VendorId, STRING_AGG(FirstName,',') UsersName\nFROM Users\nWHERE VendorId != 9\nGROUP BY VendorId\n"
}
] |
2008/10/11
|
[
"https://Stackoverflow.com/questions/194852",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
194,863
|
<p>I'm looking for some succinct, modern C# code to generate a random date between Jan 1 1995 and the current date.</p>
<p>I'm thinking some solution that utilizes Enumerable.Range somehow may make this more succinct.</p>
|
[
{
"answer_id": 194870,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": true,
"text": "private Random gen = new Random();\nDateTime RandomDay()\n{\n DateTime start = new DateTime(1995, 1, 1);\n int range = (DateTime.Today - start).Days; \n return start.AddDays(gen.Next(range));\n}\n start gen range"
},
{
"answer_id": 194992,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "Func<DateTime> RandomDayFunc()\n{\n DateTime start = new DateTime(1995, 1, 1); \n Random gen = new Random(); \n int range = ((TimeSpan)(DateTime.Today - start)).Days; \n return () => start.AddDays(gen.Next(range));\n}\n"
},
{
"answer_id": 195050,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": " static IEnumerable<DateTime> RandomDay()\n {\n DateTime start = new DateTime(1995, 1, 1);\n Random gen = new Random();\n int range = ((TimeSpan)(DateTime.Today - start)).Days;\n while (true)\n yield return start.AddDays(gen.Next(range)); \n}\n int i=0;\nforeach(DateTime dt in RandomDay())\n{\n Console.WriteLine(dt);\n if (++i == 10)\n break;\n}\n"
},
{
"answer_id": 26263669,
"author": "prespic",
"author_id": 984081,
"author_profile": "https://Stackoverflow.com/users/984081",
"pm_score": 4,
"selected": false,
"text": "class RandomDateTime\n{\n DateTime start;\n Random gen;\n int range;\n\n public RandomDateTime()\n {\n start = new DateTime(1995, 1, 1);\n gen = new Random();\n range = (DateTime.Today - start).Days;\n }\n\n public DateTime Next()\n {\n return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));\n }\n}\n RandomDateTime date = new RandomDateTime();\nfor (int i = 0; i < 100; i++)\n{\n Console.WriteLine(date.Next());\n}\n"
},
{
"answer_id": 53300329,
"author": "Hamit Gündogdu",
"author_id": 3464638,
"author_profile": "https://Stackoverflow.com/users/3464638",
"pm_score": 0,
"selected": false,
"text": " void Main()\n {\n var dateResult = GetRandomDates(new DateTime(1995, 1, 1), DateTime.UtcNow, 100);\n foreach (var r in dateResult)\n Console.WriteLine(r);\n }\n\n public static IList<DateTime> GetRandomDates(DateTime startDate, DateTime maxDate, int range)\n {\n var randomResult = GetRandomNumbers(range).ToArray();\n\n var calculationValue = maxDate.Subtract(startDate).TotalMinutes / int.MaxValue;\n var dateResults = randomResult.Select(s => startDate.AddMinutes(s * calculationValue)).ToList();\n return dateResults;\n }\n\n public static IEnumerable<int> GetRandomNumbers(int size)\n {\n var data = new byte[4];\n using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data))\n {\n for (int i = 0; i < size; i++)\n {\n rng.GetBytes(data);\n\n var value = BitConverter.ToInt32(data, 0);\n yield return value < 0 ? value * -1 : value;\n }\n }\n }\n"
},
{
"answer_id": 60612579,
"author": "BernardV",
"author_id": 3324415,
"author_profile": "https://Stackoverflow.com/users/3324415",
"pm_score": 0,
"selected": false,
"text": "public string RandomDate(int startYear = 1960, string outputDateFormat = \"yyyy-MM-dd\")\n{\n DateTime start = new DateTime(startYear, 1, 1);\n Random gen = new Random(Guid.NewGuid().GetHashCode());\n int range = (DateTime.Today - start).Days;\n return start.AddDays(gen.Next(range)).ToString(outputDateFormat);\n}\n"
},
{
"answer_id": 65782552,
"author": "Ben",
"author_id": 7471204,
"author_profile": "https://Stackoverflow.com/users/7471204",
"pm_score": -1,
"selected": false,
"text": "public static class RandomExtensions\n{\n public static DateTime Next(this Random random, DateTime start, DateTime? end = null)\n {\n end ??= new DateTime();\n int range = (end.Value - start).Days;\n return start.AddDays(random.Next(range));\n }\n}\n"
},
{
"answer_id": 69634338,
"author": "user16789193",
"author_id": 16789193,
"author_profile": "https://Stackoverflow.com/users/16789193",
"pm_score": 1,
"selected": false,
"text": "Random rnd = new Random();\nDateTime datetoday = DateTime.Now;\n\nint rndYear = rnd.Next(1995, datetoday.Year);\nint rndMonth = rnd.Next(1, 12);\nint rndDay = rnd.Next(1, 31);\n\nDateTime generateDate = new DateTime(rndYear, rndMonth, rndDay);\nConsole.WriteLine(generateDate);\n"
},
{
"answer_id": 73559337,
"author": "Hefaistos68",
"author_id": 198310,
"author_profile": "https://Stackoverflow.com/users/198310",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// A random date/time class that provides random dates within a given range\n/// </summary>\npublic class RandomDateTime\n{\n private readonly Random rng = new Random();\n private readonly int totalMinutes;\n private readonly DateTime startDateTime;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"RandomDateTime\"/> class.\n /// </summary>\n /// <param name=\"startDate\">The start date.</param>\n /// <param name=\"endDate\">The end date.</param>\n public RandomDateTime(DateTime startDate, DateTime endDate)\n {\n this.startDateTime = startDate;\n TimeSpan timeSpan = endDate - startDate;\n this.totalMinutes = (int)timeSpan.TotalMinutes;\n }\n\n /// <summary>\n /// Gets the next random datetime object within the range of startDate and endDate provided in the ctor\n /// </summary>\n /// <returns>A DateTime.</returns>\n public DateTime NextDateTime\n {\n get\n {\n TimeSpan newSpan = new TimeSpan(0, rng.Next(0, this.totalMinutes), 0);\n return this.startDateTime + newSpan;\n }\n }\n}\n RandomDateTime rdt = new RandomDateTime(DateTime.Parse(\"01/01/2020\"), DateTime.Parse(\"31/12/2022\"));\n\nfor (int i = 0; i < 5; i++)\n Debug.WriteLine(rdt.NextDateTime);\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
194,869
|
<p>I am working on a project that does a large amount of hashing, signing, and both asymmetric and symmetric encryption. Since these steps have a significant effect on our performance and available load, I was wondering if there is a hardware based solution to offloading the work. </p>
<p>I have done some surfing to find out, and the only items I can find are dedicated to SSL based communications. I need a more generic solution that will allow me to speed up signing and encryption regardless of where it occurs. </p>
<p>Is it possible to adapt these SSL based solutions (maybe it's just marketing and it would be easy to re-use elsewhere)? Is there a good generic co-processor that can help out? </p>
<p>I need this on a Windows Server 2008 based box, but I would be interested in solutions on any platform.</p>
|
[
{
"answer_id": 194870,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 9,
"selected": true,
"text": "private Random gen = new Random();\nDateTime RandomDay()\n{\n DateTime start = new DateTime(1995, 1, 1);\n int range = (DateTime.Today - start).Days; \n return start.AddDays(gen.Next(range));\n}\n start gen range"
},
{
"answer_id": 194992,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "Func<DateTime> RandomDayFunc()\n{\n DateTime start = new DateTime(1995, 1, 1); \n Random gen = new Random(); \n int range = ((TimeSpan)(DateTime.Today - start)).Days; \n return () => start.AddDays(gen.Next(range));\n}\n"
},
{
"answer_id": 195050,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": " static IEnumerable<DateTime> RandomDay()\n {\n DateTime start = new DateTime(1995, 1, 1);\n Random gen = new Random();\n int range = ((TimeSpan)(DateTime.Today - start)).Days;\n while (true)\n yield return start.AddDays(gen.Next(range)); \n}\n int i=0;\nforeach(DateTime dt in RandomDay())\n{\n Console.WriteLine(dt);\n if (++i == 10)\n break;\n}\n"
},
{
"answer_id": 26263669,
"author": "prespic",
"author_id": 984081,
"author_profile": "https://Stackoverflow.com/users/984081",
"pm_score": 4,
"selected": false,
"text": "class RandomDateTime\n{\n DateTime start;\n Random gen;\n int range;\n\n public RandomDateTime()\n {\n start = new DateTime(1995, 1, 1);\n gen = new Random();\n range = (DateTime.Today - start).Days;\n }\n\n public DateTime Next()\n {\n return start.AddDays(gen.Next(range)).AddHours(gen.Next(0,24)).AddMinutes(gen.Next(0,60)).AddSeconds(gen.Next(0,60));\n }\n}\n RandomDateTime date = new RandomDateTime();\nfor (int i = 0; i < 100; i++)\n{\n Console.WriteLine(date.Next());\n}\n"
},
{
"answer_id": 53300329,
"author": "Hamit Gündogdu",
"author_id": 3464638,
"author_profile": "https://Stackoverflow.com/users/3464638",
"pm_score": 0,
"selected": false,
"text": " void Main()\n {\n var dateResult = GetRandomDates(new DateTime(1995, 1, 1), DateTime.UtcNow, 100);\n foreach (var r in dateResult)\n Console.WriteLine(r);\n }\n\n public static IList<DateTime> GetRandomDates(DateTime startDate, DateTime maxDate, int range)\n {\n var randomResult = GetRandomNumbers(range).ToArray();\n\n var calculationValue = maxDate.Subtract(startDate).TotalMinutes / int.MaxValue;\n var dateResults = randomResult.Select(s => startDate.AddMinutes(s * calculationValue)).ToList();\n return dateResults;\n }\n\n public static IEnumerable<int> GetRandomNumbers(int size)\n {\n var data = new byte[4];\n using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(data))\n {\n for (int i = 0; i < size; i++)\n {\n rng.GetBytes(data);\n\n var value = BitConverter.ToInt32(data, 0);\n yield return value < 0 ? value * -1 : value;\n }\n }\n }\n"
},
{
"answer_id": 60612579,
"author": "BernardV",
"author_id": 3324415,
"author_profile": "https://Stackoverflow.com/users/3324415",
"pm_score": 0,
"selected": false,
"text": "public string RandomDate(int startYear = 1960, string outputDateFormat = \"yyyy-MM-dd\")\n{\n DateTime start = new DateTime(startYear, 1, 1);\n Random gen = new Random(Guid.NewGuid().GetHashCode());\n int range = (DateTime.Today - start).Days;\n return start.AddDays(gen.Next(range)).ToString(outputDateFormat);\n}\n"
},
{
"answer_id": 65782552,
"author": "Ben",
"author_id": 7471204,
"author_profile": "https://Stackoverflow.com/users/7471204",
"pm_score": -1,
"selected": false,
"text": "public static class RandomExtensions\n{\n public static DateTime Next(this Random random, DateTime start, DateTime? end = null)\n {\n end ??= new DateTime();\n int range = (end.Value - start).Days;\n return start.AddDays(random.Next(range));\n }\n}\n"
},
{
"answer_id": 69634338,
"author": "user16789193",
"author_id": 16789193,
"author_profile": "https://Stackoverflow.com/users/16789193",
"pm_score": 1,
"selected": false,
"text": "Random rnd = new Random();\nDateTime datetoday = DateTime.Now;\n\nint rndYear = rnd.Next(1995, datetoday.Year);\nint rndMonth = rnd.Next(1, 12);\nint rndDay = rnd.Next(1, 31);\n\nDateTime generateDate = new DateTime(rndYear, rndMonth, rndDay);\nConsole.WriteLine(generateDate);\n"
},
{
"answer_id": 73559337,
"author": "Hefaistos68",
"author_id": 198310,
"author_profile": "https://Stackoverflow.com/users/198310",
"pm_score": 0,
"selected": false,
"text": "/// <summary>\n/// A random date/time class that provides random dates within a given range\n/// </summary>\npublic class RandomDateTime\n{\n private readonly Random rng = new Random();\n private readonly int totalMinutes;\n private readonly DateTime startDateTime;\n\n /// <summary>\n /// Initializes a new instance of the <see cref=\"RandomDateTime\"/> class.\n /// </summary>\n /// <param name=\"startDate\">The start date.</param>\n /// <param name=\"endDate\">The end date.</param>\n public RandomDateTime(DateTime startDate, DateTime endDate)\n {\n this.startDateTime = startDate;\n TimeSpan timeSpan = endDate - startDate;\n this.totalMinutes = (int)timeSpan.TotalMinutes;\n }\n\n /// <summary>\n /// Gets the next random datetime object within the range of startDate and endDate provided in the ctor\n /// </summary>\n /// <returns>A DateTime.</returns>\n public DateTime NextDateTime\n {\n get\n {\n TimeSpan newSpan = new TimeSpan(0, rng.Next(0, this.totalMinutes), 0);\n return this.startDateTime + newSpan;\n }\n }\n}\n RandomDateTime rdt = new RandomDateTime(DateTime.Parse(\"01/01/2020\"), DateTime.Parse(\"31/12/2022\"));\n\nfor (int i = 0; i < 5; i++)\n Debug.WriteLine(rdt.NextDateTime);\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71994/"
] |
194,890
|
<p>I have a large project that I want to start using visual studio 2005 to edit. I want to tell it "Here are all the files I want you to track, now get on with it" and have them displayed as a directory tree, for example:</p>
<pre><code>Folder 1
- File A
- File B
- File C
Folder 2
- Folder 3
- File X
- File Y
- File D
- File E
</code></pre>
<p>Right now it's just showing all the header files in one big list, and all the source files in one big list, which I find unhelpful. I also don't want to spend ages creating a folder in the project for each folder on the disk.</p>
<p>Is there any way I can get VS to show me a source tree of everything in the solution, organised by where it is on the actual disk?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 3599629,
"author": "crayor",
"author_id": 434800,
"author_profile": "https://Stackoverflow.com/users/434800",
"pm_score": 0,
"selected": false,
"text": "Datei >> Neu >> Projekt aus vorhandenem Code New... Show All Files Select Folders"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13500/"
] |
194,914
|
<p>What's the best way of adding spaces between strings</p>
<pre><code>myString = string.Concat("a"," ","b")
</code></pre>
<p>or</p>
<pre><code>myString = string.Concat("a",Chr(9),"b")
</code></pre>
<p>I am using stringbuilder to build an XML file and looking for something efficient.</p>
<p>Thanks</p>
<p>Edit ~ Language VB.NET</p>
|
[
{
"answer_id": 194918,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 3,
"selected": false,
"text": "string sentence = String.Join(\" \", new string[] { \"The\", \"quick\", \"brown\", \"fox\" });\n"
},
{
"answer_id": 194940,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": true,
"text": "string.Concat(\"a\",\" \",\"b\")"
},
{
"answer_id": 194981,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 0,
"selected": false,
"text": "string[] input = new string[]{\"a\", \"b\"};\nvar withSpaces = input.Aggregate( (x,y) => x + \" \" + );\n"
},
{
"answer_id": 195026,
"author": "DancesWithBamboo",
"author_id": 1334,
"author_profile": "https://Stackoverflow.com/users/1334",
"pm_score": 0,
"selected": false,
"text": "sb.AppendFormat(\"{0} {1}\", a, b);\n"
},
{
"answer_id": 195364,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 1,
"selected": false,
"text": "s = a + \" \" + b\n s = string.Concat(a, \" \", b)\n"
},
{
"answer_id": 16684534,
"author": "Santosh Wavare",
"author_id": 2408154,
"author_profile": "https://Stackoverflow.com/users/2408154",
"pm_score": 1,
"selected": false,
"text": " Dim TestString As String\n' Returns a string with 10 spaces.\nTestString = Space(10)\n' Inserts 10 spaces between two strings.\nTestString = \"Hello\" & Space(10) & \"World\"\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
194,930
|
<p>I got one big question.</p>
<p>I got a linq query to put it simply looks like this:</p>
<pre><code>from xx in table
where xx.uid.ToString().Contains(string[])
select xx
</code></pre>
<p>The values of the <code>string[]</code> array would be numbers like (1,45,20,10,etc...)</p>
<p>the Default for <code>.Contains</code> is <code>.Contains(string)</code>.</p>
<p>I need it to do this instead: <code>.Contains(string[])</code>...</p>
<p><strong>EDIT :</strong> One user suggested writing an extension class for <code>string[]</code>. I would like to learn how, but any one willing to point me in the right direction?</p>
<p><strong>EDIT :</strong> The uid would also be a number. That's why it is converted to a string.</p>
<p>Help anyone?</p>
|
[
{
"answer_id": 194939,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "from xx in table\nwhere stringarray.Contains(xx.uid.ToString())\nselect xx\n"
},
{
"answer_id": 194970,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 2,
"selected": false,
"text": "namespace StringExtensionMethods\n{\n public static class StringExtension\n {\n public static bool Contains(this string[] stringarray, string pat)\n {\n bool result = false;\n\n foreach (string s in stringarray)\n {\n if (s == pat)\n {\n result = true;\n break;\n }\n }\n\n return result;\n }\n }\n}\n"
},
{
"answer_id": 194972,
"author": "ctrlShiftBryan",
"author_id": 6161,
"author_profile": "https://Stackoverflow.com/users/6161",
"pm_score": 1,
"selected": false,
"text": "from xx in table\nwhere (from yy in string[] \n select yy).Contains(xx.uid.ToString())\nselect xx\n"
},
{
"answer_id": 194974,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 7,
"selected": true,
"text": "List<string> string[] List<int> int List<T> Contains() uid.ToString().Contains(string[]) string[] List<int>() var uids = arrayofuids.Select(id => int.Parse(id)).ToList();\n\nvar selected = table.Where(t => uids.Contains(t.uid));\n"
},
{
"answer_id": 194975,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "string input = \"someString\";\nstring[] toSearchFor = GetSearchStrings();\nvar containsAll = toSearchFor.All(x => input.Contains(x));\n"
},
{
"answer_id": 195628,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ContainsAnyThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n string testValue = \"123345789\";\n\n //will print true\n Console.WriteLine(testValue.ContainsAny(\"123\", \"987\", \"554\")); \n\n //but so will this also print true\n Console.WriteLine(testValue.ContainsAny(\"1\", \"987\", \"554\"));\n Console.ReadKey();\n\n }\n }\n\n public static class StringExtensions\n {\n public static bool ContainsAny(this string str, params string[] values)\n {\n if (!string.IsNullOrEmpty(str) || values.Length > 0)\n {\n foreach (string value in values)\n {\n if(str.Contains(value))\n return true;\n }\n }\n\n return false;\n }\n }\n}\n"
},
{
"answer_id": 195674,
"author": "justin.m.chase",
"author_id": 12958,
"author_profile": "https://Stackoverflow.com/users/12958",
"pm_score": 0,
"selected": false,
"text": "Guid id = new Guid(uid);\nvar query = from xx in table\n where xx.uid == id\n select xx;\n"
},
{
"answer_id": 456594,
"author": "Gorkem Pacaci",
"author_id": 51749,
"author_profile": "https://Stackoverflow.com/users/51749",
"pm_score": 0,
"selected": false,
"text": "string[] search = new string[] { \"2\", \"3\" };\nvar result = from x in xx where search.Contains(x.uid.ToString()) select x;\n sp_executesql N'SELECT [t0].[uid]\nFROM [dbo].[xx] AS [t0]\nWHERE (CONVERT(NVarChar,[t0].[uid]))\nIN (@p0, @p1)',N'@p0 nvarchar(1),\n@p1 nvarchar(1)',@p0=N'2',@p1=N'3'\n"
},
{
"answer_id": 1142232,
"author": "Brett Ryan",
"author_id": 140037,
"author_profile": "https://Stackoverflow.com/users/140037",
"pm_score": 0,
"selected": false,
"text": "var users = from u in (from u in ctx.Users\n where u.Mod_Status != \"D\"\n select u).AsEnumerable()\n where ar.All(n => u.FullName.IndexOf(n,\n StringComparison.InvariantCultureIgnoreCase) >= 0)\n select u;\n string[] search = new string[] { \"John\", \"Doe\" };\nvar users = from u in ctx.Users\n from s in search\n where u.FullName.Contains(s)\n select u;\n var users = from u in ctx.Users select u;\nforeach (string s in search) {\n users = users.Where(u => u.FullName.Contains(s));\n}\n"
},
{
"answer_id": 3072348,
"author": "beauXjames",
"author_id": 370605,
"author_profile": "https://Stackoverflow.com/users/370605",
"pm_score": 0,
"selected": false,
"text": "CREATE function [dbo].[getMatches](@textStr nvarchar(50)) returns @MatchTbl table(\nFullname nvarchar(50) null,\nID nvarchar(50) null\n)\nas begin\ndeclare @SearchStr nvarchar(50);\nset @SearchStr = '%' + @textStr + '%';\ninsert into @MatchTbl \nselect (LName + ', ' + FName + ' ' + MName) AS FullName, ID = ID from employees where LName like @SearchStr;\nreturn;\nend\n\nGO\n\nselect * from dbo.getMatches('j')\n Dim db As New NobleLINQ\nDim LNameSearch As String = txt_searchLName.Text\nDim hlink As HyperLink\n\nFor Each ee In db.getMatches(LNameSearch)\n hlink = New HyperLink With {.Text = ee.Fullname & \"<br />\", .NavigateUrl = \"?ID=\" & ee.ID}\n pnl_results.Controls.Add(hlink)\nNext\n"
},
{
"answer_id": 3611735,
"author": "knroc",
"author_id": 436215,
"author_profile": "https://Stackoverflow.com/users/436215",
"pm_score": -1,
"selected": false,
"text": "string[] stringArray = {1,45,20,10};\nfrom xx in table \nwhere stringArray.Contains(xx.uid.ToString()) \nselect xx\n"
},
{
"answer_id": 5813288,
"author": "JumpingJezza",
"author_id": 345659,
"author_profile": "https://Stackoverflow.com/users/345659",
"pm_score": 3,
"selected": false,
"text": "List<string> uids = new List<string>(){\"1\", \"45\", \"20\", \"10\"};\nList<user> table = GetDataFromSomewhere();\n\nList<user> newTable = table.Where(xx => uids.Contains(xx.uid)).ToList();\n"
},
{
"answer_id": 9711404,
"author": "RJ Lohan",
"author_id": 897994,
"author_profile": "https://Stackoverflow.com/users/897994",
"pm_score": 4,
"selected": false,
"text": "string[] values = new[] { \"1\", \"2\", \"3\" };\nstring data = \"some string 1\";\nbool containsAny = values.Any(data.Contains);\n"
},
{
"answer_id": 11716734,
"author": "user1119399",
"author_id": 1119399,
"author_profile": "https://Stackoverflow.com/users/1119399",
"pm_score": 0,
"selected": false,
"text": "from xx in table\nwhere xx.uid.Split(',').Contains(string value )\nselect xx\n"
},
{
"answer_id": 11903169,
"author": "theRonny",
"author_id": 1048512,
"author_profile": "https://Stackoverflow.com/users/1048512",
"pm_score": 0,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\n\nnamespace ContainsAnyProgram\n{\n class Program\n {\n static void Main(string[] args)\n {\n const string iphoneAgent = \"Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like...\";\n\n var majorAgents = new[] { \"iPhone\", \"Android\", \"iPad\" };\n var minorAgents = new[] { \"Blackberry\", \"Windows Phone\" };\n\n // true\n Console.WriteLine(iphoneAgent.ContainsAny(majorAgents));\n\n // false\n Console.WriteLine(iphoneAgent.ContainsAny(minorAgents));\n Console.ReadKey();\n }\n }\n\n public static class StringExtensions\n {\n /// <summary>\n /// Replicates Contains but for an array\n /// </summary>\n /// <param name=\"str\">The string.</param>\n /// <param name=\"values\">The values.</param>\n /// <returns></returns>\n public static bool ContainsAny(this string str, params string[] values)\n {\n if (!string.IsNullOrEmpty(str) && values.Length > 0)\n return values.Any(str.Contains);\n\n return false;\n }\n }\n}\n"
},
{
"answer_id": 21749510,
"author": "NinjaNye",
"author_id": 611288,
"author_profile": "https://Stackoverflow.com/users/611288",
"pm_score": 2,
"selected": false,
"text": "string[] terms = new[]{\"search\", \"term\", \"collection\"};\nvar result = context.Table.Search(terms, x => x.Name);\n var result = context.Table.Search(terms, x => x.Name, p.Description);\n RankedSearch IQueryable<IRanked<T>> //Perform search and rank results by the most hits\nvar result = context.Table.RankedSearch(terms, x => x.Name, x.Description)\n .OrderByDescending(r = r.Hits);\n"
},
{
"answer_id": 23124316,
"author": "kravits88",
"author_id": 1427220,
"author_profile": "https://Stackoverflow.com/users/1427220",
"pm_score": 2,
"selected": false,
"text": " public static bool ContainsAny<T>(this IEnumerable<T> Collection, IEnumerable<T> Values)\n {\n return Collection.Any(x=> Values.Contains(x));\n }\n string[] Array1 = {\"1\", \"2\"};\nstring[] Array2 = {\"2\", \"4\"};\n\nbool Array2ItemsInArray1 = List1.ContainsAny(List2);\n"
},
{
"answer_id": 31893529,
"author": "Hedego",
"author_id": 1744906,
"author_profile": "https://Stackoverflow.com/users/1744906",
"pm_score": 0,
"selected": false,
"text": "var stringInput = \"test\";\nvar listOfNames = GetNames();\nvar result = from names in listOfNames where names.firstName.Trim().ToLower().Contains(stringInput.Trim().ToLower());\nselect names;\n"
},
{
"answer_id": 40073806,
"author": "EVONZ",
"author_id": 7027695,
"author_profile": "https://Stackoverflow.com/users/7027695",
"pm_score": -1,
"selected": false,
"text": "Dim stringArray() = {\"Pink Floyd\", \"AC/DC\"}\nDim inSQL = From alb In albums Where stringArray.Contains(alb.Field(Of String)(\"Artiste\").ToString())\nSelect New With\n {\n .Album = alb.Field(Of String)(\"Album\"),\n .Annee = StrReverse(alb.Field(Of Integer)(\"Annee\").ToString()) \n }\n"
},
{
"answer_id": 55021586,
"author": "Hari Lakkakula",
"author_id": 6601939,
"author_profile": "https://Stackoverflow.com/users/6601939",
"pm_score": 0,
"selected": false,
"text": "var SelecetdSteps = Context.FFTrakingSubCriticalSteps\n .Where(x => x.MeetingId == meetid)\n .Select(x => \n x.StepID \n );\n\n var crtiticalsteps = Context.MT_CriticalSteps.Where(x =>x.cropid==FFT.Cropid).Select(x=>new\n {\n StepID= x.crsid,\n x.Name,\n Checked=false\n\n });\n\n\n var quer = from ax in crtiticalsteps\n where (!SelecetdSteps.Contains(ax.StepID))\n select ax;\n"
},
{
"answer_id": 63497470,
"author": "William Peixoto",
"author_id": 10949845,
"author_profile": "https://Stackoverflow.com/users/10949845",
"pm_score": 0,
"selected": false,
"text": " string texto = \"CALCA 40\";\n string[] descpart = texto.Split(' ');\n\n var lst = (from item in db.InvItemsMaster\n where descpart.All(val => item.itm_desc.Contains(val))\n select item\n ).ToList();\n Console.WriteLine(\"ITM\".PadRight(10) + \"DESC\".PadRight(50)+\"EAN\".PadRight(14));\n foreach(var i in lst)\n {\n \n\n Console.Write(i.itm_id.ToString().PadRight(10));\n Console.Write(i.itm_desc.ToString().PadRight(50));\n Console.WriteLine(i.itm_ean.ToString().PadRight(14));\n\n\n }\n\n Console.ReadKey();\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7644/"
] |
194,944
|
<p>I am creating a lightweight editor in C# and would like to know the best method for converting a string into a nicely formatted XML string. I would hope that there's a public method in the C# library like "public bool FormatAsXml(string text, out string formattedXmlText)", but it couldn't be that easy, could it?</p>
<p>Very specifically, what would the method "SomeMethod" have to be that would produce the output below?</p>
<pre><code>string unformattedXml;
string formattedXml;
unformattedXml = "<?xml version=\"1.0\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>"
formattedXml = SomeMethod(unformattedXml);
Console.WriteLine(formattedXml);
</code></pre>
<p>Output:</p>
<pre><code><?xml version="1.0"?>
<book id="123">
<author>Lewis, C.S.</author>
<title>The Four Loves</title>
</book>
</code></pre>
|
[
{
"answer_id": 194951,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "XmlDocument xml = new XmlDocument();\n\nxml.LoadXml( YourString );\n"
},
{
"answer_id": 194956,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 3,
"selected": false,
"text": "writer.Formatting = Formatting.Indented;\nwriter.Indentation = 1;\nwriter.IndentChar = '\\t';\n"
},
{
"answer_id": 194996,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 4,
"selected": false,
"text": "XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\" \");\nusing (XmlWriter writer = XmlWriter.Create(\"books.xml\", settings))\n{\n // Write XML data.\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"price\", \"19.95\");\n writer.WriteEndElement();\n writer.Flush();\n}\n"
},
{
"answer_id": 195060,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 4,
"selected": false,
"text": "string theString = \"<nodeName>blah</nodeName>\";\nXDocument doc = XDocument.Parse(theString);\n string theString = \"<nodeName>blah</nodeName>\";\nXElement element = XElement.Parse(theString);\n string theString = \"blah\";\n//creates <nodeName>blah</nodeName>\nXElement element = new XElement(XName.Get(\"nodeName\"), theString); \n"
},
{
"answer_id": 195077,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 1,
"selected": false,
"text": "string myText = \"This & that > <> <\";\nmyText = System.Security.SecurityElement.Escape(myText);\n"
},
{
"answer_id": 196242,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 7,
"selected": true,
"text": "string unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nstring formattedXml = XElement.Parse(unformattedXml).ToString();\nConsole.WriteLine(formattedXml);\n <book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n XElement.Parse(unformattedXml).Save(@\"C:\\doc.xml\");\n Console.WriteLine(File.ReadAllText(@\"C:\\doc.xml\"));\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n"
},
{
"answer_id": 196738,
"author": "JohnnyM",
"author_id": 27109,
"author_profile": "https://Stackoverflow.com/users/27109",
"pm_score": 2,
"selected": false,
"text": "private static string FormatXmlString(string xmlString)\n{\n System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);\n return element.ToString();\n}\n"
},
{
"answer_id": 3475029,
"author": "Daniel Bradley",
"author_id": 366550,
"author_profile": "https://Stackoverflow.com/users/366550",
"pm_score": 3,
"selected": false,
"text": "string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nformattedXml = System.Xml.Linq.XDocument.Parse(unformattedXml).ToString();\n\nConsole.WriteLine(formattedXml);\n string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nSystem.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.LoadXml(unformattedXml);\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nSystem.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb, new System.Xml.XmlWriterSettings() { Indent = true });\ndoc.WriteTo(xw);\nxw.Flush();\nformattedXml = sb.ToString();\nConsole.WriteLine(formattedXml);\n"
},
{
"answer_id": 11421415,
"author": "radarbob",
"author_id": 463206,
"author_profile": "https://Stackoverflow.com/users/463206",
"pm_score": 0,
"selected": false,
"text": "XElement formattedXML = new XElement.Parse(unformattedXmlString);\nConsole.WriteLine(formattedXML.ToString());\n"
},
{
"answer_id": 16184805,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 1,
"selected": false,
"text": "var unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nvar xdoc = System.Xml.Linq.XDocument.Parse(unformattedXml);\nvar formattedXml = (xdoc.Declaration != null ? xdoc.Declaration + \"\\r\\n\" : \"\") + xdoc.ToString();\nConsole.WriteLine(formattedXml);\n <?xml version=\"1.0\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27109/"
] |
194,976
|
<p>I thought the web page designer screen in 2005 was mediocre until I used the one in 2008 which I think is bad. There is an interesting white paper here:</p>
<p><a href="http://www.west-wind.com/weblog/posts/484172.aspx" rel="nofollow noreferrer">http://www.west-wind.com/weblog/posts/484172.aspx</a></p>
<p>I've gotten very used to these WYSIWYG designers over the years, but I am looking now for a new way. </p>
<p>I make business web apps which call for data entry forms. I don't need anything particularly artistic, but I do need to be able to line up text boxes etc on input forms so that they lkook orderly and are convenient for the user. I use Telerik controls, and my skills with CSS are approaching passable.</p>
<p>People often mention that they don't use the designer, but they rarely state what approach they DO use.</p>
<p>What are some of the alternatives to using the VS designer? </p>
|
[
{
"answer_id": 194951,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 0,
"selected": false,
"text": "XmlDocument xml = new XmlDocument();\n\nxml.LoadXml( YourString );\n"
},
{
"answer_id": 194956,
"author": "defeated",
"author_id": 16997,
"author_profile": "https://Stackoverflow.com/users/16997",
"pm_score": 3,
"selected": false,
"text": "writer.Formatting = Formatting.Indented;\nwriter.Indentation = 1;\nwriter.IndentChar = '\\t';\n"
},
{
"answer_id": 194996,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 4,
"selected": false,
"text": "XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\" \");\nusing (XmlWriter writer = XmlWriter.Create(\"books.xml\", settings))\n{\n // Write XML data.\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"price\", \"19.95\");\n writer.WriteEndElement();\n writer.Flush();\n}\n"
},
{
"answer_id": 195060,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 4,
"selected": false,
"text": "string theString = \"<nodeName>blah</nodeName>\";\nXDocument doc = XDocument.Parse(theString);\n string theString = \"<nodeName>blah</nodeName>\";\nXElement element = XElement.Parse(theString);\n string theString = \"blah\";\n//creates <nodeName>blah</nodeName>\nXElement element = new XElement(XName.Get(\"nodeName\"), theString); \n"
},
{
"answer_id": 195077,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 1,
"selected": false,
"text": "string myText = \"This & that > <> <\";\nmyText = System.Security.SecurityElement.Escape(myText);\n"
},
{
"answer_id": 196242,
"author": "Wonko",
"author_id": 14842,
"author_profile": "https://Stackoverflow.com/users/14842",
"pm_score": 7,
"selected": true,
"text": "string unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nstring formattedXml = XElement.Parse(unformattedXml).ToString();\nConsole.WriteLine(formattedXml);\n <book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n XElement.Parse(unformattedXml).Save(@\"C:\\doc.xml\");\n Console.WriteLine(File.ReadAllText(@\"C:\\doc.xml\"));\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n"
},
{
"answer_id": 196738,
"author": "JohnnyM",
"author_id": 27109,
"author_profile": "https://Stackoverflow.com/users/27109",
"pm_score": 2,
"selected": false,
"text": "private static string FormatXmlString(string xmlString)\n{\n System.Xml.Linq.XElement element = System.Xml.Linq.XElement.Parse(xmlString);\n return element.ToString();\n}\n"
},
{
"answer_id": 3475029,
"author": "Daniel Bradley",
"author_id": 366550,
"author_profile": "https://Stackoverflow.com/users/366550",
"pm_score": 3,
"selected": false,
"text": "string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nformattedXml = System.Xml.Linq.XDocument.Parse(unformattedXml).ToString();\n\nConsole.WriteLine(formattedXml);\n string unformattedXml;\nstring formattedXml;\n\nunformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nSystem.Xml.XmlDocument doc = new System.Xml.XmlDocument();\ndoc.LoadXml(unformattedXml);\nSystem.Text.StringBuilder sb = new System.Text.StringBuilder();\nSystem.Xml.XmlWriter xw = System.Xml.XmlTextWriter.Create(sb, new System.Xml.XmlWriterSettings() { Indent = true });\ndoc.WriteTo(xw);\nxw.Flush();\nformattedXml = sb.ToString();\nConsole.WriteLine(formattedXml);\n"
},
{
"answer_id": 11421415,
"author": "radarbob",
"author_id": 463206,
"author_profile": "https://Stackoverflow.com/users/463206",
"pm_score": 0,
"selected": false,
"text": "XElement formattedXML = new XElement.Parse(unformattedXmlString);\nConsole.WriteLine(formattedXML.ToString());\n"
},
{
"answer_id": 16184805,
"author": "midspace",
"author_id": 294393,
"author_profile": "https://Stackoverflow.com/users/294393",
"pm_score": 1,
"selected": false,
"text": "var unformattedXml = \"<?xml version=\\\"1.0\\\"?><book><author>Lewis, C.S.</author><title>The Four Loves</title></book>\";\nvar xdoc = System.Xml.Linq.XDocument.Parse(unformattedXml);\nvar formattedXml = (xdoc.Declaration != null ? xdoc.Declaration + \"\\r\\n\" : \"\") + xdoc.ToString();\nConsole.WriteLine(formattedXml);\n <?xml version=\"1.0\"?>\n<book>\n <author>Lewis, C.S.</author>\n <title>The Four Loves</title>\n</book>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
194,999
|
<p>On an ASP.NET website, are static classes unique to each web request, or are they instantiated whenever needed and GCed whenever the GC decides to disposed of them?</p>
<p>The reason I ask is because I've written some static classes before in C# and the behavior is different than I would have expected. I would have expected static classes to be unique to each request, but it doesn't seem like that is the case.</p>
<p>If they are not unique to each request, is there a way to allow them to be?</p>
<p><strong>UPDATE:</strong><br>
The answer driis gave me was exactly what I needed. I was already using a singleton class, however it was using a static instance and therefore was being shared between requests even if the users were different which in this case was a bad thing. Using <code>HttpContext.Current.Items</code> solves my problem perfectly. For anyone who stumbles upon this question in the future, here is my implementation, simplified and shortened so that it easy to understand the pattern:</p>
<pre><code>using System.Collections;
using System.Web;
public class GloballyAccessibleClass
{
private GloballyAccessibleClass() { }
public static GloballyAccessibleClass Instance
{
get
{
IDictionary items = HttpContext.Current.Items;
if(!items.Contains("TheInstance"))
{
items["TheInstance"] = new GloballyAccessibleClass();
}
return items["TheInstance"] as GloballyAccessibleClass;
}
}
}
</code></pre>
|
[
{
"answer_id": 195290,
"author": "driis",
"author_id": 13627,
"author_profile": "https://Stackoverflow.com/users/13627",
"pm_score": 8,
"selected": true,
"text": "HttpContext.Current.Items HttpContext.Current.Items"
},
{
"answer_id": 195297,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 2,
"selected": false,
"text": "Application ThreadStatic HttpContext.Current.Items HttpContext.Current.Session Server.Transfer"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/194999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/392/"
] |
195,008
|
<p>What is code coverage and how do YOU measure it?</p>
<p>I was asked this question regarding our automating testing code coverage. It seems to be that, outside of automated tools, it is more art than science. Are there any real-world examples of how to use code coverage?</p>
|
[
{
"answer_id": 195044,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 8,
"selected": false,
"text": "if(customer.IsOldCustomer()) \n{\n}\nelse \n{\n}\n"
},
{
"answer_id": 195392,
"author": "moritz",
"author_id": 14132,
"author_profile": "https://Stackoverflow.com/users/14132",
"pm_score": 3,
"selected": false,
"text": "./Build testcover"
},
{
"answer_id": 56124553,
"author": "taha027",
"author_id": 1888169,
"author_profile": "https://Stackoverflow.com/users/1888169",
"pm_score": 1,
"selected": false,
"text": "iOS OSX"
},
{
"answer_id": 73251575,
"author": "Inigo",
"author_id": 8910547,
"author_profile": "https://Stackoverflow.com/users/8910547",
"pm_score": 0,
"selected": false,
"text": "(1, 1) 1 function max(a, b) {\n return a > b ? a : b\n}\n function max(a, b) {\n if (a > b) {\n return a\n } else {\n return b\n }\n}\n function max(a, b) {\n return a > b ?\n a :\n b\n}\n max (2, 1) (1, 2) (1, 1) (null, 1) (1, null) function max(a, b) {\n if (typeof a !== 'number' || typeof b !== 'number') {\n return undefined\n }\n return a > b ? a : b\n}\n a > b"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
195,010
|
<p>I have an array of 1000 or so entries, with examples below:</p>
<pre><code>wickedweather
liquidweather
driveourtrucks
gocompact
slimprojector
</code></pre>
<p>I would like to be able to split these into their respective words, as:</p>
<pre><code>wicked weather
liquid weather
drive our trucks
go compact
slim projector
</code></pre>
<p>I was hoping a regular expression my do the trick. But, since there is no boundary to stop on, nor is there any sort of capitalization that I could possibly key on, I am thinking, that some sort of reference to a dictionary might be necessary? </p>
<p>I suppose it could be done by hand, but why - when it can be done with code! =) But this has stumped me. Any ideas? </p>
|
[
{
"answer_id": 195024,
"author": "SquareCog",
"author_id": 15962,
"author_profile": "https://Stackoverflow.com/users/15962",
"pm_score": 6,
"selected": true,
"text": "#!/usr/bin/env perl\n\nuse strict;\nuse warnings;\n\nsub find_matches($);\nsub find_matches_rec($\\@\\@);\nsub find_word_seq_score(@);\nsub get_word_stats($);\nsub print_results($@);\nsub Usage();\n\nour(%DICT,$TOTAL);\n{\n my( $dict_file, $word_file ) = @ARGV;\n ($dict_file && $word_file) or die(Usage);\n\n {\n my $DICT;\n ($DICT, $TOTAL) = get_word_stats($dict_file);\n %DICT = %$DICT;\n }\n\n {\n open( my $WORDS, '<', $word_file ) or die \"unable to open $word_file\\n\";\n\n foreach my $word (<$WORDS>) {\n chomp $word;\n my $arr = find_matches($word);\n\n\n local $_;\n # Schwartzian Transform\n my @sorted_arr =\n map { $_->[0] }\n sort { $b->[1] <=> $a->[1] }\n map {\n [ $_, find_word_seq_score(@$_) ]\n }\n @$arr;\n\n\n print_results( $word, @sorted_arr );\n }\n\n close $WORDS;\n }\n}\n\n\nsub find_matches($){\n my( $string ) = @_;\n\n my @found_parses;\n my @words;\n find_matches_rec( $string, @words, @found_parses );\n\n return @found_parses if wantarray;\n return \\@found_parses;\n}\n\nsub find_matches_rec($\\@\\@){\n my( $string, $words_sofar, $found_parses ) = @_;\n my $length = length $string;\n\n unless( $length ){\n push @$found_parses, $words_sofar;\n\n return @$found_parses if wantarray;\n return $found_parses;\n }\n\n foreach my $i ( 2..$length ){\n my $prefix = substr($string, 0, $i);\n my $suffix = substr($string, $i, $length-$i);\n\n if( exists $DICT{$prefix} ){\n my @words = ( @$words_sofar, $prefix );\n find_matches_rec( $suffix, @words, @$found_parses );\n }\n }\n\n return @$found_parses if wantarray;\n return $found_parses;\n}\n\n\n## Just a simple joint probability\n## assumes independence between words, which is obviously untrue\n## that's why this is broken out -- feel free to add better brains\nsub find_word_seq_score(@){\n my( @words ) = @_;\n local $_;\n\n my $score = 1;\n foreach ( @words ){\n $score = $score * $DICT{$_} / $TOTAL;\n }\n\n return $score;\n}\n\nsub get_word_stats($){\n my ($filename) = @_;\n\n open(my $DICT, '<', $filename) or die \"unable to open $filename\\n\";\n\n local $/= undef;\n local $_;\n my %dict;\n my $total = 0;\n\n while ( <$DICT> ){\n foreach ( split(/\\b/, $_) ) {\n $dict{$_} += 1;\n $total++;\n }\n }\n\n close $DICT;\n\n return (\\%dict, $total);\n}\n\nsub print_results($@){\n #( 'word', [qw'test one'], [qw'test two'], ... )\n my ($word, @combos) = @_;\n local $_;\n my $possible = scalar @combos;\n\n print \"$word: $possible possibilities\\n\";\n foreach (@combos) {\n print ' - ', join(' ', @$_), \"\\n\";\n }\n print \"\\n\";\n}\n\nsub Usage(){\n return \"$0 /path/to/dictionary /path/to/your_words\";\n}\n"
},
{
"answer_id": 195085,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/perl\n\nuse strict;\n\nmy $WORD_FILE = '/usr/share/dict/words'; #Change as needed\nmy %words; # Hash of words in dictionary\n\n# Open dictionary, load words into hash\nopen(WORDS, $WORD_FILE) or die \"Failed to open dictionary: $!\\n\";\nwhile (<WORDS>) {\n chomp;\n $words{lc($_)} = 1;\n}\nclose(WORDS);\n\n# Read one line at a time from stdin, break into words\nwhile (<>) {\n chomp;\n my @words;\n find_words(lc($_));\n}\n\nsub find_words {\n # Print every way $string can be parsed into whole words\n my $string = shift;\n my @words = @_;\n my $length = length $string;\n\n foreach my $i ( 1 .. $length ) {\n my $word = substr $string, 0, $i;\n my $remainder = substr $string, $i, $length - $i;\n # Some dictionaries contain each letter as a word\n next if ($i == 1 && ($word ne \"a\" && $word ne \"i\"));\n\n if (defined($words{$word})) {\n push @words, $word;\n if ($remainder eq \"\") {\n print join(' ', @words), \"\\n\";\n return;\n } else {\n find_words($remainder, @words);\n }\n pop @words;\n }\n }\n\n return;\n}\n"
},
{
"answer_id": 481773,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 6,
"selected": false,
"text": "import re\nfrom collections import Counter\n\ndef viterbi_segment(text):\n probs, lasts = [1.0], [0]\n for i in range(1, len(text) + 1):\n prob_k, k = max((probs[j] * word_prob(text[j:i]), j)\n for j in range(max(0, i - max_word_length), i))\n probs.append(prob_k)\n lasts.append(k)\n words = []\n i = len(text)\n while 0 < i:\n words.append(text[lasts[i]:i])\n i = lasts[i]\n words.reverse()\n return words, probs[-1]\n\ndef word_prob(word): return dictionary[word] / total\ndef words(text): return re.findall('[a-z]+', text.lower()) \ndictionary = Counter(words(open('big.txt').read()))\nmax_word_length = max(map(len, dictionary))\ntotal = float(sum(dictionary.values()))\n >>> viterbi_segment('wickedweather')\n(['wicked', 'weather'], 5.1518198982768158e-10)\n>>> ' '.join(viterbi_segment('itseasyformetosplitlongruntogetherblocks')[0])\n'its easy for me to split long run together blocks'\n"
},
{
"answer_id": 49440472,
"author": "mhucka",
"author_id": 743730,
"author_profile": "https://Stackoverflow.com/users/743730",
"pm_score": 2,
"selected": false,
"text": "J2SEProjectTypeProfiler J2SE Project Type Profiler J2SE # spiral mStartCData nonnegativedecimaltype getUtf8Octets GPSmodule savefileas nbrOfbugs\nmStartCData: ['m', 'Start', 'C', 'Data']\nnonnegativedecimaltype: ['nonnegative', 'decimal', 'type']\ngetUtf8Octets: ['get', 'Utf8', 'Octets']\nGPSmodule: ['GPS', 'module']\nsavefileas: ['save', 'file', 'as']\nnbrOfbugs: ['nbr', 'Of', 'bugs']\n # spiral wickedweather liquidweather driveourtrucks gocompact slimprojector\nwickedweather: ['wicked', 'weather']\nliquidweather: ['liquid', 'weather']\ndriveourtrucks: ['driveourtrucks']\ngocompact: ['go', 'compact']\nslimprojector: ['slim', 'projector']\n driveourtrucks"
},
{
"answer_id": 54210972,
"author": "adam shamsudeen",
"author_id": 6741167,
"author_profile": "https://Stackoverflow.com/users/6741167",
"pm_score": 1,
"selected": false,
"text": "from mlmorph import Analyser\nanalyser = Analyser()\nanalyser.analyse(\"കേരളത്തിന്റെ\")\n [('കേരളം<np><genitive>', 179)]\n"
},
{
"answer_id": 57733635,
"author": "Rabash",
"author_id": 3266110,
"author_profile": "https://Stackoverflow.com/users/3266110",
"pm_score": 2,
"selected": false,
"text": "pip install wordsegment $ echo thisisatest | python -m wordsegment\nthis is a test\n"
},
{
"answer_id": 58010290,
"author": "kamran kausar",
"author_id": 3486460,
"author_profile": "https://Stackoverflow.com/users/3486460",
"pm_score": 4,
"selected": false,
"text": ">>> import wordninja\n>>> wordninja.split('bettergood')\n['better', 'good']\n"
},
{
"answer_id": 61159132,
"author": "Naphtali Duniya",
"author_id": 7892029,
"author_profile": "https://Stackoverflow.com/users/7892029",
"pm_score": 1,
"selected": false,
"text": "function spinalCase(str) {\n let lowercase = str.trim()\n let regEx = /\\W+|(?=[A-Z])|_/g\n let result = lowercase.split(regEx).join(\"-\").toLowerCase()\n\n return result;\n}\n\nspinalCase(\"AllThe-small Things\");\n"
},
{
"answer_id": 64449782,
"author": "Vishrant",
"author_id": 2704032,
"author_profile": "https://Stackoverflow.com/users/2704032",
"pm_score": 1,
"selected": false,
"text": "static List<String> wordBreak(\n String input,\n Set<String> dictionary\n) {\n\n List<List<String>> result = new ArrayList<>();\n List<String> r = new ArrayList<>();\n\n helper(input, dictionary, result, \"\", 0, new Stack<>());\n\n for (List<String> strings : result) {\n String s = String.join(\" \", strings);\n r.add(s);\n }\n\n return r;\n}\n\nstatic void helper(\n final String input,\n final Set<String> dictionary,\n final List<List<String>> result,\n String state,\n int index,\n Stack<String> stack\n) {\n\n if (index == input.length()) {\n\n // add the last word\n stack.push(state);\n\n for (String s : stack) {\n if (!dictionary.contains(s)) {\n return;\n }\n }\n\n result.add((List<String>) stack.clone());\n\n return;\n }\n\n if (dictionary.contains(state)) {\n // bifurcate\n stack.push(state);\n helper(input, dictionary, result, \"\" + input.charAt(index),\n index + 1, stack);\n\n String pop = stack.pop();\n String s = stack.pop();\n\n helper(input, dictionary, result, s + pop.charAt(0),\n index + 1, stack);\n\n }\n else {\n helper(input, dictionary, result, state + input.charAt(index),\n index + 1, stack);\n }\n\n return;\n}\n Tries"
},
{
"answer_id": 68095697,
"author": "Mukund Biradar",
"author_id": 11431613,
"author_profile": "https://Stackoverflow.com/users/11431613",
"pm_score": 1,
"selected": false,
"text": "output :-\n['better', 'good'] ['coffee', 'shop']\n['coffee', 'shop']\n\n pip install wordninja\nimport wordninja\nn=wordninja.split('bettergood')\nm=wordninja.split(\"coffeeshop\")\nprint(n,m)\n\nlist=['hello','coffee','shop','better','good']\nmat='coffeeshop'\nexpected=[]\nfor i in list:\n if i in mat:\n expected.append(i)\nprint(expected)\n"
},
{
"answer_id": 70162407,
"author": "Jimmy Slagle",
"author_id": 17546121,
"author_profile": "https://Stackoverflow.com/users/17546121",
"pm_score": 1,
"selected": false,
"text": "word_frequency * (e ** word_length) import numpy as np\nfrom wordfreq import get_frequency_dict\n\nword_prob = get_frequency_dict(lang='en', wordlist='large')\nmax_word_len = max(map(len, word_prob)) # 34\n\ndef viterbi_segment(text, debug=False):\n probs, lasts = [1.0], [0]\n for i in range(1, len(text) + 1):\n new_probs = []\n for j in range(max(0, i - max_word_len), i):\n substring = text[j:i]\n length_reward = np.exp(len(substring))\n freq = word_prob.get(substring, 0) * length_reward\n compounded_prob = probs[j] * freq\n new_probs.append((compounded_prob, j))\n \n if debug:\n print(f'[{j}:{i}] = \"{text[lasts[j]:j]} & {substring}\" = ({probs[j]:.8f} & {freq:.8f}) = {compounded_prob:.8f}')\n\n prob_k, k = max(new_probs) # max of a touple is the max across the first elements, which is the max of the compounded probabilities\n probs.append(prob_k)\n lasts.append(k)\n\n if debug:\n print(f'i = {i}, prob_k = {prob_k:.8f}, k = {k}, ({text[k:i]})\\n')\n\n\n # when text is a word that doesn't exist, the algorithm breaks it into individual letters.\n # in that case, return the original word instead\n if len(set(lasts)) == len(text):\n return text\n\n words = []\n k = len(text)\n while 0 < k:\n word = text[lasts[k]:k]\n words.append(word)\n k = lasts[k]\n words.reverse()\n return ' '.join(words)\n\ndef split_message(message):\n new_message = ' '.join(viterbi_segment(wordmash, debug=False) for wordmash in message.split())\n return new_message\n\nmessages = [\n 'tosplit',\n 'split',\n 'driveourtrucks',\n \"Slagle's\",\n \"Slagle's wickedweather liquidweather driveourtrucks gocompact slimprojector\",\n 'itseasyformetosplitlongruntogetherblocks',\n]\n\nfor message in messages:\n print(f'{message}')\n new_message = split_message(message)\n print(f'{new_message}\\n')\n tosplit\nto split\n\nsplit\nsplit\n\ndriveourtrucks\ndrive our trucks\n\nSlagle's\nSlagle's\n\nSlagle's wickedweather liquidweather driveourtrucks gocompact slimprojector\nSlagle's wicked weather liquid weather drive our trucks go compact slim projector\n\nitseasyformetosplitlongruntogetherblocks\nits easy for me to split long run together blocks\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14728/"
] |
195,020
|
<p>I've just started using Java's enums in my own projects (I have to use JDK 1.4 at work) and I am confused as to the best practice of using JavaDoc for an enum.</p>
<p>I have found that this method works, but the resultant code is a little unrefined:</p>
<pre><code>/**
* Doc for enum
*/
public enum Something {
/**
* First thing
*/
FIRST_THING,
/**
* Second thing
*/
SECOND_THING;
//could continue with more
}
</code></pre>
<p>Is there any way I could break up the enum declarations on their own lines without chaining them by commas, or is this the best approach for using JavaDoc for an enum?</p>
|
[
{
"answer_id": 195105,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 4,
"selected": false,
"text": "Something values are used to indicate which mode of operation a client wishes... FIRST_THING indicates that the operation should evaluate the first argument first.. /** Evaluate first argument first. */"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8026/"
] |
195,036
|
<p>I've been researching PHP frameworks as of late for some personal projects, and it looks like most of them use a front controller to mimic a response. The controller gets the params from the request, and re-routes by sending the appropriate headers depending on the logic. This is the "response". Is this the best way to do this in PHP, or are there other theories about how to handle re-routing and responses?</p>
|
[
{
"answer_id": 195047,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "switch($_GET['page']) {\n case \"one\";\n print \"page one!\";\n break;\n default:\n print \"default page\";\n break;\n}\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
195,058
|
<p>Below is my $.ajax call, how do I put a selects (multiple) selected values in the data section?</p>
<pre><code>$.ajax({
type: "post",
url: "http://myServer" ,
dataType: "text",
data: {
'service' : 'myService',
'program' : 'myProgram',
'start' : start,
'end' : end ,
},
success: function(request) {
result.innerHTML = request ;
} // End success
}); // End ajax method
</code></pre>
<p><strong>EDIT</strong> I should have included that I understand how to loop through the selects selected options with this code:</p>
<pre><code>$('#userid option').each(function(i) {
if (this.selected == true) {
</code></pre>
<p>but how do I fit that into my data: section?</p>
|
[
{
"answer_id": 195064,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "data: {\n ...\n 'select' : ['value1', 'value2', 'value3'],\n ...\n},\n 'select' : $('#myselectbox').serializeArray(),\n 'select' 'select' : [\n { 'name' : 'box', 'value' : 1 },\n { 'name' : 'box', 'value' : 2 }\n],\n <select multiple=\"true\" name=\"box\" id=\"myselectbox\">\n <option value=\"1\" name=\"option1\" selected=\"selected\">One</option>\n <option value=\"2\" name=\"option2\" selected=\"selected\">Two</option>\n <option value=\"3\" name=\"option3\">Three</option>\n</select>\n"
},
{
"answer_id": 196274,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 2,
"selected": false,
"text": " var mySelections = [];\n $('#mySelect option').each(function(i) {\n if (this.selected == true) {\n mySelections.push(this.value);\n }\n });\n\n\n $.ajax({\n type: \"post\",\n url: \"http://myServer\" ,\n dataType: \"text\",\n data: {\n 'service' : 'myService',\n 'program' : 'myProgram',\n 'selected' : mySelections\n },\n success: function(request) {\n result.innerHTML = request ;\n }\n }); // End ajax method\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
195,061
|
<p>I have some assembly that references NUnit and creates a single test class with a single test method. I am able to get the file system path to this assembly (e.g. "C:...\test.dll"). I would like to programmatically use NUnit to run against this assembly.</p>
<p>So far I have:</p>
<pre><code>var runner = new SimpleTestRunner();
runner.Load(path);
var result = runner.Run(NullListener.NULL);
</code></pre>
<p>However, calling runner.Load(path) throws a FileNotFound exception. I can see through the stack trace that the problem is with NUnit calling Assembly.Load(path) down the stack. If I change path to be something like "Test, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" then I still get the same error.</p>
<p>I have added an event handler to AppDomain.Current.AssemblyResolve to see if I could manually resolve this type but my handler never gets called.</p>
<p>What is the secret to getting Assembly.Load(...) to work??</p>
|
[
{
"answer_id": 195066,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 2,
"selected": false,
"text": "Assembly a = System.Reflection.Assembly.LoadFrom(pathToFileOnDisk);\n"
},
{
"answer_id": 450076,
"author": "Ricibald",
"author_id": 20409,
"author_profile": "https://Stackoverflow.com/users/20409",
"pm_score": 6,
"selected": true,
"text": "NUnit.ConsoleRunner.Runner.Main(new string[]\n {\n System.Reflection.Assembly.GetExecutingAssembly().Location, \n });\n NUnit.Gui.AppEntry.Main(new string[]\n {\n System.Reflection.Assembly.GetExecutingAssembly().Location, \n \"/run\"\n });\n public static void Main()\n{\n var assembly = Assembly.GetExecutingAssembly().FullName;\n new TextUI (new DebugTextWriter()).Execute(new[] { assembly, \"-wait\" });\n}\n\npublic class DebugTextWriter : StreamWriter\n{\n public DebugTextWriter()\n : base(new DebugOutStream(), Encoding.Unicode, 1024)\n {\n this.AutoFlush = true;\n }\n\n class DebugOutStream : Stream\n {\n public override void Write(byte[] buffer, int offset, int count)\n {\n Debug.Write(Encoding.Unicode.GetString(buffer, offset, count));\n }\n\n public override bool CanRead { get { return false; } }\n public override bool CanSeek { get { return false; } }\n public override bool CanWrite { get { return true; } }\n public override void Flush() { Debug.Flush(); }\n public override long Length { get { throw new InvalidOperationException(); } }\n public override int Read(byte[] buffer, int offset, int count) { throw new InvalidOperationException(); }\n public override long Seek(long offset, SeekOrigin origin) { throw new InvalidOperationException(); }\n public override void SetLength(long value) { throw new InvalidOperationException(); }\n public override long Position\n {\n get { throw new InvalidOperationException(); }\n set { throw new InvalidOperationException(); }\n }\n };\n}\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195061",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12958/"
] |
195,070
|
<p>I would like the fastest and most accurate function <code>boolean isReachable(String host, int port)</code> that passes the following JUnit tests under the conditions below. Timeout values are specified by the JUnit test itself, and may be considered "unreachable."</p>
<p><strong>Please note:</strong> All answers must be platform-independent. This means that <code>InetAddress.isReachable(int timeout)</code> is not going to work, since it relies on port <code>7</code> to do a ping on Windows (ICMP ping being an undocumented function on Windows), and this port is blocked in this setup.</p>
<p>LAN Setup:</p>
<ul>
<li><code>thisMachine</code> (<code>192.168.0.100</code>)</li>
<li><code>otherMachine</code> (<code>192.168.0.200</code>)</li>
<li><strong>no</strong> machine is called <code>noMachine</code> or has the IP <code>192.168.0.222</code> (always unreachable)</li>
<li>both machines are running Apache Tomcat on port <code>8080</code>; all other ports are unreachable (including port <code>7</code>)</li>
<li><code>example.com</code> (<code>208.77.188.166</code>) is running a webserver on port <code>80</code> and is only reachable when the LAN is connected to the Internet</li>
</ul>
<p>Occasionally, the LAN is disconnected from the Internet in which case only local machines called by IP address are reachable (all others are unreachable; there's no DNS).</p>
<p><strong>All tests are run on <code>thisMachine</code>.</strong></p>
<pre><code>@Test(timeout=1600) // ~320ms per call (should be possible to do better)
public void testLocalhost() {
// We can always reach ourselves.
assertTrue(isReachable("localhost", 8080));
assertTrue(isReachable("127.0.0.1", 8080));
assertTrue(isReachable("thisMachine", 8080)); // Even if there's no DNS!
assertTrue(isReachable("192.168.0.100", 8080));
assertFalse(isReachable("localhost", 80)); // Nothing on that port.
}
@Test(timeout=5500) // ~1867ms per call (should be able to do better)
public void testLAN() {
assertTrue(isReachable("192.168.0.200", 8080)); // Always connected to the LAN.
assertFalse(isReachable("192.168.0.222", 8080)); // No such a machine.
assertFalse(isReachable("noMachine", 8080)); // No such machine.
}
</code></pre>
<p>The following test is only run when the LAN is <strong>disconnected</strong> from the Internet.</p>
<pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testNoDNS() {
assertFalse(isReachable("otherMachine", 8080)); // No DNS.
assertFalse(isReachable("example.com", 80)); // No DNS & no Internet.
assertFalse(isReachable("208.77.188.166", 80)); // No Internet.
}
</code></pre>
<p>The following test is only run when the LAN is <strong>connected</strong> to the Internet.</p>
<pre><code>@Test(timeout=5600) // ~1867ms per call (reasonable?)
public void testHaveDNS() {
assertTrue(isReachable("otherMachine", 8080)); // DNS resolves local names.
assertTrue(isReachable("example.com", 80)); // DNS available.
assertTrue(isReachable("208.77.188.166", 80)); // Internet available.
}
</code></pre>
|
[
{
"answer_id": 195071,
"author": "grammar31",
"author_id": 12815,
"author_profile": "https://Stackoverflow.com/users/12815",
"pm_score": 0,
"selected": false,
"text": "TimedSocket testLocalHost() testLAN() testNoDNS() testHaveDNS()"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12815/"
] |
195,072
|
<p>I'm experiencing what I believe is a circular dependency issue with my PHP application. Please let me know if this is incorrect. Here is the situation:</p>
<p>Two classes, LogManager and DBSession.</p>
<p>DBSession is used to interact with the database, and LogManager is used to log to files. Both are widely used in my application. When you create an instance of DBSession, you must give it an instance of LogManager via a constructor parameter. This because DBSession will sometimes log information to a file, and will use the LogManager instance to do this. </p>
<p>Now, I wanted to extend LogManager so that it could also log to a database table, rather than a text file. Naturally, my preference is to re-use existing classes, but I soon realized this brought about an interesting situation.</p>
<p>DBSession already requires an instance of LogManager for construction. If I want to re-use the DBSession class in LogManager, it will now require an instance of DBSession. How can I satisfy both demands? Clearly, something must be wrong with my approach.</p>
<p>How would you suggest I fix this?</p>
<p>Thanks in advance, guys.</p>
|
[
{
"answer_id": 195083,
"author": "Federico A. Ramponi",
"author_id": 18770,
"author_profile": "https://Stackoverflow.com/users/18770",
"pm_score": 4,
"selected": true,
"text": "$logManager = new LogManager();\n$dbSession = new DbSession($logManager);\n$logManager->add(new FileLog($filename) );\n$logManager->add(new DBLog($dbSession) );\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21263/"
] |
195,078
|
<p>I need to hide (make private) the <code>-init</code> method of my class in Objective-C.</p>
<p>How can I do that?</p>
|
[
{
"answer_id": 195107,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 2,
"selected": false,
"text": "init @interface MyClass (PrivateMethods)\n- (NSString*) init;\n@end\n\n@implementation MyClass\n\n- (NSString*) init\n{\n // code...\n}\n\n@end\n"
},
{
"answer_id": 195223,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 7,
"selected": true,
"text": "NSInternalInconsistencyException -init - (id)init {\n [self release];\n @throw [NSException exceptionWithName:NSInternalInconsistencyException\n reason:@\"-init is not a valid initializer for the class Foo\"\n userInfo:nil];\n return nil;\n}\n -init +allocWithZone: -init -retain -release +sharedWhatever"
},
{
"answer_id": 5772821,
"author": "Jano",
"author_id": 412916,
"author_profile": "https://Stackoverflow.com/users/412916",
"pm_score": 9,
"selected": false,
"text": "NS_UNAVAILABLE - (instancetype)init NS_UNAVAILABLE;\n #define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE - (instancetype)init NS_SWIFT_UNAVAILABLE;\n unavailable unavailable -(instancetype) init __attribute__((unavailable(\"init not available\"))); \n __attribute__((unavailable)) __unavailable -(instancetype) __unavailable init; \n doesNotRecognizeSelector: doesNotRecognizeSelector: - (instancetype) init {\n [self release];\n [super doesNotRecognizeSelector:_cmd];\n return nil;\n}\n NSAssert NSAssert - (instancetype) init {\n [self release];\n NSAssert(false,@\"unavailable, use initWithBlah: instead\");\n return nil;\n}\n raise:format: raise:format: - (instancetype) init {\n [self release];\n [NSException raise:NSGenericException \n format:@\"Disabled. Use +[[%@ alloc] %@] instead\",\n NSStringFromClass([self class]),\n NSStringFromSelector(@selector(initWithStateDictionary:))];\n return nil;\n}\n [self release] alloc objc_designated_initializer init -(instancetype)myOwnInit NS_DESIGNATED_INITIALIZER;\n myOwnInit"
},
{
"answer_id": 8431959,
"author": "Peter Lapisu",
"author_id": 533422,
"author_profile": "https://Stackoverflow.com/users/533422",
"pm_score": 2,
"selected": false,
"text": "static SomeClass * SInstance = nil;\n\n- (id)init\n{\n // possibly throw smth. here\n return nil;\n}\n\n- (id)initOnce\n{\n self = [super init];\n if (self) {\n return self;\n }\n return nil;\n}\n\n+ (SomeClass *) shared \n{\n if (nil == SInstance) {\n SInstance = [[SomeClass alloc] initOnce];\n }\n return SInstance;\n}\n SomeClass * c = [[SomeClass alloc] initOnce];\n"
},
{
"answer_id": 23644634,
"author": "techniao",
"author_id": 2400328,
"author_profile": "https://Stackoverflow.com/users/2400328",
"pm_score": 0,
"selected": false,
"text": "__unavailable - (SuperClass *)initWithParameters:(Type1 *)arg1 optional:(Type2 *)arg2\n{\n ...bla bla...\n return self;\n}\n\n- (SuperClass *)initWithLessParameters:(Type1 *)arg1\n{\n self = [self initWithParameters:arg1 optional:DEFAULT_ARG2];\n return self;\n}\n - (SubClass *)initWithParameters:(Type1 *)arg1 optional:(Type2 *)arg2\n{\n [self release];\n [super doesNotRecognizeSelector:_cmd];\n return nil;\n}\n"
},
{
"answer_id": 27693034,
"author": "lehn0058",
"author_id": 1199792,
"author_profile": "https://Stackoverflow.com/users/1199792",
"pm_score": 7,
"selected": false,
"text": "- (instancetype)init NS_UNAVAILABLE;\n"
},
{
"answer_id": 30387880,
"author": "Jerry Juang",
"author_id": 2588432,
"author_profile": "https://Stackoverflow.com/users/2588432",
"pm_score": 2,
"selected": false,
"text": "- (id)init UNAVAILABLE_ATTRIBUTE;\n"
},
{
"answer_id": 45629903,
"author": "Kaunteya",
"author_id": 1311902,
"author_profile": "https://Stackoverflow.com/users/1311902",
"pm_score": 2,
"selected": false,
"text": "NS_UNAVAILABLE - (instancetype)init NS_UNAVAILABLE;\n+ (instancetype)new NS_UNAVAILABLE;\n #define NO_INIT \\\n- (instancetype)init NS_UNAVAILABLE; \\\n+ (instancetype)new NS_UNAVAILABLE;\n @interface YourClass : NSObject\nNO_INIT\n\n// Your properties and messages\n\n@end\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3740/"
] |
195,109
|
<p>Is it possible to programaticly run compiled Python (comiled via py2exe) as administrator in Vista?</p>
<p>Some more clarification:<br />
I have written a program that modifies the windows hosts file (c:\Windows\system32\drivers\etc\hosts) in Vista the program will not run and will fail with an exception unless you right-click and run as administrator even when the user has administrator privileges, unlike in XP where it will run if the user has administration rights, so I need a way to elevate it to the correct privileges programaticly.</p>
|
[
{
"answer_id": 196208,
"author": "John Fouhy",
"author_id": 15154,
"author_profile": "https://Stackoverflow.com/users/15154",
"pm_score": 2,
"selected": false,
"text": "# in setup.py\n# manifest copied from http://blogs.msdn.com/shawnfa/archive/2006/04/06/568563.aspx\nmanifest = '''\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <asmv3:trustInfo xmlns:asmv3=\"urn:schemas-microsoft-com:asm.v3\">\n <asmv3:security>\n <asmv3:requestedPrivileges>\n <asmv3:requestedExecutionLevel\n level=\"asInvoker\"\n uiAccess=\"false\" />\n </asmv3:requestedPrivileges>\n </asmv3:security>\n </asmv3:trustInfo>\n </assembly>\n'''\n\nsetup(name='MyApp',\n #...\n windows=[ { #...\n 'other_resources':[(24, 1, manifest)],\n }]\n )\n"
},
{
"answer_id": 1445547,
"author": "Ivaylo",
"author_id": 175637,
"author_profile": "https://Stackoverflow.com/users/175637",
"pm_score": 5,
"selected": false,
"text": "Python2x\\Lib\\site-packages\\py2exe\\samples\\user_access_control uac_info=\"requireAdministrator\" windows = [{\n 'script': \"admin.py\",\n 'uac_info': \"requireAdministrator\",\n},]\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
195,114
|
<p>I'm trying to do a custom button to my form (which has FormBorderStyle = none) using Visual Studio 2005. I have my 3 states button images in an ImageList linked to the button.</p>
<pre><code>this.btnClose.AutoSize = false;
this.btnClose.BackColor = System.Drawing.Color.Transparent;
this.btnClose.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.btnClose.FlatAppearance.BorderSize = 0;
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnClose.ForeColor = System.Drawing.Color.Transparent;
this.btnClose.ImageKey = "Disabled";
this.btnClose.ImageList = this.imageList1;
this.btnClose.Location = new System.Drawing.Point(368, -5);
this.btnClose.Margin = new System.Windows.Forms.Padding(0);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(31, 31);
this.btnClose.TabIndex = 0;
this.btnClose.UseVisualStyleBackColor = false;
this.btnClose.MouseLeave += new System.EventHandler(this.btnClose_MouseLeave);
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
this.btnClose.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnClose_MouseDown);
this.btnClose.MouseHover += new System.EventHandler(this.btnClose_MouseHover);
private void btnClose_MouseHover(object sender, EventArgs e)
{
btnClose.ImageKey = "enabled";
}
private void btnClose_MouseDown(object sender, MouseEventArgs e)
{
btnClose.ImageKey = "down";
}
private void btnClose_MouseLeave(object sender, EventArgs e)
{
btnClose.ImageKey = "disabled";
}
</code></pre>
<p>All is working, but there's one catch. Whenever I move the mouse hover the button I get a really annoying grey background.</p>
<p>How can I remove that?</p>
|
[
{
"answer_id": 196202,
"author": "Tute",
"author_id": 4386,
"author_profile": "https://Stackoverflow.com/users/4386",
"pm_score": 2,
"selected": false,
"text": "// \n// imageListButtons\n// \nthis.imageListButtons.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject(\"imageListButtons.ImageStream\")));\nthis.imageListButtons.TransparentColor = System.Drawing.Color.Transparent;\nthis.imageListButtons.Images.SetKeyName(0, \"close_normal\");\nthis.imageListButtons.Images.SetKeyName(1, \"close_hover\");\n// \n// lblClose\n// \nthis.lblClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));\nthis.lblClose.BackColor = System.Drawing.Color.Transparent;\nthis.lblClose.ImageKey = \"close_normal\";\nthis.lblClose.ImageList = this.imageListButtons;\nthis.lblClose.Location = new System.Drawing.Point(381, 7);\nthis.lblClose.Margin = new System.Windows.Forms.Padding(0);\nthis.lblClose.Name = \"lblClose\";\nthis.lblClose.Size = new System.Drawing.Size(12, 12);\nthis.lblClose.TabIndex = 0;\nthis.lblClose.MouseLeave += new System.EventHandler(this.lblClose_MouseLeave);\nthis.lblClose.MouseClick += new System.Windows.Forms.MouseEventHandler(this.lblClose_MouseClick);\nthis.lblClose.MouseEnter += new System.EventHandler(this.lblClose_MouseEnter);\n\n\nprivate void lblClose_MouseEnter(object sender, EventArgs e)\n{\n lblClose.ImageKey = \"close_hover\";\n}\n\nprivate void lblClose_MouseLeave(object sender, EventArgs e)\n{\n lblClose.ImageKey = \"close_normal\";\n}\n\nprivate void lblClose_MouseClick(object sender, MouseEventArgs e)\n{\n this.Close();\n}\n"
},
{
"answer_id": 2951036,
"author": "Vassili",
"author_id": 355568,
"author_profile": "https://Stackoverflow.com/users/355568",
"pm_score": 5,
"selected": false,
"text": "btnClose.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;\n"
},
{
"answer_id": 20713586,
"author": "Fazil Mir",
"author_id": 2902517,
"author_profile": "https://Stackoverflow.com/users/2902517",
"pm_score": 2,
"selected": false,
"text": "private void forAllButtons_MouseEnter(object sender, EventArgs e)\n{\n Button b = (Button)sender;\n b.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent;\n}\n"
},
{
"answer_id": 32729645,
"author": "Ahmed Suror",
"author_id": 1655837,
"author_profile": "https://Stackoverflow.com/users/1655837",
"pm_score": 2,
"selected": false,
"text": "base.OnMouseEnter(e)\n"
},
{
"answer_id": 35957916,
"author": "Peck_conyon",
"author_id": 3268370,
"author_profile": "https://Stackoverflow.com/users/3268370",
"pm_score": 1,
"selected": false,
"text": "this.btnClose.FlatStyle = FlatStyle.Flat;\n this.btnClose.FlatAppearance.MouseOverBackColor = Color.Transparent;\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4386/"
] |
195,116
|
<p>Does anyone know of a faster decimal implementation in python?</p>
<p>As the example below demonstrates, the standard library's decimal module is ~100 times slower than <code>float</code>.</p>
<pre class="lang-py prettyprint-override"><code>from timeit import Timer
def run(val, the_class):
test = the_class(1)
for c in xrange(10000):
d = the_class(val)
d + test
d - test
d * test
d / test
d ** test
str(d)
abs(d)
if __name__ == "__main__":
a = Timer("run(123.345, float)", "from decimal_benchmark import run")
print "FLOAT", a.timeit(1)
a = Timer("run('123.345', Decimal)", "from decimal_benchmark import run; from decimal import Decimal")
print "DECIMAL", a.timeit(1)
</code></pre>
<p><em>Outputs:</em></p>
<pre><code>FLOAT 0.040635041427
DECIMAL 3.39666790146
</code></pre>
|
[
{
"answer_id": 8192918,
"author": "Andrew G",
"author_id": 995672,
"author_profile": "https://Stackoverflow.com/users/995672",
"pm_score": 5,
"selected": false,
"text": "from cdecimal import Decimal\n decimal decimal cdecimal decimal"
},
{
"answer_id": 24408798,
"author": "Joel Santirso",
"author_id": 567959,
"author_profile": "https://Stackoverflow.com/users/567959",
"pm_score": 2,
"selected": false,
"text": "a = Timer(\"run('123.345', Decimal)\", \"import sys; import cdecimal; sys.modules['decimal'] = cdecimal; from decimal_benchmark import run; from decimal import Decimal\")\nprint \"CDECIMAL\", a.timeit(1)\n FLOAT 0.0257983528473\nDECIMAL 2.45782495288\nCDECIMAL 0.0687125069413\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/52490/"
] |
195,149
|
<p>I'm wondering if it's possible to sandbox JavaScript running in the browser to prevent access to features that are normally available to JavaScript code running in an HTML page.</p>
<p>For example, let's say I want to provide a JavaScript API for end users to let them define event handlers to be run when "interesting events" happen, but I don't want those users to access the properties and functions of the <code>window</code> object. Am I able to do this?</p>
<p>In the simplest case, let's say I want to prevent users calling <code>alert</code>. A couple of approaches I can think of are:</p>
<ul>
<li>Redefine <code>window.alert</code> globally. I don't think this would be a valid approach because other code running in the page (i.e., stuff not authored by users in their event handlers) might want to use <code>alert</code>.</li>
<li>Send the event handler code to the server to process. I'm not sure that sending the code to the server to process is the right approach, because the event handlers need to run in the context of the page.</li>
</ul>
<p>Perhaps a solution where the server processes the user defined function and then generates a callback to be executed on the client would work? Even if that approach works, are there better ways to solve this problem?</p>
|
[
{
"answer_id": 195153,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": -1,
"selected": false,
"text": "undefined (function (alert) {\n\nalert (\"uh oh!\"); // User code\n\n}) ();\n"
},
{
"answer_id": 195156,
"author": "Dimitry",
"author_id": 27073,
"author_profile": "https://Stackoverflow.com/users/27073",
"pm_score": -1,
"selected": false,
"text": " eval(\n unsafeUserScript\n .replace(/\\/\\/.+\\n|\\/\\*.*\\*\\/, '') // Clear all comments\n .replace(/\\s(window|document)\\s*[\\;\\)\\.]/, '') // Removes window. Or window; or window)\n )\n window.location = 'http://example.com';\nvar w = window;\n"
},
{
"answer_id": 195280,
"author": "Sergey Ilinsky",
"author_id": 23815,
"author_profile": "https://Stackoverflow.com/users/23815",
"pm_score": -1,
"selected": false,
"text": " var sCode = \"alert(document)\";\n new Function(\"window\", \"with(window){\" + sCode + \"}\")({});\n new Function(\"window\", \"with(window){\" + sCode + \"}\")({\n 'alert':function(sString){document.title = sString}\n });\n"
},
{
"answer_id": 196064,
"author": "Simon Lieschke",
"author_id": 2766,
"author_profile": "https://Stackoverflow.com/users/2766",
"pm_score": 5,
"selected": false,
"text": "template.html template.js"
},
{
"answer_id": 888139,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "function Sandbox(parent){\n\n this.scope = {\n window: {\n alert: function(str){\n alert(\"Overriden Alert: \" + str);\n },\n prompt: function(message, defaultValue){\n return prompt(\"Overriden Prompt:\" + message, defaultValue);\n },\n document: null,\n .\n .\n .\n .\n }\n };\n\n this.execute = function(codestring){\n\n // Here some code sanitizing, please\n\n with (this.scope) {\n with (window) {\n eval(codestring);\n }\n }\n };\n}\n"
},
{
"answer_id": 1024707,
"author": "Eli Grey",
"author_id": 78436,
"author_profile": "https://Stackoverflow.com/users/78436",
"pm_score": 5,
"selected": false,
"text": "jsandbox\n .eval({\n code : \"x=1;Math.round(Math.pow(input, ++x))\",\n input : 36.565010597564445,\n callback: function(n) {\n console.log(\"number: \", n); // number: 1337\n }\n }).eval({\n code : \"][];.]\\\\ (*# ($(! ~\",\n onerror: function(ex) {\n console.log(\"syntax error: \", ex); // syntax error: [error object]\n }\n }).eval({\n code : '\"foo\"+input',\n input : \"bar\",\n callback: function(str) {\n console.log(\"string: \", str); // string: foobar\n }\n }).eval({\n code : \"({q:1, w:2})\",\n callback: function(obj) {\n console.log(\"object: \", obj); // object: object q=1 w=2\n }\n }).eval({\n code : \"[1, 2, 3].concat(input)\",\n input : [4, 5, 6],\n callback: function(arr) {\n console.log(\"array: \", arr); // array: [1, 2, 3, 4, 5, 6]\n }\n }).eval({\n code : \"function x(z){this.y=z;};new x(input)\",\n input : 4,\n callback: function(x) {\n console.log(\"new x: \", x); // new x: object y=4\n }\n });\n"
},
{
"answer_id": 22214371,
"author": "alejandro",
"author_id": 505002,
"author_profile": "https://Stackoverflow.com/users/505002",
"pm_score": 2,
"selected": false,
"text": "function construct(constructor, args) {\n function F() {\n return constructor.apply(this, args);\n }\n F.prototype = constructor.prototype;\n return new F();\n}\n// Sanboxer\nfunction sandboxcode(string, inject) {\n \"use strict\";\n var globals = [];\n for (var i in window) {\n // <--REMOVE THIS CONDITION\n if (i != \"console\")\n // REMOVE THIS CONDITION -->\n globals.push(i);\n }\n globals.push('\"use strict\";\\n'+string);\n return construct(Function, globals).apply(inject ? inject : {});\n}\nsandboxcode('console.log( this, window, top , self, parent, this[\"jQuery\"], (function(){return this;}()));');\n// => Object {} undefined undefined undefined undefined undefined undefined\nconsole.log(\"return of this\", sandboxcode('return this;', {window:\"sanboxed code\"}));\n// => Object {window: \"sanboxed code\"}\n"
},
{
"answer_id": 37154736,
"author": "MarcG",
"author_id": 3411681,
"author_profile": "https://Stackoverflow.com/users/3411681",
"pm_score": 4,
"selected": false,
"text": "eval.js function safeEval(untrustedCode)\n{\n return new Promise(function (resolve, reject)\n {\n var blobURL = URL.createObjectURL(new Blob([\n \"(\",\n function ()\n {\n var _postMessage = postMessage;\n var _addEventListener = addEventListener;\n\n (function (obj)\n {\n \"use strict\";\n\n var current = obj;\n var keepProperties =\n [\n // Required\n 'Object', 'Function', 'Infinity', 'NaN', 'undefined', 'caches', 'TEMPORARY', 'PERSISTENT',\n // Optional, but trivial to get back\n 'Array', 'Boolean', 'Number', 'String', 'Symbol',\n // Optional\n 'Map', 'Math', 'Set',\n ];\n\n do\n {\n Object.getOwnPropertyNames(current).forEach(function (name)\n {\n if (keepProperties.indexOf(name) === -1)\n {\n delete current[name];\n }\n });\n\n current = Object.getPrototypeOf(current);\n }\n while (current !== Object.prototype)\n ;\n\n })(this);\n\n _addEventListener(\"message\", function (e)\n {\n var f = new Function(\"\", \"return (\" + e.data + \"\\n);\");\n _postMessage(f());\n });\n }.toString(),\n \")()\"],\n {type: \"application/javascript\"}));\n\n var worker = new Worker(blobURL);\n\n URL.revokeObjectURL(blobURL);\n\n worker.onmessage = function (evt)\n {\n worker.terminate();\n resolve(evt.data);\n };\n\n worker.onerror = function (evt)\n {\n reject(new Error(evt.message));\n };\n\n worker.postMessage(untrustedCode);\n\n setTimeout(function ()\n {\n worker.terminate();\n reject(new Error('The worker timed out.'));\n }, 1000);\n });\n}\n var promise = safeEval(\"1+2+3\");\n\npromise.then(function (result) {\n alert(result);\n });\n 6"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654/"
] |
195,150
|
<p>How can I raise an event from a SWF file loaded into a Flex application (using SWFLoader)?</p>
<p>I want to be able to detect</p>
<pre><code>a) when a button is pressed
b) when the animation ends
</code></pre>
|
[
{
"answer_id": 195160,
"author": "Christophe Herreman",
"author_id": 17255,
"author_profile": "https://Stackoverflow.com/users/17255",
"pm_score": 2,
"selected": false,
"text": "mySWFLoader.content.addEventListener(\"myEvent\", myEventHandler);\n"
},
{
"answer_id": 195249,
"author": "Simon",
"author_id": 24039,
"author_profile": "https://Stackoverflow.com/users/24039",
"pm_score": 0,
"selected": false,
"text": "package yourpackage.events\n{\n import flash.events.Event;\n\n [Event(name=\"EV_Notify\", type=\"yourpackage.events.EV_Notify\")]\n public class EV_Notify extends Event\n {\n public function EV_Notify(bubbles:Boolean=true, cancelable:Boolean=false)\n {\n super(\"EV_Notify\", bubbles, cancelable);\n }\n\n }\n}\n bubbles dispatchEvent(new EV_Notify());\n EV_ Alert package yourpackage.events\n{\n import flash.events.Event;\n\n [Event(name=\"EV_Notify\", type=\"yourpackage.events.EV_Notify\")]\n public class EV_Notify extends Event\n {\n public static var BUTTON_PRESSED:int = 1;\n public static var ANIMATION_ENDED:int = 2;\n\n public var whatHappened:int;\n\n public function EV_Notify(whatHappened:int, bubbles:Boolean=true, cancelable:Boolean=false)\n {\n this.whatHappened = whatHappened;\n super(\"EV_Notify\", bubbles, cancelable);\n }\n\n }\n}\n dispatchEvent(new EV_Notify(EV_NOTIFY.ANIMATION_ENDED));\n private function handleNotify(ev:EV_Notify):void\n{\n if (ev.whatHappened == EV_Notify.ANIMATION_ENDED)\n {\n // do something\n }\n else if (ev.whatHappened == EV_Notify.BUTTON_PRESSED)\n {\n // do something else\n }\n etc...\n}\n"
},
{
"answer_id": 195987,
"author": "Simon",
"author_id": 24727,
"author_profile": "https://Stackoverflow.com/users/24727",
"pm_score": 2,
"selected": false,
"text": "<mx:SWFLoader source=\"homeanimations/tired.swf\" id=\"swfTired\" complete=\"swfTiredLoaded(event)\" />\n\nprivate function swfTiredLoaded(event:Event): void {\n mySWFLoader.content.addEventListener(\"continueClicked\", continueClickedHandler);\n}\n dispatchEvent(new Event(\"continueClicked\", true, true));\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24727/"
] |
195,151
|
<p>I have a ListView in WPF that is databound to a basic table that I pull from the database. The code for the ListView is as follows:</p>
<pre><code><ListView Canvas.Left="402" Canvas.Top="480" Height="78" ItemsSource="{Binding}" Name="lsvViewEditCardPrint" Width="419">
<ListView.View>
<GridView>
<GridViewColumn DisplayMemberBinding="{Binding Path=IdCst}">Set</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=Language}">Language</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=Number}">Number</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Path=IdArt}">Artwork</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</code></pre>
<p>The IdCst column is a foreign key to a separate table, and I'd like to display the actual name field from that table instead of just the Id. Does anybody know how to set a databinding, or is there an event, such as OnItemDataBound, that I could intercept to modify the display?</p>
|
[
{
"answer_id": 198015,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 1,
"selected": false,
"text": "Public ReadOnly Property NameCst() as String\n Get\n Return Names.LookupName(Me.IdCst)\n End Get\nEnd Property\n"
},
{
"answer_id": 230950,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": -1,
"selected": false,
"text": "Namespace TCRConverters\n\n Public Class SetIdToNameConverter\n Implements IValueConverter\n\n Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert\n Dim taCardSet As New TCRTableAdapters.CardSetTableAdapter\n Return taCardSet.GetDataById(DirectCast(value, Integer)).Item(0).Name\n End Function\n\n Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack\n Return Nothing\n End Function\n\n End Class\n\nEnd Namespace\n <Window x:Class=\"Main\" Loaded=\"Main_Loaded\"\n // Standard references here...\n xmlns:c=\"clr-namespace:TCR_Editor.TCRConverters\"\n Title=\"TCR Editor\" Height=\"728\" Width=\"1135\" Name=\"Main\">\n <Window.Resources>\n <CollectionViewSource Source=\"{Binding Source={x:Static Application.Current}, Path=CardDetails}\" x:Key=\"CardDetails\"> \n </CollectionViewSource>\n\n <c:SetIdToNameConverter x:Key=\"SetConverter\"/> \n</Window.Resources>\n <ListView Canvas.Left=\"402\" Canvas.Top=\"480\" Height=\"78\" ItemsSource=\"{Binding}\" Name=\"lsvViewEditCardPrint\" Width=\"419\">\n <ListView.View>\n <GridView>\n <GridViewColumn DisplayMemberBinding=\"{Binding Path=IdCst, Converter={StaticResource SetConverter}}\">Set</GridViewColumn>\n // Other Columns here...\n </GridView>\n </ListView.View>\n</ListView>\n DirectCast(Me.FindResource(\"CardDetails\"), CollectionViewSource).Source = taCardDetails.GetDataById(CardId)\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/71/"
] |
195,173
|
<p>When you run something similar to:</p>
<pre><code>UPDATE table SET datetime = NOW();
</code></pre>
<p>on a table with 1 000 000 000 records and the query takes 10 seconds to run, will all the rows have the exact same time (minutes and seconds) or will they have different times? In other words, will the time be when the query started or when each row is updated?</p>
<p>I'm running MySQL, but I'm thinking this applies to all dbs.</p>
|
[
{
"answer_id": 11587803,
"author": "My Name Goes Here",
"author_id": 1541909,
"author_profile": "https://Stackoverflow.com/users/1541909",
"pm_score": 0,
"selected": false,
"text": "update TABLE set mydatetime = datetime('now');\n"
},
{
"answer_id": 38186380,
"author": "MRRaja",
"author_id": 2357497,
"author_profile": "https://Stackoverflow.com/users/2357497",
"pm_score": 3,
"selected": false,
"text": "NOW() update_date_time=now()\n UPDATE table SET datetime =update_date_time;\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5441/"
] |
195,175
|
<p>I am new to this community, but I am working on a site that requires implementation of a user/password/register check upon entry, which would check against a database, or write to the database, in the case of registration. I have experience with XHTML and CSS, and just discovered RoR. I honestly have very little insight into how to achieve my goal using just XHTML, so I decided to learn Ruby, taking a shot in the dark. I'm wondering if there's an easier language, or more direct fix that I should be implementing instead. Any thoughts?</p>
|
[
{
"answer_id": 195178,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 0,
"selected": false,
"text": "acts_as_authenticated"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27171/"
] |
195,177
|
<p>I have a Zimbra installation and I need to programmaticaly update contacts in it. It seems that its REST interface is only working to add new contacts, but I need to update existing ones. Is there a way, tool or something, open-source, to do that ?</p>
|
[
{
"answer_id": 195708,
"author": "edomaur",
"author_id": 14262,
"author_profile": "https://Stackoverflow.com/users/14262",
"pm_score": 3,
"selected": true,
"text": "box$ zmmailbox help contact\n\n autoComplete(ac) [opts] {query}\n -v/--verbose verbose output\n\n autoCompleteGal(acg) [opts] {query}\n -v/--verbose verbose output\n\n createContact(cct) [opts] [attr1 value1 [attr2 value2...]]\n -i/--ignore ignore unknown contact attrs\n -f/--folder <arg> folder-path-or-id\n -T/--tags <arg> list of tag ids/names\n\n deleteContact(dct) {contact-ids}\n\n flagContact(fct) {contact-ids} [0|1*]\n\n getAllContacts(gact) [opts] [attr1 [attr2...]]\n -f/--folder <arg> folder-path-or-id\n -v/--verbose verbose output\n\n getContacts(gct) [opts] {contact-ids} [attr1 [attr2...]]\n -v/--verbose verbose output\n\n modifyContactAttrs(mcta) [opts] {contact-id} [attr1 value1 [attr2 value2...]]\n -i/--ignore ignore unknown contact attrs\n -r/--replace replace contact (default is to merge)\n\n moveContact(mct) {contact-ids} {dest-folder-path}\n\n tagContact(tct) {contact-ids} {tag-name} [0|1*]\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14262/"
] |
195,207
|
<p>Very simply put:</p>
<p>I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other classes/functions.</p>
<p>Anyway, I have defined two static unsigned char variables in my class public scope, when I try to modify these values in the same class' constructor, I am getting an "unresolved external symbol" error at compilation.</p>
<pre><code>class test
{
public:
static unsigned char X;
static unsigned char Y;
...
test();
};
test::test()
{
X = 1;
Y = 2;
}
</code></pre>
<p>I'm new to C++ so go easy on me. Why can't I do this?</p>
|
[
{
"answer_id": 195209,
"author": "Colin Jensen",
"author_id": 9884,
"author_profile": "https://Stackoverflow.com/users/9884",
"pm_score": 8,
"selected": true,
"text": "inline unsigned char test::X;\nunsigned char test::Y;\n unsigned char test::X = 4;\n"
},
{
"answer_id": 195233,
"author": "sergtk",
"author_id": 13441,
"author_profile": "https://Stackoverflow.com/users/13441",
"pm_score": 6,
"selected": false,
"text": ".CPP enums class test {\npublic:\n const static unsigned char X = 1;\n const static unsigned char Y = 2;\n ...\n test();\n};\n\ntest::test() {\n}\n .H .CPP class test {\npublic:\n\n static unsigned char X;\n static unsigned char Y;\n\n ...\n\n test();\n};\n unsigned char test::X = 1;\nunsigned char test::Y = 2;\n\ntest::test()\n{\n // constructor is empty.\n // We don't initialize static data member here, \n // because static data initialization will happen on every constructor call.\n}\n"
},
{
"answer_id": 50169640,
"author": "Johann Studanski",
"author_id": 6155053,
"author_profile": "https://Stackoverflow.com/users/6155053",
"pm_score": 3,
"selected": false,
"text": "__declspec(dllexport)"
},
{
"answer_id": 52395927,
"author": "Penny",
"author_id": 6824513,
"author_profile": "https://Stackoverflow.com/users/6824513",
"pm_score": 3,
"selected": false,
"text": "//myClass.h\nclass myClass\n{\nstatic int m_nMyVar;\nstatic void myFunc();\n}\n //myClass.cpp\nvoid myClass::myFunc()\n{\nmyClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error\n}\n //myClass.cpp\nint myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well\nvoid myClass::myFunc()\n{\nmyClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error\n}\n"
},
{
"answer_id": 67138464,
"author": "Sanya Tayal",
"author_id": 9079222,
"author_profile": "https://Stackoverflow.com/users/9079222",
"pm_score": 3,
"selected": false,
"text": "#include <iostream>\n#include <string>\nusing namespace std;\nclass Demo{\n int var;\n static int counter;\n\n public:\n Demo(int var):var(var){\n cout<<\"Counter = \"<<counter<<endl;\n counter++;\n }\n};\nint Demo::counter = 0; //static variable initialisation\nint main()\n{\n Demo d(2), d1(10),d3(1);\n}\n\nOutput:\nCount = 0\nCount = 1\nCount = 2\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
195,208
|
<p>I'm attempting to use File.Move to move a file from one UNC location to another. This blows up if the UNC path for the destination happens to be the local machine (error: Access to the path is denied). Example <code>File.Move(@"\\someServer\path\file.txt", @"\\blah2\somewhere\file.txt")</code>. This assumes there's a network share out there somewhere named \\someServer and my local machine name is blah2. Change \\blah2 to C:\ and all is good.</p>
|
[
{
"answer_id": 195232,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 2,
"selected": false,
"text": "@\"\\\\blah2\\somewhere\\file.txt\""
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195208",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16439/"
] |
195,240
|
<p>I have the following template</p>
<pre><code><h2>one</h2>
<xsl:apply-templates select="one"/>
<h2>two</h2>
<xsl:apply-templates select="two"/>
<h2>three</h2>
<xsl:apply-templates select="three"/>
</code></pre>
<p>I would like to only display the headers (one,two,three) if there is at least one member of the corresponding template. How do I check for this?</p>
|
[
{
"answer_id": 195248,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<xsl:if test=\"one\">\n <h2>one</h2>\n <xsl:apply-templates select=\"one\"/>\n</xsl:if>\n<!-- etc -->\n <xsl:template name=\"WriteWithHeader\">\n <xsl:param name=\"header\"/>\n <xsl:param name=\"data\"/>\n <xsl:if test=\"$data\">\n <h2><xsl:value-of select=\"$header\"/></h2>\n <xsl:apply-templates select=\"$data\"/>\n </xsl:if>\n</xsl:template>\n <xsl:call-template name=\"WriteWithHeader\">\n <xsl:with-param name=\"header\" select=\"'one'\"/>\n <xsl:with-param name=\"data\" select=\"one\"/>\n </xsl:call-template>\n <h2>...</h2> <xsl:value-of select=\"name($header[1])\"/>\n"
},
{
"answer_id": 212328,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!-- test data inlined -->\n<test>\n <one>Content 1</one>\n <two>Content 2</two>\n <three>Content 3</three>\n <four/>\n <special>I'm special!</special>\n</test>\n\n<!-- any root since take test content from stylesheet -->\n<xsl:template match=\"/\">\n <html>\n <head>\n <title>Header/Content Widget</title>\n </head>\n <body>\n <xsl:apply-templates select=\"document('')//test/*\" mode=\"header-content-widget\"/>\n </body>\n </html>\n</xsl:template>\n\n<!-- default action for header-content -widget is apply header then content views -->\n<xsl:template match=\"*\" mode=\"header-content-widget\">\n <xsl:apply-templates select=\".\" mode=\"header-view\"/>\n <xsl:apply-templates select=\".\" mode=\"content-view\"/>\n</xsl:template>\n\n<!-- default header-view places element name in <h2> tag -->\n<xsl:template match=\"*\" mode=\"header-view\">\n <h2><xsl:value-of select=\"name()\"/></h2>\n</xsl:template>\n\n<!-- default header-view when no text content is no-op -->\n<xsl:template match=\"*[not(text())]\" mode=\"header-view\"/>\n\n<!-- default content-view is to apply-templates -->\n<xsl:template match=\"*\" mode=\"content-view\">\n <xsl:apply-templates/>\n</xsl:template>\n\n<!-- special content handling -->\n<xsl:template match=\"special\" mode=\"content-view\">\n <strong><xsl:apply-templates/></strong>\n</xsl:template>\n"
}
] |
2008/10/12
|
[
"https://Stackoverflow.com/questions/195240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2133/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.