qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
|---|---|---|---|---|
263,639
|
<p>I've inherited a ASP/VB6 code base (not my forte... yet) and I'm trying tease it apart to figure out the cause on an error message I'm receiving when running the app.</p>
<p>I've traced it back through an event that is being raised in on of my classes. Is there away in windows I can search the bulk of the code base for where it is being consumed?
Ctrl-F (and selecting Current Project) has not sufficed.</p>
<p>The linux geek in me is saying dump it to a <em>insert distro</em> box and just grep for the sucker. But there's got to be some way in the IDE to do it... right?</p>
|
[
{
"answer_id": 263649,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "find grep"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263639",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] |
263,640
|
<p>I've been having performance issues with a high traffic ASP.NET 2.0 site running on Windows 2000. While editing the web.config file I noticed that the authentication mode was set to 'Windows'. I changed it to 'None'. The only users this site has are anonymous and it gets 25,000+ page views at day. Could this have been a caused performance issues?</p>
|
[
{
"answer_id": 263649,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "find grep"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12252/"
] |
263,676
|
<p>In a product I work on, there is an iteration loop which can have anywhere between a few hundred to a few million iterations. Each iteration computes a set of statistic variables (double precision), and the number of variables can be up to 1000 (typically 15-50).</p>
<p>As part of the loop, we graph the change in the variables over the iterations, so the X axis is iterations, and the y axis are the variables (coded by color):</p>
<p><a href="http://sawtoothsoftware.com/download/temp/walt/graph.jpg" rel="nofollow noreferrer">http://sawtoothsoftware.com/download/temp/walt/graph.jpg</a></p>
<p>Currently the data are stored in a file with containing:<br>
a 4 byte integer for which variable,<br>
a 4 byte integer for which iteration,<br>
and a 8 byte double for the value.</p>
<p>The total scale of the y axis changes over time, and it is desired that the graph resize to accomodate the current scale (this can be seen in the picture).</p>
<p>At about 5 second intervals, the data are read and plotted on a bitmap which is then displayed to the user. We try to do a few optimizations to avoid repainting the whole thing, but if the number of iterations or the number of variables gets big, we end up with an enormous file which takes longer than 5 seconds to draw.</p>
<p>I'm looking for ideas on how to handle this much data more effectively and quickly if possible.</p>
|
[
{
"answer_id": 618973,
"author": "spoulson",
"author_id": 3347,
"author_profile": "https://Stackoverflow.com/users/3347",
"pm_score": 2,
"selected": false,
"text": "AVG() MAX() MIN() select time_collected, AVG(value)\nfrom Table\ngroup by UNIX_TIMESTAMP(time_collected)\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,695
|
<p>On my Mac OS X 10.5 (Leopard) machine, I have installed Git 1.6.0.2 using the <a href="http://code.google.com/p/git-osx-installer/" rel="nofollow noreferrer">git-OSX-Installer</a> from Google Code. The installer installs Git to /usr/local/Git.</p>
<p>I would now like to keep up with the latest stable Git release (Master branch), currently 1.6.0.3.</p>
<p>Can I run "git clone git://git.kernel.org/pub/scm/git/git.git" from within the /usr/local/Git directory, then Configure/Make/Install using XCode, or will that not work?</p>
<p>Basically I'm looking for the best practice to keep Git updated to the latest stable version.</p>
|
[
{
"answer_id": 263732,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 4,
"selected": true,
"text": "HEAD git checkout /usr/local/git-v1.6.0.2-287-g3791f77/ launchctrl load ~/Library/LaunchAgents/mylaunchagent.plist"
},
{
"answer_id": 313162,
"author": "Paul Beckingham",
"author_id": 14356,
"author_profile": "https://Stackoverflow.com/users/14356",
"pm_score": 1,
"selected": false,
"text": "git clone git://git2.kernel.org/pub/scm/git/git.git\n cd ~/git.git\ngit pull\nmake\nmake test\nsudo make install\n"
},
{
"answer_id": 321778,
"author": "Abizern",
"author_id": 41116,
"author_profile": "https://Stackoverflow.com/users/41116",
"pm_score": 0,
"selected": false,
"text": "sudo git clean -dxf\ngit pull\nmake prefix=/usr/local/git all\nsudo make prefix=/usr/local/git install\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32558/"
] |
263,697
|
<p>I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data.</p>
<p>Example array:</p>
<pre><code>array(3) {
["first"]=>
array(1) {
[0]=>
string(4) "baz1"
}
["second"]=>
array(1) {
[0]=>
string(4) "foo1"
}
["third"]=>
array(1) {
[0]=>
string(4) "foo2"
}
</code></pre>
<p>Now I want to find any values that match foo (foo1 and foo2 in the example array), insert "-bar" into them (foo-bar1, foo-bar2) and return that value. What are the best ways to approach this? </p>
<p><em>EDIT</em> I should have mentioned that foo could actually be anythingfoo (ex. examplefoo1, somethingelsefoo2, blahblahfoo3). I think this rules out str_replace.</p>
|
[
{
"answer_id": 263713,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 3,
"selected": false,
"text": "function addDashBar($arr)\n{\n foreach ($arr as $key => $value)\n {\n if (is_array($value))\n $arr[$key] = addDashBar($value)\n else\n {\n $arr[$key] = str_replace($value, \"foo\", \"foo-bar\");\n }\n }\n\n return $arr;\n}\n"
},
{
"answer_id": 263728,
"author": "Marek",
"author_id": 34452,
"author_profile": "https://Stackoverflow.com/users/34452",
"pm_score": 4,
"selected": true,
"text": "$array= array('first' => array('bazi1'), 'second' => array('foo1'), 'third' => array('foo2') );\nfunction modify_foo(&$item, $key)\n{\n $item = str_replace('foo', 'foo-bar', $item);\n}\narray_walk_recursive( $array, 'modify_foo' );\n"
},
{
"answer_id": 264955,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 1,
"selected": false,
"text": " function test_replace1(&$input, $search, $replace) {\n $result = array();\n $numReplacements = 0;\n foreach ($input as &$value) {\n if (is_array($value)) {\n $result = array_merge($result, test_replace1($value, $search, $replace));\n } else {\n $value = str_replace($search, $replace, $value, $numReplacements);\n if ($numReplacements) {\n $result[] = $value;\n }\n }\n }\n return $result;\n }\n\n $changed_values = test_replace1($arr, 'foo', 'foo-bar');\n"
},
{
"answer_id": 267601,
"author": "Vinh",
"author_id": 34561,
"author_profile": "https://Stackoverflow.com/users/34561",
"pm_score": 1,
"selected": false,
"text": "echo str_replace(\"foo\",\"foo-bar\",\"mycrazystringwithfoorightinthemiddleofit\");\n mycrazystringwithfoo-barrightinthemiddleofit\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11252/"
] |
263,735
|
<p>Problem:
How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it?</p>
<hr>
<p>Goal:
I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection.</p>
<p>Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the "Font Pt Selection" drop down displays "9". If you then select the first 20 characters, the same drop down should have a empty/blank display.</p>
<hr>
<p>What I have going so far:
I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out</p>
<pre><code>CHARFORMAT cf;
cf.cbSize = sizeof(CHARFORMAT);
CRichEditCtrl ctrl;
ctrl.GetSelectionCharFormat( cf );
int nFontPtSize = cf.yHeight / 20;
</code></pre>
<p>This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection).</p>
<p>In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on).</p>
|
[
{
"answer_id": 265414,
"author": "DavidK",
"author_id": 31394,
"author_profile": "https://Stackoverflow.com/users/31394",
"pm_score": 2,
"selected": true,
"text": "CComPtr<IRichEditOle> richOle;\nrichOle.Attach(edit.GetIRichEditOle());\nCComQIPtr<ITextDocument> textDoc(richOle);\n CComPtr<ITextSelection> range;\ntextDoc->GetSelection(&range);\n CComPtr<ITextFont> font;\nrange->GetFont(&font);\nlong size;\nfont->GetSize(&size);\n"
},
{
"answer_id": 272182,
"author": "Scott",
"author_id": 34460,
"author_profile": "https://Stackoverflow.com/users/34460",
"pm_score": 0,
"selected": false,
"text": "HWND hwnd;\nITextDocument* pDoc;\nIUnknown* pUnk = NULL;\nfloat size = 0;\nhwnd = GetSafeHwnd();\n::SendMessage( hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&pUnk );\n if ( pUnk && pUnk->QueryInterface( __uuidof(ITextDocument), (void**)&pDoc ) == NOERROR )\n {\n CComPtr<ITextSelection> range;\n pDoc->GetSelection( &range );\n CComPtr<ITextFont> font;\n range->GetFont( &font ); \n // If there are multiple font sizes in the selection, \"size\" comes back as -9999 \n font->GetSize(&size);\n }\nreturn size;\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34460/"
] |
263,741
|
<p>I built a <strong>[widget][1]</strong> that grabs the URL from the frontmost window in Safari, then allows you to shorten it using the tr.im API. Works sweet as.</p>
<p>I want to make this more flexible, so am investigating how to grab an URL from other browsers. Here's the AppleScript that works in Safari:</p>
<pre><code>tell application "Safari"
return URL of front document as string
end tell
</code></pre>
<p>After <a href="https://web.archive.org/web/20141112082406/http://hintsforums.macworld.com/showthread.php?t=32237" rel="nofollow noreferrer">some digging</a>, I determined that the following <em>might</em> work for Firefox (though one person has told me it doesn't work for him, possibly a conflict with some extension?):</p>
<pre><code>tell application "Firefox"
set myFirefox to properties of front window as list
return item 3 of myFirefox
end tell
</code></pre>
<p><em>Note: The above is an example of a less-than-best practice, relying on the position of list items. See below for a better solution for Firefox.</em></p>
<p>What I'd like to do is build a list here of the definitive equivalents for every modern browser on the Mac: Opera, Camino, Flock, etc.</p>
<p><strong>Update:</strong> In my research on the subject, I came across a helpful thread on <a href="http://www.macosxhints.com/article.php?story=20060325015454467" rel="nofollow noreferrer">MacOSXHints.com</a>. Most of my answers below are based on that discussion.</p>
<p><strong>Update 2:</strong> I've incorporated the AppleScript on this page into the [widget][1]. It seems to be working swell.</p>
|
[
{
"answer_id": 268195,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "tell application \"Opera\"\n return URL of front document as string\nend tell\n"
},
{
"answer_id": 268197,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 2,
"selected": false,
"text": "tell application \"Firefox\"\n set myURL to «class curl» of window 1\n return myURL\nend tell\n"
},
{
"answer_id": 268212,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "tell application \"Camino\"\n set p to properties of front tab of front window\n return |currentURI| of p as string\nend tell\n"
},
{
"answer_id": 268222,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "tell application \"Flock\"\n set p to properties of front window as list\n return item 3 of p\nend tell\n address"
},
{
"answer_id": 268264,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 0,
"selected": false,
"text": "tell application \"OmniWeb\"\n set myInfo to GetWindowInfo\n return item 1 of myInfo\nend tell\n"
},
{
"answer_id": 271684,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "tell application \"Firefox\" to activate\n tell application \"Firefox\"\n if (front window) exists then do_something()\nend tell\n tell application \"System Events\"\n tell process \"Firefox\"\n set frontmost to true\n set xsist to (front window) exists\n (* keep xsist value to test later on *)\n end tell\nend tell\n"
},
{
"answer_id": 287381,
"author": "piero",
"author_id": 37358,
"author_profile": "https://Stackoverflow.com/users/37358",
"pm_score": 2,
"selected": false,
"text": "tell application \"Firefox\" to activate\n"
},
{
"answer_id": 800452,
"author": "smorgan",
"author_id": 96811,
"author_profile": "https://Stackoverflow.com/users/96811",
"pm_score": 1,
"selected": false,
"text": "tell application \"Camino\"\n return URL of current tab of front browser window as text\nend tell\n"
},
{
"answer_id": 1598732,
"author": "Brian",
"author_id": 193561,
"author_profile": "https://Stackoverflow.com/users/193561",
"pm_score": 2,
"selected": false,
"text": "tell application \"Firefox\" to activate\ntell application \"System Events\"\n keystroke \"l\" using command down\n keystroke \"c\" using command down\nend tell\n"
},
{
"answer_id": 5216379,
"author": "Neffster",
"author_id": 265861,
"author_profile": "https://Stackoverflow.com/users/265861",
"pm_score": 2,
"selected": false,
"text": " tell application \"Google Chrome\"\n get URL of active tab of window 1\n end tell\n"
},
{
"answer_id": 14162637,
"author": "Fred",
"author_id": 1949435,
"author_profile": "https://Stackoverflow.com/users/1949435",
"pm_score": 1,
"selected": false,
"text": "tell application \"Firefox\" to activate\n\ntell application \"System Events\"\nkeystroke \"l\" using command down\nkeystroke \"c\" using command down\nend tell\n\nset FrontDocumentURL to the clipboard\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11577/"
] |
263,743
|
<p>How do you get the caret position in a <code><textarea></code> using JavaScript?</p>
<p>For example: <code>This is| a text</code></p>
<p>This should return <code>7</code>.</p>
<p>How would you get it to return the strings surrounding the cursor / selection?</p>
<p>E.g.: <code>'This is', '', ' a text'</code>.</p>
<p>If the word “is” is highlighted, then it would return <code>'This ', 'is', ' a text'</code>.</p>
|
[
{
"answer_id": 263796,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "function getCaret(node) {\n if (node.selectionStart) {\n return node.selectionStart;\n } else if (!document.selection) {\n return 0;\n }\n\n var c = \"\\001\",\n sel = document.selection.createRange(),\n dul = sel.duplicate(),\n len = 0;\n\n dul.moveToElementText(node);\n sel.text = c;\n len = dul.text.indexOf(c);\n sel.moveStart('character',-1);\n sel.text = \"\";\n return len;\n}\n function getCaret(el) { \n if (el.selectionStart) { \n return el.selectionStart; \n } else if (document.selection) { \n el.focus(); \n\n var r = document.selection.createRange(); \n if (r == null) { \n return 0; \n } \n\n var re = el.createTextRange(), \n rc = re.duplicate(); \n re.moveToBookmark(r.getBookmark()); \n rc.setEndPoint('EndToStart', re); \n\n return rc.text.length; \n } \n return 0; \n}\n"
},
{
"answer_id": 2735606,
"author": "mark",
"author_id": 328628,
"author_profile": "https://Stackoverflow.com/users/328628",
"pm_score": 2,
"selected": false,
"text": "function getCaret(el) {\n if (el.selectionStart) { \n return el.selectionStart; \n } else if (document.selection) { \n el.focus(); \n\n var r = document.selection.createRange(); \n if (r == null) { \n return 0; \n } \n\n var re = el.createTextRange(), \n rc = re.duplicate(); \n re.moveToBookmark(r.getBookmark()); \n rc.setEndPoint('EndToStart', re); \n\n var add_newlines = 0;\n for (var i=0; i<rc.text.length; i++) {\n if (rc.text.substr(i, 2) == '\\r\\n') {\n add_newlines += 2;\n i++;\n }\n }\n\n //return rc.text.length + add_newlines;\n\n //We need to substract the no. of lines\n return rc.text.length - add_newlines; \n } \n return 0; \n}\n"
},
{
"answer_id": 3373056,
"author": "Tim Down",
"author_id": 96100,
"author_profile": "https://Stackoverflow.com/users/96100",
"pm_score": 6,
"selected": false,
"text": "<textarea> <input> focus() function getInputSelection(el) {\n var start = 0, end = 0, normalizedValue, range,\n textInputRange, len, endRange;\n\n if (typeof el.selectionStart == \"number\" && typeof el.selectionEnd == \"number\") {\n start = el.selectionStart;\n end = el.selectionEnd;\n } else {\n range = document.selection.createRange();\n\n if (range && range.parentElement() == el) {\n len = el.value.length;\n normalizedValue = el.value.replace(/\\r\\n/g, \"\\n\");\n\n // Create a working TextRange that lives only in the input\n textInputRange = el.createTextRange();\n textInputRange.moveToBookmark(range.getBookmark());\n\n // Check if the start and end of the selection are at the very end\n // of the input, since moveStart/moveEnd doesn't return what we want\n // in those cases\n endRange = el.createTextRange();\n endRange.collapse(false);\n\n if (textInputRange.compareEndPoints(\"StartToEnd\", endRange) > -1) {\n start = end = len;\n } else {\n start = -textInputRange.moveStart(\"character\", -len);\n start += normalizedValue.slice(0, start).split(\"\\n\").length - 1;\n\n if (textInputRange.compareEndPoints(\"EndToEnd\", endRange) > -1) {\n end = len;\n } else {\n end = -textInputRange.moveEnd(\"character\", -len);\n end += normalizedValue.slice(0, end).split(\"\\n\").length - 1;\n }\n }\n }\n }\n\n return {\n start: start,\n end: end\n };\n}\n"
},
{
"answer_id": 34466831,
"author": "Michał Perłakowski",
"author_id": 3853934,
"author_profile": "https://Stackoverflow.com/users/3853934",
"pm_score": 2,
"selected": false,
"text": "selectionStart selectionEnd textarea selectionStart function getCaretPosition(textarea) {\n return textarea.selectionStart\n}\n function getSurroundingSelection(textarea) {\n return [textarea.value.substring(0, textarea.selectionStart)\n ,textarea.value.substring(textarea.selectionStart, textarea.selectionEnd)\n ,textarea.value.substring(textarea.selectionEnd, textarea.value.length)]\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32941/"
] |
263,748
|
<p>I normally store all my configs in the registry.
Even though I have started using LINQ I would not like to have the DSN in the web.config, but rather let it stay in the registry and attach it (maybe in the Application Start Event) to the System Config.</p>
<p>How can this be done?</p>
<p>Thanx for any ideas!</p>
<p>edit: to make it clear: I do not want to write to the web.config file, I just want to keep the dsn (encrypted) anywhere else than the web.config, so I have the same web.config on all development stages (local, staginf, live, backup).</p>
<p>Christoph</p>
<p><strong>Solution Code in VB.Net:</strong></p>
<p>1) Add a new Class, with one method, which inherits from the original Datacontext:</p>
<pre><code>Public Class MyDatabaseDataContext
Inherits DatabaseDataContext
Public Sub New()
MyBase.New(Settings.DSN)
End Sub
End Class
</code></pre>
<p>2) Use this Class in all Linq Datasources instead of the original Context.</p>
<pre><code> ContextTypeName="MyProject.MyDatabaseDataContext
</code></pre>
|
[
{
"answer_id": 264255,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "Application_Start aspreg_iis Configuration config = WebConfigurationManager.OpenWebConfiguration(\n HttpContext.Current.Request.ApplicationPath );\nConfigurationSection section = config.Sections[\"connectionStrings\"];\nif (!section.SectionInformation.IsProtected\n && !GlobalConfiguration.ApplicationVersion.EndsWith( \"dev\" )) // don't encrypt dev\n{\n section.SectionInformation.ProtectSection( \"DataProtectionConfigurationProvider\" );\n config.Save();\n}\n aspreg_iis Application_Start"
},
{
"answer_id": 265446,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 2,
"selected": true,
"text": "public class DataContext : DataContextBase\n{\n public DataContext()\n : base(ConnectionHolder.ConnectionString)\n {\n }\n}\n public static class ConnectionHolder\n{\n static string _ConnectionString;\n\n public static string ConnectionString\n {\n get { return _ConnectionString; }\n set { _ConnectionString = value; }\n }\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34464/"
] |
263,770
|
<p>I am looking for the best way to customize my Rails log entries (I want to add the user ID in there). I am using Rails 2.1.2. The only way I've found so far is to override method "add" of class BufferedLogger (as defined in active_support/lib/active_support). </p>
<p>But it ain't pretty: I have to copy all the code in there and it is
closely tied to the current implementation. Is there a better way?
I found this on the Google: <a href="http://pandejo.blogspot.com/2007/08/customize-logger-message-format.html" rel="nofollow noreferrer">http://pandejo.blogspot.com/2007/08/customize-logger-message-format.html</a> but it seems outdated.
One day, I might create a specific audit log, but it is overkill for
what I need: <a href="http://maintainable.com/articles/rails_logging_tips#audit-logs" rel="nofollow noreferrer">http://maintainable.com/articles/rails_logging_tips#audit-logs</a>
Cheers.</p>
|
[
{
"answer_id": 4068231,
"author": "Jochen",
"author_id": 476686,
"author_profile": "https://Stackoverflow.com/users/476686",
"pm_score": 1,
"selected": false,
"text": "after_filter :logging\n def logging\n if logger && logged_in?\n logger.info \"UserID: #{current_user.id.to_s}\"\n end\n end\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263770",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11814/"
] |
263,773
|
<p>I have a python script that I would like to add a "Shutdown when done" feature to.</p>
<p>I know I can use gksudo (when the user clicks on "shutdown when done") to ask the user for root privileges but how can I use those privileges at a later time (when the script is actually finished).</p>
<p>I have thought about chmod u+s on the shutdown command so I don't need a password but I really don't want to do that.</p>
<p>Any ideas how I can achieve this?</p>
<p>Thanks in advance,
Ashy.</p>
|
[
{
"answer_id": 263851,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 1,
"selected": false,
"text": "fork (2) wait (2)"
},
{
"answer_id": 263859,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 2,
"selected": false,
"text": "chmod u+s"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32933/"
] |
263,782
|
<p>Currently I have subversion set up so that when I make changes in Eclipse PDT, I can commit the changes and they will be saved in /home/administrator/<em>Project File</em>. This file has the /branches /tags and /trunk directories recommended by subversion. I have no problem properly uploading files to the repository, but do I have to "mv" the files in Linux to /var/www in order to make them live on the server? Is there an automatic process to do this that I am missing? I'm assuming we don't want to make the /var/www directory (which is live on the machine) the repository, but I don't know.</p>
|
[
{
"answer_id": 263791,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 4,
"selected": true,
"text": "svn export cd /var/www\nsvn export /home/administrator/MyProject/trunk MyProject\n svn export --force /home/...../ MyProject svn export /home/..../ MyProject_20081105 ln -s MyProject_20081105 MyProject www"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27673/"
] |
263,801
|
<p>I have 15 stored procedures that return data from a common table and then join that table with a specific table to retrieve inventory.</p>
<p>Example:</p>
<pre><code>Common: tblCommon
Specific: tblSpecific
</code></pre>
<p>Is there way I can pass the name "tblSpecific" into a single stored procedure as a variable, like the following?</p>
<pre><code>SELECT ....
FROM tblCommon c
INNER JOIN @TABLE s on c.primaryKey = s.foreignKey
</code></pre>
|
[
{
"answer_id": 263822,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 2,
"selected": false,
"text": "DECLARE @specificTableName nvarchar(50)\nDECLARE @specificColumnName nvarchar(50)\n\nSET @specificTableName = 'tblSpecific'\nSET @specificColumnName = 'colSpecific'\n\nDECLARE @sql nvarchar(4000)\n\nset @sql = 'SELECT ... FROM tblCommon c INNER JOIN ' +\n@specificTableName + ' s ON c.PrimaryKey = s.' + @specificColumnName\n\n\nexec (@sql)\n"
},
{
"answer_id": 263830,
"author": "John Lemp",
"author_id": 12915,
"author_profile": "https://Stackoverflow.com/users/12915",
"pm_score": 0,
"selected": false,
"text": "SELECT ....\nFROM tblCommon c\nINNER JOIN dbo.SomeFuntionThatReturnsData(@someparam) s on c.primaryKey = s.foreignKey\n"
},
{
"answer_id": 264264,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "CREATE TABLE [tables] (table_name sysname)\n SELECT @tblSpecific = table_name FROM [tables] WHERE table_name = @tblSpecific\n @tblSpecific NULL INFORMATION_SCHEMA.Tables"
},
{
"answer_id": 16689252,
"author": "mugume david",
"author_id": 692650,
"author_profile": "https://Stackoverflow.com/users/692650",
"pm_score": 1,
"selected": false,
"text": "EXECUTE(@SQLStatement)"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,815
|
<p>I have a model being populated by my data layer and then I have a partial view which is rendering an instance of that model.</p>
<pre><code><li class="<%= td.Active ? "youarehere" : string.Empty %> <%= i == ViewData.Model.Count() - 1 ? "last" : string.Empty %>">
</code></pre>
<p>The problem is that <code>class=""</code> is invalid XHTML and I will need more complex logic to output the class attribute. What would be the proper way to go about this using ASP.NET MVC. Should the logic live in the view or the model?</p>
<p>I'm just starting out with MVC and I guess I'm still struggling on where exactly to draw the lines as far as where I put logic and what is an acceptable amount of logic for each layer to contain.</p>
|
[
{
"answer_id": 263908,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 0,
"selected": false,
"text": "public static string GenerateAttribute(this HtmlHelper hh,\n string name,\n Func<string> valueFunc)\n{ \n string value = valueFunc().Trim();\n if (!string.IsNullOrEmpty(value))\n return string.Format(\"{0}=\\\"{1}\\\"\", name, value);\n return string.Empty;\n}\n <li <%= Html.GenerateAttribute(\"class\", () => string.Format(\"{0} {1}\", td.Active ? \"youarehere\" : string.Empty, i == ViewData.Model.Count() - 1 ? \"last\" : string.Empty)) %>>\n"
},
{
"answer_id": 264082,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 1,
"selected": false,
"text": "<li <%= Html.GenerateAttribute(\"class\", \n () => string.Format(\"{0} {1}\", td.Active \n ? \"youarehere\" : string.Empty, \n i == ViewData.Model.Count() - 1 \n ? \"last\" : string.Empty)) %>>\n <%= Html.ListItem( ViewData.Model.Value, \n GetItemCssClass(i, ViewData.Model.Count()) ) %>\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3957/"
] |
263,816
|
<p>Alright. I have a query that looks like this:</p>
<pre><code>SELECT
SUM(`order_items`.`quantity`) as `count`,
`menu_items`.`name`
FROM
`orders`,
`menu_items`,
`order_items`
WHERE
`orders`.`id` = `order_items`.`order_id` AND
`menu_items`.`id` = `order_items`.`menu_item_id` AND
`orders`.`date` >= '2008-11-01' AND
`orders`.`date` <= '2008-11-30'
GROUP BY
`menu_items`.`id`
</code></pre>
<p>The purpose of this query is to show the amount of items sold in a given date range. Although this works, I now need it to show a <code>count</code> of <code>0</code> if a particular item has no sales in the date range. I tried using <code>COALESCE</code> around the <code>SUM</code> but that didn't do the trick, and I didn't really expect it to. Anyhow, does anyone know how I would go about accomplishing this? I'm having one of those moments where I feel like I should know this but I can't think of it.</p>
<p>Cheers</p>
|
[
{
"answer_id": 263917,
"author": "Jamie Love",
"author_id": 27308,
"author_profile": "https://Stackoverflow.com/users/27308",
"pm_score": 2,
"selected": false,
"text": "SELECT\n name\n , nvl(count, 0) as count\nFROM \n menu_items items \n LEFT JOIN (\n SELECT\n menu_items.id\n , SUM(order_items.quantity) as count\n FROM \n menu_items\n LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id\n LEFT JOIN orders ON orders.id = order_items.order_id\n WHERE\n \"date\" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')\n GROUP BY\n menu_items.id\n ) counts on items.id = counts.id;\n SQL> create table menu_items ( id number, name varchar2(10));\ncreate table order_items (order_id number, menu_item_id number, quantity number);\ncreate table orders (id number, \"date\" date);\n\nTable created.\n\nSQL> \nTable created.\n\nSQL> \nTable created.\n\nSQL> \ninsert into menu_items values (1, 'bread');\ninsert into menu_items values (2, 'milk');\ninsert into menu_items values (3, 'honey');\ninsert into menu_items values (4, 'cheese');\nSQL> \n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \ninsert into orders values (1, to_date('2008-11-02', 'YYYY-MM-DD'));\ninsert into orders values (2, to_date('2008-11-03', 'YYYY-MM-DD'));\ninsert into orders values (3, to_date('2008-10-29', 'YYYY-MM-DD'));SQL> \n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \ninsert into order_items values (1, 1, 1);\ninsert into order_items values (1, 3, 1);\n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \ninsert into order_items values (2, 1, 1);\ninsert into order_items values (2, 2, 1);\ninsert into order_items values (2, 3, 1);\n\ninsert into order_items values (3, 4, 10);\n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \n1 row created.\n\nSQL> \n1 row created.\n\nSQL> SQL> \n\n1 row created.\n\nSQL> \nSELECT\n name\n , nvl(count, 0) as count\nFROM \n menu_items items \n LEFT JOIN (\n SELECT\n menu_items.id\n , SUM(order_items.quantity) as count\n FROM \n menu_items\n LEFT JOIN order_items ON menu_items.id = order_items.menu_item_id\n LEFT JOIN orders ON orders.id = order_items.order_id\n WHERE\n \"date\" between to_date('2008-11-01','YYYY-MM-DD') and to_date('2008-11-30','YYYY-MM-DD')\n GROUP BY\n menu_iteSQL> 2 3 4 5 6 7 ms.id\n ) counts on items.id = counts.id; 8 9 10 11 12 13 14 15 16 17 18 \n\nNAME COUNT\n---------- ----------\nbread 2\nmilk 1\nhoney 2\ncheese 0\n\nSQL> \ndrop table menu_items;\ndrop table order_items;\ndrop table orders;SQL> \nTable dropped.\n\nSQL> \nTable dropped.\n\nSQL> \n\nTable dropped.\n\nSQL> \n"
},
{
"answer_id": 263991,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "JOIN SELECT m.name, COALESCE(SUM(oi.quantity), 0) AS count\nFROM menu_items AS m\n LEFT OUTER JOIN (\n order_items AS oi JOIN orders AS o\n ON (o.id = oi.order_id)\n ) ON (m.id = oi.menu_item_id\n AND o.`date` BETWEEN '2008-11-01' AND '2008-11-30')\nGROUP BY m.id;\n +--------+-------+\n| name | count |\n+--------+-------+\n| bread | 2 | \n| milk | 1 | \n| honey | 2 | \n| cheese | 0 | \n+--------+-------+\n DROP TABLE IF EXISTS menu_items;\nCREATE TABLE menu_items (\n id INT PRIMARY KEY,\n name VARCHAR(10)\n) TYPE=InnoDB;\n\nDROP TABLE IF EXISTS orders;\nCREATE TABLE orders (\n id INT PRIMARY KEY,\n `date` DATE\n) TYPE=InnoDB;\n\nDROP TABLE IF EXISTS order_items;\nCREATE TABLE order_items (\n order_id INT,\n menu_item_id INT,\n quantity INT,\n PRIMARY KEY (order_id, menu_item_id),\n FOREIGN KEY (order_id) REFERENCES orders(id),\n FOREIGN KEY (menu_item_id) REFERENCES menu_items(id)\n) TYPE=InnoDB;\n\nINSERT INTO menu_items VALUES\n (1, 'bread'),\n (2, 'milk'),\n (3, 'honey'),\n (4, 'cheese');\n\nINSERT INTO orders VALUES\n (1, '2008-11-02'),\n (2, '2008-11-03'),\n (3, '2008-10-29');\n\nINSERT INTO order_items VALUES\n (1, 1, 1),\n (1, 3, 1),\n (2, 1, 1),\n (2, 2, 1),\n (2, 3, 1),\n (3, 4, 10);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16417/"
] |
263,820
|
<p>The first batch file launches a command prompt, i need the second command to be in the ccontext of the first. how can I do this in python?</p>
<p>As is, it launches the batch, and blocks until the batch (with its command prompt context) terminates, and then executes <code>devenv</code> without the necessary context.</p>
<pre><code>os.system(r'%comspec% /k ""C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat"" x86')
os.system(r'devenv asdf.sln /rebuild Debug /Out last-build.txt')
</code></pre>
<p>think of it as in i'm in bash, and i need to execute a command in a perl context, so i type <code>perl -c 'asdf'</code>. executing perl and asdf back to back won't work, i need to get the <code>devenv</code> inside of the perl context.</p>
|
[
{
"answer_id": 263856,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "'%comspec% /k \"...vcvarsall.bat\" x86 && devenv asdf.sln /rebuild ...'\n"
},
{
"answer_id": 263881,
"author": "Sanjaya R",
"author_id": 9353,
"author_profile": "https://Stackoverflow.com/users/9353",
"pm_score": 3,
"selected": true,
"text": "compileit.cmd\n call C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\vcvarsall.bat\n devenv $1.sln /rebuild Debug /Out last-build.txt\n"
},
{
"answer_id": 288734,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 2,
"selected": false,
"text": "call ...\\vcvarsall.bat\nc:\\python26\\python.exe myscript.py\n"
},
{
"answer_id": 1237505,
"author": "sorin",
"author_id": 99834,
"author_profile": "https://Stackoverflow.com/users/99834",
"pm_score": 2,
"selected": false,
"text": "%comspec% /C \"%VCINSTALLDIR%\\vcvarsall.bat\" x86 && vcbuild \"project.sln\"\n os.system('%comspec% /C \"%VCINSTALLDIR%\\\\vcvarsall.bat\" x86 && vcbuild \"project.sln\"')\n [HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\9.0]\n\"InstallDir\"=\"c:\\\\Program Files\\\\Microsoft Visual Studio 9.0\\\\Common7\\\\IDE\\\\\"\n ..\\..\\VC\\vcvarsall.bat"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263820",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20003/"
] |
263,821
|
<p>For example, I could just git pull and then git checkout HEAD-1. But is there a way of seeing the differences before deciding whether to git pull or not?</p>
|
[
{
"answer_id": 263833,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "git fetch git log ..origin git pull"
},
{
"answer_id": 264558,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 2,
"selected": false,
"text": "git clone git fetch"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,834
|
<p>I just lost 50% of my answer on a test because I wrote the code out instead of an algorithm on my midterm, bumping me from an A to a C. Is writing code out still considered an algorithmic representation?</p>
<p><a href="http://en.wikipedia.org/wiki/Algorithm#Expressing_algorithms" rel="nofollow noreferrer">Wikipedia: Algorithm Representation</a> (since programming style is pretty much consensus-based)</p>
<p>EDIT: Ok, so let me make a few points clear: </p>
<ol>
<li><p>The test asked for pseudo-code, which we never really "defined" in class; we just wrote out English for our algorithms.</p></li>
<li><p>It's a Java class, and wrote out the entire solution in a Java method, along with comments. All of this was hand-written, and took longer to write out than pseudo-code. I thought it would be more clear.</p></li>
<li><p>I normally wouldn't make an issue about such things, but it's the difference between an A and a C, and I have a scholarship riding on my exams.</p></li>
<li><p>Finally, I'm making this post for two reasons:</p>
<p>4.1 I want to show what the modern programming community thinks about pseudo-code and algorithmic representation.</p>
<p>4.2 I want to know what's acceptable in the "real world"; I've been programming for some time, but I want to be able to contribute to open-source projects soon, and I don't want to step on anyone's toes. (Although I'm pretty sure that this topic has little chance of coming up in the real world).</p></li>
</ol>
<p>Again, thanks for any help/advice.</p>
|
[
{
"answer_id": 263854,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": true,
"text": "sub foo { \n my @args = @_ ; \n my( $a, $b )=(@args[0],@args[1]); \n for( @{ $a } ){\n $b .= $_ ; \n s/id//g; \n }\n return [$b,$a];\n}\n | there is a subroute foo which can take a list of strings, and a default string, \n\\- which then iterates all items in that list, \n| \\- and for each item in that list \n| 1. appends the contents of that item to the end of the default string\n| 2. removes all instances of the string \"id\" in that item\n| \n \\ and returns a list, which contains \n 1. the concatentated default string \n 2. the modified input list \n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10636/"
] |
263,836
|
<p>We are using an Oracle 11 database and a java development environment (using Eclipse) and would like to migrate several xml schemas to SQL schemas.</p>
<p>Have looked ax xsd but really need something that we can run from ant/
Eclipse without SQL Server installed.</p>
<p>Regards,</p>
<p>Andy</p>
|
[
{
"answer_id": 263854,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": true,
"text": "sub foo { \n my @args = @_ ; \n my( $a, $b )=(@args[0],@args[1]); \n for( @{ $a } ){\n $b .= $_ ; \n s/id//g; \n }\n return [$b,$a];\n}\n | there is a subroute foo which can take a list of strings, and a default string, \n\\- which then iterates all items in that list, \n| \\- and for each item in that list \n| 1. appends the contents of that item to the end of the default string\n| 2. removes all instances of the string \"id\" in that item\n| \n \\ and returns a list, which contains \n 1. the concatentated default string \n 2. the modified input list \n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263836",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34469/"
] |
263,838
|
<p>I usually type my map declarations but was doing some maint and found one without typing. This got me thinking (Oh No!). What is the default typing of a Map declaration. Consider the following:</p>
<pre><code>Map map = new HashMap();
map.put("one", "1st");
map.put("two", new Integer(2));
map.put("three", "3rd");
for (Map.Entry entry : map.entrySet()) {
System.out.println(entry.getKey() + " -> " + entry.getValue());
}
</code></pre>
<p>this errors with a incompatible types on Map.Entry. So if I type the declaration with:</p>
<pre><code>Map<Object, Object> map = new HashMap();
</code></pre>
<p>then all works well. So what is the default type that gets set in the declaration about? Or am I missing something else?</p>
|
[
{
"answer_id": 263903,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 3,
"selected": true,
"text": "Map map = new HashMap();\nmap.put(\"one\", \"1st\");\nmap.put(\"two\", new Integer(2));\nmap.put(\"three\", \"3rd\");\nfor (Object o : map.entrySet()) {\n Map.Entry entry = (Map.Entry) o;\n System.out.println(entry.getKey() + \" -> \" + entry.getValue());\n}\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263838",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34475/"
] |
263,850
|
<p>Is there a way to create a Distinct query in HQL. Either by using the "distinct" keyword or some other method. I am not sure if distinct is a valid keywork for HQL, but I am looking for the HQL equivalent of the SQL keyword "distinct".</p>
|
[
{
"answer_id": 263870,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 8,
"selected": true,
"text": "String queryString = \"select distinct f from Foo f inner join foo.bars as b\" +\n \" where f.creationDate >= ? and f.creationDate < ? and b.bar = ?\";\n return getHibernateTemplate().find(queryString, new Object[] {startDate, endDate, bar});\n"
},
{
"answer_id": 313052,
"author": "Daniel Alexiuc",
"author_id": 34553,
"author_profile": "https://Stackoverflow.com/users/34553",
"pm_score": 6,
"selected": false,
"text": "distinct distinct distinct distinct select distinct o from Order o left join fetch o.lineItems\n ResultTransformer"
},
{
"answer_id": 920256,
"author": "Tadeusz Kopec for Ukraine",
"author_id": 113662,
"author_profile": "https://Stackoverflow.com/users/113662",
"pm_score": 2,
"selected": false,
"text": "final ResultTransformer trans = new DistinctRootEntityResultTransformer();\nqry.setResultTransformer(trans);\n final List found = trans.transformList(qry.list());\n"
},
{
"answer_id": 6065843,
"author": "Michael",
"author_id": 699058,
"author_profile": "https://Stackoverflow.com/users/699058",
"pm_score": 4,
"selected": false,
"text": " Criteria crit = (Criteria) session.\n createCriteria(SomeClass.class).\n setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\n List claz = crit.list();\n"
},
{
"answer_id": 15025242,
"author": "San Lin Naing",
"author_id": 2099561,
"author_profile": "https://Stackoverflow.com/users/2099561",
"pm_score": 1,
"selected": false,
"text": "FROM FLIGHT_ROUTE F WHERE F.ROUTE_ID IN (SELECT SF.ROUTE_ID FROM FLIGHT_ROUTE SF GROUP BY SF.TO_CITY);\n"
},
{
"answer_id": 25310246,
"author": "aadi53",
"author_id": 3941677,
"author_profile": "https://Stackoverflow.com/users/3941677",
"pm_score": 3,
"selected": false,
"text": "Criteria.DISTINCT_ROOT_ENTITY Query query = getSession().createQuery(\"from java_pojo_name\");\nquery.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\nreturn query.list();\n"
},
{
"answer_id": 26720538,
"author": "Nathan Mitchell",
"author_id": 4211430,
"author_profile": "https://Stackoverflow.com/users/4211430",
"pm_score": 2,
"selected": false,
"text": "@NamedQuery(name = \"getAllCentralFinancialAgencyAccountCd\", \n query = \"select distinct i from CentralFinancialAgencyAccountCd i\")\n DaoImpl DaoImpl @SuppressWarnings(\"unchecked\")\npublic List<CacheModelBase> getAllCodes() {\n\n Session session = (Session) entityManager.getDelegate();\n org.hibernate.Query q = session.getNamedQuery(\"getAllCentralFinancialAgencyAccountCd\");\n q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); // This is the one line I had to add to make it do a more distinct query.\n List<CacheModelBase> codes;\n codes = q.list();\n return codes; \n}\n"
},
{
"answer_id": 30194486,
"author": "chammu",
"author_id": 1960964,
"author_profile": "https://Stackoverflow.com/users/1960964",
"pm_score": 2,
"selected": false,
"text": "Query distinctFirstName = session.createQuery(\"select ci.firstName from Customer ci group by ci.firstName\");\nObject [] firstNamesRows = distinctFirstName.list();\n"
},
{
"answer_id": 51945678,
"author": "Santosh Singh",
"author_id": 2733355,
"author_profile": "https://Stackoverflow.com/users/2733355",
"pm_score": 2,
"selected": false,
"text": "CriteriaBuilder builder = session.getCriteriaBuilder();\nCriteriaQuery<Orders> query = builder.createQuery(Orders.class);\nRoot<Orders> root = query.from(Orders.class);\nquery.distinct(true).multiselect(root.get(\"cust_email\").as(String.class));\n"
},
{
"answer_id": 61722212,
"author": "Manish Sharma",
"author_id": 3994713,
"author_profile": "https://Stackoverflow.com/users/3994713",
"pm_score": 0,
"selected": false,
"text": "select distinct new com.org.AssetDTO(a.id, a.address, a.status) from Asset as a where ...\n"
},
{
"answer_id": 62042727,
"author": "Rustem",
"author_id": 9708287,
"author_profile": "https://Stackoverflow.com/users/9708287",
"pm_score": 0,
"selected": false,
"text": "@Query(value = \"from someTableEntity where entityCode in :entityCode\" +\n \" group by entityCode, entityName, entityType\")\nList<someTableEntity > findNameByCode(@Param(\"entityCode\") List<String> entityCode);\n"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16404/"
] |
263,890
|
<p>As a simple example, I want to write a CLI script which can print <code>=</code> across the entire width of the terminal window.</p>
<pre><code>#!/usr/bin/env php
<?php
echo str_repeat('=', ???);
</code></pre>
<p>or</p>
<pre><code>#!/usr/bin/env python
print '=' * ???
</code></pre>
<p>or</p>
<pre><code>#!/usr/bin/env bash
x=0
while [ $x -lt ??? ]; do echo -n '='; let x=$x+1 done; echo
</code></pre>
|
[
{
"answer_id": 263900,
"author": "TonyUser",
"author_id": 22873,
"author_profile": "https://Stackoverflow.com/users/22873",
"pm_score": 10,
"selected": true,
"text": "tput cols tput lines"
},
{
"answer_id": 263919,
"author": "pixelbeat",
"author_id": 4421,
"author_profile": "https://Stackoverflow.com/users/4421",
"pm_score": 4,
"selected": false,
"text": "yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\\n'\n"
},
{
"answer_id": 563592,
"author": "David Dean",
"author_id": 67829,
"author_profile": "https://Stackoverflow.com/users/67829",
"pm_score": 7,
"selected": false,
"text": "$LINES $COLUMNS"
},
{
"answer_id": 7575044,
"author": "lyceus",
"author_id": 967809,
"author_profile": "https://Stackoverflow.com/users/967809",
"pm_score": 4,
"selected": false,
"text": "function getTerminalSizeOnWindows() {\n $output = array();\n $size = array('width'=>0,'height'=>0);\n exec('mode',$output);\n foreach($output as $line) {\n $matches = array();\n $w = preg_match('/^\\s*columns\\:?\\s*(\\d+)\\s*$/i',$line,$matches);\n if($w) {\n $size['width'] = intval($matches[1]);\n } else {\n $h = preg_match('/^\\s*lines\\:?\\s*(\\d+)\\s*$/i',$line,$matches);\n if($h) {\n $size['height'] = intval($matches[1]);\n }\n }\n if($size['width'] AND $size['height']) {\n break;\n }\n }\n return $size;\n}\n"
},
{
"answer_id": 10081642,
"author": "LeoNerd",
"author_id": 1069726,
"author_profile": "https://Stackoverflow.com/users/1069726",
"pm_score": 4,
"selected": false,
"text": "TIOCGWINSZ ioctl() use Term::Size qw( chars );\n\nmy ( $columns, $rows ) = chars \\*STDOUT;\n"
},
{
"answer_id": 21190143,
"author": "Camilo Martin",
"author_id": 124119,
"author_profile": "https://Stackoverflow.com/users/124119",
"pm_score": 2,
"selected": false,
"text": "mode preg_match('/---+(\\n[^|]+?){2}(?<cols>\\d+)/', `mode`, $matches);\n $cols = $matches['cols'];\n preg_match('/CON.*:(\\n[^|]+?){3}(?<cols>\\d+)/', `mode`, $matches);\n $cols = $matches['cols'];\n"
},
{
"answer_id": 26855761,
"author": "ryenus",
"author_id": 537554,
"author_profile": "https://Stackoverflow.com/users/537554",
"pm_score": 7,
"selected": false,
"text": "stty $ stty size\n60 120 # <= sample output\n\n# To read into variables, in bash\n$ read -r rows cols < <(stty size)\n$ echo \"rows: $rows, cols: $cols\"\nrows: 60, cols: 120\n cut awk stty size | cut -d\" \" -f1 stty size | cut -d\" \" -f2"
},
{
"answer_id": 49876367,
"author": "huoneusto",
"author_id": 1814589,
"author_profile": "https://Stackoverflow.com/users/1814589",
"pm_score": 2,
"selected": false,
"text": "tput printf tr printf \"%0$(tput cols)d\" 0|tr '0' '='\n"
},
{
"answer_id": 54008767,
"author": "pourhaus",
"author_id": 3558322,
"author_profile": "https://Stackoverflow.com/users/3558322",
"pm_score": 1,
"selected": false,
"text": "function term_size\n{\n local i=0 digits='' tens_fmt='' tens_args=()\n for i in {80..8}\n do\n echo $i $(( i - 2 ))\n done\n echo \"If columns below wrap, LINES is first number in highest line above,\"\n echo \"If truncated, LINES is second number.\"\n for i in {1..14}\n do\n digits=\"${digits}1234567890\"\n tens_fmt=\"${tens_fmt}%10d\"\n tens_args=(\"${tens_args[@]}\" $i)\n done\n printf \"$tens_fmt\\n\" \"${tens_args[@]}\"\n echo \"$digits\"\n}\n"
},
{
"answer_id": 68085512,
"author": "Odin Kroeger",
"author_id": 1523367,
"author_profile": "https://Stackoverflow.com/users/1523367",
"pm_score": 2,
"selected": false,
"text": "$TERM_SIZE set_term_size() {\n TERM_SIZE=\"$(stty size 2>/dev/null)\" && [ \"$TERM_SIZE\" ] ||\n TERM_SIZE='25 80'\n}\ntrap set_term_size WINCH\nset_term_size\n stty size size stty echo \"${TERM_SIZE% *}\" # Prints the terminal's height.\necho \"${TERM_SIZE#* }\" # Prints the terminal's width.\n printf printf '%*s\\n' \"${TERM_SIZE#* }\" '' | \ntr ' ' -\n printf * tr"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28835/"
] |
263,892
|
<p>I'm using Gnome terminal and I want to change the background color or the profile through a command so I can group some commands in an alias to visually differentiate my windows when I run certain processes. I'm running Ubuntu, and bash is my shell. Are there commands in to do this?</p>
|
[
{
"answer_id": 263957,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 2,
"selected": false,
"text": "gnome-terminal --hide-menubar --geometry 115x40+0+0\ngnome-terminal --window-with-profile=logs --hide-menubar --geometry=144x15+0-55\n"
},
{
"answer_id": 1936387,
"author": "Zeograd",
"author_id": 232849,
"author_profile": "https://Stackoverflow.com/users/232849",
"pm_score": 4,
"selected": false,
"text": "setterm -term linux -back blue -fore white -clear\n"
},
{
"answer_id": 7605564,
"author": "serxyz",
"author_id": 972339,
"author_profile": "https://Stackoverflow.com/users/972339",
"pm_score": 2,
"selected": false,
"text": ".bashrc alias Gterm='gnome-terminal --window-with-profile=myGterm'\n .bashrc $ Gterm\n"
},
{
"answer_id": 14059620,
"author": "Jonathan Chad Faling",
"author_id": 1894837,
"author_profile": "https://Stackoverflow.com/users/1894837",
"pm_score": 1,
"selected": false,
"text": "$.bash_profile\n alias term1='gnome-terminal –window-with-profile=term1'\nalias term2='gnome-terminal –window-with-profile=term2'\nalias term3='gnome-terminal –window-with-profile=term3'\nalias term4='gnome-terminal –window-with-profile=term4'\n"
},
{
"answer_id": 18397919,
"author": "wessexmario",
"author_id": 2710224,
"author_profile": "https://Stackoverflow.com/users/2710224",
"pm_score": 2,
"selected": false,
"text": "gnome-terminal --window-with-profile=site2 -x ssh site2\n -x ssh"
},
{
"answer_id": 35316936,
"author": "Joniale",
"author_id": 5842403,
"author_profile": "https://Stackoverflow.com/users/5842403",
"pm_score": 0,
"selected": false,
"text": " function create_random_profile() {\n #delete previous profiles in case there were something\n #delete_one_random_profile\n prof=\"`mktemp -u HACK_PROFILE_XXXXXXXXXX`\"\n gconftool-2 --type list --list-type string --set $prof_list \"`gconftool-2 --get $prof_list | sed \"s/]/,$prof]/\"`\"\n file=\"`mktemp`\"\n gconftool-2 --dump \"/apps/gnome-terminal/profiles/Default\" | sed \"s,profiles/$2,profiles/$prof,g\" > \"$file\"\n gconftool-2 --load \"$file\"\n gconftool-2 --type string --set \"/apps/gnome-terminal/profiles/$prof/visible_name\" \"$prof\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$prof/use_theme_colors\" --type bool false\n rm -f -- \"$file\"\n export __TERM_PROF=$prof\n }\n\n function delete_one_random_profile() {\n regular=\"HACK_PROFILE_\"\n prof=$(gconftool-2 --get /apps/gnome-terminal/global/profile_list | sed -n \"s/.*\\(HACK_PROFILE_..........\\).*/\\1/p\") \n if [ ! -z \"$prof\"]; then\n echo \"size ${#prof}\"\n echo \"size of regular ${#regular}\"\n echo \"DO DELETE of $prof\"\n #if not empty\n gconftool-2 --type list --list-type string --set $prof_list \"`gconftool-2 --get $prof_list | sed \"s/$prof//;s/\\[,/[/;s/,,/,/;s/,]/]/\"`\"\n gconftool-2 --unset \"/apps/gnome-terminal/profiles/$prof\"\n else\n echo \"NOTHING TO DELETE\"\n fi\n }\n\n function setcolord() \n {\n echo \"Dont forget to change to Profile0 in the menu of your terminal->Change Profile->Profile_0\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/background_color\" --type string white\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/foreground_color\" --type string black\n }\n function setcolor_cyan() \n {\n echo \"Dont forget to change to $__TERM_PROF in the menu of your terminal->Change Profile->Profile_0\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/background_color\" --type string \"#8DCBCC\"\n gconftool-2 --set \"/apps/gnome-terminal/profiles/$__TERM_PROF/foreground_color\" --type string black\n }\n gnome-terminal --working-directory=$HOME --window-with-profile=\"$prof\" \n"
},
{
"answer_id": 58657948,
"author": "Beginer",
"author_id": 8691290,
"author_profile": "https://Stackoverflow.com/users/8691290",
"pm_score": -1,
"selected": false,
"text": "sudo apt-get install dconf-cli uuid-runtime\nbash -c \"$(wget -qO- https://git.io/vQgMr)\"\n"
},
{
"answer_id": 69015595,
"author": "Tschallacka",
"author_id": 1356107,
"author_profile": "https://Stackoverflow.com/users/1356107",
"pm_score": 2,
"selected": false,
"text": "echo -e '\\e]11;rgb:aa/bb/cc\\a'\n \\e]10; \\e]11; let bg = document.getElementById('bg');\nlet fg = document.getElementById('fg');\nlet binp = document.getElementById('numberbg');\nlet finp = document.getElementById('numberfg');\n\nbinp.addEventListener('input', (e) => {\n let val = spl(e);\n bg.innerText = \"echo -e '\\\\e]11;rgb:\"+val+\"\\\\a'\"; \n up(bg); up(fg);\n});\n\nfinp.addEventListener('input', (e) => {\n let val = spl(e);;\n fg.innerText = \"echo -e '\\\\e]10;rgb:\"+val+\"\\\\a'\";\n up(bg); up(fg);\n});\n\nfunction spl(e) { \n return e.target.value.substring(1).match(/.{1,2}/g).join('/');\n}\n\nfunction up(i) {\n i.style.backgroundColor = binp.value;\n i.style.color = finp.value;\n} code {\n margin: 20px;\n background: #ddd;\n border: 1px solid #333;\n padding:20px;\n clear:both;\n display: inline-block;\n} <div>\n <label for=\"numberbg\">set background: </label>\n <input id=\"numberbg\" type=\"color\" value=\"#000000\"> <BR>\n <code id=\"bg\">\n echo -e '\\e]11;rgb:00/00/00\\a'\n </code>\n</div>\n<div>\n <label for=\"numberfg\">set foreground: </label>\n <input id=\"numberfg\" type=\"color\" value=\"#eeeeee\"> <BR>\n <code id=\"fg\">\n echo -e '\\e]10;rgb:ee/ee/ee\\a'\n </code>\n</div>"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,899
|
<p>I have been searching for a way to allow one element of my FileHelpers mapping class to be an array of specific length.</p>
<p>For instance, I have a class like this:</p>
<pre><code>[DelimitedRecord(",")]
public class Example
{
public string code;
public int month;
public int day;
public double h1;
public double h2;
public double h3;
public double h4;
}
</code></pre>
<p>The values h1-h4 would really make more sense as an array simply called 'h'. It would make processing the file a little easier as well.
I also know that the file I am reading will always have these, and only these, fields in it.</p>
<p>Has anyone figured out a way to include arrays in your FileHelper mapping classes?</p>
|
[
{
"answer_id": 264500,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "[DelimitedRecord(\",\")]\npublic class Example\n{\n public string Code {get;set;}\n public int Month {get;set;}\n public int Day {get;set;}\n\n private readonly double[] h = new double[4];\n\n public double H1 {get {return h[0];} set {h[0] = value;}}\n public double H2 {get {return h[1];} set {h[1] = value;}}\n public double H3 {get {return h[2];} set {h[2] = value;}}\n public double H4 {get {return h[3];} set {h[3] = value;}}\n}\n public double H1 {get;set;}\n public double H2 {get;set;}\n public double H3 {get;set;}\n public double H4 {get;set;}\n"
},
{
"answer_id": 13187743,
"author": "shamp00",
"author_id": 1077279,
"author_profile": "https://Stackoverflow.com/users/1077279",
"pm_score": 1,
"selected": false,
"text": "Example[]"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263899",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23597/"
] |
263,906
|
<pre><code>AlertEvent::AlertEvent(const std::string& text) :
IMEvent(kIMEventAlert, alertText.c_str()),
alertText(text)
{
//inspection at time of crash shows alertText is a valid string
}
IMEvent::IMEvent(long eventID, const char* details)
{
//during construction, details==0xcccccccc
}
</code></pre>
<p>on a related note, the monospace font looks really terrible in chrome, whats up with that?</p>
|
[
{
"answer_id": 263911,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "alertText.c_str()"
},
{
"answer_id": 263914,
"author": "Adam Holmberg",
"author_id": 20688,
"author_profile": "https://Stackoverflow.com/users/20688",
"pm_score": 3,
"selected": true,
"text": "AlertEvent::AlertEvent(const std::string& text) :\n IMEvent(kIMEventAlert, text.c_str()),\n alertText(text)\n{\n //inspection at time of crash shows alertText is a valid string\n}\n\n\nIMEvent::IMEvent(long eventID, const char* details)\n{\n //during construction, details==0xcccccccc\n}\n"
},
{
"answer_id": 263918,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 1,
"selected": false,
"text": "alertText.c_str() text.c_str()"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20003/"
] |
263,913
|
<p>I am trying to get the DataGridView to render the "insert new row" row as the first row in the grid instead of the last row. How do I go about doing that, is it even possible in the control?</p>
|
[
{
"answer_id": 264014,
"author": "jons911",
"author_id": 34375,
"author_profile": "https://Stackoverflow.com/users/34375",
"pm_score": 4,
"selected": true,
"text": " Dim myrow = existingDataTable.NewRow\n\n existingDataTable.Rows.Add(myrow)\n\n adp.Fill(existingDataTable)\n With DataGridView1\n .DataSource =existingDataTable\n End With \n"
},
{
"answer_id": 7918419,
"author": "banifesto",
"author_id": 1016811,
"author_profile": "https://Stackoverflow.com/users/1016811",
"pm_score": 1,
"selected": false,
"text": "Insert Add Insert(0) DataGridView1.Rows.Insert(0) DataGridView1.Rows(0).Cells(n).Value = \"abc\""
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32809/"
] |
263,926
|
<p>What are some tiny open source operating systems? I'm looking for something several orders of magnitude smaller than Puppy Linux, Feather Linux, DSL, etc. I want to run a command-line text editor and compiler; anything else is extraneous. I'm looking for a system I can take apart and acquire a fairly good understanding of the whole thing in a reasonable period of time. Bonus points for something that is portable and well-documented.</p>
|
[
{
"answer_id": 11207845,
"author": "Deepthought",
"author_id": 996882,
"author_profile": "https://Stackoverflow.com/users/996882",
"pm_score": 2,
"selected": false,
"text": "qemu bochs gdb git(1) $ git clone git://pdos.csail.mit.edu/xv6/xv6.git"
}
] |
2008/11/04
|
[
"https://Stackoverflow.com/questions/263926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32944/"
] |
263,938
|
<p>For my small wiki application, I mostly need to have the textarea used to edit the contents to use soft (or virtual) wrapping. However, in some cases, not wrapping the content would be preferable. I thought I would do this by simply having a button to turn off wrapping. Here is the simplified code:</p>
<pre><code> <form name="wikiedit" action="[[script_name]]" method="post">
<textarea name="content" rows="25" cols="90" wrap="virtual">[[content]]</textarea>
<input type="button" onclick="document.wikiedit.content.wrap='off';" value="No Wrap"> &nbsp;
<input type="submit" value="Save">
</form>
</code></pre>
<p>It works with IE, but not with Firefox or Opera. How should I do this?</p>
|
[
{
"answer_id": 264006,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "wrap <textarea> wrap // this is the onclick handler for your button\ndocument.getElementById(\"nowrapButton\").onclick = function() {\n var oldOne = this.form.content; // the old textarea\n var newOne = document.createElement('textarea'); // the new textarea\n var attrs = ['name', 'rows', 'cols']; // these are the attributes to keep\n for (var i = 0; i < attrs.length; ++i) {\n // copy the attributes to the new one\n newOne.setAttribute(attrs[i], oldOne.getAttribute(attrs[i]));\n }\n\n // toggle the wrapping on and off\n if (oldOne.getAttribute('wrap') != 'off') {\n newOne.setAttribute('wrap', 'off');\n }\n\n // copy the text over\n newOne.value = oldOne.value;\n\n // add the new one\n oldOne.parentNode.insertBefore(newOne, oldOne);\n // get rid of the old one\n oldOne.parentNode.removeChild(oldOne);\n return false;\n};\n"
},
{
"answer_id": 264094,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 3,
"selected": true,
"text": "function setWrap(area, wrap) {\n if (area.wrap) {\n area.wrap= wrap;\n } else { // wrap attribute not supported - try Mozilla workaround\n area.setAttribute('wrap', wrap);\n var newarea= area.cloneNode(true);\n newarea.value= area.value;\n area.parentNode.replaceChild(newarea, area);\n }\n}\n"
},
{
"answer_id": 264218,
"author": "Jared Farrish",
"author_id": 451969,
"author_profile": "https://Stackoverflow.com/users/451969",
"pm_score": 1,
"selected": false,
"text": "white-space: pre; overflow: auto;\n <script type=\"text/javascript\">\nfunction setNoWrap(textarea) {\n textarea.style.whiteSpace = 'pre';\n textarea.style.overflow = 'auto';\n}\n</script>\n<form name=\"wikiedit\" action=\"[[script_name]]\" method=\"post\">\n <textarea name=\"content\" rows=\"25\" cols=\"90\" wrap=\"virtual\">[[content]]</textarea>\n <input type=\"button\" onclick=\"setNoWrap(this);\" value=\"No Wrap\"> \n <input type=\"submit\" value=\"Save\">\n</form>\n"
},
{
"answer_id": 4702505,
"author": "Jesse Merriman",
"author_id": 105782,
"author_profile": "https://Stackoverflow.com/users/105782",
"pm_score": 0,
"selected": false,
"text": "function setWrap(area, wrap) {\n if (area.wrap) {\n area.wrap = wrap;\n } else { // wrap attribute not supported - try Mozilla workaround\n area.setAttribute(\"wrap\", wrap);\n area.style.overflow = \"hidden\";\n area.style.overflow = \"auto\";\n }\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,945
|
<p>In the following code I loop through a map and test if an element needs to be erased. Is it safe to erase the element and keep iterating or do I need to collect the keys in another container and do a second loop to call the erase()?</p>
<pre><code>map<string, SerialdMsg::SerialFunction_t>::iterator pm_it;
for (pm_it = port_map.begin(); pm_it != port_map.end(); pm_it++)
{
if (pm_it->second == delete_this_id) {
port_map.erase(pm_it->first);
}
}
</code></pre>
<p>UPDATE: Of course, I then <a href="https://stackoverflow.com/questions/52714/stl-vector-vs-map-erase">read this question</a> which I didn't think would be related but answers my question.</p>
|
[
{
"answer_id": 263958,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 9,
"selected": true,
"text": "auto pm_it = port_map.begin();\nwhile(pm_it != port_map.end())\n{\n if (pm_it->second == delete_this_id)\n {\n pm_it = port_map.erase(pm_it);\n }\n else\n {\n ++pm_it;\n }\n}\n map<string, SerialdMsg::SerialFunction_t>::iterator pm_it = port_map.begin();\nwhile(pm_it != port_map.end())\n{\n if (pm_it->second == delete_this_id)\n {\n port_map.erase(pm_it++); // Use iterator.\n // Note the post increment.\n // Increments the iterator but returns the\n // original value for use by erase \n }\n else\n {\n ++pm_it; // Can use pre-increment in this case\n // To make sure you have the efficient version\n }\n}\n"
},
{
"answer_id": 263975,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 1,
"selected": false,
"text": "bool is_remove( pair<string, SerialdMsg::SerialFunction_t> val )\n{\n return val.second == delete_this_id;\n}\n\nmap<string, SerialdMsg::SerialFunction_t>::iterator new_end = \n remove_if (port_map.begin( ), port_map.end( ), is_remove );\n\nport_map.erase (new_end, port_map.end( ) );\n val.second == delete_this_id\n"
},
{
"answer_id": 825058,
"author": "AlaaShaker",
"author_id": 63326,
"author_profile": "https://Stackoverflow.com/users/63326",
"pm_score": 4,
"selected": false,
"text": "typedef map<string, string> StringsMap;\ntypedef StringsMap::iterator StrinsMapIterator;\n\nStringsMap m_TheMap; // Your map, fill it up with data \n\nbool IsTheOneToDelete(string str)\n{\n return true; // Add your deletion criteria logic here\n}\n\nvoid SelectiveDelete()\n{\n StringsMapIter itBegin = m_TheMap.begin();\n StringsMapIter itEnd = m_TheMap.end();\n StringsMapIter itTemp;\n\n while (itBegin != itEnd)\n {\n if (IsTheOneToDelete(itBegin->second)) // Criteria checking here\n {\n itTemp = itBegin; // Keep a reference to the iter\n ++itBegin; // Advance in the map\n m_TheMap.erase(itTemp); // Erase it !!!\n }\n else\n ++itBegin; // Just move on ...\n }\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
] |
263,962
|
<p>Is there a difference in passing parameters to <code>.load</code></p>
<pre><code>$("#myDiv").load("myScript.php?var=x&var2=y&var3=z")
</code></pre>
<p>vs</p>
<pre><code>$("#myDiv").load("myScript.php", {var1:x, var2:y, var3:z})
</code></pre>
<p>Also, is there a size limit to how much <code>.load</code> can handle? Can
<code>myScript.php</code> return a couple hundred rows of data without issue?</p>
|
[
{
"answer_id": 21646214,
"author": "Farshid Saberi",
"author_id": 1790801,
"author_profile": "https://Stackoverflow.com/users/1790801",
"pm_score": 5,
"selected": false,
"text": "$(\"#myDiv\").load(\"myScript.php?var=x&var2=y&var3=z\")\n $(\"#myDiv\").load(\"myScript.php\", {var:x, var2:y, var3:z})\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,965
|
<p>Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?</p>
<p>I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.</p>
<p>The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.</p>
<pre><code>var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';
</code></pre>
<p>Is there a better way to accomplish this?</p>
|
[
{
"answer_id": 264037,
"author": "guinaps",
"author_id": 27225,
"author_profile": "https://Stackoverflow.com/users/27225",
"pm_score": 13,
"selected": true,
"text": "var isTrueSet = (myValue === 'true');\n === isTrueSet true false var myBool = Boolean(\"false\"); // == true\n\nvar myBool = !!\"false\"; // == true\n true"
},
{
"answer_id": 264071,
"author": "Jared Farrish",
"author_id": 451969,
"author_profile": "https://Stackoverflow.com/users/451969",
"pm_score": 7,
"selected": false,
"text": "var isTrueSet = (myValue.toLowerCase() === 'true');\n var isTrueSet = document.myForm.IS_TRUE.checked;\n"
},
{
"answer_id": 264097,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 5,
"selected": false,
"text": "=== value String"
},
{
"answer_id": 264180,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 7,
"selected": false,
"text": "/*\n * Converts a string to a bool.\n *\n * This conversion will:\n *\n * - match 'true', 'on', or '1' as true.\n * - ignore all white-space padding\n * - ignore capitalization (case).\n *\n * ' tRue ','ON', and '1 ' will all evaluate as true.\n *\n */\nfunction strToBool(s)\n{\n // will match one and only one of the string 'true','1', or 'on' rerardless\n // of capitalization and regardless off surrounding white-space.\n //\n regex=/^\\s*(true|1|on)\\s*$/i\n\n return regex.test(s);\n}\n String.prototype.bool = function() {\n return strToBool(this);\n};\n\nalert(\"true\".bool());\n Object.defineProperty(String.prototype, \"com_example_bool\", {\n get : function() {\n return (/^(true|1)$/i).test(this);\n }\n});\nalert(\"true\".com_example_bool);\n"
},
{
"answer_id": 323546,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "if (String(a).toLowerCase() == \"true\") String(true) == \"true\" //returns true\nString(false) == \"true\" //returns false\nString(\"true\") == \"true\" //returns true\nString(\"false\") == \"true\" //returns false\n"
},
{
"answer_id": 920942,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "if (String(a) == \"true\"){\n //true block\n} else {\n //false block\n}\n"
},
{
"answer_id": 1414175,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "const stringToBoolean = (stringValue) => {\n switch(stringValue?.toLowerCase()?.trim()){\n case \"true\": \n case \"yes\": \n case \"1\": \n return true;\n\n case \"false\": \n case \"no\": \n case \"0\": \n case null: \n case undefined:\n return false;\n\n default: \n return JSON.parse(stringValue);\n }\n}\n"
},
{
"answer_id": 2114055,
"author": "PixelSlave",
"author_id": 256308,
"author_profile": "https://Stackoverflow.com/users/256308",
"pm_score": -1,
"selected": false,
"text": "var myBool = eval (yourString);\n alert (eval (\"true\") == true); // TRUE\nalert (eval (\"true\") == false); // FALSE\nalert (eval (\"1\") == true); // TRUE\nalert (eval (\"1\") == false); // FALSE\nalert (eval (\"false\") == true); // FALSE;\nalert (eval (\"false\") == false); // TRUE\nalert (eval (\"0\") == true); // FALSE\nalert (eval (\"0\") == false); // TRUE\nalert (eval (\"\") == undefined); // TRUE\nalert (eval () == undefined); // TRUE\n"
},
{
"answer_id": 2114091,
"author": "Thomas Eding",
"author_id": 239916,
"author_profile": "https://Stackoverflow.com/users/239916",
"pm_score": 4,
"selected": false,
"text": "Boolean.parse = function (str) {\n switch (str.toLowerCase ()) {\n case \"true\":\n return true;\n case \"false\":\n return false;\n default:\n throw new Error (\"Boolean.parse: Cannot convert string to boolean.\");\n }\n};\n"
},
{
"answer_id": 3394176,
"author": "cypher",
"author_id": 381786,
"author_profile": "https://Stackoverflow.com/users/381786",
"pm_score": 0,
"selected": false,
"text": "String.prototype.boolean = function() {\n return \"true\" == this; \n};\n\n\"true\".boolean() // returns true \"false\".boolean() // returns false\n"
},
{
"answer_id": 4380804,
"author": "thdoan",
"author_id": 452587,
"author_profile": "https://Stackoverflow.com/users/452587",
"pm_score": 5,
"selected": false,
"text": "Boolean('false') !!'false' true 'true' true 'false' false eval() eval('true') eval('false') eval()"
},
{
"answer_id": 7516741,
"author": "risingfish",
"author_id": 959378,
"author_profile": "https://Stackoverflow.com/users/959378",
"pm_score": 3,
"selected": false,
"text": "var z = 'true';\nvar y = 'false';\nvar b = (z === 'true'); // will evaluate to true\nvar c = (y === 'true'); // will evaluate to false\n"
},
{
"answer_id": 7573471,
"author": "Vitim.us",
"author_id": 938822,
"author_profile": "https://Stackoverflow.com/users/938822",
"pm_score": 1,
"selected": false,
"text": "function returnBoolean(str){\n\n str=str.toString().toLowerCase();\n\n if(str=='true' || str=='1' || str=='yes' || str=='y' || str=='on' || str=='+'){\n return(true);\n }\n else if(str=='false' || str=='0' || str=='no' || str=='n' || str=='off' || str=='-'){\n return(false);\n }else{\n return(undefined);\n }\n}\n"
},
{
"answer_id": 7833897,
"author": "Luke",
"author_id": 451139,
"author_profile": "https://Stackoverflow.com/users/451139",
"pm_score": 10,
"selected": false,
"text": "\"true\" \"false\" JSON.parse(\"True\".toLowerCase());\n $.parseJSON(\"TRUE\".toLowerCase());\n"
},
{
"answer_id": 9709935,
"author": "hajikelist",
"author_id": 822354,
"author_profile": "https://Stackoverflow.com/users/822354",
"pm_score": 2,
"selected": false,
"text": "<input type='button' onclick='this.value = tog(this.value);' />\n\n<script type=\"text/javascript\">\n\n function tog(off) {\n if(off) {\n alert('true, toggle to false');\n return '';\n } else {\n alert('false, toggle to true');\n return '1';\n }\n } \n</script>\n"
},
{
"answer_id": 10033879,
"author": "imjustmatthew",
"author_id": 864300,
"author_profile": "https://Stackoverflow.com/users/864300",
"pm_score": 3,
"selected": false,
"text": "function parseBoolean(string) {\n switch (String(string).toLowerCase()) {\n case \"true\":\n case \"1\":\n case \"yes\":\n case \"y\":\n return true;\n case \"false\":\n case \"0\":\n case \"no\":\n case \"n\":\n return false;\n default:\n //you could throw an error, but 'undefined' seems a more logical reply\n return undefined;\n }\n}\n"
},
{
"answer_id": 10727873,
"author": "Scrimothy",
"author_id": 1408356,
"author_profile": "https://Stackoverflow.com/users/1408356",
"pm_score": 2,
"selected": false,
"text": "var str=\"true\";\nvar boolStr=Boolean(str.match(/^true$/i)); \n function stringToBool(str) {\n var bool;\n if (str.match(/^(true|1|yes)$/i) !== null) {\n bool = true;\n } else if (str.match(/^(false|0|no)*$/i) !== null) {\n bool = false;\n } else {\n bool = null;\n if (console) console.log('\"' + str + '\" is not a boolean value');\n }\n return bool;\n}\n\nstringToBool('1'); // true\nstringToBool('No'); // false\nstringToBool('falsey'); // null (\"falsey\" is not a boolean value.)\nstringToBool(''); // false\n"
},
{
"answer_id": 12037917,
"author": "mbeasley",
"author_id": 984239,
"author_profile": "https://Stackoverflow.com/users/984239",
"pm_score": 1,
"selected": false,
"text": "Boolean.parse()"
},
{
"answer_id": 13030634,
"author": "jerone",
"author_id": 108448,
"author_profile": "https://Stackoverflow.com/users/108448",
"pm_score": 2,
"selected": false,
"text": "var result = !isNaN(value) ? parseFloat(value) : /^\\s*(true|false)\\s*$/i.exec(value) ? RegExp.$1.toLowerCase() === \"true\" : value;\n"
},
{
"answer_id": 14462838,
"author": "AndreasPizsa",
"author_id": 199263,
"author_profile": "https://Stackoverflow.com/users/199263",
"pm_score": 4,
"selected": false,
"text": "/^true$/i.test(myValue)\n var isTrueSet = /^true$/i.test(myValue);\n myValue /^true$/i.test(\"true\"); // true\n/^true$/i.test(\"TRUE\"); // true\n/^true$/i.test(\"tRuE\"); // true\n/^true$/i.test(\" tRuE\"); // false (notice the space at the beginning)\n/^true$/i.test(\"untrue\"); // false (some other solutions here will incorrectly return true\n/^true$/i.test(\"false\");// returns false\n/^true$/i.test(\"xyz\"); // returns false\n"
},
{
"answer_id": 14542479,
"author": "BishopZ",
"author_id": 901379,
"author_profile": "https://Stackoverflow.com/users/901379",
"pm_score": 3,
"selected": false,
"text": "JSON.parse(\"FALSE\") // fails\n if(value === \"TRUE\" || value === \"yes\" || ...) { return true; }\n return /^true$/i.test(v);\n"
},
{
"answer_id": 15125270,
"author": "jackvsworld",
"author_id": 1097054,
"author_profile": "https://Stackoverflow.com/users/1097054",
"pm_score": 2,
"selected": false,
"text": "parse:\n function (value) {\n switch (value && value.toLowerCase()) {\n case null: return null;\n case \"true\": return true;\n case \"false\": return false;\n default: try { return parseFloat(value); } catch (e) { return value; }\n }\n }\n"
},
{
"answer_id": 16937888,
"author": "purab",
"author_id": 1057818,
"author_profile": "https://Stackoverflow.com/users/1057818",
"pm_score": 1,
"selected": false,
"text": "var yourstring = yourstringValue == 1 ? true : false;"
},
{
"answer_id": 17258019,
"author": "dalimian",
"author_id": 1275064,
"author_profile": "https://Stackoverflow.com/users/1275064",
"pm_score": 2,
"selected": false,
"text": "/**\n * @example\n * <code>\n * var pageRequestParams = {'enableFeatureX': 'true'};\n * toBool(pageRequestParams.enableFeatureX); // returns true\n *\n * toBool(pageRequestParams.enableFeatureY, true, options.enableFeatureY)\n * </code>\n * @param {*}value\n * @param {Boolean}[mapEmptyStringToTrue=false]\n * @param {Boolean}[defaultVal=false] this is returned if value is undefined.\n *\n * @returns {Boolean}\n * @example\n * <code>\n * toBool({'enableFeatureX': '' }.enableFeatureX); // false\n * toBool({'enableFeatureX': '' }.enableFeatureX, true); // true\n * toBool({ }.enableFeatureX, true); // false\n * toBool({'enableFeatureX': 0 }.enableFeatureX); // false\n * toBool({'enableFeatureX': '0' }.enableFeatureX); // false\n * toBool({'enableFeatureX': '0 ' }.enableFeatureX); // false\n * toBool({'enableFeatureX': 'false' }.enableFeatureX); // false\n * toBool({'enableFeatureX': 'falsE ' }.enableFeatureX); // false\n * toBool({'enableFeatureX': 'no' }.enableFeatureX); // false\n *\n * toBool({'enableFeatureX': 1 }.enableFeatureX); // true\n * toBool({'enableFeatureX': '-2' }.enableFeatureX); // true\n * toBool({'enableFeatureX': 'true' }.enableFeatureX); // true\n * toBool({'enableFeatureX': 'false_' }.enableFeatureX); // true\n * toBool({'enableFeatureX': 'john doe'}.enableFeatureX); // true\n * </code>\n *\n */\nvar toBool = function (value, mapEmptyStringToTrue, defaultVal) {\n if (value === undefined) {return Boolean(defaultVal); }\n mapEmptyStringToTrue = mapEmptyStringToTrue !== undefined ? mapEmptyStringToTrue : false; // default to false\n var strFalseValues = ['0', 'false', 'no'].concat(!mapEmptyStringToTrue ? [''] : []);\n if (typeof value === 'string') {\n return (strFalseValues.indexOf(value.toLowerCase().trim()) === -1);\n }\n // value is likely null, boolean, or number\n return Boolean(value);\n};\n"
},
{
"answer_id": 17264572,
"author": "Andreas Dyballa",
"author_id": 1636136,
"author_profile": "https://Stackoverflow.com/users/1636136",
"pm_score": 2,
"selected": false,
"text": " MyLib.Convert.bool = function(param) {\n var res = String(param).toLowerCase();\n return !(!Boolean(res) || res === \"false\" || res === \"0\");\n }; \n"
},
{
"answer_id": 17558318,
"author": "user3638793",
"author_id": 3638793,
"author_profile": "https://Stackoverflow.com/users/3638793",
"pm_score": 2,
"selected": false,
"text": "val = 'false';\n\nval = /^false$/i.test(val) ? false : ( /^true$/i.test(val) ? true : val*1 ? val*1 : val );\n"
},
{
"answer_id": 17961343,
"author": "zobier",
"author_id": 18469,
"author_profile": "https://Stackoverflow.com/users/18469",
"pm_score": 4,
"selected": false,
"text": "function parseBool(b) {\n return !(/^(false|0)$/i).test(b) && !!b;\n}\n"
},
{
"answer_id": 18355136,
"author": "Dead.Rabit",
"author_id": 424963,
"author_profile": "https://Stackoverflow.com/users/424963",
"pm_score": 3,
"selected": false,
"text": "\"false\" var value = \"false\";\nvar result = (value == \"false\") != Boolean(value);\n\n// value = \"true\" => result = true\n// value = \"false\" => result = false\n// value = true => result = true\n// value = false => result = false\n// value = null => result = false\n// value = [] => result = true\n// etc..\n"
},
{
"answer_id": 19394362,
"author": "Cliff Mayson",
"author_id": 1100126,
"author_profile": "https://Stackoverflow.com/users/1100126",
"pm_score": 3,
"selected": false,
"text": "function parseBool(value) {\n if (typeof value === \"boolean\") return value;\n\n if (typeof value === \"number\") {\n return value === 1 ? true : value === 0 ? false : undefined;\n }\n\n if (typeof value != \"string\") return undefined;\n\n return value.toLowerCase() === 'true' ? true : false;\n}\n"
},
{
"answer_id": 19882502,
"author": "CMCDragonkai",
"author_id": 582917,
"author_profile": "https://Stackoverflow.com/users/582917",
"pm_score": 3,
"selected": false,
"text": "/**\n * Parses mixed type values into booleans. This is the same function as filter_var in PHP using boolean validation\n * @param {Mixed} value \n * @param {Boolean} nullOnFailure = false\n * @return {Boolean|Null}\n */\nvar parseBooleanStyle = function(value, nullOnFailure = false){\n switch(value){\n case true:\n case 'true':\n case 1:\n case '1':\n case 'on':\n case 'yes':\n value = true;\n break;\n case false:\n case 'false':\n case 0:\n case '0':\n case 'off':\n case 'no':\n value = false;\n break;\n default:\n if(nullOnFailure){\n value = null;\n }else{\n value = false;\n }\n break;\n }\n return value;\n};\n"
},
{
"answer_id": 21285901,
"author": "Jan Remunda",
"author_id": 77154,
"author_profile": "https://Stackoverflow.com/users/77154",
"pm_score": 5,
"selected": false,
"text": "function getBool(val) {\n return !!JSON.parse(String(val).toLowerCase());\n}\n\ngetBool(\"1\"); //true\ngetBool(\"0\"); //false\ngetBool(\"true\"); //true\ngetBool(\"false\"); //false\ngetBool(\"TRUE\"); //true\ngetBool(\"FALSE\"); //false\n function getBool(val){ \n var num = +val;\n return !isNaN(num) ? !!num : !!String(val).toLowerCase().replace(!!0,'');\n}\n"
},
{
"answer_id": 21824488,
"author": "Kyle Falconer",
"author_id": 940217,
"author_profile": "https://Stackoverflow.com/users/940217",
"pm_score": 2,
"selected": false,
"text": "Utils.parseBoolean = function(val){\n if (typeof val === 'string' || val instanceof String){\n return /true/i.test(val);\n } else if (typeof val === 'boolean' || val instanceof Boolean){\n return new Boolean(val).valueOf();\n } else if (typeof val === 'number' || val instanceof Number){\n return new Number(val).valueOf() !== 0;\n }\n return false;\n};\n Utils.Tests = function(){\n window.console.log('running unit tests');\n\n var booleanTests = [\n ['true', true],\n ['false', false],\n ['True', true],\n ['False', false],\n [, false],\n [true, true],\n [false, false],\n ['gibberish', false],\n [0, false],\n [1, true]\n ];\n\n for (var i = 0; i < booleanTests.length; i++){\n var lhs = Utils.parseBoolean(booleanTests[i][0]);\n var rhs = booleanTests[i][1];\n var result = lhs === rhs;\n\n if (result){\n console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\\t : \\tpass');\n } else {\n console.log('Utils.parseBoolean('+booleanTests[i][0]+') === '+booleanTests[i][1]+'\\t : \\tfail');\n }\n }\n};\n"
},
{
"answer_id": 21976486,
"author": "BrDaHa",
"author_id": 1827734,
"author_profile": "https://Stackoverflow.com/users/1827734",
"pm_score": 6,
"selected": false,
"text": "function isTrue(value){\n if (typeof(value) === 'string'){\n value = value.trim().toLowerCase();\n }\n switch(value){\n case true:\n case \"true\":\n case 1:\n case \"1\":\n case \"on\":\n case \"yes\":\n return true;\n default: \n return false;\n }\n}\n false true true false"
},
{
"answer_id": 22236564,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 6,
"selected": false,
"text": "var str = \"true\";\nvar mybool = JSON.parse(str);\n var parseBool = function(str, strict) \n{\n // console.log(typeof str);\n // strict: JSON.parse(str)\n \n if (str == null)\n {\n if (strict)\n throw new Error(\"Parameter 'str' is null or undefined.\");\n\n return false;\n }\n \n if (typeof str === 'boolean')\n {\n return (str === true);\n } \n \n if(typeof str === 'string')\n {\n if(str == \"\")\n return false;\n \n str = str.replace(/^\\s+|\\s+$/g, '');\n if(str.toLowerCase() == 'true' || str.toLowerCase() == 'yes')\n return true;\n \n str = str.replace(/,/g, '.');\n str = str.replace(/^\\s*\\-\\s*/g, '-');\n }\n \n // var isNum = string.match(/^[0-9]+$/) != null;\n // var isNum = /^\\d+$/.test(str);\n if(!isNaN(str))\n return (parseFloat(str) != 0);\n \n return false;\n}\n var array_1 = new Array(true, 1, \"1\",-1, \"-1\", \" - 1\", \"true\", \"TrUe\", \" true \", \" TrUe\", 1/0, \"1.5\", \"1,5\", 1.5, 5, -3, -0.1, 0.1, \" - 0.1\", Infinity, \"Infinity\", -Infinity, \"-Infinity\",\" - Infinity\", \" yEs\");\n\nvar array_2 = new Array(null, \"\", false, \"false\", \" false \", \" f alse\", \"FaLsE\", 0, \"00\", \"1/0\", 0.0, \"0.0\", \"0,0\", \"100a\", \"1 00\", \" 0 \", 0.0, \"0.0\", -0.0, \"-0.0\", \" -1a \", \"abc\");\n\n\nfor(var i =0; i < array_1.length;++i){ console.log(\"array_1[\"+i+\"] (\"+array_1[i]+\"): \" + parseBool(array_1[i]));}\n\nfor(var i =0; i < array_2.length;++i){ console.log(\"array_2[\"+i+\"] (\"+array_2[i]+\"): \" + parseBool(array_2[i]));}\n\nfor(var i =0; i < array_1.length;++i){ console.log(parseBool(array_1[i]));}\nfor(var i =0; i < array_2.length;++i){ console.log(parseBool(array_2[i]));}\n"
},
{
"answer_id": 22988422,
"author": "user3310384",
"author_id": 3310384,
"author_profile": "https://Stackoverflow.com/users/3310384",
"pm_score": 2,
"selected": false,
"text": "var isTrueSet = (myValue === \"true\") ? true : false;"
},
{
"answer_id": 24414775,
"author": "Mahes",
"author_id": 301960,
"author_profile": "https://Stackoverflow.com/users/301960",
"pm_score": 2,
"selected": false,
"text": "function asBoolean(value) {\n\n return (''+value) === 'true'; \n\n}\n\n\n// asBoolean(true) ==> true\n// asBoolean(false) ==> false\n// asBoolean('true') ==> true\n// asBoolean('false') ==> false\n"
},
{
"answer_id": 24744599,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 5,
"selected": false,
"text": "var falsy = /^(?:f(?:alse)?|no?|0+)$/i;\nBoolean.parse = function(val) { \n return !falsy.test(val) && !!val;\n};\n false true 'false' 'f' 'no' 'n' '0' // False\nBoolean.parse(false);\nBoolean.parse('false');\nBoolean.parse('False');\nBoolean.parse('FALSE');\nBoolean.parse('f');\nBoolean.parse('F');\nBoolean.parse('no');\nBoolean.parse('No');\nBoolean.parse('NO');\nBoolean.parse('n');\nBoolean.parse('N');\nBoolean.parse('0');\nBoolean.parse('');\nBoolean.parse(0);\nBoolean.parse(null);\nBoolean.parse(undefined);\nBoolean.parse(NaN);\nBoolean.parse();\n\n//True\nBoolean.parse(true);\nBoolean.parse('true');\nBoolean.parse('True');\nBoolean.parse('t');\nBoolean.parse('yes');\nBoolean.parse('YES');\nBoolean.parse('y');\nBoolean.parse('1');\nBoolean.parse('foo');\nBoolean.parse({});\nBoolean.parse(1);\nBoolean.parse(-1);\nBoolean.parse(new Date());\n"
},
{
"answer_id": 25899590,
"author": "konsumer",
"author_id": 656398,
"author_profile": "https://Stackoverflow.com/users/656398",
"pm_score": 2,
"selected": false,
"text": "BOOL=false\nif (STRING)\n BOOL=JSON.parse(STRING.toLowerCase().replace('no','false').replace('yes','true'));\n"
},
{
"answer_id": 28152765,
"author": "Timo Ernst",
"author_id": 286149,
"author_profile": "https://Stackoverflow.com/users/286149",
"pm_score": 3,
"selected": false,
"text": "function str2bool(strvalue){\n return (strvalue && typeof strvalue == 'string') ? (strvalue.toLowerCase() == 'true' || strvalue == '1') : (strvalue == true);\n}\n var test; // false\nvar test2 = null; // false\nvar test3 = 'undefined'; // false\nvar test4 = 'true'; // true\nvar test5 = 'false'; // false\nvar test6 = true; // true\nvar test7 = false; // false\nvar test8 = 1; // true\nvar test9 = 0; // false\nvar test10 = '1'; // true\nvar test11 = '0'; // false\n"
},
{
"answer_id": 28374239,
"author": "Adam Pietrasiak",
"author_id": 2446799,
"author_profile": "https://Stackoverflow.com/users/2446799",
"pm_score": 3,
"selected": false,
"text": "String.prototype.maybeBool = function(){\n\n if ( [\"yes\", \"true\", \"1\", \"on\"].indexOf( this.toLowerCase() ) !== -1 ) return true;\n if ( [\"no\", \"false\", \"0\", \"off\"].indexOf( this.toLowerCase() ) !== -1 ) return false;\n\n return this;\n\n}\n\n\"on\".maybeBool(); //returns true;\n\"off\".maybeBool(); //returns false;\n\"I like js\".maybeBool(); //returns \"I like js\"\n"
},
{
"answer_id": 28706707,
"author": "Martin Malinda",
"author_id": 3997622,
"author_profile": "https://Stackoverflow.com/users/3997622",
"pm_score": 2,
"selected": false,
"text": "var trueOrStringTrue = (trueOrStringTrue === true) || (trueOrStringTrue === 'true');\n"
},
{
"answer_id": 28987637,
"author": "Fizer Khan",
"author_id": 1154350,
"author_profile": "https://Stackoverflow.com/users/1154350",
"pm_score": 4,
"selected": false,
"text": "('' + flag) === \"true\"\n flag var flag = true\n var flag = \"true\"\n var flag = false\n var flag = \"false\"\n"
},
{
"answer_id": 29838350,
"author": "null",
"author_id": 1521606,
"author_profile": "https://Stackoverflow.com/users/1521606",
"pm_score": -1,
"selected": false,
"text": "var boolean = \"false\";\nboolean = (boolean === \"true\");\n\n//boolean = JSON.parse(boolean); //or this way.. \n var boolean = \"false\";\nboolean = (boolean === \"true\");\n\n//boolean = JSON.parse(boolean); //or this way.. \n\nif(boolean == true){\n alert(\"boolean = \"+boolean);\n}else{\n alert(\"boolean = \"+boolean);\n}"
},
{
"answer_id": 31767875,
"author": "vbranden",
"author_id": 4723237,
"author_profile": "https://Stackoverflow.com/users/4723237",
"pm_score": 3,
"selected": false,
"text": "var toBoolean = function(value) {\n var strValue = String(value).toLowerCase();\n strValue = ((!isNaN(strValue) && strValue !== '0') &&\n strValue !== '' &&\n strValue !== 'null' &&\n strValue !== 'undefined') ? '1' : strValue;\n return strValue === 'true' || strValue === '1' ? true : false\n};\n > toBoolean(true)\ntrue\n> toBoolean(false)\nfalse\n> toBoolean(undefined)\nfalse\n> toBoolean(null)\nfalse\n> toBoolean('true')\ntrue\n> toBoolean('True')\ntrue\n> toBoolean('False')\nfalse\n> toBoolean('false')\nfalse\n> toBoolean('0')\nfalse\n> toBoolean('1')\ntrue\n> toBoolean('100')\ntrue\n> \n"
},
{
"answer_id": 34296412,
"author": "Eugene Tiurin",
"author_id": 2676500,
"author_profile": "https://Stackoverflow.com/users/2676500",
"pm_score": 2,
"selected": false,
"text": "true false JSON.parse || test === true || ['true','yes','1'].indexOf(test.toString().toLowerCase()) > -1\n Array.prototype.indexOf() // Production steps of ECMA-262, Edition 5, 15.4.4.14\n// Reference: http://es5.github.io/#x15.4.4.14\nif (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function(searchElement, fromIndex) {\n\n var k;\n\n // 1. Let O be the result of calling ToObject passing\n // the this value as the argument.\n if (this == null) {\n throw new TypeError('\"this\" is null or not defined');\n }\n\n var O = Object(this);\n\n // 2. Let lenValue be the result of calling the Get\n // internal method of O with the argument \"length\".\n // 3. Let len be ToUint32(lenValue).\n var len = O.length >>> 0;\n\n // 4. If len is 0, return -1.\n if (len === 0) {\n return -1;\n }\n\n // 5. If argument fromIndex was passed let n be\n // ToInteger(fromIndex); else let n be 0.\n var n = +fromIndex || 0;\n\n if (Math.abs(n) === Infinity) {\n n = 0;\n }\n\n // 6. If n >= len, return -1.\n if (n >= len) {\n return -1;\n }\n\n // 7. If n >= 0, then Let k be n.\n // 8. Else, n<0, Let k be len - abs(n).\n // If k is less than 0, then let k be 0.\n k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);\n\n // 9. Repeat, while k < len\n while (k < len) {\n // a. Let Pk be ToString(k).\n // This is implicit for LHS operands of the in operator\n // b. Let kPresent be the result of calling the\n // HasProperty internal method of O with argument Pk.\n // This step can be combined with c\n // c. If kPresent is true, then\n // i. Let elementK be the result of calling the Get\n // internal method of O with the argument ToString(k).\n // ii. Let same be the result of applying the\n // Strict Equality Comparison Algorithm to\n // searchElement and elementK.\n // iii. If same is true, return k.\n if (k in O && O[k] === searchElement) {\n return k;\n }\n k++;\n }\n return -1;\n };\n}\n"
},
{
"answer_id": 35986765,
"author": "Siten",
"author_id": 785775,
"author_profile": "https://Stackoverflow.com/users/785775",
"pm_score": 1,
"selected": false,
"text": "var boolValue = Boolean(Number('0'));\n\nvar boolValue = Boolean(Number('1'));\n false true"
},
{
"answer_id": 36173924,
"author": "ecabuk",
"author_id": 629760,
"author_profile": "https://Stackoverflow.com/users/629760",
"pm_score": 3,
"selected": false,
"text": "function isTrue(val) {\n try {\n return !!JSON.parse(val);\n } catch {\n return false;\n }\n}\n"
},
{
"answer_id": 36705508,
"author": "jdnichollsc",
"author_id": 1532821,
"author_profile": "https://Stackoverflow.com/users/1532821",
"pm_score": 2,
"selected": false,
"text": "//Currently\nvar isTrue = 'true';\n//In the future (Other developer change the code)\nvar isTrue = true;\n//The solution to both cases\n(isTrue).toString() == 'true'\n"
},
{
"answer_id": 36942239,
"author": "benipsen",
"author_id": 296073,
"author_profile": "https://Stackoverflow.com/users/296073",
"pm_score": 3,
"selected": false,
"text": "var booleanVal = toCast > '';\n var booleanVal = toCast > '' && toCast != 'false' && toCast != '0'; \n"
},
{
"answer_id": 37610883,
"author": "Sandip Nirmal",
"author_id": 1904377,
"author_profile": "https://Stackoverflow.com/users/1904377",
"pm_score": 4,
"selected": false,
"text": "// One can specify all values against which you consider truthy\nvar TRUTHY_VALUES = [true, 'true', 1];\n\nfunction getBoolean(a) {\n return TRUTHY_VALUES.some(function(t) {\n return t === a;\n });\n}\n getBoolean('aa'); // false\ngetBoolean(false); //false\ngetBoolean('false'); //false\n\ngetBoolean('true'); // true\ngetBoolean(true); // true\ngetBoolean(1); // true\n"
},
{
"answer_id": 40801019,
"author": "Hakan Fıstık",
"author_id": 4390133,
"author_profile": "https://Stackoverflow.com/users/4390133",
"pm_score": 4,
"selected": false,
"text": "var isTrueSet = (myValue.toLowerCase() === 'true');\n"
},
{
"answer_id": 41508677,
"author": "jose.serapicos",
"author_id": 6645736,
"author_profile": "https://Stackoverflow.com/users/6645736",
"pm_score": 2,
"selected": false,
"text": "var trueValuesRange = ['1', 1, 'true', true];\n\nmyVarToTest = (trueValuesRange.indexOf(myVarToTest) >= 0);\n"
},
{
"answer_id": 42136805,
"author": "Rohman HM",
"author_id": 5531595,
"author_profile": "https://Stackoverflow.com/users/5531595",
"pm_score": 2,
"selected": false,
"text": "const ForceBoolean = require('force-boolean')\n\nconst YOUR_VAR = 'false'\nconsole.log(ForceBoolean(YOUR_VAR)) // it's return boolean false\n return false if value is number 0\n return false if value is string '0'\n return false if value is string 'false'\n return false if value is boolean false\n return true if value is number 1\n return true if value is string '1'\n return true if value is string 'true'\n return true if value is boolean true\n"
},
{
"answer_id": 42220613,
"author": "Steve Mc",
"author_id": 126540,
"author_profile": "https://Stackoverflow.com/users/126540",
"pm_score": 1,
"selected": false,
"text": "var trueVals = [\"y\", \"t\", \"yes\", \"true\", \"gimme\"];\nvar isTrueSet = (trueVals.indexOf(myValue) > -1) ? true : false;\n var trueVals = [\"y\", \"t\", \"yes\", \"true\", \"gimme\"];\nvar isTrueSet = (trueVals.indexOf(myValue) > -1);\n"
},
{
"answer_id": 43327897,
"author": "Surya R Praveen",
"author_id": 714707,
"author_profile": "https://Stackoverflow.com/users/714707",
"pm_score": 1,
"selected": false,
"text": "var vIn = \"true\";\nvar vOut = vIn.toLowerCase()==\"true\"?1:0;\n var vIn = 0;\nvar vOut = parseInt(vIn,10/*base*/);\n"
},
{
"answer_id": 43694886,
"author": "Dayem Siddiqui",
"author_id": 4400495,
"author_profile": "https://Stackoverflow.com/users/4400495",
"pm_score": 2,
"selected": false,
"text": " function convertStringToBool(str){\n return ((str === \"True\") || (str === \"true\")) ? true:false;\n }\n convertStringToBool(\"false\") //returns false\nconvertStringToBool(\"true\") // returns true\nconvertStringToBool(\"False\") // returns false\nconvertStringToBool(\"True\") // returns true\n"
},
{
"answer_id": 43852081,
"author": "Vitim.us",
"author_id": 938822,
"author_profile": "https://Stackoverflow.com/users/938822",
"pm_score": 3,
"selected": false,
"text": "true function b(v){ return v===\"false\" ? false : !!v; }\n b(true) //true\nb('true') //true\nb(false) //false\nb('false') //false\n function bool(v){ return v===\"false\" || v===\"null\" || v===\"NaN\" || v===\"undefined\" || v===\"0\" ? false : !!v; }\n bool(true) //true\nbool(\"true\") //true\nbool(1) //true\nbool(\"1\") //true\nbool(\"hello\") //true\n\nbool(false) //false\nbool(\"false\") //false\nbool(0) //false\nbool(\"0\") //false\nbool(null) //false\nbool(\"null\") //false\nbool(NaN) //false\nbool(\"NaN\") //false\nbool(undefined) //false\nbool(\"undefined\") //false\nbool(\"\") //false\n\nbool([]) //true\nbool({}) //true\nbool(alert) //true\nbool(window) //true\n"
},
{
"answer_id": 43996304,
"author": "Chanakya Vadla",
"author_id": 919216,
"author_profile": "https://Stackoverflow.com/users/919216",
"pm_score": 3,
"selected": false,
"text": "String(true).toLowerCase() == 'true'; // true\nString(\"true\").toLowerCase() == 'true'; // true\nString(\"True\").toLowerCase() == 'true'; // true\nString(\"TRUE\").toLowerCase() == 'true'; // true\n\nString(false).toLowerCase() == 'true'; // false\n"
},
{
"answer_id": 45181561,
"author": "guest271314",
"author_id": 2801559,
"author_profile": "https://Stackoverflow.com/users/2801559",
"pm_score": 0,
"selected": false,
"text": "Function Boolean \"true\" \"false\" const TRUE_OR_FALSE = str => new Function(`return ${str}`)();\n\nconst [TRUE, FALSE] = [\"true\", \"false\"];\n\nconst [T, F] = [TRUE_OR_FALSE(TRUE), TRUE_OR_FALSE(FALSE)];\n\nconsole.log(T, typeof T); // `true` `\"boolean\"`\n\nconsole.log(F, typeof F); // `false` `\"boolean\"`"
},
{
"answer_id": 45294201,
"author": "Mohammad Farahani",
"author_id": 4764069,
"author_profile": "https://Stackoverflow.com/users/4764069",
"pm_score": 4,
"selected": false,
"text": "JSON.parse \nvar trueOrFalse='True';\nresult =JSON.parse(trueOrFalse.toLowerCase());\nif(result==true)\n alert('this is true');\nelse \n alert('this is false'); .toLowerCase"
},
{
"answer_id": 45448872,
"author": "danday74",
"author_id": 1205871,
"author_profile": "https://Stackoverflow.com/users/1205871",
"pm_score": 0,
"selected": false,
"text": "const toBoolean = (bool) => {\n if (bool === 'false') bool = false\n return !!bool\n}\n\ntoBoolean('false') // returns false\n"
},
{
"answer_id": 46944503,
"author": "Kostanos",
"author_id": 2215679,
"author_profile": "https://Stackoverflow.com/users/2215679",
"pm_score": 2,
"selected": false,
"text": "boolResult = !(['false', '0', '', 'undefined'].indexOf(String(myVar).toLowerCase().trim()) + 1);\n myVar = true; // true\nmyVar = 'true'; // true\nmyVar = 'TRUE'; // true\nmyVar = '1'; // true\nmyVar = 'any other value not related to false'; // true\n\nmyVar = false; // false\nmyVar = 'false'; // false\nmyVar = 'FALSE'; // false\nmyVar = '0'; // false\n"
},
{
"answer_id": 47583302,
"author": "OhkaBaka",
"author_id": 39835,
"author_profile": "https://Stackoverflow.com/users/39835",
"pm_score": 3,
"selected": false,
"text": "testVar = testVar.toString().match(/^(true|[1-9][0-9]*|[0-9]*[1-9]+|yes)$/i) ? true : false;\n"
},
{
"answer_id": 47817211,
"author": "Yohan",
"author_id": 7061173,
"author_profile": "https://Stackoverflow.com/users/7061173",
"pm_score": 3,
"selected": false,
"text": "Boolean(JSON.parse((yourString.toString()).toLowerCase()));\n // 0-> false\n// any other number -> true\n"
},
{
"answer_id": 48929869,
"author": "pankaj sharma",
"author_id": 6565872,
"author_profile": "https://Stackoverflow.com/users/6565872",
"pm_score": 4,
"selected": false,
"text": "function stringToBoolean(val){\n var a = {\n 'true':true,\n 'false':false\n };\n return a[val];\n}\n function stringToBoolean(val) {\n var a = {\n 'true': true,\n 'false': false\n };\n return a[val];\n}\n\nconsole.log(stringToBoolean(\"true\"));\n\nconsole.log(typeof(stringToBoolean(\"true\")));\n\nconsole.log(stringToBoolean(\"false\"));\n\nconsole.log(typeof(stringToBoolean(\"false\")));\n\nconsole.log(stringToBoolean(true));\n\nconsole.log(typeof(stringToBoolean(true)));\n\nconsole.log(stringToBoolean(false));\n\nconsole.log(typeof(stringToBoolean(false)));\n\nconsole.log(\"=============================================\");\n// what if value was undefined? \nconsole.log(\"undefined result: \" + stringToBoolean(undefined));\nconsole.log(\"type of undefined result: \" + typeof(stringToBoolean(undefined)));\nconsole.log(\"=============================================\");\n// what if value was an unrelated string?\nconsole.log(\"unrelated string result: \" + stringToBoolean(\"hello world\"));\nconsole.log(\"type of unrelated string result: \" + typeof(stringToBoolean(undefined)));"
},
{
"answer_id": 54089613,
"author": "Ratan Uday Kumar",
"author_id": 6633337,
"author_profile": "https://Stackoverflow.com/users/6633337",
"pm_score": 2,
"selected": false,
"text": "Boolify(true); //true\nBoolify('true'); //true\nBoolify('TRUE'); //null\nBoolify(1); //true\nBoolify(2); //null\nBoolify(false); //false\nBoolify('false'); //false\nBoolify('FALSE'); //null\nBoolify(0); //false\nBoolify(null); //null\nBoolify(undefined); //null\nBoolify(); //null\nBoolify(''); //null\n"
},
{
"answer_id": 55019413,
"author": "Yuriy Litvin",
"author_id": 2465869,
"author_profile": "https://Stackoverflow.com/users/2465869",
"pm_score": 2,
"selected": false,
"text": "export function stringToBoolean(s: string, valueDefault: boolean = false): boolean {\n switch(s.toLowerCase())\n {\n case \"true\":\n case \"1\":\n case \"on\":\n case \"yes\":\n case \"y\":\n return true;\n\n case \"false\":\n case \"0\":\n case \"off\":\n case \"no\":\n case \"n\":\n return false;\n }\n\n return valueDefault;\n}\n"
},
{
"answer_id": 55570048,
"author": "Al Albers",
"author_id": 931513,
"author_profile": "https://Stackoverflow.com/users/931513",
"pm_score": 3,
"selected": false,
"text": "true var isTrueSet =\n myValue === true ||\n myValue != null &&\n myValue.toString().toLowerCase() === 'true';\n"
},
{
"answer_id": 56392251,
"author": "panatoni",
"author_id": 5731985,
"author_profile": "https://Stackoverflow.com/users/5731985",
"pm_score": 3,
"selected": false,
"text": "let value = 'true';\nlet output = value === 'true';\n"
},
{
"answer_id": 58470519,
"author": "olegtaranenko",
"author_id": 455491,
"author_profile": "https://Stackoverflow.com/users/455491",
"pm_score": 1,
"selected": false,
"text": "function parseBoolean(token) {\n if (typeof token === 'string') {\n switch (token.toLowerCase()) {\n case 'on':\n case 'yes':\n case 'ok':\n case 'ja':\n case 'да':\n // case '':\n // case '':\n token = true;\n break;\n default:\n token = false;\n }\n }\n let ret = false;\n try {\n ret = Boolean(JSON.parse(token));\n } catch (e) {\n // do nothing or make a notification\n }\n return ret;\n}\n"
},
{
"answer_id": 59824949,
"author": "James Anderson Jr.",
"author_id": 2690928,
"author_profile": "https://Stackoverflow.com/users/2690928",
"pm_score": 2,
"selected": false,
"text": "function convertStrToBool(str)\n {\n switch(String(str).toLowerCase())\n {\n case 'undefined': case 'null': case 'nan': case 'false': case 'no': case 'f': case 'n': case '0': case 'off': case '':\n return false;\n break;\n default:\n return true;\n };\n };\n"
},
{
"answer_id": 60324885,
"author": "sçuçu",
"author_id": 2605049,
"author_profile": "https://Stackoverflow.com/users/2605049",
"pm_score": 1,
"selected": false,
"text": "const isBooleanString = (string) => ['true', 'false'].some(item => item === string);\n JSON.parse JSON.parse(aBooleanString);\n JSON.parse SyntaxError JSON.parse function parse(string){\n return isBooleanString(string) ? JSON.parse(string)\n : string;\n}\n isBooleanString const isBooleanString = (string, spec = ['true', 'false', 'True', 'False']) => spec.some(item => item === string);\n"
},
{
"answer_id": 60430683,
"author": "Faizan Khan",
"author_id": 11884468,
"author_profile": "https://Stackoverflow.com/users/11884468",
"pm_score": 3,
"selected": false,
"text": "a = 'True';\na = !!a && ['1', 'true', 1, true].indexOf(a.toLowerCase()) > -1;\n"
},
{
"answer_id": 61674681,
"author": "Mansi",
"author_id": 6228036,
"author_profile": "https://Stackoverflow.com/users/6228036",
"pm_score": 1,
"selected": false,
"text": "const result: Boolean = strValue === \"true\" ? true : false\n"
},
{
"answer_id": 61681862,
"author": "jacobq",
"author_id": 1171509,
"author_profile": "https://Stackoverflow.com/users/1171509",
"pm_score": 2,
"selected": false,
"text": "process.env SOME_ENV_VAR=1 const toBooleanSimple = (input) => \n ['t', 'y', '1'].some(truePrefix => truePrefix === input[0].toLowerCase());\n /**\n * Converts strings to booleans in a manner that is less surprising\n * to the non-JS world (e.g. returns true for \"1\", \"yes\", \"True\", etc.\n * and false for \"0\", \"No\", \"false\", etc.)\n * @param input\n * @returns {boolean}\n */\nfunction toBoolean(input) {\n if (typeof input !== 'string') {\n return Boolean(input);\n }\n const s = input.toLowerCase();\n return ['t', 'y', '1'].some(prefix => s.startsWith(prefix));\n}\n describe(`toBoolean`, function() {\n const groups = [{\n inputs: ['y', 'Yes', 'true', '1', true, 1],\n expectedOutput: true\n }, {\n inputs: ['n', 'No', 'false', '0', false, 0],\n expectedOutput: false\n }]\n for (let group of groups) {\n for (let input of group.inputs) {\n it(`should return ${group.expectedOutput} for ${JSON.stringify(input)}`, function() {\n expect(toBoolean(input)).toEqual(group.expectedOutput);\n });\n } \n }\n});\n"
},
{
"answer_id": 62118423,
"author": "Justin Liu",
"author_id": 13363264,
"author_profile": "https://Stackoverflow.com/users/13363264",
"pm_score": 1,
"selected": false,
"text": "if function parseBool(str) {\n if (str.toLowerCase() == 'true') {\n var val = true;\n } else if (str.toLowerCase() == 'false') {\n var val = false;\n } else {\n //If it is not true of false it returns undefined.//\n var val = undefined;\n }\n return val;\n}\nconsole.log(parseBool(''), typeof parseBool(''));\nconsole.log(parseBool('TrUe'), typeof parseBool('TrUe'));\nconsole.log(parseBool('false'), typeof parseBool('false'));"
},
{
"answer_id": 62175543,
"author": "ritesh",
"author_id": 3316084,
"author_profile": "https://Stackoverflow.com/users/3316084",
"pm_score": 2,
"selected": false,
"text": "eval() eval() console.log(eval('true'), typeof eval('true'))\nconsole.log(eval('false'), typeof eval('false'))"
},
{
"answer_id": 63042101,
"author": "Neil Higgins",
"author_id": 8876947,
"author_profile": "https://Stackoverflow.com/users/8876947",
"pm_score": 1,
"selected": false,
"text": "(eval(yourBooleanString == 'true'))\n"
},
{
"answer_id": 63373352,
"author": "Bhupender Keswani",
"author_id": 4082735,
"author_profile": "https://Stackoverflow.com/users/4082735",
"pm_score": 1,
"selected": false,
"text": "const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;\n const convertStringToBoolean = (value) => value ? String(value).toLowerCase() === 'true' : false;\n\nconsole.log(convertStringToBoolean(\"a\"));\nconsole.log(convertStringToBoolean(null));\nconsole.log(convertStringToBoolean(undefined));\nconsole.log(convertStringToBoolean(\"undefined\"));\nconsole.log(convertStringToBoolean(true));\nconsole.log(convertStringToBoolean(false));\nconsole.log(convertStringToBoolean(0));\nconsole.log(convertStringToBoolean(1)); // only case which will not work"
},
{
"answer_id": 64123006,
"author": "Abderrahmen",
"author_id": 1207297,
"author_profile": "https://Stackoverflow.com/users/1207297",
"pm_score": -1,
"selected": false,
"text": "Boolean(<stringVariable>)\n"
},
{
"answer_id": 64595627,
"author": "Kal",
"author_id": 3717114,
"author_profile": "https://Stackoverflow.com/users/3717114",
"pm_score": -1,
"selected": false,
"text": "false true storeBooleanHere = stringVariable==\"true\"?true:false;\n"
},
{
"answer_id": 64817203,
"author": "cskwg",
"author_id": 4386189,
"author_profile": "https://Stackoverflow.com/users/4386189",
"pm_score": 2,
"selected": false,
"text": "/// Convert something to boolean\nfunction toBoolean( o ) {\n if ( null !== o ) {\n let t = typeof o;\n if ( \"undefined\" !== typeof o ) {\n if ( \"string\" !== t ) return !!o;\n o = o.toLowerCase().trim();\n return \"true\" === o || \"1\" === o;\n }\n }\n return false;\n}\n\ntoBoolean(false) --> false\ntoBoolean(true) --> true\ntoBoolean(\"false\") --> false\ntoBoolean(\"true\") --> true\ntoBoolean(\"TRue\") --> true\ntoBoolean(\"1\") --> true\ntoBoolean(\"0\") --> false\ntoBoolean(1) --> true\ntoBoolean(0) --> false\ntoBoolean(123.456) --> true\ntoBoolean(0.0) --> false\ntoBoolean(\"\") --> false\ntoBoolean(null) --> false\ntoBoolean() --> false\n"
},
{
"answer_id": 65113429,
"author": "Alexandre Annic",
"author_id": 5735030,
"author_profile": "https://Stackoverflow.com/users/5735030",
"pm_score": 1,
"selected": false,
"text": " ({'true': true, 'false': false})[myValue];\n ({'true': true, 'false': false})[undefined] // => undefined\n ({'true': true, 'false': false})['true'] // => true\n ({'true': true, 'false': false})['false] // => false\n"
},
{
"answer_id": 65512532,
"author": "Debasish Jena",
"author_id": 4336123,
"author_profile": "https://Stackoverflow.com/users/4336123",
"pm_score": 1,
"selected": false,
"text": "let x = 'true' ;\n//let x = 'false';\nlet y = x === 'true' ? true : false;\nconsole.log(typeof(y), y);"
},
{
"answer_id": 66044687,
"author": "OMANSAK",
"author_id": 5230705,
"author_profile": "https://Stackoverflow.com/users/5230705",
"pm_score": 2,
"selected": false,
"text": "function convertBoolean(value): boolean {\n if (typeof value == 'string') {\n value = value.toLowerCase();\n }\n switch (value) {\n case true:\n case \"true\":\n case \"evet\": // Locale\n case \"t\":\n case \"e\": // Locale\n case \"1\":\n case \"on\":\n case \"yes\":\n case 1:\n return true;\n case false:\n case \"false\":\n case \"hayır\": // Locale\n case \"f\":\n case \"h\": // Locale\n case \"0\":\n case \"off\":\n case \"no\":\n case 0:\n return false;\n default:\n return null;\n }\n}\n"
},
{
"answer_id": 66378318,
"author": "Felipe Chernicharo",
"author_id": 13111779,
"author_profile": "https://Stackoverflow.com/users/13111779",
"pm_score": 4,
"selected": false,
"text": "const stringToBoolean = (string) => string === 'false' ? false : !!string\n stringToBoolean('') // false\nstringToBoolean('false') // false\nstringToBoolean('true') // true\nstringToBoolean('hello my friend!') // true\n const betterStringToBoolean = (string) => \n string === 'false' || string === 'undefined' || string === 'null' || string === '0' ?\n false : !!string\n betterStringToBoolean('undefined') // false\nbetterStringToBoolean('null') // false\nbetterStringToBoolean('0') // false\nbetterStringToBoolean('false') // false\nbetterStringToBoolean('') // false\nbetterStringToBoolean('true') // true\nbetterStringToBoolean('anything else') // true\n"
},
{
"answer_id": 67347536,
"author": "Force Bolt",
"author_id": 15478252,
"author_profile": "https://Stackoverflow.com/users/15478252",
"pm_score": -1,
"selected": false,
"text": " const checkBoolean = Boolean(\"false\"); \n const checkBoolean1 = !!\"false\"; \n \n console.log({checkBoolean, checkBoolean1}); \n"
},
{
"answer_id": 67949024,
"author": "ru4ert",
"author_id": 11123801,
"author_profile": "https://Stackoverflow.com/users/11123801",
"pm_score": 1,
"selected": false,
"text": "const string = \"false\"\nconst string2 = \"true\"\n\nconst test = (val) => (val === \"true\" || val === \"True\")\nconsole.log(test(string))\nconsole.log(test(string2))"
},
{
"answer_id": 68562494,
"author": "Sigit",
"author_id": 6178696,
"author_profile": "https://Stackoverflow.com/users/6178696",
"pm_score": 3,
"selected": false,
"text": "const boolTrue = JSON.parse(\"true\")\nconst boolFalse = JSON.parse(\"false\")\n\n\nconsole.log(boolTrue) // true\nconsole.log(boolFalse) // false JSON.parse() JSON.parse(\"true\")"
},
{
"answer_id": 68582722,
"author": "Deepak paramesh",
"author_id": 5707334,
"author_profile": "https://Stackoverflow.com/users/5707334",
"pm_score": 7,
"selected": false,
"text": "JSON.parse('true');\n let trueResponse = JSON.parse('true');\n\nlet falseResponse = JSON.parse('false');\n\nconsole.log(trueResponse);\nconsole.log(falseResponse);"
},
{
"answer_id": 69397610,
"author": "Richard Torcato",
"author_id": 1213956,
"author_profile": "https://Stackoverflow.com/users/1213956",
"pm_score": 2,
"selected": false,
"text": "String.prototype.toBoolean = function() {\n return String(this.valueOf()).toLowerCase() === true.toString();\n};\n var myValue = \"false\"\nconsole.log(\"Bool is \" + myValue.toBoolean())\nconsole.log(\"Bool is \" + \"False\".toBoolean())\nconsole.log(\"Bool is \" + \"FALSE\".toBoolean())\nconsole.log(\"Bool is \" + \"TRUE\".toBoolean())\nconsole.log(\"Bool is \" + \"true\".toBoolean())\nconsole.log(\"Bool is \" + \"True\".toBoolean())\n var myValue = document.myForm.IS_TRUE.value;\nvar isTrueSet = myValue.toBoolean();\n"
},
{
"answer_id": 69862548,
"author": "Friedrich",
"author_id": 11769765,
"author_profile": "https://Stackoverflow.com/users/11769765",
"pm_score": 4,
"selected": false,
"text": "includes let bool = \"false\"\nbool = ![\"false\", \"0\", 0].includes(bool)\n null ''"
},
{
"answer_id": 71759831,
"author": "M. Sherbeeny",
"author_id": 5966433,
"author_profile": "https://Stackoverflow.com/users/5966433",
"pm_score": -1,
"selected": false,
"text": "const toBoolean = (x) => {\n if (typeof x === 'object') {\n for (var i in x) return true\n return false\n }\n return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())\n } const toBoolean = (x) => {\n if (typeof x === 'object') {\n for (var i in x) return true\n return false\n }\n return (x !== null) && (x !== undefined) && !['false', '', '0', 'no', 'off'].includes(x.toString().toLowerCase())\n }\n \n\n // Let's test it!\n let falseValues = [false, 'False', 0, '', 'off', 'no', [], {}, null, undefined]\n let trueValues = [ true, 'true', 'True', 1, -1, 'Any thing', ['filled array'], {'object with any key': null}]\n \n falseValues.forEach((value, index) => console.log(`False value ${index} of type ${typeof value}: ${value} -> ${toBoolean(value)}`))\n trueValues.forEach((value, index) => console.log(`True value ${index} of type ${typeof value}: ${value} -> ${toBoolean(value)}`))"
},
{
"answer_id": 73388511,
"author": "Abba",
"author_id": 6828976,
"author_profile": "https://Stackoverflow.com/users/6828976",
"pm_score": 1,
"selected": false,
"text": "const getAsBoolean = (value: string | boolean | number) => {\n if (typeof value === 'string') {\n return value === 'true';\n } else if (typeof value === 'boolean' || typeof value === 'number') {\n return Boolean(value);\n } else {\n return undefined;\n }\n};\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4599/"
] |
263,968
|
<p>What's the best way to convert NetBeans (Matisse) .form files into .java files, without using the NetBeans IDE itself? Ideally I'd like to package the .form files along with my source code, and generate the .java files at build time. This will prevent developers from "accidentally" adding code to the generated .java file using some other IDE, which could then get overwritten by NetBeans the next time the form itself is edited in the GUI designer.</p>
<p>I've searched Google and all I can find is people saying, "Use the NetBeans IDE to generate the .java file," which is kind of difficult to do at build-time.</p>
|
[
{
"answer_id": 20761239,
"author": "Naqash",
"author_id": 3132530,
"author_profile": "https://Stackoverflow.com/users/3132530",
"pm_score": 0,
"selected": false,
"text": ".java .class"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29173/"
] |
263,977
|
<p>I'm quite familiar with the reasons for wanting to copy a property vs. retain. (Essentially the value vs. relationship argument. You almost always want to copy strings, for example.)</p>
<p>What about NSColor and NSGradient? </p>
<p>They both conform to NSCopying, but as currently implemented, are immutable.</p>
<p>Thoughts?</p>
|
[
{
"answer_id": 264000,
"author": "Brian Webster",
"author_id": 23324,
"author_profile": "https://Stackoverflow.com/users/23324",
"pm_score": 2,
"selected": false,
"text": "copyWithZone: return [self retain] retain copy"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
263,985
|
<p>I want to be replace any occurrence of more than one space with a single space, but take no action in text between quotes.</p>
<p>Is there any way of doing this with a Java regex? If so, can you please attempt it or give me a hint?</p>
|
[
{
"answer_id": 264044,
"author": "Jeff Hillman",
"author_id": 3950,
"author_profile": "https://Stackoverflow.com/users/3950",
"pm_score": 2,
"selected": false,
"text": "(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|( +)\n Pattern spaceOrStringRegex = Pattern.compile( \"(\\\"[^\\\"\\\\\\\\]*(?:\\\\\\\\.[^\\\"\\\\\\\\]*)*\\\")|( +)\" );\n\nStringBuffer replacementBuffer = new StringBuffer();\n\nMatcher spaceOrStringMatcher = spaceOrStringRegex.matcher( text );\n\nwhile ( spaceOrStringMatcher.find() ) \n{\n // if the space group is the match\n if ( spaceOrStringMatcher.group( 2 ) != null ) \n {\n // replace with a single space\n spaceOrStringMatcher.appendReplacement( replacementBuffer, \" \" );\n }\n}\n\nspaceOrStringMatcher.appendTail( replacementBuffer );\n"
},
{
"answer_id": 264124,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 0,
"selected": false,
"text": "([^\\\" ])*(\\\\\\\".*?\\\\\\\")*\n try {\n Pattern regex = Pattern.compile(\"([^\\\" ])*(\\\\\\\".*?\\\\\\\")*\", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);\n Matcher regexMatcher = regex.matcher(subjectString);\n while (regexMatcher.find()) {\n for (int i = 1; i <= regexMatcher.groupCount(); i++) {\n // matched text: regexMatcher.group(i)\n // match start: regexMatcher.start(i)\n // match end: regexMatcher.end(i)\n\n // I suppose here you must use something like\n // sstr += regexMatcher.group(i) + \" \"\n }\n }\n} catch (PatternSyntaxException ex) {\n // Syntax error in the regular expression\n}\n import re\n\ntext = \"\"\"\neste es un texto de prueba \"para ver como se comporta \" la funcion sobre esto\n\"para ver como se comporta \" la funcion sobre esto \"o sobre otro\" lo q sea\n\"\"\"\n\nret = \"\"\nprint text \n\nreobj = re.compile(r'([^\\\" ])*(\\\".*?\\\")*', re.IGNORECASE)\n\nfor match in reobj.finditer(text):\n if match.group() <> \"\":\n ret = ret + match.group() + \"|\"\n\nprint ret\n"
},
{
"answer_id": 264387,
"author": "Dov Wasserman",
"author_id": 26010,
"author_profile": "https://Stackoverflow.com/users/26010",
"pm_score": 0,
"selected": false,
"text": "String text = \"ABC DEF GHI JKL\";\ntext = text.replaceAll(\"( )+\", \" \");\n// text: \"ABC DEF GHI JKL\"\n"
},
{
"answer_id": 264458,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "group(2) import java.util.regex.*;\n\npublic class Test\n{\n public static void main(String[] args) throws Exception\n {\n String text = \"blah blah \\\"boo boo boo\\\" blah blah\";\n Pattern p = Pattern.compile( \"(\\\"[^\\\"\\\\\\\\]*(?:\\\\\\\\.[^\\\"\\\\\\\\]*)*\\\")|( +)\" );\n StringBuffer sb = new StringBuffer();\n Matcher m = p.matcher( text );\n while ( m.find() ) \n {\n if ( m.group( 2 ) != null ) \n {\n m.appendReplacement( sb, \" \" );\n }\n }\n m.appendTail( sb );\n System.out.println( sb.toString() );\n }\n}\n"
},
{
"answer_id": 264491,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 3,
"selected": true,
"text": "text = text.replaceAll(\" ++(?=(?:[^\\\"]*+\\\"[^\\\"]*+\\\")*+[^\\\"]*+$)\", \" \");\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27677/"
] |
263,987
|
<p>I have a Delphi 5 executable that calls into a .NET assembly via the free <a href="http://sourceforge.net/projects/delphinet/" rel="nofollow noreferrer">Delphi .NET</a> code, and for the most part, this works great. However, one of the requirements of my application is that our clients be able to use this from a networked share as well as local. On my test machine, I can't get this to work, I just get an error message. The .NET code has it's permissions set to full, but some error comes back that Delphi can't seem to get or interpret. On a local drive, the application and assembly communicate flawlessly.</p>
<p>Can anyone tell me how to at least get the error messages back from this? Or if possible, can anyone tell me why I would get errors this way? Thanks.</p>
|
[
{
"answer_id": 264001,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 2,
"selected": false,
"text": "CasPol.exe -m -ag 1.2 -url file://\\\\ShawnFa-Srv/Tools/* FullTrust\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34504/"
] |
263,992
|
<p>I don't want to include relations in my edmx entity framework, I want to have the foreign key field as a normal property in my entity. </p>
<p>How can I do that?</p>
|
[
{
"answer_id": 503023,
"author": "Neil",
"author_id": 61480,
"author_profile": "https://Stackoverflow.com/users/61480",
"pm_score": 0,
"selected": false,
"text": "(From o In nw.Orders \n Where o.OrderID = 10281 \n Select o.Customers\n).First\n"
},
{
"answer_id": 585984,
"author": "Neil",
"author_id": 61480,
"author_profile": "https://Stackoverflow.com/users/61480",
"pm_score": 0,
"selected": false,
"text": "Contact SubscriberId Contact using (BulkSmsEntities ctx = new BulkSmsEntities())\n{\n int SubscriberId = 1;\n tb_contact contact = new tb_contact();\n contact.tb_subscriber = ctx.tb_subscriber\n .First(a => a.SubscriberId == SubscriberId);\n ctx.AddTotb_subscriber_contacts(contact);\n ctx.SaveChanges();\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/263992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,004
|
<p>By "code snippet execution", I mean the ability to write a few lines of code, run and test it without having to fire up an IDE and create a dummy project.</p>
<p>It's incredibly useful for helping people with a small code sample without creating a project, compiling everything cleanly, sending them the code snippet and deleting the project. </p>
<p>I'm not asking about the best code snippets or a snippet editor or where to store snippets!</p>
<p>For C#, I use <a href="http://www.sliver.com/dotnet/SnippetCompiler/" rel="noreferrer">Snippet Compiler</a>.</p>
<p>For Java, I use Eclipse <a href="http://www.eclipsezone.com/eclipse/forums/t61137.html" rel="noreferrer">Scrapbook</a>. </p>
<p>For LINQ, I use <a href="http://www.linqpad.net/" rel="noreferrer">LINQPad</a>. </p>
<p>Any suggestions for other (better?) tools? e.g. is there one for Java that doesn't involve firing up Eclipse?</p>
<p>What about C?</p>
|
[
{
"answer_id": 276431,
"author": "Jed",
"author_id": 33208,
"author_profile": "https://Stackoverflow.com/users/33208",
"pm_score": 1,
"selected": false,
"text": "#!/bin/sh\n\nbody=\"$1\"\nout=$(mktemp /tmp/ccrun-XXXXXX)\nsrc=${out}.c\ncat > ${src} <<EOF\n#include <limits.h>\n#include <string.h>\n#include <math.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <stdint.h>\n\n#define UNUSED __attribute__((unused))\n\nint main(int UNUSED argc,char UNUSED *argv[])\n{\nEOF\necho \"$body\" >> ${src}\necho -e \"return 0;\\n}\" >> ${src}\ncc -std=c99 -Wall -Wextra ${CCRUN_FLAGS} -o ${out} ${src} -lm\nshift\necho ${out} \"$@\"\n${out} \"$@\"\n#rm ${out} ${src}\n $ ccrun 'int f(int a){return a+1;} int g(int a){return a+2;} int (*farr[2])(int) = {f,g}; for (int i=0; i<2; i++) printf(\"%d %d\\n\",i,farr[i](i));'\n/tmp/ccrun-6nT4Wo\n0 1\n1 3\n /tmp/ccrun-6nT4Wo.c"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9922/"
] |
264,057
|
<p>I have some old C code that I would like to combine with some C++ code.</p>
<p>The C code used to have has the following includes:</p>
<pre><code>#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "mysql.h"
</code></pre>
<p>Now I'm trying to make it use C++ with iostream like this:</p>
<pre><code>#include <windows.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "mysql.h"
</code></pre>
<p>But I keep getting the following linker errors when I compile:</p>
<blockquote>
<p>[Linker error] undefined reference to `std::string::size() const'</p>
<p>[Linker error] undefined reference to `std::string::operator[](unsigned int) const'</p>
<p>[Linker error] undefined reference to `std::string::operator[](unsigned int) const'</p>
<p>[Linker error] undefined reference to `std::string::operator[](unsigned int) const'</p>
<p>[Linker error] undefined reference to `std::ios_base::Init::Init()'</p>
<p>[Linker error] undefined reference to `std::ios_base::Init::~Init()'</p>
<p>ld returned 1 exit status</p>
</blockquote>
<p>How do I resolve this?</p>
<p>Edit: My compiler is Dev-C++ 4.9.9.2</p>
|
[
{
"answer_id": 264084,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 6,
"selected": true,
"text": "string.h string"
},
{
"answer_id": 34130770,
"author": "Amaresh Kumar",
"author_id": 1343196,
"author_profile": "https://Stackoverflow.com/users/1343196",
"pm_score": 2,
"selected": false,
"text": "-L/usr/local/bin -L/usr/lib"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
264,080
|
<p>What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.</p>
<p>3.5 would return 4 for power of 2 and 1 for power of 10</p>
<p>123 would return 128 for power of 2 and 100 for power of 10</p>
<p>0.24 would return 0.25 for power of 2 and 0.1 for power of 10</p>
<p>I'm just looking for the algorithm and don't mind the language.</p>
|
[
{
"answer_id": 264093,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "n^round(log_n(x))\n log_n(x) log_n(x) = log(x) / log(n)\n log"
},
{
"answer_id": 311972,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": 3,
"selected": false,
"text": "int NextPowerOf2(int n)\n{\n n |= (n >> 16);\n n |= (n >> 8);\n n |= (n >> 4);\n n |= (n >> 2);\n n |= (n >> 1);\n ++n;\n return n;\n}\n"
},
{
"answer_id": 312087,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 1,
"selected": false,
"text": "closest = n ^ round(log_n(x))\n\nif (closest > x) {\n other = closest / n\n} else {\n other = closest * n\n}\n\nif (abs(other - x) < abs(closest - x)) {\n return other\n} else {\n return closest\n}\n"
},
{
"answer_id": 72439913,
"author": "ZXYNINE",
"author_id": 4285191,
"author_profile": "https://Stackoverflow.com/users/4285191",
"pm_score": 0,
"selected": false,
"text": "private static int ClosestPowerOfTwo(int v) {\n //gets value of bit to the right of leading bit and moves it to left by 1\n int r = (v & (v>>1))<<1; \n //rs bit in same place as vs leading bit is 1 to round up or 0 to round down.\n v >>= 1;\n //replaces leading bit with a 1 if rounding up or leaves 0 if rounding down.\n v |= r; \n //Next power of 2 exclusive\n v |= v >> 1;\n v |= v >> 2;\n v |= v >> 4;\n v |= v >> 8;\n v |= v >> 16;\n v++;\n return v;\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
] |
264,090
|
<p>How can I make:</p>
<p>DELETE FROM foo WHERE id=1 AND <strong>bar not contains id==1</strong></p>
<p>To elaborate, how can I remove a row with <code>id = 1</code>, from table <code>foo</code>, only if there is not a row in table <code>bar</code> with <code>id = 1</code>.</p>
|
[
{
"answer_id": 264103,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 5,
"selected": true,
"text": "DELETE FROM foo WHERE id=1 AND NOT EXISTS (SELECT * FROM bar WHERE id=1)\n"
},
{
"answer_id": 264517,
"author": "nathan_jr",
"author_id": 3769,
"author_profile": "https://Stackoverflow.com/users/3769",
"pm_score": 4,
"selected": false,
"text": "delete f\nfrom foo f\nleft\njoin bar b on\n f.id = b.id \nwhere f.id = 1 and\n b.id is null\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26004/"
] |
264,123
|
<p>Is there a way to have % in vim find the next ([{ or whatever, even if it is not on the same line?</p>
<p>Example:</p>
<pre><code>int main(int argc, char ** argv) {
#Your cursor is somewhere in this comment, I want
#it to get to the ( after printf
printf("Hello there.\n");
}
</code></pre>
|
[
{
"answer_id": 264137,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 3,
"selected": true,
"text": "/{ [enter]\n"
},
{
"answer_id": 264148,
"author": "puetzk",
"author_id": 14312,
"author_profile": "https://Stackoverflow.com/users/14312",
"pm_score": 2,
"selected": false,
"text": ":runtime macros/matchit.vim\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,127
|
<p>I have a program that when it starts, opens a winform (it is the one specified in Application.Run(new ...). From this form I open another form:</p>
<pre><code>OtherForm newForm=new OtherForm();
newForm.Show();
</code></pre>
<p>How can i communicate from the new winform with the form that opened it? So that I can add some items in it.</p>
|
[
{
"answer_id": 264132,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 2,
"selected": false,
"text": "OtherForm newForm=new OtherForm(string title, int data);"
},
{
"answer_id": 264151,
"author": "Jon B",
"author_id": 27414,
"author_profile": "https://Stackoverflow.com/users/27414",
"pm_score": 2,
"selected": false,
"text": "Form m_mainForm;\npublic OtherForm(Form mainForm)\n{\n m_mainForm = mainForm;\n}\n"
},
{
"answer_id": 264155,
"author": "netadictos",
"author_id": 31791,
"author_profile": "https://Stackoverflow.com/users/31791",
"pm_score": 1,
"selected": true,
"text": "public delegate void AddItemDelegate(string item);\npublic AddItemDelegate AddItemCallback;\n private void btnScenario2_Click(object sender, EventArgs e)\n{\n\n FrmDialog dlg = new FrmDialog();\n //Subscribe this form for callback\n dlg.AddItemCallback = new AddItemDelegate(this.AddItemCallbackFn);\n dlg.ShowDialog();\n\n}\nprivate void AddItemCallbackFn(string item)\n{\n\n lstBx.Items.Add(item);\n\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31791/"
] |
264,128
|
<p>I am trying to export a Ruby framework via XML-RPC. However I am having some problems when trying to call a method from a class not directly added as a handler to the XML-RPC server. Please see my example below:</p>
<p>I have a test Ruby XML-RPC server as follows:</p>
<pre><code>require "xmlrpc/server"
class ExampleBar
def bar()
return "hello world!"
end
end
class ExampleFoo
def foo()
return ExampleBar.new
end
def test()
return "test!"
end
end
s = XMLRPC::Server.new( 9090 )
s.add_introspection
s.add_handler( "example", ExampleFoo.new )
s.serve
</code></pre>
<p>And I have a test Python XML-RPC Client as follows:</p>
<pre><code>import xmlrpclib
s = xmlrpclib.Server( "http://127.0.0.1:9090/" )
print s.example.foo().bar()
</code></pre>
<p>I would expect the python client to print "hello world!" as it is the equivalent of the following ruby code:</p>
<pre><code>example = ExampleFoo.new
puts example.foo().bar()
</code></pre>
<p>However it generates an error: "xmlrpclib.ProtocolError: <ProtocolError for 127.0.0.1:9090/: 500 Internal Server Error>".</p>
<p>print s.example.test() works fine.</p>
<p>I dont expect the new ExampleBar object to go over the wire but I would expect it to be 'cached' server side and the subsequent call to bar() to be honoured.</p>
<p>Can XML-RPC support this kind of usage or is it too basic?</p>
<p>So I guess my question really is; how can I get this working, if not with XML-RPC what with?</p>
|
[
{
"answer_id": 264165,
"author": "jakber",
"author_id": 29812,
"author_profile": "https://Stackoverflow.com/users/29812",
"pm_score": 4,
"selected": true,
"text": "def foobar()\n return ExampleFoo.new().foo().bar()\nend\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14260/"
] |
264,140
|
<p>I've a web service running on server which return data either in XML format or JSON format.
I wanted to request a JSON format but using HTTP Post method.</p>
|
[
{
"answer_id": 264380,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 0,
"selected": false,
"text": "CFURLRef url = CFURLCreateWithString(NULL, CFSTR(\"http://example.com/post\"), NULL);\nCFHTTPMessageRef msg = CFHTTPMessageCreateRequest(\n NULL,\n CFSTR(\"POST\"),\n url,\n kCFHTTPVersion1_1);\n\nconst char *body = \"key=value&id=30293\";\nCFDataRef bodyData = CFDataCreate(NULL, body, strlen(body));\nCFHTTPMessageSetBody(msg, bodyData);\n\nCFReadStreamRef myReadStream = CFReadStreamCreateForHTTPRequest(NULL, myRequest);\nCFReadStreamOpen(myReadStream);\nCFHTTPMessageRef myResponse = CFReadStreamCopyProperty(\n myReadStream,\n kCFStreamPropertyHTTPResponseHeader);\n\n//\n// Handle myResponse\n//\n\nCFReadStreamClose(myReadStream);\nCFRelease(myReadStream);\nCFRelease(bodyData);\nCFRelease(msg);\nCFRelease(url);\n"
},
{
"answer_id": 264553,
"author": "Amit Vaghela",
"author_id": 451867,
"author_profile": "https://Stackoverflow.com/users/451867",
"pm_score": 6,
"selected": true,
"text": "NSArray *keys = [NSArray arrayWithObjects:@\"username\", @\"password\", @\"preference\", @\"uid\", nil];\nNSArray *objects = [NSArray arrayWithObjects:@\"accuser\", @\"accpass\", @\"abc_region\", @\"100\", nil];\nNSDictionary *theRequestDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];\n\nNSURL *theURL = [NSURL URLWithString:@\"http://url.com/request.php\"];\nNSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10.0f];\n[theRequest setHTTPMethod:@\"POST\"];\n\n[theRequest setValue:@\"application/json-rpc\" forHTTPHeaderField:@\"Content-Type\"];\nNSString *theBodyString = [[CJSONSerializer serializer] serializeDictionary:theRequestDictionary];\nNSLog(@\"%@\", theBodyString);\nNSData *theBodyData = [theBodyString dataUsingEncoding:NSUTF8StringEncoding];\n// NSLog(@\"%@\", theBodyData);\n[theRequest setHTTPBody:theBodyData];\n\nNSURLResponse *theResponse = NULL;\nNSError *theError = NULL;\nNSData *theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];\nNSString *theResponseString = [[[NSString alloc] initWithData:theResponseData encoding:NSUTF8StringEncoding] autorelease];\nNSLog(theResponseString);\nNSDictionary *theResponseDictionary = [[CJSONDeserializer deserializer] deserialize:theResponseString];\nNSLog(@\"%@\", theResponseDictionary);\nNSString *theGreeting = [theResponseDictionary objectForKey:@\"greeting\"];\n[self setValue:theGreeting forKey:@\"greeting\"];\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/451867/"
] |
264,154
|
<p>How can I fetch more than 1000 record from data store and put all in one single list to pass to django?</p>
|
[
{
"answer_id": 264171,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 4,
"selected": false,
"text": "LIMIT 1000 OFFSET 0 \n LIMIT 1000 OFFSET 1000 \n SELECT * FROM Foo WHERE ID > 0 AND ID < 1000 \n\n SELECT * FROM Foo WHERE ID >= 1000 AND ID < 2000\n"
},
{
"answer_id": 264204,
"author": "Tom Leys",
"author_id": 11440,
"author_profile": "https://Stackoverflow.com/users/11440",
"pm_score": 0,
"selected": false,
"text": "list1 = first query\nlist2 = second query\nlist1 += list2\n"
},
{
"answer_id": 721858,
"author": "JJ Geewax",
"author_id": 81019,
"author_profile": "https://Stackoverflow.com/users/81019",
"pm_score": 4,
"selected": false,
"text": "class MyModel(db.Expando):\n @classmethod\n def count_all(cls):\n \"\"\"\n Count *all* of the rows (without maxing out at 1000)\n \"\"\"\n count = 0\n query = cls.all().order('__key__')\n\n while count % 1000 == 0:\n current_count = query.count()\n if current_count == 0:\n break\n\n count += current_count\n\n if current_count == 1000:\n last_key = query.fetch(1, 999)[0].key()\n query = query.filter('__key__ > ', last_key)\n\n return count\n"
},
{
"answer_id": 1338456,
"author": "mhawthorne",
"author_id": 112181,
"author_profile": "https://Stackoverflow.com/users/112181",
"pm_score": 1,
"selected": false,
"text": "while count % 1000 == 0:\n current_count = query.count()\n if current_count == 0:\n break\n"
},
{
"answer_id": 1477027,
"author": "fun_vit",
"author_id": 179040,
"author_profile": "https://Stackoverflow.com/users/179040",
"pm_score": 2,
"selected": false,
"text": "class Count(object):\ndef getCount(self,cls):\n class Count(object):\ndef getCount(self,cls):\n \"\"\"\n Count *all* of the rows (without maxing out at 1000)\n \"\"\"\n count = 0\n query = cls.all().order('__key__')\n\n\n while 1:\n current_count = query.count()\n count += current_count\n if current_count == 0:\n break\n\n last_key = query.fetch(1, current_count-1)[0].key()\n query = query.filter('__key__ > ', last_key)\n\n return count\n"
},
{
"answer_id": 2204144,
"author": "Tiger Woods",
"author_id": 231493,
"author_profile": "https://Stackoverflow.com/users/231493",
"pm_score": 3,
"selected": false,
"text": "query = MyModel.all()\nfor doc in query:\n print doc.title\n"
},
{
"answer_id": 3681636,
"author": "Gabriel",
"author_id": 204210,
"author_profile": "https://Stackoverflow.com/users/204210",
"pm_score": 2,
"selected": false,
"text": "ModelBase @classmethod\ndef get_all(cls):\n q = cls.all()\n holder = q.fetch(1000)\n result = holder\n while len(holder) == 1000:\n holder = q.with_cursor(q.cursor()).fetch(1000)\n result += holder\n return result\n"
},
{
"answer_id": 5320613,
"author": "Timothy Tripp",
"author_id": 661751,
"author_profile": "https://Stackoverflow.com/users/661751",
"pm_score": 0,
"selected": false,
"text": "count = 0\nq = YourEntityClass.all().filter('myval = ', 2)\ncountBatch = q.count()\nwhile countBatch > 0:\n count += countBatch\n countBatch = q.with_cursor(q.cursor()).count()\n\nlogging.info('Count=%d' % count)\n"
},
{
"answer_id": 7017248,
"author": "crizCraig",
"author_id": 134077,
"author_profile": "https://Stackoverflow.com/users/134077",
"pm_score": 2,
"selected": false,
"text": "entities = []\nfor entity in Entity.all():\n entities.append(entity)\n entities = Entity.all().fetch(999999)\n Entity.all().fetch(Entity.all().count())\n"
},
{
"answer_id": 24514424,
"author": "Tzach",
"author_id": 1795244,
"author_profile": "https://Stackoverflow.com/users/1795244",
"pm_score": 3,
"selected": false,
"text": "def _iterate_table(table, chunk_size = 200):\n offset = 0\n while True:\n results = table.all().order('__key__').fetch(chunk_size+1, offset = offset)\n if not results:\n break\n for result in results[:chunk_size]:\n yield result\n if len(results) < chunk_size+1:\n break\n offset += chunk_size\n"
},
{
"answer_id": 35268792,
"author": "Oded Breiner",
"author_id": 710284,
"author_profile": "https://Stackoverflow.com/users/710284",
"pm_score": 0,
"selected": false,
"text": "@staticmethod\ndef _iterate_table(table, chunk_size=200):\n offset = 0\n while True:\n results = table.query().order(table.key).fetch(chunk_size + 1, offset=offset)\n if not results:\n break\n for result in results[:chunk_size]:\n yield result\n if len(results) < chunk_size + 1:\n break\n offset += chunk_size\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20683/"
] |
264,163
|
<p>I have a somewhat complex WPF application which seems to be 'hanging' or getting stuck in a Wait call when trying to use the dispatcher to invoke a call on the UI thread.</p>
<p>The general process is:</p>
<ol>
<li>Handle the click event on a button</li>
<li>Create a new thread (STA) which: creates a new instance of the presenter and UI, then calls the method <strong>Disconnect</strong></li>
<li>Disconnect then sets a property on the UI called <strong>Name</strong></li>
<li>The setter for Name then uses the following code to set the property:</li>
</ol>
<pre><code>
if(this.Dispatcher.Thread != Thread.CurrentThread)
{
this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{
this.Name = value; // Call same setter, but on the UI thread
});
return;
}
SetValue(nameProperty, value); // I have also tried a member variable and setting the textbox.text property directly.
</code></pre>
<p>My problem is that when the dispatcher <strong>invoke</strong> method is called it seems to hang every single time, and the callstack indicates that its in a sleep, wait or join within the Invoke implementation.</p>
<p>So, is there something I am doing wrong which I am missing, obvious or not, or is there a better way of calling across to the UI thread to set this property (and others)?</p>
<p><strong>Edit:</strong> The solution was to call System.Windows.Threading.Dispatcher.Run() at the end of the thread delegate (e.g. where the work was being performed) - Thanks to all who helped.</p>
|
[
{
"answer_id": 5215784,
"author": "Jeff",
"author_id": 164438,
"author_profile": "https://Stackoverflow.com/users/164438",
"pm_score": 2,
"selected": false,
"text": " if(this.Dispatcher.Thread != Thread.CurrentThread)\n{\n this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{\n this.Name = value; // Call same setter, but on the UI thread\n });\n return;\n}\n if(this.Dispatcher.CheckAccess())\n{\n this.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate{\n this.Name = value; // Call same setter, but on the UI thread\n });\n return;\n}\n"
},
{
"answer_id": 14254324,
"author": "Martin Lottering",
"author_id": 1308645,
"author_profile": "https://Stackoverflow.com/users/1308645",
"pm_score": 0,
"selected": false,
"text": "lock (locker) { ... } lock (locker) { ... } Interlocked.Increment(ref lockCounter) void SynchronizedMethodExample() {\n\n /* synchronize access to this method */\n if (Interlocked.Increment(ref _lockCounter) != 1) { return; }\n\n try {\n ...\n }\n finally {\n _mandatoryCounter--;\n }\n}\n"
},
{
"answer_id": 22101974,
"author": "Alexandru",
"author_id": 982639,
"author_profile": "https://Stackoverflow.com/users/982639",
"pm_score": 3,
"selected": false,
"text": "lock (someObject)\n{\n // Do one thing.\n someDispatcher.Invoke(() =>\n {\n // Do something else.\n }\n}\n someDispatcher.Invoke(() =>\n{\n lock (someObject)\n {\n // Do something.\n }\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18434/"
] |
264,196
|
<p>Are event handlers fired in the order that they attached to the event? If not, can I enforce some kind of order onto the event handlers such that they are called in a specific order?</p>
|
[
{
"answer_id": 264299,
"author": "Chad Moran",
"author_id": 25416,
"author_profile": "https://Stackoverflow.com/users/25416",
"pm_score": 2,
"selected": false,
"text": "MyObject.MyEvent += new MyEventHandler(Wrapper);\n\npublic void Wrapper()\n{\n Method1();\n Method3();\n Method2();\n}\n"
},
{
"answer_id": 264478,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Delegate.Combine/Remove Delegate.Combine Delegate.Combine/Remove"
},
{
"answer_id": 1098250,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "// this methods hooks two delegates to MyCollection.Added event, but the order results in a \"IndexOutOfRange\" exception after the event is triggered\nHookEvents()\n{\n MyCollection.Added += new CollectionItemAddedHandler(DeleteItem_After_CollectionItemAdded);\n\n MyCollection.Added += new CollectionItemAddedHandler(ShowMessage_After_CollectionItemAdded);\n}\n\n\n// when user click a button on form, add a object to MyCollection\nButton_Clicked()\n{\n MyCollection.Add(new object()); \n}\n\n// at the moment a object is added into the collection, this method remove it\nDeleteItem_After_CollectionItemAdded(NewIndexArgs e)\n{\n MyCollection.Remove(e.NewIndex); // e.NewIndex represents the newly added item index in current collection \n}\n\n// at the moment a object is added into the collection, this method show its information (hey, but remember, I just remove it in the previous method)\nShowMessage_After_CollectionItemAdded(NewIndexArgs e)\n{\n MessageBox.Show(MyCollection[e.NewIndex]); // tell user what is just added into the current collection\n // a \"IndexOutOfRange\" exception is thrown here....\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264196",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/358/"
] |
264,216
|
<p>I'm playing around with ASP.net MVC and JQuery at the moment. I've come across behavour which doesn't seem to make sense. </p>
<p>I'm calling JQuery's <code>$.getJSON</code> function to populate some div's. The event is triggered on the <code>$(document).ready</code> event. This works perfectly.</p>
<p>There is a small <code>AJAX.BeginForm</code> which adds another value to be used when populating the divs. It calls the remote function correctly and upon success calls the original javascript function to repopulate the divs.</p>
<p>Here is the weird part: In FireFox and Chrome - Everything works. BUT In IE8 (Beta) this second call to the populate Div script (which calls the $.getJSON function) gets cached data and does not ask the server!</p>
<p>Hope this question makes sense: In a nut shell - Why is <code>$.getJSON</code> getting cached data? And why is it only effecting IE8?</p>
|
[
{
"answer_id": 264351,
"author": "Andrew Harry",
"author_id": 30576,
"author_profile": "https://Stackoverflow.com/users/30576",
"pm_score": 4,
"selected": false,
"text": "var noCache = Date();\n$.getJSON(\"/somepage/someaction\", { \"noCache\": noCache }, Callback);\n"
},
{
"answer_id": 264654,
"author": "Nico",
"author_id": 22970,
"author_profile": "https://Stackoverflow.com/users/22970",
"pm_score": 7,
"selected": true,
"text": "public class NoCacheAttribute : ActionFilterAttribute\n{\n public override void OnActionExecuted(ActionExecutedContext context)\n {\n context.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);\n }\n}\n"
},
{
"answer_id": 358083,
"author": "Jitesh Patil",
"author_id": 1150244,
"author_profile": "https://Stackoverflow.com/users/1150244",
"pm_score": 7,
"selected": false,
"text": "$.ajaxSetup({ cache: false });\n$.getJSON(\"/MyQueryUrl\",function(data,item) {\n // do stuff with callback data\n $.ajaxSetup({ cache: true });\n });\n"
},
{
"answer_id": 849023,
"author": "Josh",
"author_id": 59143,
"author_profile": "https://Stackoverflow.com/users/59143",
"pm_score": 2,
"selected": false,
"text": " public static void NoCache(this HttpResponse Response)\n {\n Response.Cache.SetNoStore();\n Response.Cache.SetExpires(DateTime.MinValue);\n Response.Cache.SetCacheability(HttpCacheability.NoCache);\n Response.Cache.SetValidUntilExpires(false);\n\n Response.Expires = -1;\n Response.ExpiresAbsolute = DateTime.MinValue;\n Response.AddHeader(\"Cache-Control\", \"no-cache\");\n Response.AddHeader(\"Pragma\", \"no-cache\");\n }\n"
},
{
"answer_id": 1269939,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 4,
"selected": false,
"text": "[OutputCache(Duration = 0, VaryByParam = \"None\")]\n"
},
{
"answer_id": 10794994,
"author": "stadja",
"author_id": 1211640,
"author_profile": "https://Stackoverflow.com/users/1211640",
"pm_score": 2,
"selected": false,
"text": "jQuery.support.cors = true; \n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30576/"
] |
264,224
|
<p>I'm interested in compressing data using Python's <code>gzip</code> module. It happens that I want the compressed output to be deterministic, because that's often a really convenient property for things to have in general -- if some non-gzip-aware process is going to be looking for changes in the output, say, or if the output is going to be cryptographically signed.</p>
<p>Unfortunately, the output is different every time. As far as I can tell, the only reason for this is the timestamp field in the gzip header, which the Python module always populates with the current time. I don't think you're actually allowed to have a gzip stream without a timestamp in it, which is too bad.</p>
<p>In any case, there doesn't seem to be a way for the caller of Python's <code>gzip</code> module to supply the correct modification time of the underlying data. (The actual <code>gzip</code> program seems to use the timestamp of the input file when possible.) I imagine this is because basically the only thing that ever cares about the timestamp is the <code>gunzip</code> command when writing to a file -- and, now, me, because I want deterministic output. Is that so much to ask?</p>
<p>Has anyone else encountered this problem?</p>
<p>What's the least terrible way to <code>gzip</code> some data with an arbitrary timestamp from Python?</p>
|
[
{
"answer_id": 264297,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 0,
"selected": false,
"text": "def _write_gzip_header(self):\n self.fileobj.write('\\037\\213') # magic header\n self.fileobj.write('\\010') # compression method\n fname = self.filename[:-3]\n flags = 0\n if fname:\n flags = FNAME\n self.fileobj.write(chr(flags))\n write32u(self.fileobj, long(time.time())) # The current time!\n self.fileobj.write('\\002')\n self.fileobj.write('\\377')\n if fname:\n self.fileobj.write(fname + '\\000')\n"
},
{
"answer_id": 264303,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 3,
"selected": false,
"text": "write32u(self.fileobj, long(time.time()))\n _write_gzip_header class FakeTime:\n def time(self):\n return 1225856967.109\n\nimport gzip\ngzip.time = FakeTime()\n\n# Now call gzip, it will think time doesn't change!\n class GzipTimeFixingFile:\n def __init__(self, realfile):\n self.realfile = realfile\n self.pos = 0\n\n def write(self, bytes):\n if self.pos == 4 and len(bytes) == 4:\n self.realfile.write(\"XYZY\") # Fake time goes here.\n else:\n self.realfile.write(bytes)\n self.pos += len(bytes)\n"
},
{
"answer_id": 264348,
"author": "Tony Arkles",
"author_id": 13868,
"author_profile": "https://Stackoverflow.com/users/13868",
"pm_score": 0,
"selected": false,
"text": "import time\n\ndef fake_time():\n return 100000000.0\n\ndef do_gzip(content):\n orig_time = time.time\n time.time = fake_time\n # result = do gzip stuff here\n time.time = orig_time\n return result\n"
},
{
"answer_id": 270315,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 1,
"selected": false,
"text": "gzip write() gzip gzip gzip gzip"
},
{
"answer_id": 36034315,
"author": "Dominic Bevacqua",
"author_id": 527997,
"author_profile": "https://Stackoverflow.com/users/527997",
"pm_score": 4,
"selected": true,
"text": "import gzip\n\ncontent = b\"Some content\"\nf = open(\"/tmp/f.gz\", \"wb\")\ngz = gzip.GzipFile(fileobj=f,mode=\"wb\",filename=\"\",mtime=0)\ngz.write(content)\ngz.close()\nf.close()\n"
},
{
"answer_id": 44054997,
"author": "storm_m2138",
"author_id": 1236537,
"author_profile": "https://Stackoverflow.com/users/1236537",
"pm_score": 0,
"selected": false,
"text": "with open('test_zip1', 'rb') as f_in, open('test_zip1.gz', 'wb') as f_out:\n with gzip.GzipFile(fileobj=f_out, mode='wb', filename=\"\", mtime=0) as gz_out:\n shutil.copyfileobj(f_in, gz_out)\n md5sum test_zip*\n7e544bc6827232f67ff5508c8d6c30b3 test_zip1\n75decc5768bdc3c98d6e598dea85e39b test_zip1.gz\n7e544bc6827232f67ff5508c8d6c30b3 test_zip2\n75decc5768bdc3c98d6e598dea85e39b test_zip2.gz\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13871/"
] |
264,236
|
<p>How do you determine what to put in .rhosts file in an VAX openvms system when trying to remotely access the server using a remote shell from Cygwin on windows XP ? .rlogin and rsh are the only methods that can be used to access the VAX server and it must be using Cygwin to remote in to the VAX server. SSH is not an option. When the VAX server is accessed from a Sun server it works fine. I have tried many combination's of possible things that Cygwin could be sending the VAX as far as a user name an address of origin. </p>
|
[
{
"answer_id": 264297,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 0,
"selected": false,
"text": "def _write_gzip_header(self):\n self.fileobj.write('\\037\\213') # magic header\n self.fileobj.write('\\010') # compression method\n fname = self.filename[:-3]\n flags = 0\n if fname:\n flags = FNAME\n self.fileobj.write(chr(flags))\n write32u(self.fileobj, long(time.time())) # The current time!\n self.fileobj.write('\\002')\n self.fileobj.write('\\377')\n if fname:\n self.fileobj.write(fname + '\\000')\n"
},
{
"answer_id": 264303,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 3,
"selected": false,
"text": "write32u(self.fileobj, long(time.time()))\n _write_gzip_header class FakeTime:\n def time(self):\n return 1225856967.109\n\nimport gzip\ngzip.time = FakeTime()\n\n# Now call gzip, it will think time doesn't change!\n class GzipTimeFixingFile:\n def __init__(self, realfile):\n self.realfile = realfile\n self.pos = 0\n\n def write(self, bytes):\n if self.pos == 4 and len(bytes) == 4:\n self.realfile.write(\"XYZY\") # Fake time goes here.\n else:\n self.realfile.write(bytes)\n self.pos += len(bytes)\n"
},
{
"answer_id": 264348,
"author": "Tony Arkles",
"author_id": 13868,
"author_profile": "https://Stackoverflow.com/users/13868",
"pm_score": 0,
"selected": false,
"text": "import time\n\ndef fake_time():\n return 100000000.0\n\ndef do_gzip(content):\n orig_time = time.time\n time.time = fake_time\n # result = do gzip stuff here\n time.time = orig_time\n return result\n"
},
{
"answer_id": 270315,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 1,
"selected": false,
"text": "gzip write() gzip gzip gzip gzip"
},
{
"answer_id": 36034315,
"author": "Dominic Bevacqua",
"author_id": 527997,
"author_profile": "https://Stackoverflow.com/users/527997",
"pm_score": 4,
"selected": true,
"text": "import gzip\n\ncontent = b\"Some content\"\nf = open(\"/tmp/f.gz\", \"wb\")\ngz = gzip.GzipFile(fileobj=f,mode=\"wb\",filename=\"\",mtime=0)\ngz.write(content)\ngz.close()\nf.close()\n"
},
{
"answer_id": 44054997,
"author": "storm_m2138",
"author_id": 1236537,
"author_profile": "https://Stackoverflow.com/users/1236537",
"pm_score": 0,
"selected": false,
"text": "with open('test_zip1', 'rb') as f_in, open('test_zip1.gz', 'wb') as f_out:\n with gzip.GzipFile(fileobj=f_out, mode='wb', filename=\"\", mtime=0) as gz_out:\n shutil.copyfileobj(f_in, gz_out)\n md5sum test_zip*\n7e544bc6827232f67ff5508c8d6c30b3 test_zip1\n75decc5768bdc3c98d6e598dea85e39b test_zip1.gz\n7e544bc6827232f67ff5508c8d6c30b3 test_zip2\n75decc5768bdc3c98d6e598dea85e39b test_zip2.gz\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34531/"
] |
264,243
|
<p>I'm working on a quick project to monitor/process data. Essentially that's just monitors, schedules and processors. The monitor checks for data (ftp, local, imap, pop, etc) using a schedule and sends new data to a processor. They all have interfaces.</p>
<p>I'm trying to find a sane way to use config to configure what schedule/processor each monitor uses. That's pretty easy:</p>
<pre><code><monitor type="any.class.implementing.monitor">
<schedule type="any.class.implementing.schedule">
...
</schedule>
<processor type="any.class.implementing.processor" />
</monitor>
</code></pre>
<p>What I'm struggling with is what's the best way to configure any old monitor/schedule/processor thrown into the mix. On one hand, one could implement constructor params or properties (give ot take any syntax):</p>
<pre><code><monitor type="any.class.implementing.monitor">
<args>
<arg value="..." />
</args>
<properties>
<property name="..." value=..." />
</properties>
<schedule type="any.class.implementing.schedule">
...
</schedule>
<processor type="any.class.implementing.processor" />
</monitor>
</code></pre>
<p>Another solution is factory method in each interface that takes the custom config as a param:</p>
<pre><code>public IMonitor Create(CustomConfigSection config);
</code></pre>
<p>I've seen people use both. What do you prefer? Any tricks of the trade when mapping config to constructors?</p>
<p>I'm a little torn as to whether DI can fit into this mess. In the end, it would be a set of bindings per monitor instance, which seems pointless except for defaults, which config could cover.</p>
|
[
{
"answer_id": 264297,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 0,
"selected": false,
"text": "def _write_gzip_header(self):\n self.fileobj.write('\\037\\213') # magic header\n self.fileobj.write('\\010') # compression method\n fname = self.filename[:-3]\n flags = 0\n if fname:\n flags = FNAME\n self.fileobj.write(chr(flags))\n write32u(self.fileobj, long(time.time())) # The current time!\n self.fileobj.write('\\002')\n self.fileobj.write('\\377')\n if fname:\n self.fileobj.write(fname + '\\000')\n"
},
{
"answer_id": 264303,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 3,
"selected": false,
"text": "write32u(self.fileobj, long(time.time()))\n _write_gzip_header class FakeTime:\n def time(self):\n return 1225856967.109\n\nimport gzip\ngzip.time = FakeTime()\n\n# Now call gzip, it will think time doesn't change!\n class GzipTimeFixingFile:\n def __init__(self, realfile):\n self.realfile = realfile\n self.pos = 0\n\n def write(self, bytes):\n if self.pos == 4 and len(bytes) == 4:\n self.realfile.write(\"XYZY\") # Fake time goes here.\n else:\n self.realfile.write(bytes)\n self.pos += len(bytes)\n"
},
{
"answer_id": 264348,
"author": "Tony Arkles",
"author_id": 13868,
"author_profile": "https://Stackoverflow.com/users/13868",
"pm_score": 0,
"selected": false,
"text": "import time\n\ndef fake_time():\n return 100000000.0\n\ndef do_gzip(content):\n orig_time = time.time\n time.time = fake_time\n # result = do gzip stuff here\n time.time = orig_time\n return result\n"
},
{
"answer_id": 270315,
"author": "zaphod",
"author_id": 13871,
"author_profile": "https://Stackoverflow.com/users/13871",
"pm_score": 1,
"selected": false,
"text": "gzip write() gzip gzip gzip gzip"
},
{
"answer_id": 36034315,
"author": "Dominic Bevacqua",
"author_id": 527997,
"author_profile": "https://Stackoverflow.com/users/527997",
"pm_score": 4,
"selected": true,
"text": "import gzip\n\ncontent = b\"Some content\"\nf = open(\"/tmp/f.gz\", \"wb\")\ngz = gzip.GzipFile(fileobj=f,mode=\"wb\",filename=\"\",mtime=0)\ngz.write(content)\ngz.close()\nf.close()\n"
},
{
"answer_id": 44054997,
"author": "storm_m2138",
"author_id": 1236537,
"author_profile": "https://Stackoverflow.com/users/1236537",
"pm_score": 0,
"selected": false,
"text": "with open('test_zip1', 'rb') as f_in, open('test_zip1.gz', 'wb') as f_out:\n with gzip.GzipFile(fileobj=f_out, mode='wb', filename=\"\", mtime=0) as gz_out:\n shutil.copyfileobj(f_in, gz_out)\n md5sum test_zip*\n7e544bc6827232f67ff5508c8d6c30b3 test_zip1\n75decc5768bdc3c98d6e598dea85e39b test_zip1.gz\n7e544bc6827232f67ff5508c8d6c30b3 test_zip2\n75decc5768bdc3c98d6e598dea85e39b test_zip2.gz\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264243",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91911/"
] |
264,248
|
<p>I'm looking into integrating jBPM with my current project, so far so good just including the jpdl jar in my ear and using the spring modules 0.8 jbpm module, however I've got to have a reasonable way of going from my changes to to the process definition in the designer to deployment in production.</p>
<p>The path has to be repeatable in a number of environments (dev, many test, staging and then prod) and ideally should be done while the system itself is not running.</p>
<p>I'd Ideally package the entire definition as an SQL script, however I haven't seen any tool to translate from processdefinition.xml to sql and assembling it all manually seems too fiddly and error prone.</p>
<p>Has anyone else out there had any experiences here?</p>
<p>The system is running on websphere 6.1 and it's my preference to avoid executing java code at migration time (running java code to generate artifacts that can then be used during migration is ok though)</p>
|
[
{
"answer_id": 266157,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 0,
"selected": false,
"text": "DeployProcessTask .par jbpm-cfg.xml"
},
{
"answer_id": 286822,
"author": "Harry Lime",
"author_id": 21590,
"author_profile": "https://Stackoverflow.com/users/21590",
"pm_score": 1,
"selected": false,
"text": ".par JbpmConfiguration jbpmConfiguration = JbpmConfiguration.getInstance(\"jbpm.cfg.xml\"));\nProcessDefinition processDefinition = ProcessDefinition.parseXmlInputStream(newPdStream);\nJbpmContext context = jbpmConfiguration.createJbpmContext();\ncontext.getGraphSession().deployProcessDefinition(processDefinition);\n hibernate.properties hibernate.cfg.xml"
},
{
"answer_id": 333354,
"author": "Balint Pato",
"author_id": 19621,
"author_profile": "https://Stackoverflow.com/users/19621",
"pm_score": 1,
"selected": false,
"text": "context.getGraphSession().deployProcessDefinition(processDefinition);\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,249
|
<p>I've been beating my head against this wall for quite some time now, so I thought I'd ask some experts.</p>
<p>I need to send an xml string from one computer to the next. I would like to format the xml something like this:</p>
<pre><code><xml>
<author>Joe the Magnificent</author>
<title>Joe Goes Home</title>
</xml>
</code></pre>
<p>Can anyone provide some assistance?</p>
<p>Edit: More detail</p>
<p>I control both the send and receive, and have successfully transfered a hard coded string one-way.</p>
<p>Here is the receive side:</p>
<pre><code> Dim author As String
Dim title As String
Dim xDoc As New XmlDocument
Dim xAuthor As XmlElement
Dim xTitle As XmlElement
xDoc.LoadXml(xml)
xAuthor = xDoc.FirstChild.Item("author")
xTitle = xDoc.FirstChild.Item("title")
author = xAuthor.FirstChild.Value
title = xTitle.FirstChild.Value
ShowMessage(author, title)
</code></pre>
<p>Mostly this is an exercise in learning how to do XML for me, so there's no real purpose to it other than my own knowledge. I was kind of looking for some opinions on the best way to do such things.</p>
|
[
{
"answer_id": 264279,
"author": "Jim Burger",
"author_id": 20164,
"author_profile": "https://Stackoverflow.com/users/20164",
"pm_score": 2,
"selected": false,
"text": " Dim settings As XmlWriterSettings = New XmlWriterSettings()\n settings.Indent = true\n settings.IndentChars = (ControlChars.Tab)\n settings.OmitXmlDeclaration = true\n\n Dim myNetworkStream As New NetworkStream(mySocket) 'mySocket is a whole other code sample\n\n ' Create the XmlWriter object and write some content.\n writer = XmlWriter.Create(myNetworkStream, settings)\n XmlDocument.WriteTo(writer)\n Dim doc As New XmlDocument()\n Dim root As XmlElement = doc.CreateElement(\"xml\")\n Dim author As XmlElement = doc.CreateElement(\"author\")\n author.Value = \"Joe the magnificent\"\n Dim title As XmlElement = doc.CreateElement(\"title\")\n title.Value = \"Joe goes home\"\n\n root.AppendChild(author)\n root.AppendChild(title)\n doc.AppendChild(root)\n"
},
{
"answer_id": 264282,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 1,
"selected": false,
"text": "Sub Send()\n Dim myxml = <xml>\n <author>Joe the Magnificent</author>\n <title>Joe Goes Home</title>\n </xml>\nReadxml(myxml)\nEnd Sub\n\nSub Readxml(myxml as XDocument)\nDim Data = From xml in myxml...<xml> _\n Select New With {.Author = xml.<author>.value, _\n .title = xml.<title>.value}\n\nFor each item in Data\n ShowMessage(item.Author,Item.Title)\nNext\nEnd Sub\n"
},
{
"answer_id": 283819,
"author": "Krakerjak",
"author_id": 34539,
"author_profile": "https://Stackoverflow.com/users/34539",
"pm_score": 3,
"selected": true,
"text": "Public Function FormatMessage(ByVal author As String, ByVal title As String, ByVal genre As String) As String\nDim xDoc As New XmlDocument\n\n' Create outer XML\nDim xNode As XmlNode = xDoc.AppendChild(xDoc.CreateElement(\"xml\"))\n\n' Create Author Node\nDim xAuthor As XmlNode = xNode.AppendChild(xDoc.CreateElement(\"author\"))\nxAuthor.InnerText = author\n\n' Create Message Node\nDim xTitle As XmlNode = xNode.AppendChild(xDoc.CreateElement(\"message\"))\nxtitle.InnerText = title\n\n' Create Genre Node\nDim xGenre As XmlNode = xNode.AppendChild(xDoc.CreateElement(\"genre\"))\nxGenre.InnerText = genre\n\n' Create StringWriter to convert XMLDoc to string\nDim xWriter As New IO.StringWriter()\nDim xml_writer As New XmlTextWriter(xWriter)\nxDoc.WriteContentTo(xml_writer)\nReturn xWriter.ToString\n\nEnd Function\n Dim author As String\nDim title As String\nDim genre As String\n\nDim xDoc As New XmlDocument\nDim xAuthor As XmlElement\nDim xTitle As XmlElement\nDim xGenre as XmlElement\n\nxDoc.LoadXml(xml)\nIf xDoc.DocumentElement.Name = \"xml\" Then\n xAuthor = xDoc.FirstChild.Item(\"author\")\n xTitle = xDoc.FirstChild.Item(\"title\")\n\n author = xAuthor.FirstChild.Value\n title = xTitle.FirstChild.Value\n genre = xGenre.FirstChild.Value\nEnd If\n\nShowMessage(author, title, genre)\n"
},
{
"answer_id": 53653627,
"author": "Danny James",
"author_id": 7709026,
"author_profile": "https://Stackoverflow.com/users/7709026",
"pm_score": 0,
"selected": false,
"text": "Imports System.Data\n\nPublic Class STKReservedStock_insertrow\nInherits Request\nPublic Sub New(User As String, Company As String)\n MyBase.New(\"stkreservestockall\", User, Company)\nEnd Sub\n\n\n#Region \"Properties\"\n\nPublic Property _pdt As String\n Get\n Return DirectCast(Field(\"pdt\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"pdt\") = value\n End Set\nEnd Property\nPublic Property _whse As String\n Get\n Return DirectCast(Field(\"whse\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"whse\") = value\n End Set\nEnd Property\nPublic Property _traceNumber As Integer\n Get\n Return DirectCast(Field(\"traceNumber\"), Integer)\n End Get\n Set(ByVal value As Integer)\n Field(\"traceNumber\") = value\n End Set\nEnd Property\nPublic Property _bin As String\n Get\n Return DirectCast(Field(\"bin\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"bin\") = value\n End Set\nEnd Property\nPublic Property _lotref As String\n Get\n Return DirectCast(Field(\"lotref\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"lotref\") = value\n End Set\nEnd Property\nPublic Property _packUOM As String\n Get\n Return DirectCast(Field(\"packUOM\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"packUOM\") = value\n End Set\nEnd Property\nPublic Property _grade As String\n Get\n Return DirectCast(Field(\"grade\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"grade\") = value\n End Set\nEnd Property\nPublic Property _shpLabel As Integer\n Get\n Return DirectCast(Field(\"shpLabel\"), Integer)\n End Get\n Set(ByVal value As Integer)\n Field(\"shpLabel\") = value\n End Set\nEnd Property\nPublic Property _countLoc As String\n Get\n Return DirectCast(Field(\"countLoc\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"countLoc\") = value\n End Set\nEnd Property\nPublic Property _palletType As String\n Get\n Return DirectCast(Field(\"palletType\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"palletType\") = value\n End Set\nEnd Property\nPublic Property _subPdt As String\n Get\n Return DirectCast(Field(\"subPdt\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"subPdt\") = value\n End Set\nEnd Property\nPublic Property _subTn As Integer\n Get\n Return DirectCast(Field(\"subTn\"), Integer)\n End Get\n Set(ByVal value As Integer)\n Field(\"subTn\") = value\n End Set\nEnd Property\nPublic Property _origReserved As Decimal\n Get\n Return DirectCast(Field(\"origReserved\"), Integer)\n End Get\n Set(ByVal value As Decimal)\n Field(\"origReserved\") = value\n End Set\nEnd Property\nPublic Property _reserved As Decimal\n Get\n Return DirectCast(Field(\"reserved\"), Integer)\n End Get\n Set(ByVal value As Decimal)\n Field(\"reserved\") = value\n End Set\nEnd Property\nPublic Property _dateReserved As Date\n Get\n Return DirectCast(Field(\"dateReserved\"), Date)\n End Get\n Set(ByVal value As Date)\n Field(\"dateReserved\") = value\n End Set\nEnd Property\nPublic Property _reservedBy As String\n Get\n Return DirectCast(Field(\"reservedBy\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"reservedBy\") = value\n End Set\nEnd Property\nPublic Property _reason As String\n Get\n Return DirectCast(Field(\"reason\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"reason\") = value\n End Set\nEnd Property\nPublic Property _party As String\n Get\n Return DirectCast(Field(\"party\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"party\") = value\n End Set\nEnd Property\nPublic Property _Cancelled As String\n Get\n Return DirectCast(Field(\"Cancelled\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"Cancelled\") = value\n End Set\nEnd Property\nPublic Property _CancelledByUsr As String\n Get\n Return DirectCast(Field(\"CancelledByUsr\"), String)\n End Get\n Set(ByVal value As String)\n Field(\"CancelledByUsr\") = value\n End Set\nEnd Property\nPublic Property _RsvQty As Decimal\n Get\n Return DirectCast(Field(\"RsvQty\"), Integer)\n End Get\n Set(ByVal value As Decimal)\n Field(\"RsvQty\") = value\n End Set\nEnd Property\n#End Region\n\nEnd Class\n Dim XMLRqst As New STKReservedStock_insertrow(User, Company)\n\n Rqst._pdt = If(IsDBNull(drStock.Item(\"pdt\")), \"\", drStock.Item(\"pdt\").ToString)\n Rqst._whse = If(IsDBNull(drStock.Item(\"whse\")), \"\", drStock.Item(\"whse\").ToString)\n Rqst._traceNumber = If(IsDBNull(drStock.Item(\"traceNumber\")), 0, CInt(drStock.Item(\"traceNumber\")))\n Rqst._bin = If(IsDBNull(drStock.Item(\"bin\")), \"\", drStock.Item(\"bin\").ToString)\n Rqst._lotref = If(IsDBNull(drStock.Item(\"lotref\")), \"\", drStock.Item(\"lotref\").ToString)\n Rqst._packUOM = If(IsDBNull(drStock.Item(\"packUOM\")), \"\", drStock.Item(\"packUOM\").ToString)\n Rqst._grade = If(IsDBNull(drStock.Item(\"grade\")), \"\", drStock.Item(\"grade\").ToString)\n Rqst._shpLabel = If(IsDBNull(drStock.Item(\"shpLabel\")), 0, CInt(drStock.Item(\"shpLabel\")))\n Rqst._countLoc = If(IsDBNull(drStock.Item(\"countLoc\")), \"\", drStock.Item(\"countLoc\").ToString)\n Rqst._palletType = If(IsDBNull(drStock.Item(\"palletType\")), \"\", drStock.Item(\"palletType\").ToString)\n Rqst._subPdt = If(IsDBNull(drStock.Item(\"subPdt\")), \"\", drStock.Item(\"subPdt\").ToString)\n Rqst._subTn = If(IsDBNull(drStock.Item(\"subTn\")), 0, CInt(drStock.Item(\"subTn\")))\n Rqst._origReserved = reservedqty\n Rqst._reserved = reservedqty\n Rqst._dateReserved = Now\n Rqst._reservedBy = User\n Rqst._reason = reason\n Rqst._party = party\n Rqst._Cancelled = \"f\"\n Rqst._CancelledByUsr = \"\"\n Rqst._RsvQty = reservedqty\n\nSend(XMLRqst.toxml)\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34539/"
] |
264,266
|
<p>I have a php web application that is occasionally hanging. When I navigate to the page it will just sit there trying to load for hours, even though max execution is 210. This is an application uses curl behind a proxy to download stuff. Error reporting is set to all, but that dosn't matter since the page is blank and hung.</p>
<p>I can not find anything on debugging a hung PHP process.</p>
|
[
{
"answer_id": 264320,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 1,
"selected": false,
"text": "curl_setopt()"
},
{
"answer_id": 266059,
"author": "Zak",
"author_id": 2112692,
"author_profile": "https://Stackoverflow.com/users/2112692",
"pm_score": 0,
"selected": false,
"text": "i.e.\n\n$fh = fopen(\"/tmp/debug.txt\", \"w\");\n\nfwrite($fh, \"made it to here 1 \\n\");\n\n//some code\n\nfwrite($fh, \"made it to here 2 \\n\");\n\n//more code\n\nfwrite($fh, \"made it to here 3 \\n\");\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264266",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,269
|
<p>A basic definition and example and a few references for "<a href="http://en.wikipedia.org/wiki/C_preprocessor#X-Macros" rel="nofollow noreferrer">X-Macros</a>" is given in this <a href="http://en.wikipedia.org/wiki/C_preprocessor" rel="nofollow noreferrer">wikipedia entry on the C pre-processor</a>:</p>
<blockquote>
<p>An X-Macro is a header file (commonly
using a ".def" extension instead of
the traditional ".h") that contains a
list of similar macro calls (which can
be referred to as "component macros").</p>
</blockquote>
<p>What are some good sources of information on how to use this powerful technique?
Are there well-known open source libraries using this method?</p>
|
[
{
"answer_id": 265560,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 6,
"selected": true,
"text": "token1##token2 #token X_ERROR /* \n * X Macro() data list\n * Format: Enum, Value, Text\n */\n#define X_ERROR \\\n X(ERROR_NONE, 1, \"Success\") \\\n X(ERROR_SYNTAX, 5, \"Invalid syntax\") \\\n X(ERROR_RANGE, 8, \"Out of range\")\n\n/* \n * Build an array of error return values\n * e.g. {0,5,8}\n */\nstatic int ErrorVal[] =\n{\n #define X(Enum,Val,Text) Val,\n X_ERROR\n #undef X\n};\n\n/* \n * Build an array of error enum names\n * e.g. {\"ERROR_NONE\",\"ERROR_SYNTAX\",\"ERROR_RANGE\"}\n */\n\nstatic char * ErrorEnum[] = {\n #define X(Enum,Val,Text) #Enum,\n X_ERROR\n #undef X\n};\n\n/* \n * Build an array of error strings\n * e.g. {\"Success\",\"Invalid syntax\",\"Out of range\"}\n */\nstatic char * ErrorText[] = {\n #define X(Enum,Val,Text) Text,\n X_ERROR\n #undef X\n};\n\n/* \n * Create an enumerated list of error indexes\n * e.g. 0,1,2\n */\nenum {\n #define X(Enum,Val,Text) IDX_##Enum,\n X_ERROR\n #undef X\n IDX_MAX /* Array size */\n};\n\nvoid showErrorInfo(void)\n{\n int i;\n\n /* \n * Access the values\n */\n for (i=0; i<IDX_MAX; i++)\n printf(\" %s == %d [%s]\\n\", ErrorEnum[i], ErrorVal[i], ErrorText[i]);\n\n}\n /*\n * Test validity of an error value\n * case ERROR_SUCCESS:\n * case ERROR_SYNTAX:\n * case ERROR_RANGE:\n */\n\n switch(value)\n {\n\n #define X(Enum,Val,Text) case Val:\n X_ERROR\n #undef X\n printf(\"Error %d is ok\\n\",value);\n break;\n default:\n printf(\"Invalid error: %d\\n\",value);\n break;\n }\n"
},
{
"answer_id": 9384365,
"author": "ACRL",
"author_id": 519285,
"author_profile": "https://Stackoverflow.com/users/519285",
"pm_score": 4,
"selected": false,
"text": "/* declare an enumeration of state codes */\nenum{ STATE0, STATE1, STATE2, ... , STATEX, NUM_STATES};\n\n/* declare a table of function pointers */\np_func_t jumptable[NUM_STATES] = {func0, func1, func2, ... , funcX};\n #define STATE_TABLE \\\n ENTRY(STATE0, func0) \\\n ENTRY(STATE1, func1) \\\n ENTRY(STATE2, func2) \\\n ...\n ENTRY(STATEX, funcX) \\\n enum\n{\n#define ENTRY(a,b) a,\n STATE_TABLE\n#undef ENTRY\n NUM_STATES\n};\n p_func_t jumptable[NUM_STATES] =\n{\n#define ENTRY(a,b) b,\n STATE_TABLE\n#undef ENTRY\n};\n #define ENTRY(a,b) static void b(void);\n STATE_TABLE\n#undef ENTRY\n #define IO_ADDRESS_OFFSET (0x8000)\n#define REGISTER_TABLE\\\n ENTRY(reg0, IO_ADDRESS_OFFSET + 0, 0x11)\\\n ENTRY(reg1, IO_ADDRESS_OFFSET + 1, 0x55)\\\n ENTRY(reg2, IO_ADDRESS_OFFSET + 2, 0x1b)\\\n ...\n ENTRY(regX, IO_ADDRESS_OFFSET + X, 0x33)\\\n\n/* declare the registers (where _at_ is a compiler specific directive) */\n#define ENTRY(a, b, c) volatile uint8_t a _at_ b:\n REGISTER_TABLE\n#undef ENTRY\n\n/* initialize registers */\n#def ENTRY(a, b, c) a = c;\n REGISTER_TABLE\n#undef ENTRY\n #define COMMAND_TABLE \\\n ENTRY(RESERVED, reserved, 0x00) \\\n ENTRY(COMMAND1, command1, 0x01) \\\n ENTRY(COMMAND2, command2, 0x02) \\\n ...\n ENTRY(COMMANDX, commandX, 0x0X) \\\n typedef struct {...}command1_cmd_t;\ntypedef struct {...}command2_cmd_t;\n\netc.\n typedef struct {...}response1_resp_t;\ntypedef struct {...}response2_resp_t;\n\netc.\n enum\n{\n#define ENTRY(a,b,c) a##_CMD = c,\n COMMAND_TABLE\n#undef ENTRY\n};\n enum\n{\n#define ENTRY(a,b,c) a##_CMD_LENGTH = sizeof(b##_cmd_t);\n COMMAND_TABLE\n#undef ENTRY\n};\n enum\n{\n#define ENTRY(a,b,c) a##_RESP_LENGTH = sizeof(b##_resp_t);\n COMMAND_TABLE\n#undef ENTRY\n};\n typedef struct\n{\n#define ENTRY(a,b,c) uint8_t b;\n COMMAND_TABLE\n#undef ENTRY\n} offset_struct_t;\n\n#define NUMBER_OF_COMMANDS sizeof(offset_struct_t)\n p_func_t jump_table[NUMBER_OF_COMMANDS] = \n{\n#define ENTRY(a,b,c) process_##b,\n COMMAND_TABLE\n#undef ENTRY\n}\n #define ENTRY(a,b,c) void process_##b(void);\n COMMAND_TABLE\n#undef ENTRY\n /* reminder the sizeof a union is the size of its largest member */\ntypedef union\n{\n#define ENTRY(a,b,c) uint8_t b##_buf[sizeof(b##_cmd_t)];\n COMMAND_TABLE\n#undef ENTRY\n}tx_buf_t\n uint8_t tx_buf[sizeof(tx_buf_t)];\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30636/"
] |
264,281
|
<p>Is there a way (in C#) to access the systray?
I am not talking about making a notify icon.
I want to iterate through the items in the tray (I would guess through the processes but I don't know how to determine what is actually in the tray and what is just a process) and also represent the items with their icons in my own ui.</p>
|
[
{
"answer_id": 264595,
"author": "Rob",
"author_id": 34224,
"author_profile": "https://Stackoverflow.com/users/34224",
"pm_score": 4,
"selected": true,
"text": "NotifyWnd = FindWindowEx(SysTray, 0, \"TrayNotifyWnd\", 0); hHook=SetWindowsHookEx(WH_CALLWNDPROC,HOOKPROC(MsgProc),\n hInstance,dwExplorerThreadId); TWDataT* twd=(TWDataT*)GetWindowLong(NotifyWnd,0); pTWIconDataT p=COMCTL32_332(twd->iconsInfo,i);"
},
{
"answer_id": 264733,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 1,
"selected": false,
"text": "TB_BUTTONCOUNT TB_GETBUTTON VirtualAllocEx"
},
{
"answer_id": 6242630,
"author": "michalczerwinski",
"author_id": 306146,
"author_profile": "https://Stackoverflow.com/users/306146",
"pm_score": 0,
"selected": false,
"text": " static IntPtr GetSystemTrayHandle()\n {\n IntPtr hWndTray = FindWindow(\"Shell_TrayWnd\", null);\n if (hWndTray != IntPtr.Zero)\n {\n hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, \"TrayNotifyWnd\", null);\n if (hWndTray != IntPtr.Zero)\n {\n hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, \"SysPager\", null);\n if (hWndTray != IntPtr.Zero)\n {\n hWndTray = FindWindowEx(hWndTray, IntPtr.Zero, \"ToolbarWindow32\", null);\n return hWndTray;\n }\n }\n }\n\n return IntPtr.Zero;\n }\n private static unsafe bool GetTBButton(IntPtr hToolbar, int i, ref TBBUTTON tbButton, ref string text, ref IntPtr ipWindowHandle)\n {\n // One page\n const int BUFFER_SIZE = 0x1000;\n\n byte[] localBuffer = new byte[BUFFER_SIZE];\n\n UInt32 processId = 0;\n UInt32 threadId = User32.GetWindowThreadProcessId(hToolbar, out processId);\n\n IntPtr hProcess = Kernel32.OpenProcess(ProcessRights.ALL_ACCESS, false, processId);\n if (hProcess == IntPtr.Zero) { Debug.Assert(false); return false; }\n\n IntPtr ipRemoteBuffer = Kernel32.VirtualAllocEx(\n hProcess,\n IntPtr.Zero,\n new UIntPtr(BUFFER_SIZE),\n MemAllocationType.COMMIT,\n MemoryProtection.PAGE_READWRITE);\n\n if (ipRemoteBuffer == IntPtr.Zero) { Debug.Assert(false); return false; }\n\n // TBButton\n fixed (TBBUTTON* pTBButton = &tbButton)\n {\n IntPtr ipTBButton = new IntPtr(pTBButton);\n\n int b = (int)User32.SendMessage(hToolbar, TB.GETBUTTON, (IntPtr)i, ipRemoteBuffer);\n if (b == 0) { Debug.Assert(false); return false; }\n\n // this is fixed\n Int32 dwBytesRead = 0;\n IntPtr ipBytesRead = new IntPtr(&dwBytesRead);\n\n bool b2 = Kernel32.ReadProcessMemory(\n hProcess,\n ipRemoteBuffer,\n ipTBButton,\n new UIntPtr((uint)sizeof(TBBUTTON)),\n ipBytesRead);\n\n if (!b2) { Debug.Assert(false); return false; }\n }\n\n // button text\n fixed (byte* pLocalBuffer = localBuffer)\n {\n IntPtr ipLocalBuffer = new IntPtr(pLocalBuffer);\n\n int chars = (int)User32.SendMessage(hToolbar, TB.GETBUTTONTEXTW, (IntPtr)tbButton.idCommand, ipRemoteBuffer);\n if (chars == -1) { Debug.Assert(false); return false; }\n\n // this is fixed\n Int32 dwBytesRead = 0;\n IntPtr ipBytesRead = new IntPtr(&dwBytesRead);\n\n bool b4 = Kernel32.ReadProcessMemory(\n hProcess,\n ipRemoteBuffer,\n ipLocalBuffer,\n new UIntPtr(BUFFER_SIZE),\n ipBytesRead);\n\n if (!b4) { Debug.Assert(false); return false; }\n\n text = Marshal.PtrToStringUni(ipLocalBuffer, chars);\n\n if (text == \" \") text = String.Empty;\n }\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34514/"
] |
264,290
|
<p>Sometimes I need to access some servers running Linux (or maybe another Unix-like SO), but I don't know how to verify which <a href="http://en.wikipedia.org/wiki/Linux_distribution" rel="noreferrer">distribution</a> is in use on the server (there are times that even the "responsible" person for the server doesn't know). </p>
<p>Is there an easy and reliable way to discover that, one that is uniform and consistent across all of them?</p>
|
[
{
"answer_id": 264294,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": -1,
"selected": false,
"text": "uname -a"
},
{
"answer_id": 264298,
"author": "Yojik",
"author_id": 34532,
"author_profile": "https://Stackoverflow.com/users/34532",
"pm_score": 0,
"selected": false,
"text": "[anton@localhost ~]$ uname -a\nLinux localhost 2.6.26-ARCH #1 SMP PREEMPT Tue Aug 26 21:15:43 UTC 2008 i686 AMD Athlon(tm) 64 Processor 3000+ AuthenticAMD GNU/Linux\n"
},
{
"answer_id": 264300,
"author": "Peter",
"author_id": 22517,
"author_profile": "https://Stackoverflow.com/users/22517",
"pm_score": 0,
"selected": false,
"text": "uname -r\n"
},
{
"answer_id": 264301,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 6,
"selected": true,
"text": "lsb_release -i lsb_release -a"
},
{
"answer_id": 264306,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 5,
"selected": false,
"text": "cat /etc/*release\n /etc/ /etc/redhat-release /etc/gentoo-release"
},
{
"answer_id": 264316,
"author": "Andrew Stein",
"author_id": 13029,
"author_profile": "https://Stackoverflow.com/users/13029",
"pm_score": 1,
"selected": false,
"text": ".cshrc setenv DISTRO `sed -e 's/.*(//' -e 's/)).*//' /proc/version`\n export DISTRO=`sed -e 's/.*(//' -e 's/)).*//' /proc/version`\n"
},
{
"answer_id": 264328,
"author": "Charles Merriam",
"author_id": 1320510,
"author_profile": "https://Stackoverflow.com/users/1320510",
"pm_score": 3,
"selected": false,
"text": "$ lsb_release --all\nNo LSB modules are available.\nDistributor ID: Ubuntu\nDescription: Ubuntu 8.04.1\nRelease: 8.04\nCodename: hardy\n$ lsb_release -i\nDistributor ID: Ubuntu\n $ uname -a\nLinux blue-laptop 2.6.24-21-generic #1 SMP Tue Oct 21 23:43:45 UTC 2008 i686 GNU/Linux\n"
},
{
"answer_id": 3060821,
"author": "rahijain",
"author_id": 35289,
"author_profile": "https://Stackoverflow.com/users/35289",
"pm_score": 1,
"selected": false,
"text": "cd /proc/\n"
},
{
"answer_id": 47631841,
"author": "N Randhawa",
"author_id": 4854721,
"author_profile": "https://Stackoverflow.com/users/4854721",
"pm_score": 2,
"selected": false,
"text": "lsb_release -a -d uname -a man uname cat"
},
{
"answer_id": 56967682,
"author": "hoijui",
"author_id": 586229,
"author_profile": "https://Stackoverflow.com/users/586229",
"pm_score": 0,
"selected": false,
"text": "neofetch --stdout | grep '^OS: ' | sed -e 's/OS:[[:space:]]\\+//'\n neofetch wget 'https://raw.githubusercontent.com/dylanaraps/neofetch/master/neofetch' \\\n && bash neofetch --stdout \\\n && rm neofetch\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27959/"
] |
264,309
|
<p>There is a similar question going around, but it just got the same old answers that people always give about Regex syntax, but that's not the point here, so please try to not knee jerk the same old answers about regex syntax. Try to be a little more original and personal about it this time.</p>
<p>Regex syntax is very VERY compact, almost too compact to be good. Its like code-golfing,
and everyone agrees code-golfing isn't a good thing in production code. However most people accept regex syntax, which seems... contradictory to say the least.</p>
<p>So now some common defenses one is likely to hear include :</p>
<ul>
<li><p><em>Answer</em>: It's compact</p></li>
<li><p><em>Counter</em>: Haven't we all agreed in this day and age that code should be literate and a variable like "client" is better than "c"?</p></li>
<li><p><em>Answer</em>: It's a "domain specific language"</p></li>
<li><p><em>Counter</em>: how about all the very easy to understand, non compact, non cryptic and dare I say pretty domain languages out there like SQL or LINQ?</p></li>
<li><p><em>Answer</em>: Its easy to understand once you know it.</p></li>
<li><p><em>Counter</em>: Most great languages are easy to understand even if you've never used them before. For example anyone could jump into Python very easily even if they had never seen it before. And why do people defend Regex when its such a hard language to look at, but then go on and complain about Lisps parenthesis?</p></li>
</ul>
<p>Ok now everyone try to be original and honest here, don't just pull out the same old rote answers programmers used 20 years ago to design regex. Unless you really believe they are valid propositions in this day and age.</p>
<hr>
<p><strong>Edit:</strong> For the record, I know Regex from years ago, use them frequently even today and might even grok them. However I suddenly had a feeling it was perhaps time to reconsider things I had taken as "truths" about regex, and look at them from a modern standpoint. Mostly because questioning principles is necessary for further development, and because so many newcomers complain vehemently about them, they can't just be flat out right, so I decided to try to step into the shoes of a newcomer and consider what are some good points against regex.</p>
<p>As for being <strong>subjective</strong>, I don't think this is less subjective OR less programmer related than <strong>Programmer Jokes</strong> of the days stuff. On the contrary it is very programmer related.</p>
<p>As for <strong>argumentative</strong>, thats the point of the question. To get good arguments pro and con regex outdated syntax, that can serve newcomers to actually understand more about why regex are what they are, and even better hopefully get some newcomer to come up with a better solution US old minded can't see because we are blinded by the "coolness" of regex.</p>
<hr>
<p><strong>Quote:</strong></p>
<blockquote>
<p>The Perl 5.10 documentation for
regexes has melted down into a heap of
unreadable drivel because so many zany
features have creeped into the syntax
that no-one can write sensible
documentation for it any more.</p>
</blockquote>
<p>You're trying to say regex have become unmaintainable? Well then as good programmers should we consider refactoring them? Maybe cleaning up and trying over as we've done with some many other technologies?</p>
|
[
{
"answer_id": 264384,
"author": "he_the_great",
"author_id": 34435,
"author_profile": "https://Stackoverflow.com/users/34435",
"pm_score": 6,
"selected": true,
"text": "<TAG\\b[^>]*>(.*?)</TAG>\n"
},
{
"answer_id": 264416,
"author": "AmbroseChapel",
"author_id": 242241,
"author_profile": "https://Stackoverflow.com/users/242241",
"pm_score": 3,
"selected": false,
"text": "LOOK FOR \"<TAG\" THEN WORDBOUNDARY THEN ZERO-OR-MORE NOT('>') FOLLOWED-BY '>' THEN ZERO-OR-MORE SOMETHING REMEMBERED THEN NEAREST \"</TAG>\""
},
{
"answer_id": 265553,
"author": "Axeman",
"author_id": 11289,
"author_profile": "https://Stackoverflow.com/users/11289",
"pm_score": 3,
"selected": false,
"text": "overload::constants Parse::RecDescent"
},
{
"answer_id": 265684,
"author": "Brandon",
"author_id": 28916,
"author_profile": "https://Stackoverflow.com/users/28916",
"pm_score": 3,
"selected": false,
"text": "from pyparsing import Word, alphas\ngreet = Word( alphas ) + \",\" + Word( alphas ) + \"!\"\ngreet.parseString(\"Hello, World!\")\n"
},
{
"answer_id": 10827356,
"author": "Matthew Lock",
"author_id": 74585,
"author_profile": "https://Stackoverflow.com/users/74585",
"pm_score": 2,
"selected": false,
"text": " use Regexp::English;\n\n my $re = Regexp::English\n -> start_of_line\n -> literal('Flippers')\n -> literal(':')\n -> optional\n -> whitespace_char\n -> end\n -> remember\n -> multiple\n -> digit;\n\n while (<INPUT>) {\n if (my $match = $re->match($_)) {\n print \"$match\\n\";\n }\n }\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
] |
264,312
|
<p>I'm trying to squeeze some more performance out of my rendering pipeline. The (by far) slowest part is performing a java.awt.imaging.LookupOp on a large image. </p>
<p>The image size is about 2048x2048.</p>
<p>I have figured out that having the filter done along with the drawing operation is much faster than calling the filter method. However this still leaves us with lookup ops that take around 250ms (or 4 fps). Does anyone have any rendering tips?</p>
<p>Heres essentially what we are doing:</p>
<pre><code>public void paint(Graphics g)
{
if(recalcLUT)
{
Graphics2D g2d = (Graphics2D) displayImage.getGraphics();
g2d.drawImage(srcImage, lut, 0, 0);
}
Graphics2D g2d = (Graphics2D) g;
g2d.clearRect(0, 0, this.getWidth(), this.getHeight());
AffineTransform at = new AffineTransform();
at.setToIdentity();
at.scale(scale, scale);
g2d.drawImage(displayImage, at, null);
}
</code></pre>
<p>the lut variable is a LookupOp usually a ShortLookupOp, the image a 16bit grayscale image</p>
<p>Thanks</p>
<p><a href="https://stackoverflow.com/users/27818/ryan-boucher" title="Ryan Bucher">Ryan Bucher:</a></p>
<p>I know there are some other obvious performance optimizations that could be done here. But the major problem is just doing the LookupOp operation so im looking for advice with regard to that.</p>
<p>Lookup Ops are essentially where you create an array and instead of rendering each pixel of the image as its color, you use the color as an index into the array and render the color as the value in the index. In this particular example Im using it to do some simple brightness/contrast operations.
You can also implement this using a rescaleOp which is essentially a way to apply a linear function to the value of all the pixels. But this turns out to be slower.</p>
|
[
{
"answer_id": 272413,
"author": "Ryan Boucher",
"author_id": 27818,
"author_profile": "https://Stackoverflow.com/users/27818",
"pm_score": 0,
"selected": false,
"text": "//Has filter or source image changed?\n// yes, recalculate filter and cache\n// no, render cached image\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25920/"
] |
264,318
|
<p>I am calling an unmanaged C++ dll that expects a char* as one of its parameters and I want to push a byte[] into it. The project is written in VB.NET. </p>
<p>What type of marshalling will work for this?</p>
|
[
{
"answer_id": 264605,
"author": "Chris Thompson",
"author_id": 5982,
"author_profile": "https://Stackoverflow.com/users/5982",
"pm_score": 1,
"selected": false,
"text": " // (c) 2007 Marc Clifton\n /// <summary>\n /// A helper class for pinning a managed structure so that it is suitable for\n /// unmanaged calls. A pinned object will not be collected and will not be moved\n /// by the GC until explicitly freed.\n /// </summary>\n\n internal class PinnedObject<T> : IDisposable where T : struct\n {\n protected T managedObject;\n protected GCHandle handle;\n protected IntPtr ptr;\n protected bool disposed;\n\n public T ManangedObject\n {\n get\n {\n return (T)handle.Target;\n }\n set\n {\n Marshal.StructureToPtr(value, ptr, false);\n }\n }\n\n public IntPtr Pointer\n {\n get { return ptr; }\n }\n\n public int Size\n {\n get { return Marshal.SizeOf(managedObject); }\n }\n\n public PinnedObject()\n {\n managedObject = new T();\n handle = GCHandle.Alloc(managedObject, GCHandleType.Pinned);\n ptr = handle.AddrOfPinnedObject();\n }\n\n ~PinnedObject()\n {\n Dispose();\n }\n\n public void Dispose()\n {\n if (!disposed)\n {\n if (handle.IsAllocated)\n handle.Free();\n ptr = IntPtr.Zero;\n disposed = true;\n }\n }\n }\n}\n PinnedObject<BatteryQueryInformation> pinBatteryQueryInfo = new PinnedObject<BatteryQueryInformation>();\npinBatteryQueryInfo.ManangedObject = _structBatteryQueryInfo;\nUnmanaged.Method(pinBatteryQueryInfo.Pointer);\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34550/"
] |
264,323
|
<p>Is there a way to delete a folder, lets call it FolderX from an SVN trunk recursively? A quick search on google only tells me how to recursively delete all .svn folders and this is not what I want to do</p>
|
[
{
"answer_id": 264345,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 6,
"selected": true,
"text": "find ./ -name \"FolderX\" | xargs svn delete --force\n for /R . %1 in (*.EXT) do svn delete %1\n"
},
{
"answer_id": 264456,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 3,
"selected": false,
"text": "svn delete FolX --force"
},
{
"answer_id": 3364888,
"author": "harshad",
"author_id": 405937,
"author_profile": "https://Stackoverflow.com/users/405937",
"pm_score": 2,
"selected": false,
"text": "find . -name \".svn\" -exec rm -rf {} \\;\n"
},
{
"answer_id": 6831794,
"author": "Eduardo Cuomo",
"author_id": 717267,
"author_profile": "https://Stackoverflow.com/users/717267",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash if [ $\\# -eq 0 ] ; then echo\n echo \"Path not found\"\n echo \"Use:\"\n echo \" $0 path\"`\n echo \" $0 /var/www/test/svn/website\"\n echo \" $0 .\"\n echo \"Operation cancelled\"\n echo\n exit 1\nfi\n\necho \necho \"Recursively delete .svn directories in:\"\nif [ $1 != \".\" ] ; then\n echo $1\nelse\n pwd\nfi\n\necho\nread -p \"Continue? [Yes/No]: \" x\nif [ \"$x\" != \"Yes\" ] ; then\n echo \"Operation cancelled\"\n echo\n exit 1\nfi\n\nfind $1 -name .svn -exec rm -rf {} \\;\necho \"End!\"\necho\nexit 0`\n chmod +x rm_svn_dirs rm_svn_dirs /var/www/svn/www rm_svn_dirs ./svn/www rm_svn_dirs ."
},
{
"answer_id": 17990790,
"author": "Manikandan S",
"author_id": 1506356,
"author_profile": "https://Stackoverflow.com/users/1506356",
"pm_score": -1,
"selected": false,
"text": "find directory_to_delete/ -type d -name '*.svn' | xargs rm -rf\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17211/"
] |
264,339
|
<p>I'm not sure how to describe this problem, so I think an example is the best way to ask my question:</p>
<p>I have two tables with a manyToMany relationship:</p>
<p>DriversLicence <-> LicenceClass</p>
<p>LicenceClass is things like "Car", "Motorbike", and "Medium Rigid".</p>
<p>Using Hibernate Criteria, how can I find all licences that have both "Car" and "Motorbike" LicenceClasses?</p>
<p>UPDATE 12/11/2008
I have discovered that this can easily be achieved by using a custom ResultTransformer. However the problem is that a result transformer only gets applied AFTER the query returns its results, it does not actually become part of the SQL. So I guess my question is now "Can you do what I initially described in SQL - and is there a Hibernate Criteria analog?"</p>
|
[
{
"answer_id": 264420,
"author": "Nick",
"author_id": 34558,
"author_profile": "https://Stackoverflow.com/users/34558",
"pm_score": 0,
"selected": false,
"text": "session.createCriteria(DriversLicence.class)\n .add(Expression.or(\n Expression.eq(\"licenceClass.type\", \"Car\"),\n Expression.eq(\"licenceClass.type\", \"Motorbike\")\n )\n).list();\n session.createQuery(\"from DriversLicence where licenceClass.type in (:types)\")\n .setParameterList(\"types\", myListOfTypes)\n .list();\n"
},
{
"answer_id": 282898,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 0,
"selected": false,
"text": "Select e from Enterprise As e inner join e.Users As u inner join u.Roles As r \nWhere u.UserCode=?\n Select dl from LicenceClass As l inner join l.DriversLicences As dl\nWhere \nl.LicenseClass.Name = ? OR \nl.LicenseClass.Name=? OR \nl.LicenseClass.Name=?\n"
},
{
"answer_id": 313040,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "public List<DriversLicence> findDriversLicencesWith(List<LicenceClass> licenceClasses) {\n String hqlString = \"select dl from DriversLicenceImpl dl where 1=1 \";\n for (int i = 0; i < licenceClasses.size(); i++) {\n hqlString += \" and :licenceClass\" + i + \" = some elements(dl.licenceClasses)\";\n }\n\n Query query = getSession().createQuery(hqlString);\n for (int i = 0; i < licenceClasses.size(); i++) {\n query.setParameter(\"licenceClass\" + i, licenceClasses.get(i));\n }\n return query.list();\n}\n for (LicenceClass licenceClass : licenceClasses) { \n criteria.add(Restrictions.sqlRestriction(\"? = some(select \" + LicenceClass.PRIMARY_KEY + \" from \" +\n LICENCE_CLASS_JOIN_TABLE + \" where {alias}.\" +\n DriversLicence.PRIMARY_KEY + \" = \" + DriversLicence.PRIMARY_KEY + \")\",\n licenceClass.getId(), Hibernate.LONG));\n}\n"
},
{
"answer_id": 39852021,
"author": "Mara B",
"author_id": 6920391,
"author_profile": "https://Stackoverflow.com/users/6920391",
"pm_score": 0,
"selected": false,
"text": " List<Predicate> predicates = new ArrayList<>();\n for(Integer lcId : licenceClassIdList) {\n SetJoin<DriversLicence, LicenceClass> dlClasses = dlRoot.join(DriversLicence_.licenceClasses);\n predicates.add(builder.equal(dlClasses.get(LicenseClass_.id), lcId));\n }\n Predicate predicate = builder.and(predicates.toArray(new Predicate[predicates.size()]));\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34553/"
] |
264,350
|
<p>In traditional embedded programming, we will give a delay function like so:</p>
<pre><code>for(i=0;i<255;i++)
for(j=0;j<255;j++);
</code></pre>
<p>In the microprocessor's view, is this how the sleep() function works?</p>
<p>Is there an alternative for the sleep() function in C?</p>
|
[
{
"answer_id": 264360,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 3,
"selected": false,
"text": "void sleep (unsigned int delay) {\n unsigned int target = peek(0x33) + delay;\n while (peek(0x33) != target);\n}\n"
},
{
"answer_id": 264378,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 5,
"selected": false,
"text": "select() // Sleep for 1.5 sec\nstruct timeval tv;\ntv.tv_sec = 1;\ntv.tv_usec = 500000;\nselect(0, NULL, NULL, NULL, &tv);\n select() select()"
},
{
"answer_id": 264432,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 2,
"selected": false,
"text": "poll(0, 0, milliseconds);\n select Sleep"
},
{
"answer_id": 264518,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 4,
"selected": false,
"text": "//Pseudo code\nint start = getTime();\nint end = start + sleepTime;\n\nwhile (getTime() < end) {\n asm(\"SLEEP\");\n}\n"
},
{
"answer_id": 14726433,
"author": "user2046229",
"author_id": 2046229,
"author_profile": "https://Stackoverflow.com/users/2046229",
"pm_score": 0,
"selected": false,
"text": "// Sleep for both Windows and Linux: \n// Too bad? No one proposed you a solution that works? \n// Since Windows has no select.h nor poll.h, an implementation\n// is necessary.\n// \n// Solutions on boards are often refered to use either select or poll, but ok, what about C (not c++)?\n//\n/// implementation of poll is destined in this attempt for windows\n/// Ideally, you add this part of code to the header of you *.c file, and it might work through...\n\n#ifdef WIN32\n#include <time.h>\n#include <sys/time.h>\n#include <ws2tcpip.h>\n#include <Winsock2.h>\n#include <windows.h>\n/* winsock doesn't feature poll(), so there is a version implemented\n * in terms of select() in mingw.c. The following definitions\n * are copied from linux man pages. A poll() macro is defined to\n * call the version in mingw.c.\n */\n#define POLLIN 0x0001 /* There is data to read */\n#define POLLPRI 0x0002 /* There is urgent data to read */\n#define POLLOUT 0x0004 /* Writing now will not block */\n#define POLLERR 0x0008 /* Error condition */\n#define POLLHUP 0x0010 /* Hung up */\n#define POLLNVAL 0x0020 /* Invalid request: fd not open */\nstruct pollfd {\n SOCKET fd; /* file descriptor */\n short events; /* requested events */\n short revents; /* returned events */\n};\n\nint mingw_poll (struct pollfd *, unsigned int, int);\n\n#define poll(x, y, z) mingw_poll(x, y, z)\n#endif\n\n\n\n\n\nint mingw_poll(struct pollfd *fds, unsigned int nfds, int timo)\n{\n struct timeval timeout, *toptr;\n fd_set ifds, ofds, efds, *ip, *op;\n int i, rc;\n\n /* Set up the file-descriptor sets in ifds, ofds and efds. */\n FD_ZERO(&ifds);\n FD_ZERO(&ofds);\n FD_ZERO(&efds);\n for (i = 0, op = ip = 0; i < nfds; ++i) {\n fds[i].revents = 0;\n if(fds[i].events & (POLLIN|POLLPRI)) {\n ip = &ifds;\n FD_SET(fds[i].fd, ip);\n }\n if(fds[i].events & POLLOUT) {\n op = &ofds;\n FD_SET(fds[i].fd, op);\n }\n FD_SET(fds[i].fd, &efds);\n } \n\n /* Set up the timeval structure for the timeout parameter */\n if(timo < 0) {\n toptr = 0;\n } else {\n toptr = &timeout;\n timeout.tv_sec = timo / 1000;\n timeout.tv_usec = (timo - timeout.tv_sec * 1000) * 1000;\n }\n\n#ifdef DEBUG_POLL\n printf(\"Entering select() sec=%ld usec=%ld ip=%lx op=%lx\\n\",\n (long)timeout.tv_sec, (long)timeout.tv_usec, (long)ip, (long)op);\n#endif\n rc = select(0, ip, op, &efds, toptr);\n#ifdef DEBUG_POLL\n printf(\"Exiting select rc=%d\\n\", rc);\n#endif\n\n if(rc <= 0)\n return rc;\n\n if(rc > 0) {\n for (i = 0; i < nfds; ++i) {\n int fd = fds[i].fd;\n if(fds[i].events & (POLLIN|POLLPRI) && FD_ISSET(fd, &ifds))\n fds[i].revents |= POLLIN;\n if(fds[i].events & POLLOUT && FD_ISSET(fd, &ofds))\n fds[i].revents |= POLLOUT;\n if(FD_ISSET(fd, &efds))\n /* Some error was detected ... should be some way to know. */\n fds[i].revents |= POLLHUP;\n#ifdef DEBUG_POLL\n printf(\"%d %d %d revent = %x\\n\", \n FD_ISSET(fd, &ifds), FD_ISSET(fd, &ofds), FD_ISSET(fd, &efds), \n fds[i].revents\n );\n#endif\n }\n }\n return rc;\n}\n"
},
{
"answer_id": 28370606,
"author": "Rosana Aira",
"author_id": 4538058,
"author_profile": "https://Stackoverflow.com/users/4538058",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <windows.h>\n\nint main()\n{\n puts(\"Hello \\n\");\n /* in windows.h is declared the Sleep (upper S) function and it takes time in \nmiliseconds */\n Sleep(3000);\n puts(\"World \\n\");\n return 0;\n}\n"
},
{
"answer_id": 31411723,
"author": "Oskar Dahlberg",
"author_id": 4858189,
"author_profile": "https://Stackoverflow.com/users/4858189",
"pm_score": 2,
"selected": false,
"text": "#include <Windows.h>\n\nstatic NTSTATUS(__stdcall *NtDelayExecution)(BOOL Alertable, PLARGE_INTEGER DelayInterval) = (NTSTATUS(__stdcall*)(BOOL, PLARGE_INTEGER)) GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"NtDelayExecution\");\n\nstatic NTSTATUS(__stdcall *ZwSetTimerResolution)(IN ULONG RequestedResolution, IN BOOLEAN Set, OUT PULONG ActualResolution) = (NTSTATUS(__stdcall*)(ULONG, BOOLEAN, PULONG)) GetProcAddress(GetModuleHandle(\"ntdll.dll\"), \"ZwSetTimerResolution\");\n\n\n\n\nstatic void SleepShort(float milliseconds) {\n static bool once = true;\n if (once) {\n ULONG actualResolution;\n ZwSetTimerResolution(1, true, &actualResolution);\n once = false;\n }\n\n LARGE_INTEGER interval;\n interval.QuadPart = -1 * (int)(milliseconds * 10000.0f);\n NtDelayExecution(false, &interval);\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
264,358
|
<p>let us have a situation in which the following program prints some 10 lines of #</p>
<pre><code>for(i=0;i<10;i++)
prinf("\n#");
</code></pre>
<p>now how to go back to 5 th line and edit that # and change the color of it without clearing the screen or clearing the below 5 lines?
<p>I have tried </p>
<pre><code>window(5,0,20,20);
textcolor(GREEN);
cprintf("#");
</code></pre>
<p>but it is not editing that one but it is printing on the side of the original one.why?
<p>is there any other way of doing it and changing the color of the already printed text dynamically?
please help me..my environment is turbo c on windows</p>
|
[
{
"answer_id": 264371,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 0,
"selected": false,
"text": "cprintf(\"\\b#\");\n"
},
{
"answer_id": 264388,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 1,
"selected": false,
"text": "-1: for(i=0;i<10;i++)\n prinf(\"#\");\n #"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264358",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
264,372
|
<p>Is there a reason to sort MultiMap in Java and how to do that?</p>
|
[
{
"answer_id": 271361,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "org.apache.commons.collections.MultiMap Collection List org.apache.commons.collections.MultiHashMap ArrayList Collections.sort() MultiMap HashMap<K, Collection<V>>"
},
{
"answer_id": 40101882,
"author": "Artur Biesiadowski",
"author_id": 4210615,
"author_profile": "https://Stackoverflow.com/users/4210615",
"pm_score": 0,
"selected": false,
"text": "TreeMultimap<...> sortedMap = TreeMultimap.create(notSortedMultiMap);\n TreeMultimap<...> sortedMap = TreeMultimap.create(keyComparator, valueComparator);\nsortedMap.putAll(notSortedMultiMap);\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,381
|
<p>I'm doing some searching of tags, and some users like "cat" while others like "Cat" Go figure...</p>
<p>Anyways, is there a way to force a particular find to be case sensitive? Such as:</p>
<pre><code>Tag.find(:some-special-option-here)
</code></pre>
<p>Any ideas?</p>
|
[
{
"answer_id": 264389,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "ALTER TABLE `sets` CHANGE `set_name` `set_name` VARCHAR( 64 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL\n"
},
{
"answer_id": 264645,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 6,
"selected": true,
"text": "SELECT * FROM mytable WHERE myfield='Value' \n SELECT * FROM mytable WHERE BINARY myfield='Value'\n"
},
{
"answer_id": 458544,
"author": "Paul Grayson",
"author_id": 56777,
"author_profile": "https://Stackoverflow.com/users/56777",
"pm_score": 2,
"selected": false,
"text": "create_table( \"page_infos\", :force => true, :options => \"ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_bin\") do |t|\n t.string \"title\", :limit => 120\nend\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264381",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19964/"
] |
264,385
|
<p>I'm building my app in vc2008 and testing it on a network of machines.</p>
<p>Is there any way, other than installing Visual Studio 2008, to run a debug build of a C++ program on another machine? (i.e. that doesn't have vc2008 installed)</p>
<p>Installing the redist package only installs the release mode support DLL's for vc2008 programs. Currently it complains that "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.", which I assume is code for "I'm missing DLL's".</p>
|
[
{
"answer_id": 264447,
"author": "Franci Penov",
"author_id": 17028,
"author_profile": "https://Stackoverflow.com/users/17028",
"pm_score": 0,
"selected": false,
"text": "C:\\Program Files\\Common Files\\Merge Modules"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33847/"
] |
264,395
|
<p>I've found the "open" command in Mac OS X very handy in the command line. From "man open":</p>
<blockquote>
<p>The <code>open</code> command opens a file (or a directory or URL), just as if you had
double-clicked the file's icon. If no application name is specified, the
default application as determined via LaunchServices is used to open the
specified files.</p>
</blockquote>
<p>That is, if I want to open a PDF file with the default PDF viewer (happens to be Preview), I only need to do:</p>
<pre><code>open my.pdf
</code></pre>
<p>In Linux, however, to open a PDF file from the command line, I had to dig around to find the default PDF viewer is, for instance, "evince" (who'd have guessed??), and then</p>
<pre><code>evince my.pdf
</code></pre>
<p>So, is there a simple equivalent of the 'open' command in the Linux command line?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 264401,
"author": "number5",
"author_id": 29489,
"author_profile": "https://Stackoverflow.com/users/29489",
"pm_score": 9,
"selected": true,
"text": "xdg-open"
},
{
"answer_id": 264467,
"author": "Jeremy Visser",
"author_id": 10839,
"author_profile": "https://Stackoverflow.com/users/10839",
"pm_score": 6,
"selected": false,
"text": "xdg-open open xdg-open ~/Documents/Chubby_Bubbies.odt\n open ] .bashrc alias ']'='xdg-open'\n ] www.google.com\n] file.txt\n] ~/Pictures\n] ssh://myserver.local/home/jeremy\n ] .\n"
},
{
"answer_id": 264954,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 4,
"selected": false,
"text": "man see\n"
},
{
"answer_id": 9909794,
"author": "Anake",
"author_id": 299000,
"author_profile": "https://Stackoverflow.com/users/299000",
"pm_score": 4,
"selected": false,
"text": "open ~/bin xdg-open \"$1\" &> /dev/null &\n"
},
{
"answer_id": 12700860,
"author": "WonderLi",
"author_id": 493951,
"author_profile": "https://Stackoverflow.com/users/493951",
"pm_score": -1,
"selected": false,
"text": "nautilus `pwd` &\n"
},
{
"answer_id": 18020765,
"author": "stacksia",
"author_id": 1457221,
"author_profile": "https://Stackoverflow.com/users/1457221",
"pm_score": 2,
"selected": false,
"text": "mimeopen"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264395",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,400
|
<p>I am trying to do the following in ASP.NET 3.5. Basically, I am binding a LINQDataSource to a DataList. There is a property called "Deleted" and if it is true, I want to display different markup. The following code throws errors:</p>
<pre><code><asp:DataList runat="server">
<ItemTemplate>
<% If CBool(Eval("Deleted")) Then%>
...
<% Else%>
...
<% End If%>
</ItemTemplate>
</asp:DataList>
</code></pre>
<p>Is this possible? If not, what are the alternatives?</p>
|
[
{
"answer_id": 264445,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 3,
"selected": false,
"text": "<asp:DataList runat=\"server\">\n <ItemTemplate>\n <asp:Panel Visible=\"<%# Eval(\"Deleted\") %>\">\n ...(deleted content here)...\n </asp:Panel>\n <asp:Panel Visible=\"<%# Not Eval(\"Deleted\") %>\">\n ...(other content here)...\n </asp:Panel>\n </ItemTemplate>\n</asp:DataList>\n"
},
{
"answer_id": 1110783,
"author": "Ben Griswold",
"author_id": 4115,
"author_profile": "https://Stackoverflow.com/users/4115",
"pm_score": 4,
"selected": false,
"text": "<asp:DataList runat=\"server\">\n <ItemTemplate>\n <%# GetText(Container.DataItem) %>\n </ItemTemplate>\n</asp:DataList>\n protected static string GetText(object dataItem)\n{ \n if (Convert.ToBoolean(DataBinder.Eval(dataItem, \"Deleted\"))\n return \"Deleted\";\n\n return \"Not Deleted\";\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40/"
] |
264,402
|
<p>I have used this in my HTML:</p>
<pre><code><q> Hai How r u </q>
</code></pre>
<p>Which shows the text in quotes, like "Hai How r u", for example.</p>
<p>This is working fine in FF but not in IE 6.0.</p>
<p>Please let me know why this happens, and any solutions you might know of. </p>
<p>I don't want to use the quote (") character in my HTML or a separate css file for this.</p>
|
[
{
"answer_id": 264405,
"author": "Karan",
"author_id": 11110,
"author_profile": "https://Stackoverflow.com/users/11110",
"pm_score": 0,
"selected": false,
"text": "\" <b> <i> <q>"
},
{
"answer_id": 264410,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": true,
"text": "<q>"
},
{
"answer_id": 269858,
"author": "soypunk",
"author_id": 26512,
"author_profile": "https://Stackoverflow.com/users/26512",
"pm_score": 2,
"selected": false,
"text": "<q> <q> <q> <q>"
},
{
"answer_id": 624495,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 0,
"selected": false,
"text": "q:before { content: \"\\201c\"; }\nq:after { content: \"\\201d\"; }\n\nq q:before { content: \"\\2018\"; }\nq q:after { content: \"\\2019\"; }\n q 201c 201d 0022 q q { font-style: italic; color: #444444; }\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
264,414
|
<p>I've got a Repeater and its SqlDatasource nested inside a Gridview TemplatedField.<br>
The Repeater's datasource SelectCommand is set using the FormatString of an Eval from the Gridview.<br>
The SelectCommand has a WHERE clause which is to compare a string.<br>
Because I have already used the single and double quotes, I am having trouble delimiting the string in the SQL WHERE clause.</p>
<p><strong>How do I add single quotes inside an Eval FormatString?</strong> </p>
<p>I have tried using '<a href="http://forums.asp.net/p/1116668/1732706.aspx#1732706" rel="noreferrer">Replace</a>'.<br>
I have tried using '<a href="http://www.firstobject.com/dn_markspecialchar.htm" rel="noreferrer">Special Characters</a>' (... WHERE StringField = '{0}' ...) </p>
<p>No luck so far. I appreciate any help you may be able to offer. </p>
<pre><code><asp:GridView ID="GridView1" runat="server" DataSourceID="DataSource1" DataKeyNames="Foo" AutoGenerateColumns="False" AllowSorting="true" >
<Columns>
<asp:BoundField DataField="Foo" HeaderText="Foo" SortExpression="Foo" />
<asp:BoundField DataField="Bar" HeaderText="Bar" SortExpression="Bar" />
<asp:TemplateField>
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="DataSourceNested">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Blah") %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="DataSourceNested" runat="server" DataFile="~/App_Data/DatabaseName"
SelectCommand='<%# Eval("Bar", "SELECT Blah FROM TableName WHERE (StringField = {0})") %>' >
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</code></pre>
|
[
{
"answer_id": 264426,
"author": "Ty.",
"author_id": 16948,
"author_profile": "https://Stackoverflow.com/users/16948",
"pm_score": 0,
"selected": false,
"text": "... WHERE (StringField = \\'{0}\\') ...\n"
},
{
"answer_id": 264443,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 2,
"selected": false,
"text": "protected const string SELECTCLAUSE = \n\"SELECT Blah FROM TableName WHERE (StringField = '{0}')\";\n SelectCommand='<%# Eval(\"Bar\", SELECTCLAUSE ) %>'\n"
},
{
"answer_id": 264451,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 5,
"selected": true,
"text": "<asp:Repeater ID=\"repeatTheLabel\" runat=\"server\">\n <ItemTemplate>\n <asp:Label ID=\"Label1\" Text=\"<%# Eval("Id", "This is item '{0}'.") %>\" runat=\"server\" />\n </ItemTemplate>\n <SeparatorTemplate>\n <br />\n </SeparatorTemplate>\n</asp:Repeater>\n <%# %> Eval(\"Id\", \"This is item '{0}'.\")"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/242/"
] |
264,428
|
<p>I am using BSD style pty/tty pairs to implement running a sub shell. When the user exits the sub shell, how do I detect in the master process that this has occurred? I am using select(nfds, &read_fds, NULL, NULL, &timeout); with the master pty file descriptor set in the read_fds on the master side.</p>
|
[
{
"answer_id": 264449,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "fork() waitpid()"
},
{
"answer_id": 267422,
"author": "Matthew Smith",
"author_id": 20889,
"author_profile": "https://Stackoverflow.com/users/20889",
"pm_score": 3,
"selected": true,
"text": "int status;\npid_t pid = waitpid((pid_t)-1, &status, WNOHANG);\nsyslog (LOG_INFO, \"child process %ld exited: %d\",\n (long) pid, WEXITSTATUS(status));\n// do cleanup code\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264428",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20889/"
] |
264,430
|
<p>I want to be able to get a list of all differences between two JavaScript object graphs, with the property names and values where the deltas occur. </p>
<p>For what it is worth, these objects are usually retrieved from the server as JSON and typically are no more than a handful of layers deep (i.e. it may be an array of objects that themselves have data and then arrays with other data objects).</p>
<p>I want to not only see the changes to basic properties, but differences in the number of members of an array, etc. etc.</p>
<p>If I don't get an answer, I will probably end up writing this myself, but hope someone has already done this work or know of someone who has.</p>
<hr>
<p>EDIT: These objects will typically be very close in structure to one another, so we are not talking about objects that are utterly different from one another, but may have 3 or 4 deltas.</p>
|
[
{
"answer_id": 266306,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 4,
"selected": false,
"text": "function findDifferences(objectA, objectB) {\n var propertyChanges = [];\n var objectGraphPath = [\"this\"];\n (function(a, b) {\n if(a.constructor == Array) {\n // BIG assumptions here: That both arrays are same length, that\n // the members of those arrays are _essentially_ the same, and \n // that those array members are in the same order...\n for(var i = 0; i < a.length; i++) {\n objectGraphPath.push(\"[\" + i.toString() + \"]\");\n arguments.callee(a[i], b[i]);\n objectGraphPath.pop();\n }\n } else if(a.constructor == Object || (a.constructor != Number && \n a.constructor != String && a.constructor != Date && \n a.constructor != RegExp && a.constructor != Function &&\n a.constructor != Boolean)) {\n // we can safely assume that the objects have the \n // same property lists, else why compare them?\n for(var property in a) {\n objectGraphPath.push((\".\" + property));\n if(a[property].constructor != Function) {\n arguments.callee(a[property], b[property]);\n }\n objectGraphPath.pop();\n }\n } else if(a.constructor != Function) { // filter out functions\n if(a != b) {\n propertyChanges.push({ \"Property\": objectGraphPath.join(\"\"), \"ObjectA\": a, \"ObjectB\": b });\n }\n }\n })(objectA, objectB);\n return propertyChanges;\n}\n var person1 = { \n FirstName : \"John\", \n LastName : \"Doh\", \n Age : 30, \n EMailAddresses : [\n \"john.doe@gmail.com\", \n \"jd@initials.com\"\n ], \n Children : [ \n { \n FirstName : \"Sara\", \n LastName : \"Doe\", \n Age : 2 \n }, { \n FirstName : \"Beth\", \n LastName : \"Doe\", \n Age : 5 \n } \n ] \n};\n\nvar person2 = { \n FirstName : \"John\", \n LastName : \"Doe\", \n Age : 33, \n EMailAddresses : [\n \"john.doe@gmail.com\", \n \"jdoe@hotmail.com\"\n ], \n Children : [ \n { \n FirstName : \"Sara\", \n LastName : \"Doe\", \n Age : 3 \n }, { \n FirstName : \"Bethany\", \n LastName : \"Doe\", \n Age : 5 \n } \n ] \n};\n\nvar differences = findDifferences(person1, person2);\n differences [\n {\n \"Property\":\"this.LastName\", \n \"ObjectA\":\"Doh\", \n \"ObjectB\":\"Doe\"\n }, {\n \"Property\":\"this.Age\", \n \"ObjectA\":30, \n \"ObjectB\":33\n }, {\n \"Property\":\"this.EMailAddresses[1]\", \n \"ObjectA\":\"jd@initials.com\", \n \"ObjectB\":\"jdoe@hotmail.com\"\n }, {\n \"Property\":\"this.Children[0].Age\", \n \"ObjectA\":2, \n \"ObjectB\":3\n }, {\n \"Property\":\"this.Children[1].FirstName\", \n \"ObjectA\":\"Beth\", \n \"ObjectB\":\"Bethany\"\n }\n]\n this Property"
},
{
"answer_id": 6622892,
"author": "mozey",
"author_id": 639133,
"author_profile": "https://Stackoverflow.com/users/639133",
"pm_score": 3,
"selected": false,
"text": "// Given two objects find the first key or value not matching, algorithm is a\n// inspired by of _.isEqual.\nfunction diffObjects(a, b) {\n console.info(\"---> diffObjects\", {\"a\": a, \"b\": b});\n // Check object identity.\n if (a === b) return true;\n // Different types?\n var atype = typeof(a), btype = typeof(b);\n if (atype != btype) {\n console.info(\"Type mismatch:\", {\"a\": a, \"b\": b});\n return false;\n };\n // Basic equality test (watch out for coercions).\n if (a == b) return true;\n // One is falsy and the other truthy.\n if ((!a && b) || (a && !b)) {\n console.info(\"One is falsy and the other truthy:\", {\"a\": a, \"b\": b});\n return false;\n }\n // Unwrap any wrapped objects.\n if (a._chain) a = a._wrapped;\n if (b._chain) b = b._wrapped;\n // One of them implements an isEqual()?\n if (a.isEqual) return a.isEqual(b);\n // Check dates' integer values.\n if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();\n // Both are NaN?\n if (_.isNaN(a) && _.isNaN(b)) {\n console.info(\"Both are NaN?:\", {\"a\": a, \"b\": b});\n return false;\n }\n // Compare regular expressions.\n if (_.isRegExp(a) && _.isRegExp(b))\n return a.source === b.source &&\n a.global === b.global &&\n a.ignoreCase === b.ignoreCase &&\n a.multiline === b.multiline;\n // If a is not an object by this point, we can't handle it.\n if (atype !== 'object') {\n console.info(\"a is not an object:\", {\"a\": a});\n return false;\n }\n // Check for different array lengths before comparing contents.\n if (a.length && (a.length !== b.length)) {\n console.info(\"Arrays are of different length:\", {\"a\": a, \"b\": b});\n return false;\n }\n // Nothing else worked, deep compare the contents.\n var aKeys = _.keys(a), bKeys = _.keys(b);\n // Different object sizes?\n if (aKeys.length != bKeys.length) {\n console.info(\"Different object sizes:\", {\"a\": a, \"b\": b});\n return false;\n }\n // Recursive comparison of contents.\n for (var key in a) if (!(key in b) || !diffObjects(a[key], b[key])) return false;\n return true;\n};\n"
},
{
"answer_id": 22335525,
"author": "Mirek Rusin",
"author_id": 177776,
"author_profile": "https://Stackoverflow.com/users/177776",
"pm_score": 3,
"selected": false,
"text": "var person1 = {\n FirstName: \"John\",\n LastName: \"Doh\",\n Age: 30,\n EMailAddresses: [\"john.doe@gmail.com\", \"jd@initials.com\"],\n Children: [\n {\n FirstName: \"Sara\",\n LastName: \"Doe\",\n Age: 2\n }, {\n FirstName: \"Beth\",\n LastName: \"Doe\",\n Age: 5\n }\n ]\n};\n\nvar person2 = {\n FirstName: \"John\",\n LastName: \"Doe\",\n Age: 33,\n EMailAddresses: [\"john.doe@gmail.com\", \"jdoe@hotmail.com\"],\n Children: [\n {\n FirstName: \"Sara\",\n LastName: \"Doe\",\n Age: 3\n }, {\n FirstName: \"Bethany\",\n LastName: \"Doe\",\n Age: 5\n }\n ]\n};\n\nvar rusDiff = require('rus-diff').rusDiff\n\nconsole.log(rusDiff(person1, person2))\n { '$set': \n { 'Age': 33,\n 'Children.0.Age': 3,\n 'Children.1.FirstName': 'Bethany',\n 'EMailAddresses.1': 'jdoe@hotmail.com',\n 'LastName': 'Doe' } }\n"
},
{
"answer_id": 31254990,
"author": "B T",
"author_id": 122422,
"author_profile": "https://Stackoverflow.com/users/122422",
"pm_score": 1,
"selected": false,
"text": "odiff var a = [{a:1,b:2,c:3}, {x:1,y: 2, z:3}, {w:9,q:8,r:7}]\nvar b = [{a:1,b:2,c:3},{t:4,y:5,u:6},{x:1,y:'3',z:3},{t:9,y:9,u:9},{w:9,q:8,r:7}]\n\nvar diffs = odiff(a,b)\n\n/* diffs now contains:\n[{type: 'add', path:[], index: 2, vals: [{t:9,y:9,u:9}]},\n {type: 'set', path:[1,'y'], val: '3'},\n {type: 'add', path:[], index: 1, vals: [{t:4,y:5,u:6}]}\n]\n*/\n"
},
{
"answer_id": 37308356,
"author": "Danny Coulombe",
"author_id": 538323,
"author_profile": "https://Stackoverflow.com/users/538323",
"pm_score": 1,
"selected": false,
"text": "/**\n * Diff\n * Original author: Danny Coulombe\n * Creation date: 2016-05-18\n * \n * Work with objects to find their differences.\n */\ncontrollers.factory('diff', [function() {\n\n var factory = {\n\n /**\n * Compare the original object with the modified one and return their differences.\n * \n * @param original: Object\n * @param modified: Object\n * \n * @return Object\n */\n getDifferences: function(original, modified) {\n\n var type = modified.constructor === Array ? [] : {};\n var result = angular.copy(type);\n var comparisons = [[original, modified, 1], [modified, original, 0]];\n\n comparisons.forEach(function(comparison) {\n\n angular.forEach(comparison[0], function(value, key) {\n\n if(result[key] === undefined) {\n\n if(comparison[1][key] !== undefined && value !== null && comparison[1][key] !== null && [Object, Array].indexOf(comparison[1][key].constructor) !== -1) {\n\n result[key] = factory.getDifferences(value, comparison[1][key]);\n }\n else if(comparison[1][key] !== value) {\n\n result[key] = comparison[comparison[2]][key];\n }\n\n if(angular.equals(type, result[key])\n || result[key] === undefined\n || (\n comparison[0][key] !== undefined\n && result[key] !== null\n && comparison[0][key] !== null\n && comparison[0][key].length === comparison[1][key].length\n && result[key].length === 0\n )) {\n delete result[key];\n }\n }\n });\n });\n\n return result;\n }\n };\n\n return factory;\n}]);\n"
},
{
"answer_id": 47216576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "var d = { \n FirstName : \"John\", \n LastName : \"Doh\", \n Age : 30, \n EMailAddresses : [\n \"john.doe@gmail.com\", \n \"jd@initials.com\"\n ], \n Children : [ \n { \n FirstName : \"Sara\", \n LastName : \"Doe\", \n Age : 2 \n }, { \n FirstName : \"Beth\", \n LastName : \"Doe\", \n Age : 5 \n } \n ] \n};\n\nvar f = { \n FirstName : \"John\", \n LastName : \"Doe\", \n Age : 33, \n EMailAddresses : [\n \"john.doe@gmail.com\", \n \"jdoe@hotmail.com\"\n ], \n Children : [ \n { \n FirstName : \"Sara\", \n LastName : \"Doe\", \n Age : 3 \n }, { \n FirstName : \"Bethany\", \n LastName : \"Doe\", \n Age : 5 \n } \n ] \n};\n\nresultobj = []\nfunction comp_obj(t1,t2){\n flag = 1;\n key1_arr = Object.keys(t1)\n key2_arr = Object.keys(t2)\n if(key1_arr.length == key2_arr.length){\n for(key1 in t1){\n ty1 = Object.prototype.toString.call(t1[key1])\n ty2 = Object.prototype.toString.call(t2[key1])\n if(ty1 == ty2) {\n if(ty1 == '[object String]' || ty1 == '[object Number]' ){\n if(t2[key1] != t1[key1]){\n flag = 0;\n break;\n } \n }else if(ty1 == '[object Array]'){\n var result = comp_arr(t1[key1],t2[key1]);\n console.log(ty1,ty2)\n if(!result)\n flag = 0;\n }else if(ty1 == '[object Object]'){\n var result = comp_obj(t1[key1],t2[key1])\n if(!result)\n flag = 0;\n \n }\n }else{\n flag = 0;\n break; \n }\n\n }\n }else{\n flag = 0;\n }\n if(flag)\n return true\n else\n return false;\n}\nfunction comp_arr(a,b){\n flag = 1;\n if(a.length == b.length ){\n for(var i=0,l=a.length;i<l;i++){\n type1 = Object.prototype.toString.call(a[i])\n type2 = Object.prototype.toString.call(b[i])\n if(type1 == type2) {\n if(type1 == '[object String]' || type1 == '[object Number]' ){\n if( a[i] != b[i]){\n flag = 0;\n break;\n } \n }else if(type1 == '[object Array]'){\n var result = comp_arr(a[i],b[i]);\n if(!result)\n flag = 0;\n }else if(type1 == '[object Object]'){\n var result = comp_obj(a[i],b[i])\n if(!result)\n flag = 0;\n } \n }else{\n flag = 0;\n break; \n }\n }\n }else\n flag = 0;\n if(flag)\n return true\n else\n return false;\n}\nfunction create(t,attr,parent_node,innerdata){\n var dom = document.createElement(t)\n for(key in attr){\n dom.setAttribute(key,attr[key])\n }\n dom.innerHTML = innerdata;\n parent_node.appendChild(dom)\n return dom;\n}\nwindow.onload = function () {\n for(key in f){\n if(!(key in d)) \n resultobj.push({'Property_name':key,'f_value':JSON.stringify(f[key]),'d_value':JSON.stringify(d[key])})\n type1 = Object.prototype.toString.call(f[key])\n type2 = Object.prototype.toString.call(d[key])\n if(type1 == type2){\n if(type1 == '[object String]' || type1 == '[object Number]' ){\n if(f[key] != d[key])\n resultobj.push({'Property_name':key,'f_value':JSON.stringify(f[key]),'d_value':JSON.stringify(d[key])})\n }else if(type1 == '[object Array]'){\n var result = comp_arr(f[key],d[key]);\n if(!result)\n resultobj.push({'Property_name':key,'f_value':JSON.stringify(f[key]),'d_value':JSON.stringify(d[key])})\n }else if(type1 == '[object Object]'){\n var result = comp_obj(f[key],d[key]) \n if(!result)\n resultobj.push({'Property_name':key,'f_value':JSON.stringify(f[key]),'d_value':JSON.stringify(d[key])})\n }\n }else \n resultobj.push({'Property_name':key,'f_value':JSON.stringify(f[key]),'d_value':JSON.stringify(d[key])})\n }\n var tb = document.getElementById('diff');\n var s1 = document.getElementById('source1');\n var s2 = document.getElementById('source2');\n s1.innerHTML = 'Object 1 :'+ JSON.stringify(f)\n s2.innerHTML = 'Object 2 :'+JSON.stringify(d)\n resultobj.forEach(function(data,i){\n tr_dom = create('tr',{},tb,'')\n no = create('td',{},tr_dom,i+1)\n Object.keys(data).forEach(function(tr){\n td_dom = create('td',{},tr_dom,data[tr])\n })\n })\n} <html>\n <body>\n <p id=\"source1\"> </p>\n <p id=\"source2\"> </p>\n <p id=\"source7\"> DIFFERENCE TABLE</p>\n <table border=''>\n <thead>\n <th>S.no</th>\n <th>Name Of the Key</th>\n <th>Object1 Value</th>\n <th>Object2 Value</th>\n </thead>\n <tbody id=\"diff\">\n\n </tbody>\n </table>\n </body>\n</html>"
},
{
"answer_id": 65008941,
"author": "Farouk Rabhi",
"author_id": 6052110,
"author_profile": "https://Stackoverflow.com/users/6052110",
"pm_score": -1,
"selected": false,
"text": "var first = [ 1, 2, 3, 4, 5 ];\nvar second = [ 4, 5, 6 ];\n\nvar difference = first.filter(x => second.indexOf(x) === -1);\nconsole.log(difference);\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1790/"
] |
264,440
|
<p>Apple strongly recommends using the binary plist format when reading large XML-based data sets into iPhone apps. Among their reasoning is the fact that XML parsing is very taxing on the iPhone. However, this requires that files residing on the remote web server be converted first.</p>
<p>For frequently-changing content, it is not acceptable to do this manually. If at all possible, I'd like to avoid having a web based app call the command line to perform the conversion (i.e., plutil). </p>
<p>Are there publicly available algorithms to perform this conversion?</p>
|
[
{
"answer_id": 264487,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 3,
"selected": false,
"text": "NSPropertyListSerialization NSString *xmlPlistPath; // already set\nNSString *outPath; // already set\n\n\nNSData *plistData;\nNSString *error;\nNSPropertyListFormat format;\nid plist;\nplistData = [NSData dataWithContentsOfFile:xmlPlistPath];\n\nplist = [NSPropertyListSerialization propertyListFromData:plistData\n mutabilityOption:NSPropertyListImmutable\n format:&format\n errorDescription:&error];\n\nif(plist == nil) { // unable to parse plist\n //deal with failure -- error gives description of the error\n} else {\n binaryPlistData = [NSPropertyListSerialization dataFromPropertyList:plist\n format:NSPropertyListBinaryFormat_v1_0\n errorDescription:&error];\n if(binaryPlistData == nil) {//unable to create serialized plist\n // deal with failure -- error gives description of the error\n }\n\n if(![binaryPlistData writeToFile:outPath atomically:YES]) {\n // unable to write file\n }\n}\n"
},
{
"answer_id": 30669014,
"author": "Cameron Lowell Palmer",
"author_id": 410867,
"author_profile": "https://Stackoverflow.com/users/410867",
"pm_score": 2,
"selected": false,
"text": "/usr/libexec/Plistbuddy /usr/bin/plutil plutil -convert xml1 stops2.plist\nplutil -convert binary1 stops2.plist\nplutil -convert json stops2.plist\n"
},
{
"answer_id": 55841516,
"author": "ngbaanh",
"author_id": 4974497,
"author_profile": "https://Stackoverflow.com/users/4974497",
"pm_score": 1,
"selected": false,
"text": "Gist"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32536/"
] |
264,441
|
<pre><code>function array_value_from_key($array,$key)
{
return !empty($array[$key]) ? $array[$key] : null;
}
</code></pre>
<p>The reason I ask is because I have a class function that returns an array.</p>
<p>Instead of having to do</p>
<pre><code>$myArray = myClass::giveMeArray();
$myValue = $myArray[$myKey];
</code></pre>
<p>I'd like to do something along the lines of</p>
<pre><code>$myValue = array_value_from_key(myClass::giveMeArray(),$myKey);
</code></pre>
<p>When an object is returned, you can chain the object such as</p>
<pre><code>$myValue = myClass::giveMeObject()->aValue;
</code></pre>
<p>Voila, nice and clean.. not being able to find what seems to be a simple and trivial function is driving me crazy...</p>
<p>PS.. one more example of how I'd like to use such a function</p>
<pre><code>if(arrayKeyVal(aClass::giveMeArray(),$myKey)) {
do_something();
}
</code></pre>
|
[
{
"answer_id": 264465,
"author": "Jason",
"author_id": 33975,
"author_profile": "https://Stackoverflow.com/users/33975",
"pm_score": 1,
"selected": false,
"text": "$myValue = @$myArray[$myKey];\n $myValue = (array_key_exists($myKey, $myArray)) ? $myArray[$myKey] : null;\n"
},
{
"answer_id": 264493,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": -1,
"selected": false,
"text": "document.getElementById('abc').style.color = \"#fff\";\n $myElement = $document->getElementById('abc');\n$myElement->style->color = \"#fff\";\n $myObject->myArray[5]->anotherProperty->anotherArray[3]->anotherObject->aFunction();\n"
},
{
"answer_id": 264635,
"author": "Dave Marshall",
"author_id": 1248,
"author_profile": "https://Stackoverflow.com/users/1248",
"pm_score": 1,
"selected": false,
"text": "<?\nclass MyClass\n{\n public static function getArray()\n {\n $arr = array('dave' => 1, 'bob' => 2, 'james' => 3);\n return new ArrayObject($arr, ArrayObject::ARRAY_AS_PROPS);\n }\n}\n\n$var = MyClass::getArray()->bob;\n\n?>\n"
},
{
"answer_id": 264791,
"author": "Jrgns",
"author_id": 6681,
"author_profile": "https://Stackoverflow.com/users/6681",
"pm_score": -1,
"selected": false,
"text": "function giveMeArray($key = false) {\n $array = $whatever;\n $toret = null;\n if ($key) {\n if (array_key_exists($key, $array)) {\n $toret = $array[$key];\n }\n } else {\n $toret = $array()\n }\n return $toret;\n}\n $arr = myClass::giveMeArray(); //To get the whole array\n$value = myClass::giveMeArray($myKey); //To get the specific element\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34561/"
] |
264,454
|
<p>I run Jetty6 yet gladly place Apache in the front if needs be.</p>
<p>I would like to have two webserver instances running on the same machine on different ports.
I would like the instance on port 80 to redirect the second public domain name to the second webserver on port 8080.</p>
<p>This should not be visible to web users.</p>
<p>Thank you.</p>
|
[
{
"answer_id": 264470,
"author": "number5",
"author_id": 29489,
"author_profile": "https://Stackoverflow.com/users/29489",
"pm_score": 2,
"selected": false,
"text": " ProxyRequests Off\n\n <Proxy *>\n Order deny,allow\n Allow from all\n </Proxy>\n\n ProxyPass / http://localhost:8080/\n ProxyPassReverse / http://localhost:8080/\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34565/"
] |
264,480
|
<p>My php is weak and I'm trying to change this string:</p>
<pre><code>http://www.example.com/backend.php?/c=crud&m=index&t=care
^
</code></pre>
<p>to be:</p>
<pre><code>http://www.example.com/backend.php?c=crud&m=index&t=care
^
</code></pre>
<p>removing the <code>/</code> after the <code>backend.php?</code>. Any ideas on the best way to do this?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 264485,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "$str = preg_replace('/\\?\\//', '?', $str);\n"
},
{
"answer_id": 264490,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "$length = strlen($urlString);\nfor ($i=0; $i<$length; i++) {\n if ($urlString[$i] === '?') {\n $urlString[$i+1] = '';\n break;\n }\n}\n"
},
{
"answer_id": 264503,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "<?\n$badUrl = \"http://www.site.com/backend.php?/c=crud&m=index&t=care\";\n$goodUrl = str_replace('?/', '?', $badUrl);\n"
},
{
"answer_id": 264504,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "$splitPos = strpos($url, \"?/\");\nif ($splitPos !== false) {\n $url = substr($url, 0, $splitPos) . \"?\" . substr($url, $splitPos + 2);\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34571/"
] |
264,482
|
<p>I am not able to access localhost https pages in firefox3. It gave the error </p>
<blockquote>
<p>'Can't connect securely because the SSL protocol has been disabled.
(Error code: ssl_error_ssl_disabled)'</p>
</blockquote>
<p>I enabled all the SSL2 related preferences through about:config and the error changed to </p>
<blockquote>
<p>'Data Transfer Error
The browser connected successfully, but the connection was interrupted while transferring information. Please try again.'</p>
</blockquote>
<p>The first error seems most likely due to a invalid certificate but can't figure out the second...</p>
|
[
{
"answer_id": 264485,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 3,
"selected": false,
"text": "$str = preg_replace('/\\?\\//', '?', $str);\n"
},
{
"answer_id": 264490,
"author": "Henrik Paul",
"author_id": 2238,
"author_profile": "https://Stackoverflow.com/users/2238",
"pm_score": 0,
"selected": false,
"text": "$length = strlen($urlString);\nfor ($i=0; $i<$length; i++) {\n if ($urlString[$i] === '?') {\n $urlString[$i+1] = '';\n break;\n }\n}\n"
},
{
"answer_id": 264503,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 8,
"selected": true,
"text": "<?\n$badUrl = \"http://www.site.com/backend.php?/c=crud&m=index&t=care\";\n$goodUrl = str_replace('?/', '?', $badUrl);\n"
},
{
"answer_id": 264504,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "$splitPos = strpos($url, \"?/\");\nif ($splitPos !== false) {\n $url = substr($url, 0, $splitPos) . \"?\" . substr($url, $splitPos + 2);\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16488/"
] |
264,495
|
<p>I've got an application that's using string.compare(string,string) to sort some values. The thing I can't figure out is why "1022" compares as less than "10-23" and "10-23" compares as less than "1024".</p>
<p>Is there something specific to the value of "-" that causes this result? Will that overload of string.compare give the same result with different culture settings for the same type of data (numbers with dashes)?</p>
|
[
{
"answer_id": 264525,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "StringComparison.Ordinal string.Compare string s1 = \"-0.67:-0.33:0.33\";\nstring s2 = \"0.67:-0.33:0.33\";\nstring s3 = \"-0.67:0.33:-0.33\"; \nConsole.WriteLine(s1.CompareTo(s2));\nConsole.WriteLine(s2.CompareTo(s3));\nConsole.WriteLine(s1.CompareTo(s3));\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] |
264,496
|
<p>Should we use Generic Collection to improve safety and performance?</p>
|
[
{
"answer_id": 264506,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "ArrayList list = new ArrayList();\nlist.Add(5);\nlist.Add(\"FooBar\");\n List<int> list = new List();\nlist.Add(5);\n// Compile Time Error.\nlist.Add(\"FooBar\")\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,508
|
<p>Here is the scenario. There is content loaded in iframe from other site. I click to some link inside the iframe.</p>
<p>Is it possible to catch somehow outside the iframe what is that link? </p>
<p>UPDATE
Since I recieved question if my intentions are pure, I would explain more on the use case. May be I started in wrong direction for this task.</p>
<p>So, we have a desktop client that walks around web (for shoping actually) and when customer finds something she wants to buy, she clicks on "that" (anything - picture, link, address) and send "that" to our service where it is manually resolved to link to product and transformed to entry in her register. Nothing unusual.</p>
<p>Now, the task is to make it web app. So, customer registers in our site and starts browsing internet stores. Hence my first choice was iframe. But the question is how to find what she clicked on? </p>
<p>Or, generally - how to save a "bookmark" to some object from the other site? </p>
|
[
{
"answer_id": 265139,
"author": "user34280",
"author_id": 34280,
"author_profile": "https://Stackoverflow.com/users/34280",
"pm_score": 0,
"selected": false,
"text": "<a href=\"javascript:void(0)\" onclick=\"top.harvestLink(this)\" title=\"Item=foo\" alt=\"\">Foo</a>\n function harvestLink(anAnchor,aShoppingListArray) {\n var itemName = anAnchor.title.split(\"=\")[1];\n aShoppingList.push({item:itemName,dateStamp:new Date()});\n}\n"
},
{
"answer_id": 303332,
"author": "bbrown",
"author_id": 20595,
"author_profile": "https://Stackoverflow.com/users/20595",
"pm_score": 0,
"selected": false,
"text": "window.name window.name window.name iframeID.contentWindow.name"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34577/"
] |
264,526
|
<p>I want to determine if a certain window is visible to the user or hidden/occluded. In Windows XP I would use the GetClipBox() function and check for a NULLREGION or empty RECT return value. This worked perfectly fine, but on Windows Vista it does not work if another window is occluding the window. In this case, GetClipBox() is returning SIMPLEREGION with a non-empty RECT.</p>
<p>Does anybody know why this is not working on Vista or if there is another way to check if a window can be seen by the user?</p>
|
[
{
"answer_id": 265497,
"author": "flashk",
"author_id": 25149,
"author_profile": "https://Stackoverflow.com/users/25149",
"pm_score": 2,
"selected": false,
"text": "DwmEnableComposition(DWM_EC_DISABLECOMPOSITION);\n"
},
{
"answer_id": 265525,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 0,
"selected": false,
"text": "function bool IsWindowVisible()\n{\n bool isVisible = false;\n\n if (OSVersion == \"XP\")\n {\n // GetClipRect tests which run on XP and set isVisible\n }\n else if (OSVersion == \"Vista\")\n {\n if (DWMCompisitionEnabled == true)\n {\n // GetClipRect tests for Vista with DWM enabled and set isVisible\n }\n else\n {\n // GetClipRect tests for Vista with DWM disabled and set isVisible\n }\n }\n return isVisible;\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25149/"
] |
264,530
|
<p>I need to find two adjacent repeating digits in a string and replace with a single one. How to do this in Java. Some examples:</p>
<p>123345 should be 12345
77433211 should be 74321</p>
|
[
{
"answer_id": 264543,
"author": "Jake",
"author_id": 24730,
"author_profile": "https://Stackoverflow.com/users/24730",
"pm_score": 0,
"selected": false,
"text": "var myString='123345'\nmyString.replace(/([0-9])\\1/g,'$1')\n '123334'.replace(/([0-9])\\1+/g,'$1')\n"
},
{
"answer_id": 264550,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 5,
"selected": true,
"text": "replaceAll(\"(\\\\d)\\\\1+\", \"$1\") $ + (\\\\d)\\\\1 777xx 77xx System.out.println(\"77433211\".replaceAll(\"(\\\\d)\\\\1+\", \"$1\"));\n 74321\n String java.lang.String.replaceAll(String regex, String replacement)\n str.replaceAll(regex, repl) java.util.regex.Pattern.compile(regex).matcher(str).replaceAll(repl)\n String.replaceAll() replaceAll() String aString = \"77433211\"\naString = aString.replaceAll(\"(\\\\d)\\\\1+\", \"$1\"));\n"
},
{
"answer_id": 264554,
"author": "Drejc",
"author_id": 6482,
"author_profile": "https://Stackoverflow.com/users/6482",
"pm_score": 0,
"selected": false,
"text": "[x]{2}(?!=[x])\n"
},
{
"answer_id": 264597,
"author": "ashokgelal",
"author_id": 33203,
"author_profile": "https://Stackoverflow.com/users/33203",
"pm_score": 3,
"selected": false,
"text": "import java.util.regex.*;\n\npublic class RepetingDigits{\n public static void main(String[] args) {\n String word = \"77433211\";\n Pattern pattern = Pattern.compile(\"(\\\\d)\\\\1\");\n Matcher matcher = pattern.matcher(word);\n word = matcher.replaceAll(\"$1\"); \n System.out.println(word);\n }\n}\n **word = word.replaceAll(\"(\\\\d)\\\\1\", \"$1\");**\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
264,541
|
<p>Is there such a thing? </p>
<p>I'm talking about something like a C++ <code>new</code> command i.e. allocation of memory which necessitates explicit releasing of the memory (or risk memory leaks).</p>
<p>I ask because I remember having to solve some GDI leak problems previously by setting forms/controls/other objects to <code>Nothing</code> but can't remember what or why now...</p>
<p>Do we ever have to worry about memory management when developing in VB6?</p>
|
[
{
"answer_id": 265143,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 4,
"selected": true,
"text": "Option Explicit Public Event GetRef(ByRef RHS As MyObject)\n\nPublic Function GetMyObject() As MyObject\n Dim Ref As MyObject\n RaiseEvent GetRef(Ref)\n Set GetMyObject = Ref\nEnd Function\n Private WithEvents MyProxy As MyObjectProxy\n\nPrivate Sub Class_Initialize()\n Set MyProxy = New MyObjectProxy\nEnd Sub\n Public Property Get Proxy() As MyObjectProxy\n Set Proxy = MyProxy\nEnd Property\n\nPrivate Sub MyProxy_GetRef(RHS As MyObject)\n Set RHS = Me\nEnd Sub\n Private ParentProxy As MyObjectProxy\n\nPublic Property Get Parent() As MyObject\n If ParentProxy Is Nothing Then\n Set Parent = Nothing\n Else\n Set Parent = ParentProxy.GetRef\n End If\nEnd Property\n\nPublic Property Set Parent(RHS As MyObject)\n If RHS Is Me Then\n Set MyObjectProxy = Nothing\n ElseIf Target Is Nothing Then\n Set MyObjectProxy = Nothing\n Else\n Set MyObjectProxy = RHS.Proxy\n End If\nEnd Property\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4368/"
] |
264,552
|
<p>I have a big lump of binary data in a char[] array which I need to interpret as an array of packed 6-bit values.</p>
<p>I <em>could</em> sit down and write some code to do this but I'm thinking there has to be a good extant class or function somebody has written already.</p>
<p>What I need is something like:</p>
<pre><code>int get_bits(char* data, unsigned bitOffset, unsigned numBits);
</code></pre>
<p>so I could get the 7th 6-bit character in the data by calling:</p>
<pre><code>const unsigned BITSIZE = 6;
char ch = static_cast<char>(get_bits(data, 7 * BITSIZE, BITSIZE));
</code></pre>
|
[
{
"answer_id": 264600,
"author": "Marco M.",
"author_id": 28375,
"author_profile": "https://Stackoverflow.com/users/28375",
"pm_score": 1,
"selected": false,
"text": "int get_bit(char *data, unsigned bitoffset) // returns the n-th bit\n{\n int c = (int)(data[bitoffset >> 3]); // X>>3 is X/8\n int bitmask = 1 << (bitoffset & 7); // X&7 is X%8\n return ((c & bitmask)!=0) ? 1 : 0;\n}\n\nint get_bits(char* data, unsigned bitOffset, unsigned numBits)\n{\n int bits = 0;\n for (int currentbit = bitOffset; currentbit < bitOffset + numBits; currentbit++)\n {\n bits = bits << 1;\n bits = bits | get_bit(data, currentbit);\n }\n return bits;\n}\n int bitmask = 1 << (bitoffset & 7); // X&7 is X%8\n int bitmask = 1 << (7 - (bitoffset & 7)); // X&7 is X%8\n"
},
{
"answer_id": 264670,
"author": "user34619",
"author_id": 34619,
"author_profile": "https://Stackoverflow.com/users/34619",
"pm_score": 4,
"selected": true,
"text": "int get_bits(char* data, unsigned int bitOffset, unsigned int numBits) {\n numBits = pow(2,numBits) - 1; //this will only work up to 32 bits, of course\n data += bitOffset/8;\n bitOffset %= 8;\n return (*((int*)data) >> bitOffset) & numBits; //little endian\n //return (flip(data[0]) >> bitOffset) & numBits; //big endian\n}\n\n//flips from big to little or vice versa\nint flip(int x) {\n char temp, *t = (char*)&x;\n temp = t[0];\n t[0] = t[3];\n t[3] = temp;\n temp = t[1];\n t[1] = t[2];\n t[2] = temp;\n return x;\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264552",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2994/"
] |
264,575
|
<p>Here is my sample code. It is meant to be an iterative procedure for gauss seidel (matrix solver). Essentially when the error is small enough it breaks out of the while loop.</p>
<pre><code>i=1
while (i>0):
x_past = x_present
j=0
while(j<3):
value=0
k=0
while(k<3):
if(k!=j):
if(i==1):
if(k>j):
value=value+0
else:
value=value+x_present[k]*eqn[j][k]
else:
value=value+x_present[k]*eqn[j][k]
else:
value=value+eqn[j][k]
k=k+1
x_present[j:j+1]=[value]
j=j+1
print "X_PAST"
print x_past
print "X_PRESENT"
print x_present
if(error(x_past, x_present)<10**-2):
break;
i=i+1
</code></pre>
<p>I've reduced the code so its more manageable. if you don't understand what its doing its not really that important to solving this problem.</p>
<p>Here is the issue. Everytime </p>
<pre><code>x_present[j:j+1]=[value]
</code></pre>
<p>is run, x_past is made equal to x_present. I don't know why this is the case as the only place i have set x_past equal to x_present is at the top of the loop. If I take away the </p>
<pre><code>x_past=x_present
</code></pre>
<p>sentence, x_past is never made equal to x_present. This leads me to think it is some combination of the two statements that is causing the issue.</p>
<p>This is a big problem cause if x_past = x_present the error = 0 every time and the loop breaks after the first iteration. The code does work, for example if I tell the code to run for 8 iterations and the break it gives me the answer its supposed to.</p>
<p>I've been trying to figure this out for the last 4 hours and am completely stumped. I haven't been working with python long, so my trouble shooting skills syntax wise aren't that great. Any help would be appreciated!!</p>
|
[
{
"answer_id": 264592,
"author": "monkut",
"author_id": 24718,
"author_profile": "https://Stackoverflow.com/users/24718",
"pm_score": 6,
"selected": true,
"text": ">>> x_present = [4,5,6]\n>>>\n>>> x_past = x_present\n>>>\n>>> x_past\n[4, 5, 6]\n>>>\n>>> x_present.append(7)\n>>>\n>>> x_past\n[4, 5, 6, 7]\n>>>\n import copy;listcopy = copy.copy(mylist) >>> x_past = x_present[:]\n>>> x_past\n[4, 5, 6, 7]\n>>>\n>>> x_present.append(8)\n>>>\n>>> x_past\n[4, 5, 6, 7]\n"
},
{
"answer_id": 264593,
"author": "Lukman",
"author_id": 34586,
"author_profile": "https://Stackoverflow.com/users/34586",
"pm_score": 0,
"selected": false,
"text": "x_past = x_present x_past = [x for x in x_present] greaterthan100 = [x for x in number if x > 100] notinblacklist = [x for x in mylist if x not in blacklist] firstchildofbigfamily = [x.child[0] for x in familylist if len(x.child) > 10]"
},
{
"answer_id": 264715,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "x_past = x_present x_past = x_present[:] copy >>> import copy\n>>> a = range(10)\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n>>> b = a\n>>> a += 10, 11\n>>> a\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> b\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> c = copy.copy(a) # shallow copy\n>>> c\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n>>> del a[3:]\n>>> a\n[0, 1, 2]\n>>> b\n[0, 1, 2]\n>>> c\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n import copy\n# assert(len(x_present) >= len(eqn))\n\nfirst = True\nwhile True:\n x_past = copy.copy(x_present) # copy\n\n for j, eqj in enumerate(eqn):\n x_present[j] = sum(x_present[k] * eqj[k] \n for k in range(j if first else len(eqj)) \n if k != j)\n x_present[j] += eqj[j] \n\n print \"X_PAST\\n%s\\nX_PRESENT\\n%s\" % (x_past, x_present)\n if allequal(x_past, x_present, tolerance=10**-2):\n break\n first = False\n allequal() def allequal(x, y, tolerance):\n return (len(x) == len(y) and \n all(-tolerance < (xx - yy) < tolerance\n for xx, yy in zip(x, y)))\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338360/"
] |
264,578
|
<p>i.e. as I compose my test suites to include other suites as well as test cases,
is there a global count of how many tests the TestRunner has executed, will be executing?</p>
<p>Any way I can progammatically access that count?</p>
|
[
{
"answer_id": 265003,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 2,
"selected": false,
"text": "self.methods.grep(/test_/)"
},
{
"answer_id": 2742102,
"author": "Andrew Grimm",
"author_id": 38765,
"author_profile": "https://Stackoverflow.com/users/38765",
"pm_score": 0,
"selected": false,
"text": "Test::Unit::TestSuite#size Test::Unit::TestCase#size"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34594/"
] |
264,582
|
<p>I know there is a <code>WeakHashMap</code> in <code>java.util</code>, but since it uses <code>WeakReference</code>s for everything, which is only referenced by this <code>Map</code>, referenced objects will get lost on the next GC cycle. So it's nearly useless if you want to cache random data, which is very likely to be requested again without being Hard-linked the rest of the time. The best solution would be a map, which uses <code>SoftReference</code>s instead, but I didn't find one in the Java RT Package.</p>
|
[
{
"answer_id": 264591,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "Cache SoftHashMap CacheBuilder.newBuilder().softKeys() SoftHashMap SoftHashMap ConcurrentMap java.util.Timer"
},
{
"answer_id": 265573,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 1,
"selected": false,
"text": "Runtime.getRuntime().getFreeMemory();\n"
},
{
"answer_id": 62834985,
"author": "Richard Kotal",
"author_id": 5934449,
"author_profile": "https://Stackoverflow.com/users/5934449",
"pm_score": 1,
"selected": false,
"text": "package cz.b2b.jcl.util;\n\nimport java.util.*;\nimport java.lang.ref.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.AbstractMap.SimpleImmutableEntry;\n\npublic class ConcurrentSoftHashMap<K, V> extends AbstractMap {\n\n /**\n The internal HashMap that will hold the SoftReference.\n */\n private final Map<Object, SoftReference> hash = new ConcurrentHashMap<>();\n /**\n The number of \"hard\" references to hold internally.\n */\n private final int HARD_SIZE;\n /**\n The FIFO list of hard references, order of last access.\n */\n private final ConcurrentLinkedSetQueue hardCache = new ConcurrentLinkedSetQueue();\n /**\n Reference queue for cleared SoftReference objects.\n */\n private final ReferenceQueue queue = new ReferenceQueue();\n\n public ConcurrentSoftHashMap(int hardSize) {\n HARD_SIZE = hardSize;\n }\n\n @Override\n public Object get(Object key) {\n Object result = null;\n // We get the SoftReference represented by that key\n SoftReference soft_ref = hash.get(key);\n if (soft_ref != null) {\n // From the SoftReference we get the value, which can be\n // null if it was not in the map, or it was removed in\n // the processQueue() method defined below\n result = soft_ref.get();\n if (result == null) {\n // If the value has been garbage collected, remove the\n // entry from the HashMap.\n hash.remove(key);\n } else {\n // We now add this object to the beginning of the hard\n // reference queue. \n hardCache.enqueue(result);\n if (hardCache.size() > HARD_SIZE) {\n // Remove the last entry if list longer than HARD_SIZE\n hardCache.dequeue();\n }\n }\n }\n return result;\n }\n\n /**\n Here we put the key, value pair into the HashMap using\n a SoftValue object.\n @param key\n @param value\n @return\n */\n @Override\n public Object put(Object key, Object value) {\n processQueue(); // throw out garbage collected values first\n return hash.put(key, new SoftValue(value, key, queue));\n }\n\n @Override\n public Object remove(Object key) {\n processQueue(); // throw out garbage collected values first\n return hash.remove(key);\n }\n\n @Override\n public void clear() {\n hardCache.clear();\n processQueue(); // throw out garbage collected values\n hash.clear();\n }\n\n @Override\n public int size() {\n processQueue(); // throw out garbage collected values first\n return hash.size();\n }\n\n @Override\n public boolean containsKey(Object key) {\n processQueue(); // throw out garbage collected values first\n return hash.containsKey(key);\n }\n\n @Override\n public Set entrySet() {\n Set<Map.Entry> entry = new HashSet<>();\n Map.Entry simpleImmutableEntry = null;\n Object result = null;\n processQueue(); // throw out garbage collected values first\n for (Map.Entry<Object, SoftReference> item : hash.entrySet()) {\n if (item == null) {\n continue;\n }\n Object key = item.getKey();\n SoftReference soft_ref = item.getValue();\n if (soft_ref != null) {\n result = soft_ref.get();\n if (result == null) {\n hash.remove(key);\n } else {\n hardCache.enqueue(result);\n if (hardCache.size() > HARD_SIZE) {\n hardCache.dequeue();\n }\n simpleImmutableEntry = new SimpleImmutableEntry(key, result);\n entry.add(simpleImmutableEntry);\n\n }\n }\n\n }\n\n return entry;\n }\n\n private class ConcurrentLinkedSetQueue<E> extends ConcurrentLinkedQueue<E> {\n\n public void enqueue(E o) {\n if (!contains(o)) {\n add(o);\n }\n }\n\n public E dequeue() {\n return poll();\n }\n\n }\n\n /**\n We define our own subclass of SoftReference which contains\n not only the value but also the key to make it easier to find\n the entry in the HashMap after it's been garbage collected.\n */\n private static class SoftValue extends SoftReference {\n\n private final Object key; // always make data member final\n\n /**\n Did you know that an outer class can access private data\n members and methods of an inner class? I didn't know that!\n I thought it was only the inner class who could access the\n outer class's private information. An outer class can also\n access private members of an inner class inside its inner\n class.\n */\n private SoftValue(Object k, Object key, ReferenceQueue q) {\n super(k, q);\n this.key = key;\n }\n }\n\n /**\n Here we go through the ReferenceQueue and remove garbage\n collected SoftValue objects from the HashMap by looking them\n up using the SoftValue.key data member.\n */\n private void processQueue() {\n SoftValue sv;\n while ((sv = (SoftValue) queue.poll()) != null) {\n hash.remove(sv.key); // we can access private data!\n }\n }\n\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30294/"
] |
264,596
|
<p>I'm trying to deserialize an xml structure that looks like this:</p>
<pre><code><somecontainer>
<key1>Value1</key1>
<key1>Value2</key1>
<key2>Value3</key2>
<key2>Value4</key2>
</somecontainer>
</code></pre>
<p>I can basically choose what kind if element to deserialize to, maybe something like a List of Pair or something. The essence here is that the element names are the keys.</p>
<p>And no, I cannot change the xml structure. Anyone know how to do this with xstream ?</p>
|
[
{
"answer_id": 264591,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 6,
"selected": true,
"text": "Cache SoftHashMap CacheBuilder.newBuilder().softKeys() SoftHashMap SoftHashMap ConcurrentMap java.util.Timer"
},
{
"answer_id": 265573,
"author": "luke",
"author_id": 25920,
"author_profile": "https://Stackoverflow.com/users/25920",
"pm_score": 1,
"selected": false,
"text": "Runtime.getRuntime().getFreeMemory();\n"
},
{
"answer_id": 62834985,
"author": "Richard Kotal",
"author_id": 5934449,
"author_profile": "https://Stackoverflow.com/users/5934449",
"pm_score": 1,
"selected": false,
"text": "package cz.b2b.jcl.util;\n\nimport java.util.*;\nimport java.lang.ref.*;\nimport java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.ConcurrentLinkedQueue;\nimport java.util.AbstractMap.SimpleImmutableEntry;\n\npublic class ConcurrentSoftHashMap<K, V> extends AbstractMap {\n\n /**\n The internal HashMap that will hold the SoftReference.\n */\n private final Map<Object, SoftReference> hash = new ConcurrentHashMap<>();\n /**\n The number of \"hard\" references to hold internally.\n */\n private final int HARD_SIZE;\n /**\n The FIFO list of hard references, order of last access.\n */\n private final ConcurrentLinkedSetQueue hardCache = new ConcurrentLinkedSetQueue();\n /**\n Reference queue for cleared SoftReference objects.\n */\n private final ReferenceQueue queue = new ReferenceQueue();\n\n public ConcurrentSoftHashMap(int hardSize) {\n HARD_SIZE = hardSize;\n }\n\n @Override\n public Object get(Object key) {\n Object result = null;\n // We get the SoftReference represented by that key\n SoftReference soft_ref = hash.get(key);\n if (soft_ref != null) {\n // From the SoftReference we get the value, which can be\n // null if it was not in the map, or it was removed in\n // the processQueue() method defined below\n result = soft_ref.get();\n if (result == null) {\n // If the value has been garbage collected, remove the\n // entry from the HashMap.\n hash.remove(key);\n } else {\n // We now add this object to the beginning of the hard\n // reference queue. \n hardCache.enqueue(result);\n if (hardCache.size() > HARD_SIZE) {\n // Remove the last entry if list longer than HARD_SIZE\n hardCache.dequeue();\n }\n }\n }\n return result;\n }\n\n /**\n Here we put the key, value pair into the HashMap using\n a SoftValue object.\n @param key\n @param value\n @return\n */\n @Override\n public Object put(Object key, Object value) {\n processQueue(); // throw out garbage collected values first\n return hash.put(key, new SoftValue(value, key, queue));\n }\n\n @Override\n public Object remove(Object key) {\n processQueue(); // throw out garbage collected values first\n return hash.remove(key);\n }\n\n @Override\n public void clear() {\n hardCache.clear();\n processQueue(); // throw out garbage collected values\n hash.clear();\n }\n\n @Override\n public int size() {\n processQueue(); // throw out garbage collected values first\n return hash.size();\n }\n\n @Override\n public boolean containsKey(Object key) {\n processQueue(); // throw out garbage collected values first\n return hash.containsKey(key);\n }\n\n @Override\n public Set entrySet() {\n Set<Map.Entry> entry = new HashSet<>();\n Map.Entry simpleImmutableEntry = null;\n Object result = null;\n processQueue(); // throw out garbage collected values first\n for (Map.Entry<Object, SoftReference> item : hash.entrySet()) {\n if (item == null) {\n continue;\n }\n Object key = item.getKey();\n SoftReference soft_ref = item.getValue();\n if (soft_ref != null) {\n result = soft_ref.get();\n if (result == null) {\n hash.remove(key);\n } else {\n hardCache.enqueue(result);\n if (hardCache.size() > HARD_SIZE) {\n hardCache.dequeue();\n }\n simpleImmutableEntry = new SimpleImmutableEntry(key, result);\n entry.add(simpleImmutableEntry);\n\n }\n }\n\n }\n\n return entry;\n }\n\n private class ConcurrentLinkedSetQueue<E> extends ConcurrentLinkedQueue<E> {\n\n public void enqueue(E o) {\n if (!contains(o)) {\n add(o);\n }\n }\n\n public E dequeue() {\n return poll();\n }\n\n }\n\n /**\n We define our own subclass of SoftReference which contains\n not only the value but also the key to make it easier to find\n the entry in the HashMap after it's been garbage collected.\n */\n private static class SoftValue extends SoftReference {\n\n private final Object key; // always make data member final\n\n /**\n Did you know that an outer class can access private data\n members and methods of an inner class? I didn't know that!\n I thought it was only the inner class who could access the\n outer class's private information. An outer class can also\n access private members of an inner class inside its inner\n class.\n */\n private SoftValue(Object k, Object key, ReferenceQueue q) {\n super(k, q);\n this.key = key;\n }\n }\n\n /**\n Here we go through the ReferenceQueue and remove garbage\n collected SoftValue objects from the HashMap by looking them\n up using the SoftValue.key data member.\n */\n private void processQueue() {\n SoftValue sv;\n while ((sv = (SoftValue) queue.poll()) != null) {\n hash.remove(sv.key); // we can access private data!\n }\n }\n\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23691/"
] |
264,609
|
<p>I want to pass a reference type by value to a method in C#. Is there a way to do it.</p>
<p>In C++, I could always rely on the copy constructor to come into play if I wanted to pass by Value. Is there any way in C# except:
1. Explicitly creating a new object
2. Implementing IClonable and then calling Clone method.</p>
<p>Here's a small example:</p>
<p>Let's take a class A in C++ which implements a copy constructor.</p>
<p>A method func1(Class a), I can call it by saying func1(objA) (Automatically creates a copy)</p>
<p>Does anything similar exist in C#. By the way, I'm using Visual Studio 2005.</p>
|
[
{
"answer_id": 264613,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "ICloneable"
},
{
"answer_id": 6080403,
"author": "Mohsen",
"author_id": 514329,
"author_profile": "https://Stackoverflow.com/users/514329",
"pm_score": 0,
"selected": false,
"text": "public class Product\n{\n public string Name;\n public string Color;\n public string Category;\n\n public Product(Product o)\n {\n this.Name=o.Name;\n this.Color=o.Color;\n this.Category=o.Category;\n } \n // Note we need to give a default constructor when override it\n\n public Product()\n {\n }\n} \npublic Product Produce(Product sample)\n{\n Product p=new Product(sample);\n p.Category=\"Finished Product\";\n return p;\n}\nProduct sample=new Product();\nsample.Name=\"Toy\";\nsample.Color=\"Red\";\nsample.Category=\"Sample Product\";\nProduct p=Produce(sample);\nConsole.WriteLine(String.Format(\"Product: Name={0}, Color={1}, Category={2}\", p.Name, p.Color, p.Category));\nConsole.WriteLine(String.Format(\"Sample: Name={0}, Color={1}, Category={2}\", sample.Name, sample.Color, sample.Category));\n"
},
{
"answer_id": 33997611,
"author": "redspidermkv",
"author_id": 4026153,
"author_profile": "https://Stackoverflow.com/users/4026153",
"pm_score": 2,
"selected": false,
"text": "class PassingRefByVal \n{\n static void Change(int[] pArray)\n {\n pArray[0] = 888; // This change affects the original element.\n pArray = new int[5] {-3, -1, -2, -3, -4}; // This change is local.\n System.Console.WriteLine(\"Inside the method, the first element is: {0}\", pArray[0]);\n }\n\n static void Main() \n {\n int[] arr = {1, 4, 5};\n System.Console.WriteLine(\"Inside Main, before calling the method, the first element is: {0}\", arr [0]);\n\n Change(arr);\n System.Console.WriteLine(\"Inside Main, after calling the method, the first element is: {0}\", arr [0]);\n }\n}\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,617
|
<p>A few months ago I was introduced to the new <a href="http://msdn.microsoft.com/library/system.datetimeoffset.aspx" rel="noreferrer"><code>DateTimeOffset</code></a> type and was glad <a href="http://msdn.microsoft.com/library/system.datetime.aspx" rel="noreferrer"><code>DateTime</code></a>'s flaws with regard to time zones were finally taken care of.</p>
<p>However, I was left wondering if there were any overhead or problems that could occur from using this new type.</p>
<p>I work on a multi-locale web application. Does anyone know of anything that could sway me from just using it for all my date/time work? Is there a window for abuse here?</p>
<p>Reference: <a href="http://blogs.msdn.com/bclteam/archive/2007/06/14/datetimeoffset-a-new-datetime-structure-in-net-3-5-justin-van-patten.aspx" rel="noreferrer">DateTimeOffset: A New DateTime Structure in .NET 3.5 by Justin Van Patten</a></p>
|
[
{
"answer_id": 264643,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 7,
"selected": true,
"text": "DateTimeOffset DateTimeTimeZone DateTimeOffset"
},
{
"answer_id": 54658746,
"author": "brewmanz",
"author_id": 2821586,
"author_profile": "https://Stackoverflow.com/users/2821586",
"pm_score": 0,
"selected": false,
"text": "ReadXml XmlReadMode.InferTypedSchema"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4979/"
] |
264,623
|
<p>Throughout or C# sourcecode we have a lot of comments that miss the actual content such like this:</p>
<pre><code>/// <summary>
/// </summary>
</code></pre>
<p>or this:</p>
<pre><code>/// <summary>
///
/// </summary>
</code></pre>
<p>or this:</p>
<pre><code>/// <param Name="flag"></param>
</code></pre>
<p>Unfortunately Visual Studio does not generate warnings for this type of missing comments. But for us it would be nice if we could just klick on an item in a list (eg. the warings list) inside visual studio and then be taken to the faulty location in source code to correct it. Also it would be nice to see the list of missing xml comment content upon each build of the xml files. Do you have any idea on how to achieve this?</p>
|
[
{
"answer_id": 35051409,
"author": "ANIL KHANDEI",
"author_id": 5686453,
"author_profile": "https://Stackoverflow.com/users/5686453",
"pm_score": 0,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\" exclude-result-prefixes=\"msxsl\"\n>\n <xsl:output method=\"xml\" indent=\"yes\"/>\n\n <xsl:template match=\"@* | node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@* | node()\"/>\n </xsl:copy>\n </xsl:template>\n</xsl:stylesheet>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264623",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4227/"
] |
264,625
|
<p>Does anyone know how to use CruiseControl.Net to publish to an FTP server?</p>
|
[
{
"answer_id": 1656085,
"author": "Sergejs Kravcenko",
"author_id": 200351,
"author_profile": "https://Stackoverflow.com/users/200351",
"pm_score": 2,
"selected": false,
"text": "edtFTPnet.dll"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/691/"
] |
264,626
|
<p>I can't seem to get Javascript debugging working for my ASP.NET MVC application even though I can for a traditional ASP.NET WebForm app.</p>
<p>I have followed the steps for unchecking the 'Disable Script Debugging' boxes for both IE and other.</p>
<p>when I add a simple function to display an alert in both the site.master and any content view the breakpoint will not fire.</p>
<p>Have i missed something obvious or do I need to use an outside tool for debugging like FireBug?</p>
<p>By the way, I'm using Visual Studio Web Developer Express 2008.</p>
<p>thx</p>
|
[
{
"answer_id": 1189189,
"author": "malckier",
"author_id": 102265,
"author_profile": "https://Stackoverflow.com/users/102265",
"pm_score": 1,
"selected": false,
"text": " <script type=\"text/javascript\" src=\"../../Scripts/DebugJScript.js?<%=DateTime.Now %>\" ></script> \n"
},
{
"answer_id": 1189953,
"author": "Jean-Francois",
"author_id": 41174,
"author_profile": "https://Stackoverflow.com/users/41174",
"pm_score": 3,
"selected": false,
"text": "function test()\n{\n debugger;\n alert(\"hi\");\n}\n"
},
{
"answer_id": 5478477,
"author": "tracileemt",
"author_id": 682822,
"author_profile": "https://Stackoverflow.com/users/682822",
"pm_score": 3,
"selected": false,
"text": ".js default.js"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5132/"
] |
264,640
|
<p>I'd like to create a text field with a dropdown list that lets the user choose some predefined values. The user should also be able to type a new value or select a predefined one from a dropdown list. I know that I can use two widgets for that but in my app it would be more ergonomnic if it was unified in a one widget.</p>
<p>Is there a standard widget or do I have to use a third party javascript?</p>
<p>How about browser portability?</p>
|
[
{
"answer_id": 264648,
"author": "Treb",
"author_id": 22114,
"author_profile": "https://Stackoverflow.com/users/22114",
"pm_score": 3,
"selected": false,
"text": "<select> <input type=\"text\""
},
{
"answer_id": 17658653,
"author": "Alexandru Boerescu",
"author_id": 2584226,
"author_profile": "https://Stackoverflow.com/users/2584226",
"pm_score": 7,
"selected": false,
"text": "<datalist> <input type=\"text\" name=\"product\" list=\"productName\" />\n<datalist id=\"productName\">\n <option value=\"Pen\">Pen</option>\n <option value=\"Pencil\">Pencil</option>\n <option value=\"Paper\">Paper</option>\n</datalist>"
},
{
"answer_id": 19239273,
"author": "atom217",
"author_id": 2368848,
"author_profile": "https://Stackoverflow.com/users/2368848",
"pm_score": 1,
"selected": false,
"text": "<div style=\"position: absolute;top: 32px; left: 430px;\" id=\"outerFilterDiv\">\n<input name=\"filterTextField\" type=\"text\" id=\"filterTextField\" tabindex=\"2\" style=\"width: 140px;\n position: absolute; top: 1px; left: 1px; z-index: 2;border:none;\" />\n <div style=\"position: absolute;\" id=\"filterDropdownDiv\">\n<select name=\"filterDropDown\" id=\"filterDropDown\" tabindex=\"1000\"\n onchange=\"DropDownTextToBox(this,'filterTextField');\" style=\"position: absolute;\n top: 0px; left: 0px; z-index: 1; width: 165px;\">\n <option value=\"-1\" selected=\"selected\" disabled=\"disabled\">-- Select Column Name --</option>\n</select>\n"
},
{
"answer_id": 31474567,
"author": "Max",
"author_id": 1509147,
"author_profile": "https://Stackoverflow.com/users/1509147",
"pm_score": 4,
"selected": false,
"text": ".dropdown {\n position: relative;\n width: 200px;\n}\n\n.dropdown select {\n width: 100%;\n}\n\n.dropdown > * {\n box-sizing: border-box;\n height: 1.5em;\n}\n\n.dropdown input {\n position: absolute;\n width: calc(100% - 20px);\n} <div class=\"dropdown\">\n <input type=\"text\" />\n <select onchange=\"this.previousElementSibling.value=this.value; this.previousElementSibling.focus()\">\n <option>This is option 1</option>\n <option>Option 2</option>\n </select>\n</div> previousElementSibling()"
},
{
"answer_id": 31734324,
"author": "Natraj",
"author_id": 5175539,
"author_profile": "https://Stackoverflow.com/users/5175539",
"pm_score": 5,
"selected": false,
"text": "$(document).ready(function(){\n \n $(\".editableBox\").change(function(){ \n $(\".timeTextBox\").val($(\".editableBox option:selected\").html());\n });\n}); .editableBox {\n width: 75px;\n height: 30px;\n}\n\n.timeTextBox {\n width: 54px;\n margin-left: -78px;\n height: 25px;\n border: none;\n} <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<div class=\"wrapper\">\n <select class=\"editableBox\"> \n <option value=\"1\">01:00</option>\n <option value=\"2\">02:00</option>\n <option value=\"3\">03:00</option>\n <option value=\"4\">04:00</option>\n <option value=\"5\">05:00</option>\n <option value=\"6\">06:00</option>\n <option value=\"7\">07:00</option>\n <option value=\"8\">08:00</option>\n <option value=\"9\">09:00</option>\n <option value=\"10\">10:00</option>\n <option value=\"11\">11:00</option>\n <option value=\"12\">12:00</option>\n <option value=\"13\">13:00</option>\n <option value=\"14\">14:00</option>\n <option value=\"15\">15:00</option>\n <option value=\"16\">16:00</option>\n <option value=\"17\">17:00</option>\n <option value=\"18\">18:00</option>\n <option value=\"19\">19:00</option>\n <option value=\"20\">20:00</option>\n <option value=\"21\">21:00</option>\n <option value=\"22\">22:00</option>\n <option value=\"23\">23:00</option>\n <option value=\"24\">24:00</option>\n </select>\n <input class=\"timeTextBox\" name=\"timebox\" maxlength=\"5\"/>\n</div>"
},
{
"answer_id": 57280940,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 2,
"selected": false,
"text": "<span class=\"combobox withtextlist\">\n <input value=\"Fruit\">\n <span tabindex=\"-1\" class=\"downarrow\"></span>\n <select size=\"10\" class=\"sticky\">\n <option>Apple</option>\n <option>Banana</option>\n <option>Cherry</option>\n <option>Dewberry</option>\n </select>\n</span>\n /* ------------------------------------------ */\n/* ----- combobox / dropdown list styling */\n/* ------------------------------------------ */\n.combobox {\n /* Border slightly darker than Chrome's <select>, slightly lighter than FireFox's */\n border: 1px solid #999;\n padding-right: 1.25em; /* leave room for ▾ */\n}\n.dropdown, .combobox { \n /* \"relative\" and \"inline-block\" (or just \"block\") are needed\n here so that \"absolute\" works correctly in children */\n position: relative;\n display: inline-block;\n}\n.combobox > .downarrow, .dropdown > .downarrow {\n /* ▾ Outside normal flow, relative to container */\n display: inline-block;\n position: absolute;\n top: 0;\n bottom: 0;\n right: 0;\n width: 1.25em;\n\n cursor: default;\n nav-index: -1; /* nonfunctional in most browsers */\n\n border-width: 0px; /* disable by default */\n border-style: inherit; /* copy parent border */\n border-color: inherit; /* copy parent border */\n}\n/* Add a divider before the ▾ down arrow in non-dropdown comboboxes */\n.combobox:not(.dropdown) > .downarrow {\n border-left-width: 1px;\n}\n/* Auto-down-arrow if one is not provided */\n.downarrow:empty::before {\n content: '▾';\n}\n.downarrow::before, .downarrow > *:only-child {\n text-align: center;\n\n /* vertical centering trick */\n position: relative;\n top: 50%;\n display: block; /* transform requires block/inline-block */\n transform: translateY(-50%);\n}\n.combobox > input {\n border: 0\n}\n.dropdown > *:last-child,\n.combobox > *:last-child {\n /* Using `display:block` here has two desirable effects:\n (1) Accessibility: it lets input widgets in the dropdown to\n be selected with the tab key when the dropdown is closed. \n (2) It lets the opacity transition work.\n But it also makes the contents visible, which is undesirable \n before the list drops down. To compensate, use `opacity: 0`\n and disable mouse pointer events. Another side effect is that\n the user can select and copy the contents of the hidden list,\n but don't worry, the selected content is invisible. */\n display: block;\n opacity: 0;\n pointer-events: none;\n\n transition: 0.4s; /* fade out */\n position: absolute;\n left: 0;\n top: 100%;\n border: 1px solid #888;\n background-color: #fff;\n box-shadow: 1px 2px 4px 1px #666;\n box-shadow: 1px 2px 4px 1px #4448;\n z-index: 9999;\n min-width: 100%;\n box-sizing: border-box;\n}\n/* List of situations in which to show the dropdown list.\n - Focus dropdown or non-last child of it => show last-child\n - Focus .downarrow of combobox => show last-child\n - Stay open for focus in last child, unless .less-sticky\n - .sticky last child stays open on hover\n - .less-sticky stays open on hover, ignores focus in last-child */\n.dropdown:focus > *:last-child,\n.dropdown > *:focus ~ *:last-child,\n.combobox > .downarrow:focus ~ *:last-child,\n.combobox > .sticky:last-child:hover,\n.dropdown > .sticky:last-child:hover,\n.combobox > .less-sticky:last-child:hover,\n.dropdown > .less-sticky:last-child:hover,\n.combobox > *:last-child:focus:not(.less-sticky),\n.dropdown > *:last-child:focus:not(.less-sticky) {\n display: block;\n opacity: 1;\n transition: 0.15s;\n pointer-events: auto;\n}\n/* focus-within not supported by Edge/IE. Unsupported selectors cause \n the entire block to be ignored, so we must repeat all styles for \n focus-within separately. */\n.combobox > *:last-child:focus-within:not(.less-sticky),\n.dropdown > *:last-child:focus-within:not(.less-sticky) {\n display: block;\n opacity: 1;\n transition: 0.15s;\n pointer-events: auto;\n}\n/* detect Edge/IE and behave if though less-sticky is on for all\n dropdowns (otherwise links won't be clickable) */\n@supports (-ms-ime-align:auto) {\n .dropdown > *:last-child:hover {\n display: block;\n opacity: 1;\n pointer-events: auto;\n }\n}\n/* detect IE and do the same thing. */\n@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {\n .dropdown > *:last-child:hover {\n display: block;\n opacity: 1;\n pointer-events: auto;\n }\n}\n.dropdown:not(.sticky) > *:not(:last-child):focus,\n.downarrow:focus, .dropdown:focus {\n pointer-events: none; /* Causes second click to close */\n}\n.downarrow:focus {\n outline: 2px solid #8BF; /* Edge/IE can't do outline transparency */\n outline: 2px solid #48F8;\n}\n\n/* ---------------------------------------------- */\n/* Optional extra styling for combobox / dropdown */\n/* ---------------------------------------------- */\n*, *:before, *:after {\n /* See https://css-tricks.com/international-box-sizing-awareness-day/ */\n box-sizing: border-box; \n}\n.combobox > *:first-child {\n display: inline-block;\n width: 100%;\n box-sizing: border-box; /* so 100% includes border & padding */\n}\n/* `.combobox:focus-within { outline:...}` doesn't work properly \n in Firefox because the focus box is expanded to include the \n (possibly hidden) drop list. As a workaround, put focus box on \n the focused child. It is barely-visible so that it doesn't look\n TOO ugly if the child isn't the same size as the parent. It\n may be uglier if the first child is not styled as width:100% */\n.combobox > *:not(:last-child):focus {\n outline: 2px solid #48F8;\n}\n.combobox {\n margin: 5px; \n}\n function parentComboBox(el) {\n for (el = el.parentNode; el != null && Array.prototype.indexOf.call(el.classList, \"combobox\") <= -1;)\n el = el.parentNode;\n return el;\n}\n// Uses jQuery\n$(\".combobox.withtextlist > select\").change(function() { \n var textbox = parentComboBox(this).firstElementChild;\n textbox.value = this[this.selectedIndex].text;\n});\n$(\".combobox.withtextlist > select\").keypress(function(e) {\n if (e.keyCode == 13) // Enter pressed\n parentComboBox(this).firstElementChild.focus(); // Closes the popup\n});\n"
},
{
"answer_id": 60545075,
"author": "Alexey",
"author_id": 10862228,
"author_profile": "https://Stackoverflow.com/users/10862228",
"pm_score": -1,
"selected": false,
"text": "function editDropBox() {\n var cSelect = document.getElementById('changingList');\n\n var optionsSavehouse = [];\n if(cSelect != null) {\n var optionsArray = Array.from(cSelect.options);\n\n var arrayLength = optionsArray.length;\n for (var o = 0; o < arrayLength; o++) {\n var option = optionsArray[o];\n var oVal = option.value;\n\n if(oVal > 0) {\n var localParams = [];\n localParams.push(option.text);\n localParams.push(option.value);\n //localParams.push(option.selected); // if needed\n optionsSavehouse.push(localParams);\n }\n }\n }\n\n var hidden = (\"<input id='hidden_select_options' type='hidden' value='\" + JSON.stringify(optionsSavehouse) + \"' />\");\n\n var cSpan = document.getElementById('changingSpan');\n if(cSpan != null) {\n cSpan.innerHTML = (hidden + \"<input size='2' type='text' id='tempInput' name='fname' onchange='restoreDropBox()'>\");\n }\n}\n\nfunction restoreDropBox() {\n var cSpan = document.getElementById('changingSpan');\n var cInput = document.getElementById('tempInput');\n var hOptions = document.getElementById('hidden_select_options');\n\n if(cSpan != null) {\n\n var optionsArray = [];\n\n if(hOptions != null) {\n optionsArray = JSON.parse(hOptions.value);\n }\n\n var selectList = \"<select id='changingList'>\\n\";\n\n var arrayLength = optionsArray.length;\n for (var o = 0; o < arrayLength; o++) {\n var option = optionsArray[o];\n selectList += (\"<option value='\" + option[1] + \"'>\" + option[0] + \"</option>\\n\");\n }\n\n if(cInput != null) {\n selectList += (\"<option value='-1' selected>\" + cInput.value + \"</option>\\n\");\n }\n\n selectList += (\"<option value='-2' onclick='editDropBox()'>- Edit -</option>\\n</select>\");\n cSpan.innerHTML = selectList;\n }\n} <span id=\"changingSpan\">\n <select id=\"changingList\">\n <option value=\"1\">Apple</option>\n <option value=\"2\">Banana</option>\n <option value=\"3\">Cherry</option>\n <option value=\"4\">Dewberry</option>\n <option onclick=\"editDropBox()\" value=\"-2\">- Edit -</option>\n </select>\n</span>"
},
{
"answer_id": 71686476,
"author": "FRANK SERMEÑO",
"author_id": 18638521,
"author_profile": "https://Stackoverflow.com/users/18638521",
"pm_score": 0,
"selected": false,
"text": "<input type=\"murillo\" name=\"murillo\"/>\n <datalist id=\"null\">\n <option value=\"password\">null</option>\n <option value=\"email-address\">null</option>\n \n </datalist>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24028/"
] |
264,656
|
<p><code>getopt()</code> is not behaving as I expect for short options.</p>
<p>eg: Invoking the below program with a missing parameter:</p>
<p>Valid Case: <code>testopt -d dir -a action -b build</code></p>
<p>Error Case: <code>testopt -d -a action -b build</code></p>
<p>This did not throw any error as I was expecting an error message operand missing for <code>-d</code></p>
<ul>
<li>Is this a known bug? </li>
<li>If so, is there any standard fix available?</li>
</ul>
<p>My code:</p>
<pre><code>#include <unistd.h>
/* testopt.c */
/* Test program for testing getopt */
int main(int argc, char **argv)
{
int chr;
while ( ( chr = getopt(argc, argv, ":d:a:b:") ) != -1 )
{
switch(chr)
{
case 'a':
printf("Got a...\n");
break;
case 'b':
printf("Got b...\n");
break;
case 'd':
printf("Got d...\n");
break;
case ':':
printf("Missing operand for %c\n", optopt);
break;
case '?':
printf("Unknown option %c\n", optopt);
break;
}
}
printf("execution over\n");
return 0;
}
</code></pre>
|
[
{
"answer_id": 264665,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "getopt() ':' '?'"
},
{
"answer_id": 264684,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 3,
"selected": true,
"text": "getopt() -a -d testopt -a action -b build -d -d optarg"
},
{
"answer_id": 264789,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 0,
"selected": false,
"text": "$ ./a.out -d test\nGot d...\nexecution over\n\n$ ./a.out -d\nMissing operand for d\nexecution over\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18657/"
] |
264,668
|
<p>I had read that SEO is applicable for static website, which holding the information in the initial page itself. Is it possible to get search engines to index the dynamically added information?</p>
<p>I used AJAX for loading information. In this situation how can I optimize a site for search engines?</p>
|
[
{
"answer_id": 270887,
"author": "Michael Glenn",
"author_id": 9424,
"author_profile": "https://Stackoverflow.com/users/9424",
"pm_score": 0,
"selected": false,
"text": "<noscript>"
},
{
"answer_id": 3095701,
"author": "llazzaro",
"author_id": 127153,
"author_profile": "https://Stackoverflow.com/users/127153",
"pm_score": 0,
"selected": false,
"text": "www.example.com/level_one/level_two/page1.html,\nwww.example.com/level_one/level_two/page2.html,\n...\n www.example.com"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
264,676
|
<p>Is this possible? I had troubles with SVN clients not being able to access the repository with the following error message:</p>
<blockquote>
<p>Repository moved permanently to '<a href="http://svn.example.com/test/" rel="noreferrer">http://svn.example.com/test/</a>'; please relocate</p>
</blockquote>
<p>If I added the '/' to the end of the path I was trying to access, it just strips it off again, and shows the same error message. My configuration file looks like:</p>
<pre><code><VirtualHost *>
ServerName svn.example.com
# Normal VirtualHost stuff here
<Location /svn>
# Uncomment this to enable the repository
DAV svn
SVNParentPath /some/path/to/repositories
# Setup mod_authz_svn, etc, etc here
</Location>
</VirtualHost>
</code></pre>
<p>Note: This works. But if I change the Location to just <code>/</code> it stops working again with the error above. Is it possible to use the root directory, or am I missing something here? Firefox displays the repository listing fine when serving the repositories out of the root.</p>
<p>As someone else pointed out, this only seems to be an issue inside named virtual hosts... Anyone have any smart ideas why?</p>
|
[
{
"answer_id": 266987,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 1,
"selected": false,
"text": "/svn /repository_name # Rewrite / into /svn to avoid errors that seem to occur when using the root\n# for repositories.\nRewriteEngine On\n# Subdirectories that SHOULD be accessed directly, ie. trac\n# /svn should be here to avoid redirect loops\nRewriteCond %{REQUEST_URI} !^/(trac|svn)/\nRewriteRule ^/(.*)$ /svn/$1 [PT]\n"
},
{
"answer_id": 267029,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 0,
"selected": false,
"text": "This is working for me:\n\n<Location />\n DAV svn\n SVNPath /repository\n AuthType Basic\n AuthName \"Repository authentication\"\n AuthUserFile /repository/.svn-auth\n AuthzSVNAccessFile /repository/.svn-access\n Satisfy All\n Require valid-user\n</Location>\n"
},
{
"answer_id": 267309,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 2,
"selected": false,
"text": "<VirtualHost 127.0.0.1:80>\n<Location />\n DAV svn\n SVNPath /repository\n AuthType Basic\n AuthName \"Repository authentication\"\n AuthUserFile /repository/.svn-auth\n AuthzSVNAccessFile /repository/.svn-access\n Satisfy All\n Require valid-user\n</Location>\n</VirtualHost>\n"
},
{
"answer_id": 267338,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 1,
"selected": false,
"text": "<VirtualHost dave.test>\n<Location />\n DAV svn\n SVNPath /repository\n AuthType Basic\n AuthName \"Repository authentication\"\n AuthUserFile /repository/.svn-auth\n AuthzSVNAccessFile /repository/.svn-access\n Satisfy All\n Require valid-user\n</Location>\n</VirtualHost>\n svn ls http://dave.test svn: Server sent unexpected return value (405 Method Not Allowed) in response to\nPROPFIND request for '/'\n"
},
{
"answer_id": 374490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<VirtualHost *:80>\n ServerAdmin webmaster@example.com\n ServerName svn.example.com\n ServerAlias svn\n DocumentRoot /home/svn.example.com/public_html\n\n RewriteEngine On\n\n RewriteCond %{REQUEST_URI} ^/svn$\n RewriteRule .* /svn/ [PT]\n\n RewriteCond %{REQUEST_URI} !^/svn/\n RewriteRule ^/(.*)$ /svn/$1 [PT]\n\n <Location /svn>\n DAV svn\n SVNParentPath /home/svn.example.com/public_html\n SVNListParentPath on\n </Location>\n\n <LocationMatch /svn/.+>\n AuthzSVNAccessFile /home/svn.example.com/support/access.cfg\n\n AuthType Basic\n AuthName \"Subversion\"\n AuthUserFile /home/svn.example.com/.htpasswd\n Require valid-user\n </LocationMatch>\n</VirtualHost>\n RewriteCond %{REQUEST_URI} ^/svn$\nRewriteRule .* /svn/ [PT]\n"
},
{
"answer_id": 374602,
"author": "azkotoki",
"author_id": 28581,
"author_profile": "https://Stackoverflow.com/users/28581",
"pm_score": 4,
"selected": true,
"text": "DocumentRoot SVNParentPath <VirtualHost *:80>\n DocumentRoot /home/svn.example.com/docroot\n\n <Location />\n SVNParentPath /home/svn.example.com/svnroot\n SVNListParentPath on\n </Location>\n</VirtualHost>\n"
},
{
"answer_id": 387579,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "ReWriteEngine On\nRewriteCond %{REQUEST_URI} ^/svn$\nRewriteRule .* /svn/ [PT]\n\n<Location /svn>\n DAV svn\n SVNParentPath /svn/repos\n SVNListParentPath on\n\n # Limit write permission to list of valid users.\n <LimitExcept GET PROPFIND OPTIONS REPORT>\n AuthType Basic\n AuthName \"Subversion\"\n AuthUserFile /svn/authfiles/svn-htpasswd\n AuthzSVNAccessFile /svn/authfiles/svn-access.conf\n Require valid-user\n </LimitExcept>\n</Location>\n\n<LocationMatch /svn/myProject/>\n AuthType Basic\n AuthName \"Subversion (private)\"\n AuthUserFile /svn/authfiles/svn-htpasswd\n AuthzSVNAccessFile /svn/authfiles/svn-access.conf\n Require user user1 user2 user3...\n</LocationMatch>\n"
},
{
"answer_id": 1943920,
"author": "yurique",
"author_id": 236534,
"author_profile": "https://Stackoverflow.com/users/236534",
"pm_score": 2,
"selected": false,
"text": "<VirtualHost *>\n ServerName svn.example.com\n ErrorLog /var/log/apache2/svn.example.com-error_log\n TransferLog /var/log/apache2/svn.example.com-access_log\n #\n # Do not set DocumentRoot. It is not needed here and just causes trouble.\n #\n # Map the error documents back to their defaults.\n # Otherwise mod_dav_svn tries to find a \"error\" repository.\n #\n ErrorDocument 400 default\n ErrorDocument 401 default\n ErrorDocument 403 default\n ErrorDocument 404 default\n ErrorDocument 405 default\n ErrorDocument 408 default\n ErrorDocument 410 default\n ErrorDocument 411 default\n ErrorDocument 412 default\n ErrorDocument 413 default\n ErrorDocument 414 default\n ErrorDocument 415 default\n ErrorDocument 500 default\n ErrorDocument 501 default\n ErrorDocument 502 default\n ErrorDocument 503 default\n #\n <Location />\n...\n </Location>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15537/"
] |
264,680
|
<p>I have a bunch of JUnit 3 classes which extend TestCase and would like to automatically migrate them to be JUnit4 tests with annotations such as <code>@Before</code>, <code>@After</code>, <code>@Test</code>, etc.<br>
Any tool out there to do this in a big batch run?</p>
|
[
{
"answer_id": 677356,
"author": "guerda",
"author_id": 32043,
"author_profile": "https://Stackoverflow.com/users/32043",
"pm_score": 7,
"selected": true,
"text": "import org.junit.After;\nimport org.junit.Before;\nimport org.junit.Test;`\n import junit.framework.TestCase; test* public void test @Test setUp() @Override\nprotected void setUp() throws Exception { }\n @Before\npublic void setUp() throws Exception { }\n tearDown() @Override\nprotected void tearDown() throws Exception { }\n @After\npublic void tearDown() throws Exception { }\n extends TestCase \" extends TestCase\"\n suite() @RunWithClass suite() @RunWith(Suite.class)\n@Suite.SuiteClasses({\n TestDog.class\n TestCat.class\n TestAardvark.class\n})\n"
},
{
"answer_id": 3130393,
"author": "Designpattern",
"author_id": 377779,
"author_profile": "https://Stackoverflow.com/users/377779",
"pm_score": 1,
"selected": false,
"text": "public void test\n@Test\\n public void test\n\n@Override\\n.*protected void onSetUp\n@Before\\n protected void onSetUp\n\n@Override\\n.*protected void onTearDown\n@After\\n protected void onTearDown\n"
},
{
"answer_id": 4535170,
"author": "Geoffrey De Smet",
"author_id": 472109,
"author_profile": "https://Stackoverflow.com/users/472109",
"pm_score": 5,
"selected": false,
"text": "// Add @Test\nReplace:\n^[ \\t]+(public +void +test)\nWith:\n @Test\\n $1\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Remove double @Test's on already @Test annotated files\nReplace:\n^[ \\t]+@Test\\n[ \\t]+@Test\nWith:\n @Test\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove all empty setUp's\nReplace:\n^[ \\*]+((public|protected) +)?void +setUp\\(\\)[^\\{]*\\{\\s*(super\\.setUp\\(\\);)?\\s*\\}\\n([ \\t]*\\n)?\nWith nothing\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Add @Before to all setUp's\nReplace:\n^([ \\t]+@Override\\n)?[ \\t]+((public|protected) +)?(void +setUp\\(\\))\nWith:\n @Before\\n public void setUp()\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Remove double @Before's on already @Before annotated files\nReplace:\n^[ \\t]+@Before\\n[ \\t]+@Before\nWith:\n @Before\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove all empty tearDown's\nReplace:\n^[ \\*]+((public|protected) +)?void +tearDown\\(\\)[^\\{]*\\{\\s*(super\\.tearDown\\(\\);)?\\s*\\}\\n([ \\t]*\\n)?\nWith nothing\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Add @After to all tearDown's\nReplace:\n^([ \\t]+@Override\\n)?[ \\t]+((public|protected) +)?(void +tearDown\\(\\))\nWith:\n @After\\n public void tearDown()\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n// Remove double @After's on already @After annotated files\nReplace:\n^[ \\t]+@After\\n[ \\t]+@After\nWith:\n @After\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove old imports, add new imports\nReplace:\n^([ \\t]*import[ \\t]+junit\\.framework\\.Assert;\\n)?[ \\t]*import[ \\t]+junit\\.framework\\.TestCase;\nWith:\nimport org.junit.After;\\nimport org.junit.Before;\\nimport org.junit.Test;\\nimport static org.junit.Assert.*;\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n// Remove all extends TestCase\nReplace:\n[ \\t]+extends[ \\t]+TestCase[ \\t]+\\{\nWith:\n {\nRegular Expression: on\nCase sensitive: on\nFile name filter:\n*Test.java\n\n\n\n// Look for import junit.framework;\nFind:\nimport junit\\.framework\nManually fix\nRegular Expression: on\nCase sensitive: on\n\n\n// Look for ignored tests (FIXME, disabled, ...)\nFind:\npublic[ \\t]+void[ \\t]+\\w+test\nManually fix\nRegular Expression: on\nCase sensitive: on\n\n\n// Look for dummy/empty tests\nFind:\npublic[ \\t]+void[ \\t]+test[\\w\\d]*\\(\\s*\\)\\s*\\{\\s*(//[^\\n]*)?\\s*\\}\nManually fix\nRegular Expression: on\nCase sensitive: on\n"
},
{
"answer_id": 16731352,
"author": "Francisco",
"author_id": 766289,
"author_profile": "https://Stackoverflow.com/users/766289",
"pm_score": 3,
"selected": false,
"text": "TestCase.setUp() TestCase.tearDown() TestCase(String) TestCase.assert* Assert junit.framework org.junit"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
264,681
|
<p>We have a Java program run as <strong>root</strong> on Unix, that therefore can read for example the content of the folders <code>/home/user1</code> and <code>/home/user2</code>. However, if the Unix user "user1" is logged in in our application, he should not be able to access "/home/user2" data.
We would like to use directly the Unix rights and not recreate all the permissions in our application !
So, could we...</p>
<ol>
<li>try to change the UID of our
program depending on the user logged
in ? Sounds difficult, and each file
access is in different threads so
the UID would be different on each
thread of our program... </li>
<li>use JNI to read permissions of
"<code>/home/user2</code>"...And then determine
if user1 has sufficient permissions
on "<code>/home/user2</code>" ? (how ?).</li>
</ol>
|
[
{
"answer_id": 264751,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 2,
"selected": false,
"text": "setfsuid() setfsgid()"
},
{
"answer_id": 264754,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 0,
"selected": false,
"text": "setuid setuid setuid"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/264681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19281/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.