qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
49,596 |
<p>What is the difference between</p>
<pre><code>char str1[32] = "\0";
</code></pre>
<p>and </p>
<pre><code>char str2[32] = "";
</code></pre>
|
[
{
"answer_id": 49620,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 6,
"selected": true,
"text": "char a[] = \"a\\0\";\nchar b[] = \"a\";\n\nprintf(\"%i %i\\n\", sizeof(a), sizeof(b));\n 3 2\n"
},
{
"answer_id": 59445,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "char str1[32] = \"\\0\";\nchar str2[32] = \"\";\n char str1[32] = {'\\0','\\0'};\nchar str2[32] = {'\\0'};\n char str1[32] = {'\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0'};\nchar str2[32] = {'\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0',\n '\\0','\\0','\\0','\\0','\\0','\\0','\\0','\\0'};\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] |
49,599 |
<p>Jquery has a great language construct that looks like this:</p>
<pre><code>$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</code></pre>
<p>As you might guess this, once the document has loaded, binds a custom function to the onClick event of all <strong><em>a</em></strong> tags.</p>
<p>The question is, how can I achieve this same kind of behavior in Prototype?</p>
|
[
{
"answer_id": 49618,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 1,
"selected": false,
"text": "Event.observe(window, 'load', function() { \n Event.observe(element, 'click', function() { \n alert(\"Hello World!\");\n });\n});\n"
},
{
"answer_id": 49654,
"author": "erlando",
"author_id": 4192,
"author_profile": "https://Stackoverflow.com/users/4192",
"pm_score": 4,
"selected": true,
"text": "document.observe(\"dom:loaded\", function() {\n $$('a').each(function(elem) {\n elem.observe(\"click\", function() { alert(\"Hello World\"); });\n });\n});\n"
},
{
"answer_id": 173410,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "$(document).observe('dom:loaded', function() {\n $$('a').invoke('observe', 'click', function() {\n alert('Hello world!');\n });\n});\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
49,601 |
<p>I'm trying to find a source control for my own personal use that's as simple as possible. The main feature I need is being able to read/pull a past version of my code. I am the only developer. I've looked at a lot of different version control systems, but they all seem way more complicated than I need. I need one that's simple, runs under Windows, and doesn't expose itself to the network.</p>
<p>Specifically, the version control system should <em>not</em> require exposing an HTTP interface, it should interact with the local filesystem only. It just needs to be a version control system geared for one guy and one guy only. Graphical UI is a plus.</p>
<p>Does anyone know of software would satisfy what I'm looking for?</p>
<p>Thanks!</p>
<p>-Mike</p>
|
[
{
"answer_id": 49750,
"author": "Bmore",
"author_id": 5211,
"author_profile": "https://Stackoverflow.com/users/5211",
"pm_score": 2,
"selected": false,
"text": "$ bzr commit -m \"Added first line of text\" bzr update"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5198/"
] |
49,602 |
<p>In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" <code>rownum</code> column. Consider the following example, which will return, at most, 10 rows.</p>
<pre>SELECT * FROM all_tables WHERE rownum <= 10</pre>
<p>Is there a simple, generic way to do something similar in Ingres?</p>
|
[
{
"answer_id": 49604,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 4,
"selected": true,
"text": "Select First 10 * from myTable\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5193/"
] |
49,630 |
<p>I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.</p>
<p>The html looks like this:</p>
<pre><code><div onmouseover="jsHoverIn('1')"
onmouseout="jsHoverOut('1')">
<div id="image1" />
<div id="text1" style="display: none;">
<p>some content</p>
<p>some more content</p>
</div>
</div>
</code></pre>
<p>And the javascript (It uses scriptaculous):</p>
<pre><code>function jsHoverIn(id) {
if(!visible[id]) {
new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } });
visible[id] = true;
}
}
function jsHoverOut (id) {
var scope = Effect.Queues.get(id);
scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } });
visible[id] = false;
}
</code></pre>
<p>This seems really simple, but i just cant wrap my head around it.</p>
|
[
{
"answer_id": 49645,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": -1,
"selected": false,
"text": "if (bWasHoverIn){\n ...\n}\n"
},
{
"answer_id": 49687,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 4,
"selected": true,
"text": "position: relative;\n position: absolute;\ntop: 0;\nbottom: 0;\nleft: 0;\nright: 0;\n"
},
{
"answer_id": 196838,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 2,
"selected": false,
"text": "mouseenter mouseleave // Observe mouseEnterLeave on mouseover/mouseout\nvar mouseEnterLeave = function(e) {\n var rel = e.relatedTarget, cur = e.currentTarget;\n if (rel && rel.nodeType == 3) {\n rel = rel.parentNode;\n }\n if(\n // Outside window\n rel == undefined ||\n // Firefox/other XUL app chrome\n (rel.tagName && rel.tagName.match(/^xul\\:/i)) ||\n // Some external element\n (rel && rel != cur && rel.descendantOf && !rel.descendantOf(cur))\n ) {\n e.currentTarget.fire('mouse:' + this, e);\n return;\n }\n};\n$(yourDiv).observe('mouseover', mouseEnterLeave.bind('enter'));\n$(yourDiv).observe('mouseout', mouseEnterLeave.bind('leave'));\n\n// Use mouse:enter and mouse:leave for your events\n$(yourDiv).observe(!!Prototype.Browser.IE ? 'mouseenter' : 'mouse:enter', yourObserver);\n$(yourDiv).observe(!!Prototype.Browser.IE ? 'mouseleave' : 'mouse:leave', yourObserver);\n mouseenter mouseleave"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550/"
] |
49,652 |
<p>Can someone suggest some good automated test suite framework for Perl?</p>
|
[
{
"answer_id": 70367,
"author": "Ovid",
"author_id": 8003,
"author_profile": "https://Stackoverflow.com/users/8003",
"pm_score": 6,
"selected": true,
"text": "use Test::More tests => 2;\n\nis 3, 3, 'basic equality should work';\nok !0, '... and zero should be false';\n prove --verbose t/numbers.t\n prove --verbose -r t/\n"
},
{
"answer_id": 72448,
"author": "Peter Stuifzand",
"author_id": 1633,
"author_profile": "https://Stackoverflow.com/users/1633",
"pm_score": 0,
"selected": false,
"text": "prove prove prove -r -Ilib t\n lib"
},
{
"answer_id": 72545,
"author": "Darren Meyer",
"author_id": 7826,
"author_profile": "https://Stackoverflow.com/users/7826",
"pm_score": 1,
"selected": false,
"text": " prove t/*.t\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] |
49,662 |
<p>My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers.</p>
<p>One model we've seen is tying a license to a MAC address so the software will only work on one machine.</p>
<p>What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions?</p>
|
[
{
"answer_id": 49666,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": true,
"text": "# License key for XYZZY\nexpiry-date=2009-01-01\nother-info=blah\nkey=[md5 has of MAC address, expiry date, other-info]\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5106/"
] |
49,668 |
<p>I need to find out time taken by a function in my application. Application is a MS VIsual Studio 2005 solution, all C code. </p>
<p>I used thw windows API GetLocalTime(SYSTEMTIME *) to get the current system time before and after the function call which I want to measure time of.
But this has shortcoming that it lowest resolution is only 1msec. Nothing below that. So I cannot get any time granularity in micro seconds. </p>
<p>I know that time() which gives the time elapsed since the epoch time, also has resolution of 1msec (No microseconds) </p>
<p>1.) Is there any other Windows API which gives time in microseconds which I can use to measure the time consumed by my function?</p>
<p>-AD</p>
|
[
{
"answer_id": 49767,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "function QueryPerfCounterAsUS: int64; \nbegin\n if QueryPerformanceCounter(Result) and\n QueryPerformanceFrequency(perfFreq)\n then\n Result := Round(Result / perfFreq * 1000000);\n else\n Result := 0;\nend;\n function CPUGetTick: int64;\nasm\n dw 310Fh // rdtsc\nend;\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
49,699 |
<p>I have been looking at the new <a href="http://cappuccino.org/" rel="noreferrer">Objective-J / Cappuccino</a> javascript framework from <a href="http://280north.com/" rel="noreferrer">280North</a>. They provide plug-ins for SubEthaEdit and TextMate to handle syntax highlighting, but I primarily use vi. Does anyone know of a way to get Objective-J syntax highlighting in vi, or a good way to convert whatever format the other two editors use?</p>
|
[
{
"answer_id": 49769,
"author": "Claes Mogren",
"author_id": 4992,
"author_profile": "https://Stackoverflow.com/users/4992",
"pm_score": 1,
"selected": false,
"text": " augroup objective-j\n au! BufRead,BufNewFile *.j set filetype=objective-j\n au! Syntax objective-j source /usr/share/vim/vim71/syntax/javascript.vim\n augroup END\n"
},
{
"answer_id": 613550,
"author": "bootload",
"author_id": 2092,
"author_profile": "https://Stackoverflow.com/users/2092",
"pm_score": 3,
"selected": false,
"text": "cd Tools/ sh install-tools cp Tools/Editors/objj.vim /usr/share/vim/vim71/syntax/ sudo vim /usr/share/vim/vim71/synmenu.vim an 50.70.465 &Syntax.Me-NO.Objective\\ J :cal SetSyn(\"objj\")<CR> :wq! sudo vim /usr/share/vim/vim7.1/filetype.vim \"\" Objective J au BufNewFile,BufRead *.j setf objj"
},
{
"answer_id": 3694887,
"author": "Rafael Bugajewski",
"author_id": 133166,
"author_profile": "https://Stackoverflow.com/users/133166",
"pm_score": 3,
"selected": false,
"text": "~/.vim/syntax/ au BufNewFile,BufRead *.j setf objj ~/.vim/filetype.vim ~/.vimrc filetype plugin on"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3078/"
] |
49,724 |
<p>Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?</p>
<p>I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).</p>
<p>Any tips or resources would be appreciated.</p>
<p><strong>Edit</strong>: thanks to everyone, <a href="https://stackoverflow.com/users/3655/aardvark">Aardvark</a>'s answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.</p>
<pre><code>using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
...
public List<string> GetMacrosFromDoc()
{
Document doc = GetWordDoc(@"C:\Temp\test.docm");
List<string> macros = new List<string>();
VBProject prj;
CodeModule code;
string composedFile;
prj = doc.VBProject;
foreach (VBComponent comp in prj.VBComponents)
{
code = comp.CodeModule;
// Put the name of the code module at the top
composedFile = comp.Name + Environment.NewLine;
// Loop through the (1-indexed) lines
for (int i = 0; i < code.CountOfLines; i++)
{
composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
}
// Add the macro to the list
macros.Add(composedFile);
}
CloseDoc(doc);
return macros;
}
</code></pre>
|
[
{
"answer_id": 49773,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 5,
"selected": true,
"text": "Sub GetCode()\n\n Dim prj As VBProject\n Dim comp As VBComponent\n Dim code As CodeModule\n Dim composedFile As String\n Dim i As Integer\n\n Set prj = ThisDocument.VBProject\n For Each comp In prj.VBComponents\n Set code = comp.CodeModule\n\n composedFile = comp.Name & vbNewLine\n\n For i = 1 To code.CountOfLines\n composedFile = composedFile & code.Lines(i, 1) & vbNewLine\n Next\n\n MsgBox composedFile\n Next\n\nEnd Sub\n"
},
{
"answer_id": 49796,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 5,
"selected": false,
"text": "Sub ExportCode()\n\n If Not CanAccessVBOM Then Exit Sub ' Exit if access to VB object model is not allowed\n If (ThisWorkbook.VBProject.VBE.ActiveWindow Is Nothing) Then\n Exit Sub ' Exit if VBA window is not open\n End If\n Dim comp As VBComponent\n Dim codeFolder As String\n\n codeFolder = CombinePaths(GetWorkbookPath, \"Code\")\n On Error Resume Next\n MkDir codeFolder\n On Error GoTo 0\n Dim FileName As String\n\n For Each comp In ThisWorkbook.VBProject.VBComponents\n Select Case comp.Type\n Case vbext_ct_ClassModule\n FileName = CombinePaths(codeFolder, comp.Name & \".cls\")\n DeleteFile FileName\n comp.Export FileName\n Case vbext_ct_StdModule\n FileName = CombinePaths(codeFolder, comp.Name & \".bas\")\n DeleteFile FileName\n comp.Export FileName\n Case vbext_ct_MSForm\n FileName = CombinePaths(codeFolder, comp.Name & \".frm\")\n DeleteFile FileName\n comp.Export FileName\n Case vbext_ct_Document\n FileName = CombinePaths(codeFolder, comp.Name & \".cls\")\n DeleteFile FileName\n comp.Export FileName\n End Select\n Next\n\nEnd Sub\nFunction CanAccessVBOM() As Boolean\n ' Check resgistry to see if we can access the VB object model\n Dim wsh As Object\n Dim str1 As String\n Dim AccessVBOM As Long\n\n Set wsh = CreateObject(\"WScript.Shell\")\n str1 = \"HKEY_CURRENT_USER\\Software\\Microsoft\\Office\\\" & _\n Application.Version & \"\\Excel\\Security\\AccessVBOM\"\n On Error Resume Next\n AccessVBOM = wsh.RegRead(str1)\n Set wsh = Nothing\n CanAccessVBOM = (AccessVBOM = 1)\nEnd Function\n\n\nSub DeleteFile(FileName As String)\n On Error Resume Next\n Kill FileName\nEnd Sub\n\nFunction GetWorkbookPath() As String\n Dim fullName As String\n Dim wrkbookName As String\n Dim pos As Long\n\n wrkbookName = ThisWorkbook.Name\n fullName = ThisWorkbook.fullName\n\n pos = InStr(1, fullName, wrkbookName, vbTextCompare)\n\n GetWorkbookPath = Left$(fullName, pos - 1)\nEnd Function\n\nFunction CombinePaths(ByVal Path1 As String, ByVal Path2 As String) As String\n If Not EndsWith(Path1, \"\\\") Then\n Path1 = Path1 & \"\\\"\n End If\n CombinePaths = Path1 & Path2\nEnd Function\n\nFunction EndsWith(ByVal InString As String, ByVal TestString As String) As Boolean\n EndsWith = (Right$(InString, Len(TestString)) = TestString)\nEnd Function\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194/"
] |
49,737 |
<p>Recently I was talking to a co-worker about C++ and lamented that there was no way to take a string with the name of a class field and extract the field with that name; in other words, it lacks reflection. He gave me a baffled look and asked when anyone would ever need to do such a thing.</p>
<p>Off the top of my head I didn't have a good answer for him, other than "hey, I need to do it right now". So I sat down and came up with a list of some of the things I've actually done with reflection in various languages. Unfortunately, most of my examples come from my web programming in Python, and I was hoping that the people here would have more examples. Here's the list I came up with:</p>
<ol>
<li><p>Given a config file with lines like<br>
x = "Hello World!"<br>
y = 5.0<br>
dynamically set the fields of some <code>config</code> object equal to the values in that file. (This was what I wished I could do in C++, but actually couldn't do.)</p></li>
<li><p>When sorting a list of objects, sort based on an arbitrary attribute given that attribute's name from a config file or web request.</p></li>
<li><p>When writing software that uses a network protocol, reflection lets you call methods based on string values from that protocol. For example, I wrote an IRC bot that would translate<br>
<code>!some_command arg1 arg2</code><br>
into a method call <code>actions.some_command(arg1, arg2)</code> and print whatever that function returned back to the IRC channel.</p></li>
<li><p>When using Python's __getattr__ function (which is sort of like method_missing in Ruby/Smalltalk) I was working with a class with a whole lot of statistics, such as late_total. For every statistic, I wanted to be able to add _percent to get that statistic as a percentage of the total things I was counting (for example, stats.late_total_percent). Reflection made this very easy.</p></li>
</ol>
<p>So can anyone here give any examples from their own programming experiences of times when reflection has been helpful? The next time a co-worker asks me why I'd "ever want to do something like that" I'd like to be more prepared.</p>
|
[
{
"answer_id": 49760,
"author": "jrcs3",
"author_id": 3819,
"author_profile": "https://Stackoverflow.com/users/3819",
"pm_score": 2,
"selected": false,
"text": "string src = MethodInfo.GetCurrentMethod().ToString();\nstring msg = \"Big Mistake\";\nException newEx = new Exception(msg, ex);\nnewEx.Source = src;\n string src = \"MyMethod\";\nstring msg = \"Big MistakeA\";\nException newEx = new Exception(msg, ex);\nnewEx.Source = src;\n"
},
{
"answer_id": 109923,
"author": "davenpcj",
"author_id": 4777,
"author_profile": "https://Stackoverflow.com/users/4777",
"pm_score": 1,
"selected": false,
"text": "#define GetX() Get(\"X\")"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
49,757 |
<p>So if I have a method of parsing a text file and returning a <strong>list</strong> <em>of a</em> <strong>list</strong> <em>of</em> <strong>key value pairs</strong>, and want to create objects from the kvps returned (each list of kvps represents a different object), what would be the best method?</p>
<p>The first method that pops into mind is pretty simple, just keep a list of keywords:</p>
<pre><code>private const string NAME = "name";
private const string PREFIX = "prefix";
</code></pre>
<p>and check against the keys I get for the constants I want, defined above. This is a fairly core piece of the project I'm working on though, so I want to do it well; does anyone have any more robust suggestions (not saying there's anything inherently un-robust about the above method - I'm just asking around)?</p>
<h1>Edit:</h1>
<p>More details have been asked for. I'm working on a little game in my spare time, and I am building up the game world with configuration files. There are four - one defines all creatures, another defines all areas (and their locations in a map), another all objects, and a final one defines various configuration options and things that don't fit else where. With the first three configuration files, I will be creating objects based on the content of the files - it will be quite text-heavy, so there will be a lot of strings, things like names, plurals, prefixes - that sort of thing. The configuration values are all like so:</p>
<pre><code>-
key: value
key: value
-
key: value
key: value
-
</code></pre>
<p>Where the '-' line denotes a new section/object.</p>
|
[
{
"answer_id": 49782,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "public class DataObject {\n [Column(\"name\")]\n public string Name { get; set; }\n\n [Column(\"prefix\")]\n public string Prefix { get; set; }\n}\n"
},
{
"answer_id": 49785,
"author": "Argelbargel",
"author_id": 2992,
"author_profile": "https://Stackoverflow.com/users/2992",
"pm_score": 2,
"selected": false,
"text": "\nclass RestrictedKVDataStore {\n const ALLOWED_KEYS = new Collection('name', 'prefix');\n Map data = new Map();\n\n void put(String key, Object value) {\n if (ALLOWED_KEYS.contains(key))\n data.put(key, value)\n }\n\n Object get(String key) {\n return data.get(key);\n }\n}\n"
},
{
"answer_id": 49793,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "private class Factory {\n\n public static IConfigurationObject Factory(List<string> keyValuePair) {\n\n switch (keyValuePair[0]) {\n\n case \"x\":\n return new x(keyValuePair[1]);\n break;\n /* etc. */\n default:\n throw new ArgumentException(\"Wrong parameter in the file\");\n }\n\n }\n\n}\n"
},
{
"answer_id": 49899,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 1,
"selected": false,
"text": "List<List<KeyValuePair<String,String>>> itemConfig = \n new List<List<KeyValuePair<String,String>>>();\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] |
49,790 |
<p>In my specific example, I'm dealing with a drop-down, e.g.:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="foo" id="bar">
<option disabled="disabled" selected="selected">Select an item:</option>
<option>an item</option>
<option>another item</option>
</select></code></pre>
</div>
</div>
</p>
<p>Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected.</p>
<p><strong>Update:</strong> To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs <code>onchange()</code>. This is <em>fairly</em> well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out <code>onchange</code> drop downs altogether, or should the "select..." option be selectable, just with no effect?</p>
|
[
{
"answer_id": 49814,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 2,
"selected": false,
"text": "<option>"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] |
49,799 |
<p>I am sure a responsive UI is something that everyone strives for and the reccomended way to do stuff is to use the BackgroundWorker for this. </p>
<p>Do you find it easy to work with ? Do you use it often ? Or do you have your own frameworks for lengthy tasks and reporting process.</p>
<p>I have found that I am using it quite a lot and even using its delegates wherever I need some sort of progress reporting.</p>
|
[
{
"answer_id": 49836,
"author": "DonkeyMaster",
"author_id": 5178,
"author_profile": "https://Stackoverflow.com/users/5178",
"pm_score": 3,
"selected": true,
"text": "void ThreadStart()"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4694/"
] |
49,806 |
<p>In my application I have a window which I popup with small messages on it (think similar to tooltip). This window uses the layered attributes to draw alpha backgrounds etc.</p>
<p>If I have several of these windows open at once, and I click one with my mouse, when they disappear they cause my application to lose focus (it switches focus to the app behind the current one).</p>
<p>How do I stop any interaction in my window?</p>
|
[
{
"answer_id": 49836,
"author": "DonkeyMaster",
"author_id": 5178,
"author_profile": "https://Stackoverflow.com/users/5178",
"pm_score": 3,
"selected": true,
"text": "void ThreadStart()"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/986/"
] |
49,824 |
<p>Besides the dynamic nature of Python (and the syntax), what are some of the major features of the Python language that Java doesn't have, and vice versa?</p>
|
[
{
"answer_id": 49837,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 3,
"selected": false,
"text": ";"
},
{
"answer_id": 49953,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 7,
"selected": true,
"text": "[line.replace(\"spam\",\"eggs\") for line in open(\"somefile.txt\") if line.startswith(\"nee\")] people.sort(key=lambda p: p.age) Array.sort Student(name=\"Eli\", age=25) spam, eggs = nee() Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(\"test.xml\"); doc = parse(\"test.xml\")"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223/"
] |
49,883 |
<p>Say I have this given XML file:</p>
<pre><code><root>
<node>x</node>
<node>y</node>
<node>a</node>
</root>
</code></pre>
<p>And I want the following to be displayed:</p>
<pre><code>ayx
</code></pre>
<p>Using something similar to:</p>
<pre><code><xsl:template match="/">
<xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
</code></pre>
|
[
{
"answer_id": 49887,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 2,
"selected": false,
"text": "xsl:sort data-type=\"number\" <xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort \n select=\"position()\" \n order=\"descending\" \n data-type=\"number\"/>\n </xsl:apply-templates>\n</xsl:template>\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n"
},
{
"answer_id": 49893,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort select=\"position()\" data-type=\"number\" order=\"descending\"/>\n </xsl:apply-templates>\n</xsl:template>\n\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n"
},
{
"answer_id": 50015246,
"author": "imran",
"author_id": 9665536,
"author_profile": "https://Stackoverflow.com/users/9665536",
"pm_score": 0,
"selected": false,
"text": "<xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node[3]\"/>\n <xsl:apply-templates select=\"root/node[2]\"/>\n <xsl:apply-templates select=\"root/node[1]\"/>\n </xsl:template>\n <xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n </xsl:template>\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] |
49,890 |
<p>I created a few mediawiki custom tags, using the guide found here</p>
<p><a href="http://www.mediawiki.org/wiki/Manual:Tag_extensions" rel="nofollow noreferrer">http://www.mediawiki.org/wiki/Manual:Tag_extensions</a></p>
<p>I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page.</p>
<p>Any Ideas?</p>
<pre><code>if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
$wgHooks['ParserFirstCallInit'][] = 'tagregister';
} else { // Otherwise do things the old fashioned way
$wgExtensionFunctions[] = 'tagregister';
}
function tagregister(){
global $wgParser;
$wgParser->setHook('tag1','tag1func');
$wgParser->setHook('tag2','tag2func');
return true;
}
function tag1func($input,$params)
{
return "It called me";
}
function tag2func($input,$params)
{
return "It called me -- 2";
}
</code></pre>
<p>Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior.</p>
|
[
{
"answer_id": 49887,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 2,
"selected": false,
"text": "xsl:sort data-type=\"number\" <xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort \n select=\"position()\" \n order=\"descending\" \n data-type=\"number\"/>\n </xsl:apply-templates>\n</xsl:template>\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n"
},
{
"answer_id": 49893,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 6,
"selected": true,
"text": "<xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node\">\n <xsl:sort select=\"position()\" data-type=\"number\" order=\"descending\"/>\n </xsl:apply-templates>\n</xsl:template>\n\n<xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n</xsl:template>\n"
},
{
"answer_id": 50015246,
"author": "imran",
"author_id": 9665536,
"author_profile": "https://Stackoverflow.com/users/9665536",
"pm_score": 0,
"selected": false,
"text": "<xsl:template match=\"/\">\n <xsl:apply-templates select=\"root/node[3]\"/>\n <xsl:apply-templates select=\"root/node[2]\"/>\n <xsl:apply-templates select=\"root/node[1]\"/>\n </xsl:template>\n <xsl:template match=\"node\">\n <xsl:value-of select=\".\"/>\n </xsl:template>\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] |
49,896 |
<p>When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router?</p>
<p>The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable. </p>
|
[
{
"answer_id": 49945,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 0,
"selected": false,
"text": "#!/bin/bash\n\nssh-agent sh -c 'ssh-add < /dev/null && bash'\n scp file_to_send.txt your.domain.name:~/\n"
},
{
"answer_id": 49976,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 3,
"selected": false,
"text": "zyxel.png antti@local:~$ zssh remote\nPress ^@ (C-Space) to enter file transfer mode, then ? for help\n...\nantti@remote:~$ sz zyxel.png\n**B00000000000000\n^@\nzssh > rz\nReceiving: zyxel.png\nBytes received: 104036/ 104036 BPS:16059729\n\nTransfer complete\nantti@remote:~$ \n"
},
{
"answer_id": 74866,
"author": "Nick",
"author_id": 5222,
"author_profile": "https://Stackoverflow.com/users/5222",
"pm_score": 1,
"selected": true,
"text": "function grabfrom() { ssh -R 2202:127.0.0.1:22 ${@}; };\nfunction grab() { scp -P 2202 $@ [email protected]:~; };\n localhost% grabfrom remoteuser@remotehost\npassword: <remote password goes here>\nremotehost% grab somefile1 somefile2 *.txt\npassword: <local password goes here>\n"
},
{
"answer_id": 8415063,
"author": "aculich",
"author_id": 462302,
"author_profile": "https://Stackoverflow.com/users/462302",
"pm_score": 2,
"selected": false,
"text": "local> remote> ssh> local> ssh username@remote\nremote> ~C\nssh> -L6666:localhost:6666\nremote> nc -l 6666 < /etc/passwd\nremote> ~^Z\n[suspend ssh]\n[1]+ Stopped ssh username@remote\nlocal> (sleep 1; nc localhost 6666 > /tmp/file) & fg\n[2] 17357\nssh username@remote\nremote> exit\n[2]- Done ( sleep 1; nc localhost 6666 > /tmp/file )\nlocal> cat /tmp/file\nroot:x:0:0:root:/root:/bin/bash\nbin:x:1:1:bin:/bin:/sbin/nologin\ndaemon:x:2:2:daemon:/sbin:/sbin/nologin\n...\n ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys local> ssh username@remote\nremote> ~C\nssh> -R5555:localhost:5555\nremote> ~^Z\n[suspend ssh]\n[1]+ Stopped ssh username@remote\nlocal> nc -l 5555 < ~/.ssh/id_rsa.pub &\n[2] 26607\nlocal> fg\nssh username@remote\nremote> nc localhost 5555 >> ~/.ssh/authorized_keys\nremote> cat ~/.ssh/authorized_keys\nssh-rsa AAAAB3NzaC1yc2ZQQQQBIwAAAQEAsgaVp8mnWVvpGKhfgwHTuOObyfYSe8iFvksH6BGWfMgy8poM2+5sTL6FHI7k0MXmfd7p4rzOL2R4q9yjG+Hl2PShjkjAVb32Ss5ZZ3BxHpk30+0HackAHVqPEJERvZvqC3W2s4aKU7ae4WaG1OqZHI1dGiJPJ1IgFF5bWbQl8CP9kZNAHg0NJZUCnJ73udZRYEWm5MEdTIz0+Q5tClzxvXtV4lZBo36Jo4vijKVEJ06MZu+e2WnCOqsfdayY7laiT0t/UsulLNJ1wT+Euejl+3Vft7N1/nWptJn3c4y83c4oHIrsLDTIiVvPjAj5JTkyH1EA2pIOxsKOjmg2Maz7Pw== username@local\n LocalForward ~C remote> ~C\nssh> help\nCommands:\n -L[bind_address:]port:host:hostport Request local forward\n -R[bind_address:]port:host:hostport Request remote forward\n -D[bind_address:]port Request dynamic forward\n -KR[bind_address:]port Cancel remote forward\n LocalForward nc netcat nc /etc/passwd ~^Z tilde control-Z nc -l nc nc nc nc ssh & (sleep + nc) sleep fg -R -L RemoteForward -l nc -e escape_char\n Sets the escape character for sessions with a pty (default: ‘~’). The escape character is only recognized at the beginning of a line. The escape character followed by a dot\n (‘.’) closes the connection; followed by control-Z suspends the connection; and followed by itself sends the escape character once. Setting the character to “none” disables any\n escapes and makes the session fully transparent.\n ESCAPE CHARACTERS\n When a pseudo-terminal has been requested, ssh supports a number of functions through the use of an escape character.\n\n A single tilde character can be sent as ~~ or by following the tilde by a character other than those described below. The escape character must always follow a newline to be interpreted\n as special. The escape character can be changed in configuration files using the EscapeChar configuration directive or on the command line by the -e option.\n\n The supported escapes (assuming the default ‘~’) are:\n\n ~. Disconnect.\n\n ~^Z Background ssh.\n\n ~# List forwarded connections.\n\n ~& Background ssh at logout when waiting for forwarded connection / X11 sessions to terminate.\n\n ~? Display a list of escape characters.\n\n ~B Send a BREAK to the remote system (only useful for SSH protocol version 2 and if the peer supports it).\n\n ~C Open command line. Currently this allows the addition of port forwardings using the -L, -R and -D options (see above). It also allows the cancellation of existing remote port-\n forwardings using -KR[bind_address:]port. !command allows the user to execute a local command if the PermitLocalCommand option is enabled in ssh_config(5). Basic help is avail‐\n able, using the -h option.\n\n ~R Request rekeying of the connection (only useful for SSH protocol version 2 and if the peer supports it).\n"
},
{
"answer_id": 61432784,
"author": "Googlian",
"author_id": 5380942,
"author_profile": "https://Stackoverflow.com/users/5380942",
"pm_score": 0,
"selected": false,
"text": "ZSSH python3 -m pip install zssh\n python3 -m zssh -as --path /desktop/path_to_expose\n python3 -m zssh -ad --path /desktop/path_to_download --zip http://example.com/temp_file.zip\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
] |
49,900 |
<p>We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.</p>
<p>The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.</p>
|
[
{
"answer_id": 49920,
"author": "Chris Dail",
"author_id": 5077,
"author_profile": "https://Stackoverflow.com/users/5077",
"pm_score": 4,
"selected": false,
"text": "<antcall target=\"reusable\">\n <param name=\"some.variable\" value=\"var1\"/>\n</antcall>\n\n<target name=\"reusable\">\n <!-- Do something with ${some.variable} -->\n</target>\n"
},
{
"answer_id": 49935,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 2,
"selected": false,
"text": "<project name=\"subant\" default=\"subant1\">\n <property name=\"build.dir\" value=\"subant.build\"/>\n <target name=\"subant1\">\n <subant target=\"\">\n <property name=\"build.dir\" value=\"subant1.build\"/>\n <property name=\"not.overloaded\" value=\"not.overloaded\"/>\n <fileset dir=\".\" includes=\"*/build.xml\"/>\n </subant>\n </target>\n</project>\n"
},
{
"answer_id": 65947,
"author": "Vladimir",
"author_id": 9641,
"author_profile": "https://Stackoverflow.com/users/9641",
"pm_score": 7,
"selected": true,
"text": "<target name=\"vss.check\">\n <vssadd localpath=\"D:\\build\\build.00012.zip\" \n comment=\"Added by automatic build\"/>\n</target>\n <macrodef name=\"private-vssadd\">\n <attribute name=\"file\"/>\n <sequential>\n <vssadd localpath=\"@{file}\" \n comment=\"Added by automatic build\"/>\n </sequential>\n</macrodef>\n <target name=\"vss.check\">\n <private-vssadd file=\"D:\\build\\File1.zip\"/>\n <private-vssadd file=\"D:\\build\\File2.zip\"/>\n</target>\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
] |
49,908 |
<p>I know I've seen this in the past, but I can't seem to find it now.</p>
<p>Basically I want to create a page that I can host on a <a href="http://www.codeplex.com/dasblog" rel="nofollow noreferrer">dasBlog</a> instance that contains the layout from my theme, but the content of the page I control.</p>
<p>Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this?</p>
|
[
{
"answer_id": 172280,
"author": "Nick",
"author_id": 22407,
"author_profile": "https://Stackoverflow.com/users/22407",
"pm_score": 3,
"selected": true,
"text": "<add matchExpression=\"(?<basedir>.*?)/Static\\.aspx\\?=(?<value>.+)\" mapTo=\"{basedir}/FormatPage.aspx?path=content/static/{value}.format.html\" />\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381/"
] |
49,919 |
<p>I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET</p>
|
[
{
"answer_id": 49938,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 5,
"selected": true,
"text": "DateTime parsedDate;\n\nif ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )\n{\n // logic goes here.\n}\n"
},
{
"answer_id": 49948,
"author": "Sam Hasler",
"author_id": 2541,
"author_profile": "https://Stackoverflow.com/users/2541",
"pm_score": 1,
"selected": false,
"text": " ([1-9]|1\\d|2[0-8]) // matches 1 to 28 but woudn't allow leading zeros for single digits\n(0?[1-9]|1\\d|2[0-8]) // matches 1 to 28 and would allow 01, 02,... 09\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
49,925 |
<p>What is the difference between <code>UNION</code> and <code>UNION ALL</code>?</p>
|
[
{
"answer_id": 49928,
"author": "Jim Harte",
"author_id": 4544,
"author_profile": "https://Stackoverflow.com/users/4544",
"pm_score": 12,
"selected": true,
"text": "UNION UNION ALL UNION UNION ALL SELECT 'foo' AS bar UNION SELECT 'foo' AS bar\n +-----+\n| bar |\n+-----+\n| foo |\n+-----+\n1 row in set (0.00 sec)\n SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar\n +-----+\n| bar |\n+-----+\n| foo |\n| foo |\n+-----+\n2 rows in set (0.00 sec)\n"
},
{
"answer_id": 49965,
"author": "Jakub Šturc",
"author_id": 2361,
"author_profile": "https://Stackoverflow.com/users/2361",
"pm_score": 3,
"selected": false,
"text": "UNION UNION ALL UNION UNION ALL"
},
{
"answer_id": 92126,
"author": "mathewbutler",
"author_id": 2288,
"author_profile": "https://Stackoverflow.com/users/2288",
"pm_score": 6,
"selected": false,
"text": "UNION UNION ALL PGA_AGGREGATE_TARGET WORKAREA_SIZE_POLICY=AUTO SORT_AREA_SIZE SOR_AREA_RETAINED_SIZE WORKAREA_SIZE_POLICY=MANUAL"
},
{
"answer_id": 11926815,
"author": "Ihor Vorotnov",
"author_id": 1185107,
"author_profile": "https://Stackoverflow.com/users/1185107",
"pm_score": 4,
"selected": false,
"text": "SELECT * FROM mytable WHERE a=X UNION ALL SELECT * FROM mytable WHERE b=Y AND a!=X AND a!=X"
},
{
"answer_id": 11991931,
"author": "DotNetGuy",
"author_id": 1422311,
"author_profile": "https://Stackoverflow.com/users/1422311",
"pm_score": 5,
"selected": false,
"text": "UNION JOIN UNION UNION UNION ALL UNION UNION ALL Union Union all Union all UNION SELECT DISTINCT UNION ALL"
},
{
"answer_id": 16959029,
"author": "Peter Perháč",
"author_id": 81520,
"author_profile": "https://Stackoverflow.com/users/81520",
"pm_score": 4,
"selected": false,
"text": "UNION UNION ALL"
},
{
"answer_id": 21275382,
"author": "Pawan Kumar",
"author_id": 2432468,
"author_profile": "https://Stackoverflow.com/users/2432468",
"pm_score": 1,
"selected": false,
"text": "select project_id from t_project\nunion\nselect project_id from t_project_contact \n select project_id from t_project\nunion all\nselect project_id from t_project_contact\n"
},
{
"answer_id": 29587511,
"author": "shA.t",
"author_id": 4519059,
"author_profile": "https://Stackoverflow.com/users/4519059",
"pm_score": 3,
"selected": false,
"text": "UNION DISTINCT SELECT * FROM Table1\nUNION\nSELECT * FROM Table2\n SELECT DISTINCT * FROM (\n SELECT * FROM Table1\n UNION ALL\n SELECT * FROM Table2) DT\n DISTINCT UNION ALL UNION ORDER BY 1, 2, 3, ..., n (n = column number of Tables)"
},
{
"answer_id": 35772419,
"author": "AjV Jsy",
"author_id": 2078245,
"author_profile": "https://Stackoverflow.com/users/2078245",
"pm_score": 1,
"selected": false,
"text": "ORDER BY UNION ALL UNION UNION ALL UNION ALL"
},
{
"answer_id": 37267992,
"author": "Pedram",
"author_id": 1156018,
"author_profile": "https://Stackoverflow.com/users/1156018",
"pm_score": 2,
"selected": false,
"text": "UNION UNION UNION ALL UNION will UNION ALL Union UNION ALL UNION DISTINCT UNION ALL UNION UNION ALL UNION UNION UNION ALL"
},
{
"answer_id": 37672576,
"author": "reza.cse08",
"author_id": 2597706,
"author_profile": "https://Stackoverflow.com/users/2597706",
"pm_score": 2,
"selected": false,
"text": "Teacher - ID(int), Name(varchar(50)), Address(varchar(50)), PositionID(varchar(50))\n Student- ID(int), Name(varchar(50)), Email(varchar(50)), PositionID(int)\n UNION SELECT * FROM Student\nUNION\nSELECT * FROM Teacher\n UNION ALL SELECT * FROM Student\nUNION ALL\nSELECT * FROM Teacher\n"
},
{
"answer_id": 37950816,
"author": "DBA",
"author_id": 6481481,
"author_profile": "https://Stackoverflow.com/users/6481481",
"pm_score": 4,
"selected": false,
"text": "CREATE TABLE #T1 (data VARCHAR(10))\n\nINSERT INTO #T1\nSELECT 'abc'\nUNION ALL\nSELECT 'bcd'\nUNION ALL\nSELECT 'cde'\nUNION ALL\nSELECT 'def'\nUNION ALL\nSELECT 'efg'\n\n\nCREATE TABLE #T2 (data VARCHAR(10))\n\nINSERT INTO #T2\nSELECT 'abc'\nUNION ALL\nSELECT 'cde'\nUNION ALL\nSELECT 'efg'\n"
},
{
"answer_id": 43648727,
"author": "James Grey",
"author_id": 3728901,
"author_profile": "https://Stackoverflow.com/users/3728901",
"pm_score": 3,
"selected": false,
"text": "SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual\nUNION\nSELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;\n SELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual\nUNION ALL\nSELECT to_date(sysdate, 'yyyy-mm-dd') FROM dual;\n"
},
{
"answer_id": 53721250,
"author": "Aris Mist",
"author_id": 9075992,
"author_profile": "https://Stackoverflow.com/users/9075992",
"pm_score": 1,
"selected": false,
"text": "SELECT T1.YEAR, T1.PRODUCT FROM T1\n\nUNION ALL\n\nSELECT T2.YEAR, T2.PRODUCT FROM T2\n SELECT T1.YEAR, T1.PRODUCT FROM T1\n\nUNION\n\nSELECT T2.YEAR, T2.PRODUCT FROM T2\n"
},
{
"answer_id": 58480245,
"author": "Dowlers",
"author_id": 223139,
"author_profile": "https://Stackoverflow.com/users/223139",
"pm_score": 0,
"selected": false,
"text": "UNION ALL select a.SHAPE from tableA a\nunion\nselect b.SHAPE from tableB b\n The data type geometry cannot be used as an operand to the UNION, INTERSECT or EXCEPT operators because it is not comparable. union all"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] |
49,926 |
<p>Is there an open-source alternative to MATLAB's <a href="https://www.mathworks.com/help/optim/index.html;jsessionid=95cd06964ab253598de29e7d0a80" rel="nofollow noreferrer"><code>fmincon</code></a> function for constrained linear optimization? I'm rewriting a MATLAB program to use Python / <a href="https://numpy.org/" rel="nofollow noreferrer">NumPy</a> / <a href="https://scipy.org/" rel="nofollow noreferrer">SciPy</a> and this is the only function I haven't found an equivalent to. A NumPy-based solution would be ideal, but any language will do.</p>
|
[
{
"answer_id": 70798,
"author": "WalkingRandomly",
"author_id": 1856916,
"author_profile": "https://Stackoverflow.com/users/1856916",
"pm_score": 4,
"selected": false,
"text": " Constrained Optimizers (multivariate)\n\n fmin_l_bfgs_b -- Zhu, Byrd, and Nocedal's L-BFGS-B constrained optimizer\n (if you use this please quote their papers -- see help)\n\n fmin_tnc -- Truncated Newton Code originally written by Stephen Nash and\n adapted to C by Jean-Sebastien Roy.\n\n fmin_cobyla -- Constrained Optimization BY Linear Approximation\n"
},
{
"answer_id": 444167,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "fmincon"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3002/"
] |
49,950 |
<p>Is it necessary to set large objects to <code>null</code> when implementing a <code>Dispose()</code> method?</p>
|
[
{
"answer_id": 49957,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "using(DisposableClass dc = new DisposableClass()) \n{ \n dc.PerformActionOnUmanagedResources(); \n dc.PerformAnotherActionOnUmanagedResources(); \n} \n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49950",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] |
49,962 |
<p>Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies.</p>
<p>For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer)</p>
<ul>
<li>What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself)</li>
<li>What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc)</li>
<li>Is it realtime, or can it be made realtime</li>
</ul>
<p>Current strategies:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/49962/task-schedulers#74894">Priority Based Preemptive</a></li>
<li><a href="https://stackoverflow.com/questions/49962/task-schedulers#50056">Lowest power slowest clock</a></li>
</ul>
<p>-Adam</p>
|
[
{
"answer_id": 50056,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 4,
"selected": true,
"text": "Repeat forever {\n if tasks are waiting to be scheduled {\n Sort deadlines in ascending order\n Schedule task with earliest deadline\n Check if deadline can be met at lower speed (voltage)\n If deadline can be met,\n schedule task to execute at lower voltage (speed)\n If deadline cannot be met,\n check if deadline can be met at higher speed (voltage)\n If deadline can be met,\n schedule task to execute at higher voltage (speed)\n If deadline cannot be met,\n task cannot be scheduled: run the exception handler!\n }\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] |
49,964 |
<p>Each cell contains some text and a background color. So I have some cells that are blue and some that are red. What function do I use to count the number of red cells?</p>
<p>I have tried <code>=COUNTIF(D3:D9,CELL("color",D3))</code> with no success (Where <code>D3</code> is red).</p>
|
[
{
"answer_id": 49983,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 3,
"selected": false,
"text": "=SUMCOLOR(B11:B17,B11:B17,3,FALSE)"
},
{
"answer_id": 50462,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 3,
"selected": false,
"text": "=CELL(\"color\",D3) 1 0 Function CellColor(xlRange As Excel.Range)\n CellColor = xlRange.Cells(1, 1).Interior.ColorIndex\nEnd Function\n =CellColor(D3) .ColorIndex D3"
},
{
"answer_id": 18542074,
"author": "Stan Towianski",
"author_id": 2366973,
"author_profile": "https://Stackoverflow.com/users/2366973",
"pm_score": 2,
"selected": false,
"text": "=GetColorIndex(E5) <- returns color number for the cell\n =CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14\n =ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )\n Function GetColorIndex(Cell As Range)\n GetColorIndex = Cell.Interior.ColorIndex\nEnd Function\n\nFunction CountColorIndexInRange(Rng As Range, TestColor As Long)\n Dim cnt\n Dim cl As Range\n cnt = 0\n\n For Each cl In Rng\n If GetColorIndex(cl) = TestColor Then\n Rem Debug.Print \">\" & TestColor & \"<\"\n cnt = cnt + 1\n End If\n Next\n\n CountColorIndexInRange = cnt\n\nEnd Function\n"
},
{
"answer_id": 34723980,
"author": "jsxt",
"author_id": 3627676,
"author_profile": "https://Stackoverflow.com/users/3627676",
"pm_score": 2,
"selected": false,
"text": "Function CountBgColor(range As range, criteria As range) As Long\n Dim cell As range\n Dim color As Long\n color = criteria.Interior.color\n For Each cell In range\n If cell.Interior.color = color Then\n CountBgColor = CountBgColor + 1\n End If\n Next cell\nEnd Function\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/453046/"
] |
49,966 |
<p>When I turn an image (<code><img></code>) into a hyperlink (by wrapping it in <code><a></code>), Firefox adds a black border around the image. Safari does not display the same border. </p>
<p>What CSS declaration would be best to eliminate the border?</p>
|
[
{
"answer_id": 49975,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 2,
"selected": false,
"text": "a img {\n border-width: 0;\n}\n"
},
{
"answer_id": 49977,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": true,
"text": "img {\n border: 0\n}\n <img border=\"0\" src=\"...\" />\n ^^^^^^^^^^\n"
},
{
"answer_id": 49979,
"author": "Kamil Zadora",
"author_id": 3515,
"author_profile": "https://Stackoverflow.com/users/3515",
"pm_score": 3,
"selected": false,
"text": "border: 0;\n a img {\n border: 0;\n}\n"
},
{
"answer_id": 49981,
"author": "enigmatic",
"author_id": 443575,
"author_profile": "https://Stackoverflow.com/users/443575",
"pm_score": 3,
"selected": false,
"text": "<img href=\"mypic.gif\" border=\"0\" />\n border : 0;\n"
},
{
"answer_id": 18372971,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "img {\n border-style: none;\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
49,988 |
<p>Occasionally a program on a Windows machine goes crazy and just hangs. So I'll call up the task manager and hit the "End Process" button for it. However, this doesn't always work; if I try it enough times then it'll usually die eventually, but I'd really like to be able to just kill it immediately. On Linux I could just <code>kill -9</code> to guarantee that a process will die.</p>
<p>This also could be used for writing batch scripts and writing batch scripts is programming.</p>
<p><strong>Is there some</strong> program or <strong>command that comes with Windows that will always kill a process?</strong> A free third-party app would be fine, although I'd prefer to be able to do this on machines I sit down at for the first time.</p>
|
[
{
"answer_id": 49990,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 8,
"selected": false,
"text": "taskkill /im myprocess.exe /f\n taskkill /pid 1234 /f\n"
},
{
"answer_id": 50011,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 9,
"selected": true,
"text": "TerminateProcess kill -9 D kill vfork exec D"
},
{
"answer_id": 50040,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 4,
"selected": false,
"text": "ntsd -pn myapp.exe\n"
},
{
"answer_id": 13894135,
"author": "David Ruark",
"author_id": 1906581,
"author_profile": "https://Stackoverflow.com/users/1906581",
"pm_score": 3,
"selected": false,
"text": "AT 12:34 /interactive \"C:/procexp.exe\"\n"
},
{
"answer_id": 23441528,
"author": "Dhruv Chandhok",
"author_id": 2656347,
"author_profile": "https://Stackoverflow.com/users/2656347",
"pm_score": 5,
"selected": false,
"text": "taskkill /im processname.exe /f\n"
},
{
"answer_id": 54930322,
"author": "RmccurdyDOTcom",
"author_id": 4776140,
"author_profile": "https://Stackoverflow.com/users/4776140",
"pm_score": 0,
"selected": false,
"text": "sc config TrustedInstaller binPath= \"cmd /c TASKKILL /F /IM notepad.exe\nsc start \"TrustedInstaller\"\n"
},
{
"answer_id": 72704655,
"author": "Monsignor",
"author_id": 322984,
"author_profile": "https://Stackoverflow.com/users/322984",
"pm_score": 0,
"selected": false,
"text": "wmic process where processid=\"11008\" call terminate"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/49988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
50,005 |
<p>I have a weird bug involving Flash text and hyperlinks, htmlText in a TextField with <code><a></code> tags seem to truncate surrounding space:</p>
<p><a href="https://i.stack.imgur.com/FDA7a.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FDA7a.gif" alt="output"></a></p>
<p>Once I place my cursor over the text, it "fixes" itself:</p>
<p><a href="https://i.stack.imgur.com/YFbSR.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YFbSR.gif" alt="output with mouseover"></a></p>
<p>Here is the HTML in the textField:</p>
<pre><code><p>The speeches at both the <a href="http://www.demconvention.com/speeches/" target="_blank">Democratic National Convention</a> last week and the <a href="http://www.gopconvention2008.com/videos" target="_blank">Republican National Convention</a> this week, have been, for me at least, must see TV.</p>
</code></pre>
<p>When I disable the styleSheet attached to it, the effect still occurs, but placing my mouse over it does not fix the spacing. I am using "Anti-alias for readability", and have embedded the all Uppercase, Lowercase, Numerals, and Punctuation. I will also point out that if I change the rendering setting to "Use Device fonts" the bug goes away.</p>
<p>Any thoughts?</p>
|
[
{
"answer_id": 51590,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 0,
"selected": false,
"text": "<p> ... <a ... >Link text</a> ... </p>\n"
},
{
"answer_id": 1827708,
"author": "Sandro",
"author_id": 107797,
"author_profile": "https://Stackoverflow.com/users/107797",
"pm_score": 1,
"selected": false,
"text": "_description = new TextField();\n_description.selectable = false;\n_description.width = WIDTH; // Global.\naddChild(_description);\n\nvar myriadPro:Font = new MyriadPro(); // Embedded font.\nvar style:StyleSheet = new StyleSheet();\n\nvar styleObj:Object = new Object();\nstyleObj.fontFamily = myriadPro.fontName;\nstyleObj.fontSize = 13;\nstyleObj.textAlign = \"left\";\nstyleObj.color = \"#FFFFFF\";\n\nstyle.setStyle(\"p\", styleObj);\nstyle.setStyle(\"a:link\", styleObj);\nstyle.setStyle(\"a:hover\", styleObj);\n\n_description.autoSize = TextFieldAutoSize.LEFT;\n_description.antiAliasType = AntiAliasType.ADVANCED;\n_description.condenseWhite = true;\n_description.wordWrap = true;\n_description.multiline = true;\n_description.embedFonts = true;\n\n_description.styleSheet = style;\n_description.htmlText = '<p>A short description with an <a href=\"http://www.example.com/\">HTML</a> link that can be clicked.</p>';\n"
},
{
"answer_id": 3054815,
"author": "Sean Higgins",
"author_id": 368413,
"author_profile": "https://Stackoverflow.com/users/368413",
"pm_score": 1,
"selected": false,
"text": "yourTextField.gridFitType = GridFitType.SUBPIXEL;\n AntiAliasType"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] |
50,033 |
<p>The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). </p>
<p>Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. </p>
<p>For more information on the bug, <a href="http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html" rel="noreferrer">read it here</a>.</p>
<p>This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. </p>
<p>Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.</p>
|
[
{
"answer_id": 50039,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "function WebForm_FireDefaultButton(event, target) {\nif (!__defaultFired && event.keyCode == 13 && !(event.srcElement && \n(event.srcElement.tagName.toLowerCase() == \"textarea\"))) {\nvar defaultButton;\nif (__nonMSDOMBrowser) {\ndefaultButton = document.getElementById(target);\n}\nelse {\ndefaultButton = document.all[target];\n}\nif (defaultButton && typeof(defaultButton.click) != \n\"undefined\") {\n__defaultFired = true;\ndefaultButton.click();\nevent.cancelBubble = true;\nif (event.stopPropagation) event.stopPropagation();\nreturn false;\n}\n}\nreturn true;\n}\n function WebForm_FireDefaultButton(event, target) {\nvar element = event.target || event.srcElement;\nif (!__defaultFired && event.keyCode == 13 && !(element && \n(element.tagName.toLowerCase() == \"textarea\"))) {\n protected void Page_Load(object sender, EventArgs e)\n{\nClientScript.RegisterClientScriptInclude(\"js1\", \"JScript.js\");\n}\n"
},
{
"answer_id": 1454033,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 2,
"selected": false,
"text": "// Fixes ASP.NET's behavior of default button by testing for more controls\n// than just textarea where the event should not be caugt by the DefaultButton\n// action. This method has to override ASP.NET's WebForm_FireDefaultButton, so\n// it has to included at the bottom of the page.\nfunction WebForm_FireDefaultButton(event, target) {\n if (event.keyCode == 13) {\n var src = event.srcElement || event.target;\n if (!(\n src\n &&\n (\n src.tagName.toLowerCase() == \"textarea\"\n || src.tagName.toLowerCase() == \"a\"\n ||\n (\n src.tagName.toLowerCase() == \"input\"\n &&\n (\n src.getAttribute(\"type\").toLowerCase() == \"submit\"\n || src.getAttribute(\"type\").toLowerCase() == \"button\"\n || src.getAttribute(\"type\").toLowerCase() == \"reset\"\n )\n )\n || src.tagName.toLowerCase() == \"option\"\n || src.tagName.toLowerCase() == \"select\"\n ) \n )) {\n var defaultButton;\n if (__nonMSDOMBrowser) {\n defaultButton = document.getElementById(target);\n }\n else {\n defaultButton = document.all[target];\n }\n if (defaultButton && typeof (defaultButton.click) != \"undefined\") {\n defaultButton.click();\n event.cancelBubble = true;\n if (event.stopPropagation) event.stopPropagation();\n return false;\n }\n }\n }\n return true;\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3617/"
] |
50,064 |
<p>This is pretty simple, I come from a swing/awt background.</p>
<p>I'm just wondering what the proper way to set the background color for a SWT widget is?</p>
<p>I've been trying:</p>
<pre><code>widget.setBackground( );
</code></pre>
<p>Except I have no idea how to create the color Object in SWT?</p>
|
[
{
"answer_id": 50128,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 7,
"selected": true,
"text": "Device device = Display.getCurrent ();\nColor red = new Color (device, 255, 0, 0);\n"
},
{
"answer_id": 75509,
"author": "qualidafial",
"author_id": 13253,
"author_profile": "https://Stackoverflow.com/users/13253",
"pm_score": 6,
"selected": false,
"text": "Display.getSystemColor(int) SWT.COLOR_* Display display = Display.getCurrent();\nColor blue = display.getSystemColor(SWT.COLOR_BLUE);\nColor listBackground = display.getSystemColor(SWT.COLOR_LIST_BACKGROUND);\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
] |
50,096 |
<p>I know it is not recommended, but is it at all possible to pass the user's password to scp?</p>
<p>I'd like to copy a file via scp as part of a batch job and the receiving server does, of course, need a password and, no, I cannot easily change that to key-based authentication.</p>
|
[
{
"answer_id": 50113,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "expect sub copyover {\n $scp = Expect->spawn(\"/usr/bin/scp ${srcpath}/$file $who:${destpath}/$file\");\n $scp->expect(30,\"ssword: \") || die \"Never got password prompt from $dest:$!\\n\";\n print $scp 'password' . \"\\n\";\n $scp->expect(30,\"-re\",'$\\s') || die \"Never got prompt from parent system:$!\\n\";\n $scp->soft_close();\n return;\n}\n"
},
{
"answer_id": 4310068,
"author": "gWay",
"author_id": 524607,
"author_profile": "https://Stackoverflow.com/users/524607",
"pm_score": 6,
"selected": false,
"text": "-pw"
},
{
"answer_id": 9386143,
"author": "mustafaturan",
"author_id": 960702,
"author_profile": "https://Stackoverflow.com/users/960702",
"pm_score": 6,
"selected": false,
"text": "ssh-keygen -t rsa -C \"[email protected]\"\n ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys 0700 for ~./ssh folder 0600 for ~/.ssh/authorized_keys"
},
{
"answer_id": 13955428,
"author": "KevinS",
"author_id": 905853,
"author_profile": "https://Stackoverflow.com/users/905853",
"pm_score": 9,
"selected": false,
"text": "sshpass -p \"password\" scp -r [email protected]:/some/remote/path /some/local/path\n sshpass -f \"/path/to/passwordfile\" scp -r [email protected]:/some/remote/path /some/local/path\n apt install sshpass yum install sshpass port install sshpass brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb"
},
{
"answer_id": 14361319,
"author": "Prabhjeet",
"author_id": 1955593,
"author_profile": "https://Stackoverflow.com/users/1955593",
"pm_score": 5,
"selected": false,
"text": "#!/usr/bin/expect\n spawn scp /usr/bin/file.txt root@<ServerLocation>:/home\n set pass \"Your_Password\"\n expect {\n password: {send \"$pass\\r\"; exp_continue}\n }\n expect test.exp \n"
},
{
"answer_id": 22007042,
"author": "valk",
"author_id": 400745,
"author_profile": "https://Stackoverflow.com/users/400745",
"pm_score": -1,
"selected": false,
"text": "rsync -r -v --progress -e ssh user@remote-system:/address/to/remote/file /home/user/\n"
},
{
"answer_id": 22551406,
"author": "Kevin Chui",
"author_id": 3230321,
"author_profile": "https://Stackoverflow.com/users/3230321",
"pm_score": 0,
"selected": false,
"text": "# apt-get install expect spawn scp /path_from/file_name user_name_here@to_host_name:/path_to expect \"password:\" send put_password_here\\n; interact # expect /root/scriptfile"
},
{
"answer_id": 40738243,
"author": "Shen JI",
"author_id": 6477230,
"author_profile": "https://Stackoverflow.com/users/6477230",
"pm_score": 3,
"selected": false,
"text": "ssh-copy-id $which ssh-copy-id #check whether it exists\n ssh-copy-id \"user@remote-system\"\n"
},
{
"answer_id": 46843996,
"author": "hi15",
"author_id": 3587282,
"author_profile": "https://Stackoverflow.com/users/3587282",
"pm_score": 3,
"selected": false,
"text": "ssh-keygen scp -i ~/.ssh/id_rsa /local/path/to/file [email protected]:/path/in/remote/server/ .bash_profile alias remote_scp='scp -i ~/.ssh/id_rsa /local/path/to/file [email protected]:/path/in/remote/server/\n source ~/.bash_profile remote_scp scp"
},
{
"answer_id": 47328516,
"author": "MBerg",
"author_id": 8951145,
"author_profile": "https://Stackoverflow.com/users/8951145",
"pm_score": 5,
"selected": false,
"text": "curl --insecure --user username:password -T /path/to/sourcefile sftp://desthost/path/\n"
},
{
"answer_id": 57807535,
"author": "Yash",
"author_id": 9401270,
"author_profile": "https://Stackoverflow.com/users/9401270",
"pm_score": -1,
"selected": false,
"text": "$ nohup scp file_to_copy user@server:/path/to/copy/the/file > nohup.out 2>&1\n"
},
{
"answer_id": 59252427,
"author": "JohnMudd",
"author_id": 487992,
"author_profile": "https://Stackoverflow.com/users/487992",
"pm_score": 2,
"selected": false,
"text": "(\n echo 'scp [email protected]:./install.sh .'\n sleep 5\n echo 'scp-passwd'\n sleep 5\n echo 'exit'\n) |\n\npython -c 'import pty; pty.spawn(\"/usr/bin/bash\")'\n scp [email protected]:install.sh .\nbash-4.2$ scp [email protected]:install.sh .\nPassword: \ninstall.sh 100% 15KB 236.2KB/s 00:00 \nbash-4.2$ exit\nexit\n"
},
{
"answer_id": 63877892,
"author": "Finesse",
"author_id": 1118709,
"author_profile": "https://Stackoverflow.com/users/1118709",
"pm_score": 2,
"selected": false,
"text": "/etc/ssh/sshd_config PasswordAuthentication=no # sudo systemctl restart ssh -o PreferredAuthentications=\"password\" scp scp -o PreferredAuthentications=\"password\" /path/to/file user@server:/destination/directory\n"
},
{
"answer_id": 65111598,
"author": "Sachin Rastogi",
"author_id": 8230674,
"author_profile": "https://Stackoverflow.com/users/8230674",
"pm_score": -1,
"selected": false,
"text": "-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null sshpass -p \"password\" scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null [email protected]:/tmp/from/psoutput /tmp/to/psoutput"
},
{
"answer_id": 67064479,
"author": "Sudheer Mareddy",
"author_id": 8228506,
"author_profile": "https://Stackoverflow.com/users/8228506",
"pm_score": 0,
"selected": false,
"text": "apt-get update\napt-get install putty \necho n | pscp -pw \"Password@1234\" -r user_name@source_server_IP:/copy_file_path/files /path_to_copy/files\n"
},
{
"answer_id": 72019549,
"author": "Rakesh Raushan",
"author_id": 8422153,
"author_profile": "https://Stackoverflow.com/users/8422153",
"pm_score": -1,
"selected": false,
"text": "scp -C -i <path_to opens sshkey> <'local file_path'> user@<ip_address_VM>: <'remote file_path’>"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50096",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2992/"
] |
50,097 |
<p>I would like to use an add-in like simple-modal or the dialog add-in in the UI kit. However, how do I use these or any other and get a result back. Basically I want the modal to do some AJAX interaction with the server and return the result for the calling code to do some stuff with.</p>
|
[
{
"answer_id": 50172,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "$(document).ready(function () {\n $('#confirmDialog input:eq(0)').click(function (e) {\n e.preventDefault();\n\n // example of calling the confirm function\n // you must use a callback function to perform the \"yes\" action\n confirm(\"Continue to the SimpleModal Project page?\", function () {\n window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';\n });\n });\n});\n\nfunction confirm(message, callback) {\n $('#confirm').modal({\n close: false,\n overlayId: 'confirmModalOverlay',\n containerId: 'confirmModalContainer', \n onShow: function (dialog) {\n dialog.data.find('.message').append(message);\n\n // if the user clicks \"yes\"\n dialog.data.find('.yes').click(function () {\n // call the callback\n if ($.isFunction(callback)) {\n callback.apply();\n }\n // close the dialog\n $.modal.close();\n });\n }\n });\n}\n"
},
{
"answer_id": 54705634,
"author": "Code_Ninja",
"author_id": 7639034,
"author_profile": "https://Stackoverflow.com/users/7639034",
"pm_score": 1,
"selected": false,
"text": "$(\"button.try-it\").on(\"click\", function() {\n $(\".modal-container\").removeClass(\"hide\");\n});\n$(\".close-btn\").on(\"click\", function() {\n $(\".modal-container\").addClass(\"hide\");\n}); .modal-container {\n position: absolute;\n background-color: rgba(35, 35, 35, 0.41);\n top: 0;\n bottom: 0;\n height: 300px;\n width: 100%;\n}\n\n.modal-body {\n width: 100px;\n height: 100px;\n margin: 0 auto;\n background: white;\n}\n\n.close-btn {\n float: right;\n}\n\n.hide {\n display: none;\n}\n\n.body-container {\n position: relative;\n box-sizing: border-box;\n}\n\n.close-btn {\n cursor: pointer;\n} <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n<div class=\"body-container\">\n <div class=\"button\">\n <button class=\"try-it\">Try It!!</button>\n </div>\n <div class=\"modal-container hide\">\n <div class=\"modal-body\">\n <span class=\"close-btn\">x</span>\n <p>Here is the content of the modal</p>\n <!--You can apply AJAX on this structure since this just like any other part of the HTML of your page-->\n <!--Or you can use Bootstrap modal instead of this one.-->\n </div>\n </div>\n</div>"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] |
50,098 |
<p>I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.</p>
<p>I've read the other thread about <a href="https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c">Enumerable.SequenceEqual</a>, but it's not exactly what I'm looking for.</p>
<p>In my case, two collections would be equal if they both contain the same items (no matter the order).</p>
<p>Example:</p>
<pre><code>collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
</code></pre>
<p>What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).</p>
<pre><code>if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
</code></pre>
<p>However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.</p>
<p>An example I can think of that would be wrong is:</p>
<pre><code>collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
</code></pre>
<p>Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?</p>
<hr>
<p>The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.</p>
<p><strong>Note:</strong> I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).</p>
|
[
{
"answer_id": 50154,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 5,
"selected": false,
"text": " private bool SetEqual (List<int> left, List<int> right) {\n\n if (left.Count != right.Count)\n return false;\n\n Dictionary<int, int> dict = new Dictionary<int, int>();\n\n foreach (int member in left) {\n if (dict.ContainsKey(member) == false)\n dict[member] = 1;\n else\n dict[member]++;\n }\n\n foreach (int member in right) {\n if (dict.ContainsKey(member) == false)\n return false;\n else\n dict[member]--;\n }\n\n foreach (KeyValuePair<int, int> kvp in dict) {\n if (kvp.Value != 0)\n return false;\n }\n\n return true;\n\n }\n"
},
{
"answer_id": 50171,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 0,
"selected": false,
"text": "(new HashBag(collection1)).equals(new HashBag(collection2))\n"
},
{
"answer_id": 50177,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "bool equal = collection1.OrderBy(i => i).SequenceEqual(\n collection2.OrderBy(i => i));\n"
},
{
"answer_id": 50465,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Represents a service used to compare two collections for equality.\n/// </summary>\n/// <typeparam name=\"T\">The type of the items in the collections.</typeparam>\npublic class CollectionComparer<T>\n{\n /// <summary>\n /// Compares the content of two collections for equality.\n /// </summary>\n /// <param name=\"foo\">The first collection.</param>\n /// <param name=\"bar\">The second collection.</param>\n /// <returns>True if both collections have the same content, false otherwise.</returns>\n public bool Execute(ICollection<T> foo, ICollection<T> bar)\n {\n // Declare a dictionary to count the occurence of the items in the collection\n Dictionary<T, int> itemCounts = new Dictionary<T,int>();\n\n // Increase the count for each occurence of the item in the first collection\n foreach (T item in foo)\n {\n if (itemCounts.ContainsKey(item))\n {\n itemCounts[item]++;\n }\n else\n {\n itemCounts[item] = 1;\n }\n }\n\n // Wrap the keys in a searchable list\n List<T> keys = new List<T>(itemCounts.Keys);\n\n // Decrease the count for each occurence of the item in the second collection\n foreach (T item in bar)\n {\n // Try to find a key for the item\n // The keys of a dictionary are compared by reference, so we have to\n // find the original key that is equivalent to the \"item\"\n // You may want to override \".Equals\" to define what it means for\n // two \"T\" objects to be equal\n T key = keys.Find(\n delegate(T listKey)\n {\n return listKey.Equals(item);\n });\n\n // Check if a key was found\n if(key != null)\n {\n itemCounts[key]--;\n }\n else\n {\n // There was no occurence of this item in the first collection, thus the collections are not equal\n return false;\n }\n }\n\n // The count of each item should be 0 if the contents of the collections are equal\n foreach (int value in itemCounts.Values)\n {\n if (value != 0)\n {\n return false;\n }\n }\n\n // The collections are equal\n return true;\n }\n}\n"
},
{
"answer_id": 1015692,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "return c1.Count == c2.Count && c1.Intersect(c2).Count() == c1.Count;\n __Test Latency(ms)__\nN, SetEquals, OrderBy, Intersect \n1024, 0, 0, 0 \n2048, 0, 0, 0 \n4096, 31.2468, 0, 0 \n8192, 62.4936, 0, 0 \n16384, 156.234, 15.6234, 0 \n32768, 312.468, 15.6234, 46.8702 \n65536, 640.5594, 46.8702, 31.2468 \n131072, 1312.3656, 93.7404, 203.1042 \n262144, 3765.2394, 187.4808, 187.4808 \n524288, 5718.1644, 374.9616, 406.2084 \n1048576, 11420.7054, 734.2998, 718.6764 \n2097152, 35090.1564, 1515.4698, 1484.223\n"
},
{
"answer_id": 2564351,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 3,
"selected": false,
"text": "public class SetComparer<T> : IEqualityComparer<IEnumerable<T>> \nwhere T:IComparable<T>\n{\n public bool Equals(IEnumerable<T> first, IEnumerable<T> second)\n {\n if (first == second)\n return true;\n if ((first == null) || (second == null))\n return false;\n return first.ToHashSet().SetEquals(second);\n }\n\n public int GetHashCode(IEnumerable<T> enumerable)\n {\n int hash = 17;\n\n foreach (T val in enumerable.OrderBy(x => x))\n hash = hash * 23 + val.GetHashCode();\n\n return hash;\n }\n}\n"
},
{
"answer_id": 2740602,
"author": "user329244",
"author_id": 329244,
"author_profile": "https://Stackoverflow.com/users/329244",
"pm_score": 2,
"selected": false,
"text": "var list1 = new[] { \"Bill\", \"Bob\", \"Sally\" };\nvar list2 = new[] { \"Bob\", \"Bill\", \"Sally\" };\nbool isequal = list1.Compare(list2).IsSame;\n var list1 = new[] { \"Billy\", \"Bob\" };\nvar list2 = new[] { \"Bob\", \"Sally\" };\nvar diff = list1.Compare(list2);\nvar onlyinlist1 = diff.Removed; //Billy\nvar onlyinlist2 = diff.Added; //Sally\nvar inbothlists = diff.Equal; //Bob\n var original = new Dictionary<int, string>() { { 1, \"a\" }, { 2, \"b\" } };\nvar changed = new Dictionary<int, string>() { { 1, \"aaa\" }, { 2, \"b\" } };\nvar diff = original.Compare(changed, (x, y) => x.Value == y.Value, (x, y) => x.Value == y.Value);\nforeach (var item in diff.Different)\n Console.Write(\"{0} changed to {1}\", item.Key.Value, item.Value.Value);\n//Will output: a changed to aaa\n"
},
{
"answer_id": 3790621,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 8,
"selected": true,
"text": "public class MultiSetComparer<T> : IEqualityComparer<IEnumerable<T>>\n{\n private readonly IEqualityComparer<T> m_comparer;\n public MultiSetComparer(IEqualityComparer<T> comparer = null)\n {\n m_comparer = comparer ?? EqualityComparer<T>.Default;\n }\n\n public bool Equals(IEnumerable<T> first, IEnumerable<T> second)\n {\n if (first == null)\n return second == null;\n\n if (second == null)\n return false;\n\n if (ReferenceEquals(first, second))\n return true;\n\n if (first is ICollection<T> firstCollection && second is ICollection<T> secondCollection)\n {\n if (firstCollection.Count != secondCollection.Count)\n return false;\n\n if (firstCollection.Count == 0)\n return true;\n }\n\n return !HaveMismatchedElement(first, second);\n }\n\n private bool HaveMismatchedElement(IEnumerable<T> first, IEnumerable<T> second)\n {\n int firstNullCount;\n int secondNullCount;\n\n var firstElementCounts = GetElementCounts(first, out firstNullCount);\n var secondElementCounts = GetElementCounts(second, out secondNullCount);\n\n if (firstNullCount != secondNullCount || firstElementCounts.Count != secondElementCounts.Count)\n return true;\n\n foreach (var kvp in firstElementCounts)\n {\n var firstElementCount = kvp.Value;\n int secondElementCount;\n secondElementCounts.TryGetValue(kvp.Key, out secondElementCount);\n\n if (firstElementCount != secondElementCount)\n return true;\n }\n\n return false;\n }\n\n private Dictionary<T, int> GetElementCounts(IEnumerable<T> enumerable, out int nullCount)\n {\n var dictionary = new Dictionary<T, int>(m_comparer);\n nullCount = 0;\n\n foreach (T element in enumerable)\n {\n if (element == null)\n {\n nullCount++;\n }\n else\n {\n int num;\n dictionary.TryGetValue(element, out num);\n num++;\n dictionary[element] = num;\n }\n }\n\n return dictionary;\n }\n\n public int GetHashCode(IEnumerable<T> enumerable)\n {\n if (enumerable == null) throw new \n ArgumentNullException(nameof(enumerable));\n\n int hash = 17;\n\n foreach (T val in enumerable)\n hash ^= (val == null ? 42 : m_comparer.GetHashCode(val));\n\n return hash;\n }\n}\n var set = new HashSet<IEnumerable<int>>(new[] {new[]{1,2,3}}, new MultiSetComparer<int>());\nConsole.WriteLine(set.Contains(new [] {3,2,1})); //true\nConsole.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false\n var comp = new MultiSetComparer<string>();\nConsole.WriteLine(comp.Equals(new[] {\"a\",\"b\",\"c\"}, new[] {\"a\",\"c\",\"b\"})); //true\nConsole.WriteLine(comp.Equals(new[] {\"a\",\"b\",\"c\"}, new[] {\"a\",\"b\"})); //false\n var strcomp = new MultiSetComparer<string>(StringComparer.OrdinalIgnoreCase);\nConsole.WriteLine(strcomp.Equals(new[] {\"a\", \"b\"}, new []{\"B\", \"A\"})); //true\n"
},
{
"answer_id": 6985006,
"author": "Korayem",
"author_id": 80434,
"author_profile": "https://Stackoverflow.com/users/80434",
"pm_score": 2,
"selected": false,
"text": "// Create the IEnumerable data sources.\nstring[] names1 = System.IO.File.ReadAllLines(@\"../../../names1.txt\");\nstring[] names2 = System.IO.File.ReadAllLines(@\"../../../names2.txt\");\n// Create the query. Note that method syntax must be used here.\nIEnumerable<string> differenceQuery = names1.Except(names2);\n// Execute the query.\nConsole.WriteLine(\"The following lines are in names1.txt but not names2.txt\");\nforeach (string s in differenceQuery)\n Console.WriteLine(s);\n"
},
{
"answer_id": 9658866,
"author": "Eric J.",
"author_id": 141172,
"author_profile": "https://Stackoverflow.com/users/141172",
"pm_score": 1,
"selected": false,
"text": "static public class EnumerableExtensions \n{\n static public bool IsEquivalentTo<T>(this IEnumerable<T> first, IEnumerable<T> second)\n {\n if ((first == null) != (second == null))\n return false;\n\n if (!object.ReferenceEquals(first, second) && (first != null))\n {\n if (first.Count() != second.Count())\n return false;\n\n if ((first.Count() != 0) && HaveMismatchedElement<T>(first, second))\n return false;\n }\n\n return true;\n }\n\n private static bool HaveMismatchedElement<T>(IEnumerable<T> first, IEnumerable<T> second)\n {\n int firstCount;\n int secondCount;\n\n var firstElementCounts = GetElementCounts<T>(first, out firstCount);\n var secondElementCounts = GetElementCounts<T>(second, out secondCount);\n\n if (firstCount != secondCount)\n return true;\n\n foreach (var kvp in firstElementCounts)\n {\n firstCount = kvp.Value;\n secondElementCounts.TryGetValue(kvp.Key, out secondCount);\n\n if (firstCount != secondCount)\n return true;\n }\n\n return false;\n }\n\n private static Dictionary<T, int> GetElementCounts<T>(IEnumerable<T> enumerable, out int nullCount)\n {\n var dictionary = new Dictionary<T, int>();\n nullCount = 0;\n\n foreach (T element in enumerable)\n {\n if (element == null)\n {\n nullCount++;\n }\n else\n {\n int num;\n dictionary.TryGetValue(element, out num);\n num++;\n dictionary[element] = num;\n }\n }\n\n return dictionary;\n }\n\n static private int GetHashCode<T>(IEnumerable<T> enumerable)\n {\n int hash = 17;\n\n foreach (T val in enumerable.OrderBy(x => x))\n hash = hash * 23 + val.GetHashCode();\n\n return hash;\n }\n}\n"
},
{
"answer_id": 38003867,
"author": "palswim",
"author_id": 393280,
"author_profile": "https://Stackoverflow.com/users/393280",
"pm_score": 3,
"selected": false,
"text": "static bool SetsContainSameElements<T>(IEnumerable<T> set1, IEnumerable<T> set2) {\n var setXOR = new HashSet<T>(set1);\n setXOR.SymmetricExceptWith(set2);\n return (setXOR.Count == 0);\n}\n System.Collections.Generic SymmetricExceptWith"
},
{
"answer_id": 44248556,
"author": "N73k",
"author_id": 4379238,
"author_profile": "https://Stackoverflow.com/users/4379238",
"pm_score": 1,
"selected": false,
"text": "public static bool HasSameElementsAs<T>(\n this IEnumerable<T> first, \n IEnumerable<T> second, \n IEqualityComparer<T> comparer = null)\n {\n var firstMap = first\n .GroupBy(x => x, comparer)\n .ToDictionary(x => x.Key, x => x.Count(), comparer);\n\n var secondMap = second\n .GroupBy(x => x, comparer)\n .ToDictionary(x => x.Key, x => x.Count(), comparer);\n\n if (firstMap.Keys.Count != secondMap.Keys.Count)\n return false;\n\n if (firstMap.Keys.Any(k1 => !secondMap.ContainsKey(k1)))\n return false;\n\n return firstMap.Keys.All(x => firstMap[x] == secondMap[x]);\n }\n"
},
{
"answer_id": 47289089,
"author": "Pier-Lionel Sgard",
"author_id": 8500879,
"author_profile": "https://Stackoverflow.com/users/8500879",
"pm_score": 3,
"selected": false,
"text": "collection1 = {1, 2, 3, 4};\ncollection2 = {2, 4, 1, 3};\n\ncollection1.ShouldAllBe(item=>collection2.Contains(item)); // true\n public static class ShouldlyIEnumerableExtensions\n{\n public static void ShouldEquivalentTo<T>(this IEnumerable<T> list, IEnumerable<T> equivalent)\n {\n list.ShouldAllBe(l => equivalent.Contains(l));\n }\n}\n collection1.ShouldBe(collection2, ignoreOrder: true); // true\n"
},
{
"answer_id": 51775026,
"author": "Josh Gust",
"author_id": 4629442,
"author_profile": "https://Stackoverflow.com/users/4629442",
"pm_score": 0,
"selected": false,
"text": "IEnumerable<T> .GroupBy() ListA.Where(a => ListB.Contains(a)).ToList() public static bool IsSameAs<T, TKey>(this IEnumerable<T> source, IEnumerable<T> target, Expression<Func<T, TKey>> keySelectorExpression)\n {\n // check the object\n if (source == null && target == null) return true;\n if (source == null || target == null) return false;\n\n var sourceList = source.ToList();\n var targetList = target.ToList();\n\n // check the list count :: { 1,1,1 } != { 1,1,1,1 }\n if (sourceList.Count != targetList.Count) return false;\n\n var keySelector = keySelectorExpression.Compile();\n var groupedSourceList = sourceList.GroupBy(keySelector).ToList();\n var groupedTargetList = targetList.GroupBy(keySelector).ToList();\n\n // check that the number of grouptings match :: { 1,1,2,3,4 } != { 1,1,2,3,4,5 }\n var groupCountIsSame = groupedSourceList.Count == groupedTargetList.Count;\n if (!groupCountIsSame) return false;\n\n // check that the count of each group in source has the same count in target :: for values { 1,1,2,3,4 } & { 1,1,1,2,3,4 }\n // key:count\n // { 1:2, 2:1, 3:1, 4:1 } != { 1:3, 2:1, 3:1, 4:1 }\n var countsMissmatch = groupedSourceList.Any(sourceGroup =>\n {\n var targetGroup = groupedTargetList.Single(y => y.Key.Equals(sourceGroup.Key));\n return sourceGroup.Count() != targetGroup.Count();\n });\n return !countsMissmatch;\n }\n"
},
{
"answer_id": 53857873,
"author": "Jo Ham",
"author_id": 4348580,
"author_profile": "https://Stackoverflow.com/users/4348580",
"pm_score": 0,
"selected": false,
"text": "IEnumerable IComparable OrderBy bool equal = collection1.OrderBy(i => i?.GetHashCode())\n .SequenceEqual(collection2.OrderBy(i => i?.GetHashCode()));\n"
},
{
"answer_id": 57664570,
"author": "crokusek",
"author_id": 538763,
"author_profile": "https://Stackoverflow.com/users/538763",
"pm_score": 0,
"selected": false,
"text": "using Microsoft.VisualStudio.TestTools.UnitTesting;\n\n// define collection1, collection2, ...\n\nAssert.Equal(collection1.OrderBy(c=>c).ToCsv(), collection2.OrderBy(c=>c).ToCsv());\n public static string ToCsv<T>(\n this IEnumerable<T> values,\n Func<T, string> selector,\n string joinSeparator = \",\")\n{\n if (selector == null)\n {\n if (typeof(T) == typeof(Int16) ||\n typeof(T) == typeof(Int32) ||\n typeof(T) == typeof(Int64))\n {\n selector = (v) => Convert.ToInt64(v).ToStringInvariant();\n }\n else if (typeof(T) == typeof(decimal))\n {\n selector = (v) => Convert.ToDecimal(v).ToStringInvariant();\n }\n else if (typeof(T) == typeof(float) ||\n typeof(T) == typeof(double))\n {\n selector = (v) => Convert.ToDouble(v).ToString(CultureInfo.InvariantCulture);\n }\n else\n {\n selector = (v) => v.ToString();\n }\n }\n\n return String.Join(joinSeparator, values.Select(v => selector(v)));\n}\n"
},
{
"answer_id": 67486151,
"author": "xhafan",
"author_id": 379279,
"author_profile": "https://Stackoverflow.com/users/379279",
"pm_score": 1,
"selected": false,
"text": " public static bool AreEquivalentIgnoringDuplicates<T>(this IEnumerable<T> items, IEnumerable<T> otherItems)\n {\n var itemList = items.ToList();\n var otherItemList = otherItems.ToList();\n var except = itemList.Except(otherItemList);\n return itemList.Count == otherItemList.Count && except.IsEmpty();\n }\n\n public static bool AreEquivalent<T>(this IEnumerable<T> items, IEnumerable<T> otherItems)\n {\n var itemList = items.ToList();\n var otherItemList = otherItems.ToList();\n var except = itemList.Except(otherItemList);\n return itemList.Distinct().Count() == otherItemList.Count && except.IsEmpty();\n }\n [Test]\n public void collection_with_duplicates_are_equivalent()\n {\n var a = new[] {1, 5, 5};\n var b = new[] {1, 1, 5};\n\n a.AreEquivalentIgnoringDuplicates(b).ShouldBe(true); \n }\n\n [Test]\n public void collection_with_duplicates_are_not_equivalent()\n {\n var a = new[] {1, 5, 5};\n var b = new[] {1, 1, 5};\n\n a.AreEquivalent(b).ShouldBe(false); \n }\n"
},
{
"answer_id": 72801254,
"author": "Adam Simon",
"author_id": 8656352,
"author_profile": "https://Stackoverflow.com/users/8656352",
"pm_score": 0,
"selected": false,
"text": "public static class EnumerableExtensions\n{\n public static bool SequenceEqualUnordered<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> second)\n {\n return SequenceEqualUnordered(source, second, EqualityComparer<TSource>.Default);\n }\n \n public static bool SequenceEqualUnordered<TSource>(this IEnumerable<TSource> source, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)\n {\n if (source == null)\n throw new ArgumentNullException(nameof(source));\n\n if (second == null)\n throw new ArgumentNullException(nameof(second));\n\n if (source.TryGetCount(out int firstCount) && second.TryGetCount(out int secondCount))\n {\n if (firstCount != secondCount)\n return false;\n\n if (firstCount == 0)\n return true;\n }\n\n IEqualityComparer<ValueTuple<TSource>> wrapperComparer = comparer != null ? new WrappedItemComparer<TSource>(comparer) : null;\n\n Dictionary<ValueTuple<TSource>, int> counters;\n ValueTuple<TSource> key;\n int counter;\n\n using (IEnumerator<TSource> enumerator = source.GetEnumerator())\n {\n if (!enumerator.MoveNext())\n return !second.Any();\n\n counters = new Dictionary<ValueTuple<TSource>, int>(wrapperComparer);\n\n do\n {\n key = new ValueTuple<TSource>(enumerator.Current);\n\n if (counters.TryGetValue(key, out counter))\n counters[key] = counter + 1;\n else\n counters.Add(key, 1);\n }\n while (enumerator.MoveNext());\n }\n\n foreach (TSource item in second)\n {\n key = new ValueTuple<TSource>(item);\n\n if (counters.TryGetValue(key, out counter))\n {\n if (counter <= 0)\n return false;\n\n counters[key] = counter - 1;\n }\n else\n return false;\n }\n\n return counters.Values.All(cnt => cnt == 0);\n }\n\n private static bool TryGetCount<TSource>(this IEnumerable<TSource> source, out int count)\n {\n switch (source)\n {\n case ICollection<TSource> collection:\n count = collection.Count;\n return true;\n case IReadOnlyCollection<TSource> readOnlyCollection:\n count = readOnlyCollection.Count;\n return true;\n case ICollection nonGenericCollection:\n count = nonGenericCollection.Count;\n return true;\n default:\n count = default;\n return false;\n }\n }\n\n private sealed class WrappedItemComparer<TSource> : IEqualityComparer<ValueTuple<TSource>>\n {\n private readonly IEqualityComparer<TSource> _comparer;\n\n public WrappedItemComparer(IEqualityComparer<TSource> comparer)\n {\n _comparer = comparer;\n }\n\n public bool Equals(ValueTuple<TSource> x, ValueTuple<TSource> y) => _comparer.Equals(x.Item1, y.Item1);\n\n public int GetHashCode(ValueTuple<TSource> obj) => _comparer.GetHashCode(obj.Item1);\n }\n}\n ReferenceEquals(first, second) IEnumerable<T> public IEnumerator<T> GetEnumerator() => Enumerable.Repeat(default(T), new Random().Next(10)).GetEnumerator() ICollection<T>"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] |
50,106 |
<p>If any of you have worked with a cool tool for viewing/querying the SQL Transaction logs, please let me know. This should show all the transactional sql statements which are committed or rolled back.</p>
<p>For Database files, if it has some additional graphical capabilities like showing the internal Binary Tree structure of the indexes, that will be awesome but I guess I am asking for too much huh..</p>
|
[
{
"answer_id": 19081981,
"author": "Ardalan Shahgholi",
"author_id": 2063547,
"author_profile": "https://Stackoverflow.com/users/2063547",
"pm_score": 1,
"selected": false,
"text": "Select * from ::fn_dblog(null,null)\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50106",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4337/"
] |
50,114 |
<p>I understand the value of the three-part service/host/client model offered by WCF. But is it just me or does it seem like WCF took something pretty direct and straightforward (the ASMX model) and made a mess out of it? </p>
<p>Is there an alternative to using SvcUtil's command line step back in time to generate the proxy? With ASMX services a test harness was automatically provided; is there a good alternative today with WCF? </p>
<p>I appreciate that the WS* stuff is more tightly integrated with WCF and hope to find some payoff for WCF there, but geeze, otherwise I'm perplexed. </p>
<p>Also, the state of books available for WCF is abysmal at best. Juval Lowy, a superb author, has written a good O'Reilly reference book "Programming WCF Services" but it doesn't do that much (for me anyway) for learning now to use WCF. That book's precursor (and a little better organized, but not much, as a tutorial) is Michele Leroux Bustamante's Learning WCF. It has good spots but is outdated in place and its corresponding Web site is gone. </p>
<p>Do you have good WCF learning references besides just continuing to Google the bejebus out of things?</p>
|
[
{
"answer_id": 50139,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 2,
"selected": false,
"text": "[ServiceContract]\n[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]\npublic class SimpleService\n{\n [OperationContract]\n public string HelloWorld()\n {\n return \"Hello World\";\n }\n\n}\n"
},
{
"answer_id": 23482186,
"author": "Babak.Abad",
"author_id": 2672788,
"author_profile": "https://Stackoverflow.com/users/2672788",
"pm_score": 2,
"selected": false,
"text": "ASMX is older than WCF, and anything ASMX can do so can WCF (and more)"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2536/"
] |
50,115 |
<p>So my site uses <a href="http://mjijackson.com/shadowbox/" rel="nofollow noreferrer">shadowbox</a> to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. </p>
<p>Right-clicking and selecting copy works but <kbd>Ctrl</kbd>+<kbd>C</kbd> doesn't (no keyboard shortcuts do) and most people use <kbd>Ctrl</kbd>+<kbd>C</kbd>? You can see an example of what I'm talking about <a href="http://mjijackson.com/shadowbox/" rel="nofollow noreferrer">here</a>. </p>
<p>Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas?</p>
|
[
{
"answer_id": 58198,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 3,
"selected": true,
"text": "var handleKey=function(e){\n var code=SL.keyCode(e);\n SL.preventDefault(e);\n if(code==81||code==88||code==27){\n SB.close()\n }else{\n if(code==37){\n SB.previous()\n }else{\n if(code==39){\n SB.next()\n }else{\n if(code==32){\n SB[(typeof slide_timer==\"number\"?\"pause\":\"play\")]()\n }\n }\n }\n }\n};\n var handleKey=function(e){\n switch(SL.keyCode(e)) {\n case 81:\n case 88:\n case 27:\n SB.close()\n SL.preventDefault(e);\n break;\n\n case 37:\n SB.previous()\n SL.preventDefault(e);\n break;\n\n case 39:\n SB.next()\n SL.preventDefault(e);\n break;\n\n case 32:\n SB[(typeof slide_timer==\"number\"?\"pause\":\"play\")]()\n SL.preventDefault(e);\n break;\n }\n};\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] |
50,120 |
<p>What options exist for accessing different databases from C++?
Put differently, what alternatives are there to ADO?
What are the pros and cons?</p>
|
[
{
"answer_id": 10654970,
"author": "herzbube",
"author_id": 1054378,
"author_profile": "https://Stackoverflow.com/users/1054378",
"pm_score": 1,
"selected": false,
"text": "QtSql QtSql QString"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5237/"
] |
50,148 |
<p>I know that it does in PHP, and I'm pretty sure it does in Java. I haven't used the latest versions of .NET, so I won't speak for them. It seems very awkward, but I was wondering if there was an underlying reason for this.</p>
|
[
{
"answer_id": 50173,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 1,
"selected": false,
"text": "file_exists() is_file() is_dir() is_link()"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
50,149 |
<p>I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it. </p>
<p>(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).</p>
<p>Here is the function I've written:</p>
<pre><code>CREATE FUNCTION dbo.GetFriendlyDateTimeValue
(
@CompareDate DateTime
)
RETURNS nvarchar(48)
AS
BEGIN
DECLARE @Now DateTime
DECLARE @Hours int
DECLARE @Suff nvarchar(256)
DECLARE @Found bit
SET @Found = 0
SET @Now = getDate()
SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60
IF @Hours <= 1
BEGIN
SET @Suff = 'Just Now'
SET @Found = 1
RETURN @Suff
END
IF @Hours < 24
BEGIN
SET @Suff = ' Hours Ago'
SET @Found = 1
END
IF @Hours >= 8760 AND @Found = 0
BEGIN
SET @Hours = @Hours / 8760
SET @Suff = ' Years Ago'
SET @Found = 1
END
IF @Hours >= 720 AND @Found = 0
BEGIN
SET @Hours = @Hours / 720
SET @Suff = ' Months Ago'
SET @Found = 1
END
IF @Hours >= 168 AND @Found = 0
BEGIN
SET @Hours = @Hours / 168
SET @Suff = ' Weeks Ago'
SET @Found = 1
END
IF @Hours >= 24 AND @Found = 0
BEGIN
SET @Hours = @Hours / 24
SET @Suff = ' Days Ago'
SET @Found = 1
END
RETURN Convert(nvarchar, @Hours) + @Suff
END
</code></pre>
|
[
{
"answer_id": 50193,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 4,
"selected": true,
"text": "CASE\n WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now() \n THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')\n\n WHEN datediff(now(), compare_date) = 1 \n THEN 'Yesterday'\n\n WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now() \n THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')\n\n ELSE concat(datediff(now(), compare_date),' days ago')\nEND\n"
},
{
"answer_id": 50228,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "select\n CC.MOD_DATETIME,\n 'Last modified ' ||\n case when (sysdate - cc.mod_datetime) < 1\n then round((sysdate - CC.MOD_DATETIME)*24) || ' hours ago'\n when (sysdate - CC.MOD_DATETIME) between 1 and 7\n then round(sysdate-CC.MOD_DATETIME) || ' days ago'\n when (sysdate - CC.MOD_DATETIME) between 8 and 365\n then round((sysdate - CC.MOD_DATETIME) / 7) || ' weeks ago'\n when (sysdate - CC.MOD_DATETIME) > 365 \n then round((sysdate - CC.MOD_DATETIME) / 365) || ' years ago'\n end\nfrom \n customer_catalog CC\n"
},
{
"answer_id": 50301,
"author": "Jasmine",
"author_id": 5255,
"author_profile": "https://Stackoverflow.com/users/5255",
"pm_score": 1,
"selected": false,
"text": "drop function dbo.time_diff_message \nGO\n\ncreate function dbo.time_diff_message (\n @input_date datetime\n)\nreturns varchar(200) \nas \nbegin \ndeclare @msg varchar(200) \ndeclare @hourdiff int\n\nset @hourdiff = datediff(hour, @input_date, getdate()) \nset @msg = case when @hourdiff < 0 then ' from now' else ' ago' end \nset @hourdiff = abs(@hourdiff) \nset @msg = case when @hourdiff > 24 then convert(varchar, @hourdiff/24) + ' days' + @msg\n else convert(varchar, @hourdiff) + ' hours' + @msg\n end\n\nreturn @msg\nend\n\nGO \nselect dbo.time_diff_message('Dec 7 1941')\n"
},
{
"answer_id": 50341,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION dbo.GetFriendlyDateTimeValue( @CompareDate DATETIME ) RETURNS NVARCHAR(48) AS BEGIN\ndeclare @s nvarchar(48)\nset @s='Now'\nselect top 1 @s=convert(nvarchar,abs(n))+' '+s+case when abs(n)>1 then 's' else '' end+case when n>0 then ' ago' else ' from now' end from (\n select convert(int,(convert(float,(getdate()-@comparedate))*n)) as n, s from (\n select 1/365 as n, 'Year' as s union all\n select 1/30, 'Month' union all\n select 1, 'Day' union all\n select 7, 'Week' union all\n select 24, 'Hour' union all\n select 24*60, 'Minute' union all\n select 24*60*60, 'Second'\n ) k\n) j where abs(n)>0 order by abs(n)\nreturn @s\nEND\n"
},
{
"answer_id": 1453961,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "CREATE FUNCTION [dbo].[GetFriendlyDateTimeValue]( @CompareDate DATETIME ) RETURNS NVARCHAR(48) AS BEGIN\ndeclare @s nvarchar(48)\n\nset @s='Now'\nselect top 1 @s=convert(nvarchar,abs(n))+' '+s+case when abs(n)>1 then 's' else '' end+case when n>0 then ' ago' else ' from now' end from (\n select convert(int,(convert(float,(getdate()-@comparedate))*n)) as n, s from (\n select 1/365 as n, 'year' as s union all\n select 1/30, 'month' union all\n select 1/7, 'week' union all\n select 1, 'day' union all\n select 24, 'hour' union all\n select 24*60, 'minute' union all\n select 24*60*60, 'second'\n ) k\n) j where abs(n)>0 order by abs(n)\n\nif @s like '%days%'\nBEGIN\n -- if over 2 months ago then express in months\n IF convert(nvarchar,DATEDIFF(MM, @CompareDate, GETDATE())) >= 2\n BEGIN\n select @s = convert(nvarchar,DATEDIFF(MM, @CompareDate, GETDATE())) + ' months ago'\n END\n\n -- if over 2 weeks ago then express in weeks, otherwise express as days\n ELSE IF convert(nvarchar,DATEDIFF(DD, @CompareDate, GETDATE())) >= 14\n BEGIN\n select @s = convert(nvarchar,DATEDIFF(WK, @CompareDate, GETDATE())) + ' weeks ago'\n END\n\n ELSE\n select @s = convert(nvarchar,DATEDIFF(DD, @CompareDate, GETDATE())) + ' days ago'\nEND\n\nreturn @s\nEND\n"
},
{
"answer_id": 32572897,
"author": "Eric Bynum",
"author_id": 4465532,
"author_profile": "https://Stackoverflow.com/users/4465532",
"pm_score": 0,
"selected": false,
"text": " CREATE FUNCTION [dbo].[FN_TIME_ELAPSED] \n (\n @TIMESTAMP DATETIME\n )\n RETURNS VARCHAR(50)\n AS\n BEGIN\n\n RETURN \n (\n SELECT TIME_ELAPSED = \n CASE\n WHEN @TIMESTAMP IS NULL THEN NULL\n WHEN MINUTES_AGO < 60 THEN CONCAT(MINUTES_AGO, ' minutes ago')\n WHEN HOURS_AGO < 24 THEN CONCAT(HOURS_AGO, ' hours ago')\n WHEN DAYS_AGO < 365 THEN CONCAT(DAYS_AGO, ' days ago')\n ELSE CONCAT(YEARS_AGO, ' years ago') END\n FROM ( SELECT MINUTES_AGO = DATEDIFF(MINUTE, @TIMESTAMP, GETDATE()) ) TIMESPAN_MIN\n CROSS APPLY ( SELECT HOURS_AGO = DATEDIFF(HOUR, @TIMESTAMP, GETDATE()) ) TIMESPAN_HOUR\n CROSS APPLY ( SELECT DAYS_AGO = DATEDIFF(DAY, @TIMESTAMP, GETDATE()) ) TIMESPAN_DAY\n CROSS APPLY ( SELECT YEARS_AGO = DATEDIFF(YEAR, @TIMESTAMP, GETDATE()) ) TIMESPAN_YEAR\n )\n END\n GO\n SELECT TIME_ELAPSED = DBO.FN_TIME_ELAPSED(AUDIT_TIMESTAMP)\n FROM SOME_AUDIT_TABLE\n"
},
{
"answer_id": 69703438,
"author": "Nitin Luhar",
"author_id": 9325508,
"author_profile": "https://Stackoverflow.com/users/9325508",
"pm_score": 0,
"selected": false,
"text": "CASE WHEN datediff(SECOND,OM.OrderDate,GETDATE()) < 60 THEN\n CONVERT(NVARCHAR(MAX),datediff(SECOND,OM.OrderDate,GETDATE())) +' seconds ago'\nWHEN datediff(MINUTE,OM.OrderDate,GETDATE()) < 60 THEN\n CONVERT(NVARCHAR(MAX),datediff(MINUTE,OM.OrderDate,GETDATE())) +' minutes ago'\nWHEN datediff(HOUR,OM.OrderDate,GETDATE()) < 24 THEN\n CONVERT(NVARCHAR(MAX),datediff(HOUR,OM.OrderDate,GETDATE())) +' hours ago'\nWHEN datediff(DAY,OM.OrderDate,GETDATE()) < 8 THEN\n CONVERT(NVARCHAR(MAX),datediff(DAY,OM.OrderDate,GETDATE())) +' Days ago'\nELSE FORMAT(OM.OrderDate,'dd/MM/yyyy hh:mm tt') END AS TimeStamp\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] |
50,151 |
<p>I have several wpf pages with update/delete/add buttons. I want to display to the user messages like "successful delete", etc. How can I best implement this so the message is defined in a single place (similar to an asp.net master page) and I can update this message from anywhere?</p>
|
[
{
"answer_id": 50214,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "MyAppUserSettings.StatusMessage = \"You just deleted the administrator!\" \n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50151",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3047/"
] |
50,159 |
<p>I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?</p>
|
[
{
"answer_id": 50166,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": false,
"text": "ldd path/to/the/tool\n"
},
{
"answer_id": 50218,
"author": "John Vasileff",
"author_id": 5076,
"author_profile": "https://Stackoverflow.com/users/5076",
"pm_score": 9,
"selected": true,
"text": "ldd find /bin -type f -perm /a+x -exec ldd {} \\; \\\n| grep so \\\n| sed -e '/^[^\\t]/ d' \\\n| sed -e 's/\\t//' \\\n| sed -e 's/.*=..//' \\\n| sed -e 's/ (0.*)//' \\\n| sort \\\n| uniq -c \\\n| sort -n\n 1 /lib64/libexpat.so.0\n 1 /lib64/libgcc_s.so.1\n 1 /lib64/libnsl.so.1\n 1 /lib64/libpcre.so.0\n 1 /lib64/libproc-3.2.7.so\n 1 /usr/lib64/libbeecrypt.so.6\n 1 /usr/lib64/libbz2.so.1\n 1 /usr/lib64/libelf.so.1\n 1 /usr/lib64/libpopt.so.0\n 1 /usr/lib64/librpm-4.4.so\n 1 /usr/lib64/librpmdb-4.4.so\n 1 /usr/lib64/librpmio-4.4.so\n 1 /usr/lib64/libsqlite3.so.0\n 1 /usr/lib64/libstdc++.so.6\n 1 /usr/lib64/libz.so.1\n 2 /lib64/libasound.so.2\n 2 /lib64/libblkid.so.1\n 2 /lib64/libdevmapper.so.1.02\n 2 /lib64/libpam_misc.so.0\n 2 /lib64/libpam.so.0\n 2 /lib64/libuuid.so.1\n 3 /lib64/libaudit.so.0\n 3 /lib64/libcrypt.so.1\n 3 /lib64/libdbus-1.so.3\n 4 /lib64/libresolv.so.2\n 4 /lib64/libtermcap.so.2\n 5 /lib64/libacl.so.1\n 5 /lib64/libattr.so.1\n 5 /lib64/libcap.so.1\n 6 /lib64/librt.so.1\n 7 /lib64/libm.so.6\n 9 /lib64/libpthread.so.0\n 13 /lib64/libselinux.so.1\n 13 /lib64/libsepol.so.1\n 22 /lib64/libdl.so.2\n 83 /lib64/ld-linux-x86-64.so.2\n 83 /lib64/libc.so.6\n"
},
{
"answer_id": 50245,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "ldd ldd /bin/* /usr/bin/* ... | sed -e '/^[^\\t]/ d; s/^\\t\\(.* => \\)\\?\\([^ ]*\\) (.*/\\2/g' | sort | uniq -c\n sed sort | uniq -c sort -g linux-gate.so.1"
},
{
"answer_id": 5727326,
"author": "Raghwendra",
"author_id": 716714,
"author_profile": "https://Stackoverflow.com/users/716714",
"pm_score": 3,
"selected": false,
"text": "ldd test\n"
},
{
"answer_id": 8176075,
"author": "Fabiano Tarlao",
"author_id": 1052899,
"author_profile": "https://Stackoverflow.com/users/1052899",
"pm_score": 6,
"selected": false,
"text": "lsof -P -T -p Application_PID\n ldd"
},
{
"answer_id": 15520982,
"author": "smichak",
"author_id": 329855,
"author_profile": "https://Stackoverflow.com/users/329855",
"pm_score": 6,
"selected": false,
"text": "objdump -p /usr/bin/python:\n\nDynamic Section:\n NEEDED libpthread.so.0\n NEEDED libdl.so.2\n NEEDED libutil.so.1\n NEEDED libssl.so.1.0.0\n NEEDED libcrypto.so.1.0.0\n NEEDED libz.so.1\n NEEDED libm.so.6\n NEEDED libc.so.6\n INIT 0x0000000000416a98\n FINI 0x000000000053c058\n GNU_HASH 0x0000000000400298\n STRTAB 0x000000000040c858\n SYMTAB 0x0000000000402aa8\n STRSZ 0x0000000000006cdb\n SYMENT 0x0000000000000018\n DEBUG 0x0000000000000000\n PLTGOT 0x0000000000832fe8\n PLTRELSZ 0x0000000000002688\n PLTREL 0x0000000000000007\n JMPREL 0x0000000000414410\n RELA 0x0000000000414398\n RELASZ 0x0000000000000078\n RELAENT 0x0000000000000018\n VERNEED 0x0000000000414258\n VERNEEDNUM 0x0000000000000008\n VERSYM 0x0000000000413534\n"
},
{
"answer_id": 28161306,
"author": "bluebadge",
"author_id": 3889589,
"author_profile": "https://Stackoverflow.com/users/3889589",
"pm_score": 3,
"selected": false,
"text": "ldd objdump lsof otool -L $ otool -L `which openssl`\n/usr/bin/openssl:\n /usr/lib/libcrypto.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)\n /usr/lib/libssl.0.9.8.dylib (compatibility version 0.9.8, current version 0.9.8)\n /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)\n which openssl"
},
{
"answer_id": 43026880,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 4,
"selected": false,
"text": "readelf -d redelf -d objdump -p readelf -d /bin/ls | grep 'NEEDED'\n 0x0000000000000001 (NEEDED) Shared library: [libselinux.so.1]\n 0x0000000000000001 (NEEDED) Shared library: [libacl.so.1]\n 0x0000000000000001 (NEEDED) Shared library: [libc.so.6]\n $ locate libselinux.so.1\n/lib/i386-linux-gnu/libselinux.so.1\n/lib/x86_64-linux-gnu/libselinux.so.1\n/mnt/debootstrap/lib/x86_64-linux-gnu/libselinux.so.1\n readelf -d /lib/x86_64-linux-gnu/libselinux.so.1 | grep 'NEEDED'\n 0x0000000000000001 (NEEDED) Shared library: [libpcre.so.3]\n0x0000000000000001 (NEEDED) Shared library: [libdl.so.2]\n0x0000000000000001 (NEEDED) Shared library: [libc.so.6]\n0x0000000000000001 (NEEDED) Shared library: [ld-linux-x86-64.so.2]\n /proc/<pid>/maps sudo awk '/\\.so/{print $6}' /proc/1/maps | sort -u\n init 1 /lib/x86_64-linux-gnu/ld-2.23.so\n/lib/x86_64-linux-gnu/libapparmor.so.1.4.0\n/lib/x86_64-linux-gnu/libaudit.so.1.0.0\n/lib/x86_64-linux-gnu/libblkid.so.1.1.0\n/lib/x86_64-linux-gnu/libc-2.23.so\n/lib/x86_64-linux-gnu/libcap.so.2.24\n/lib/x86_64-linux-gnu/libdl-2.23.so\n/lib/x86_64-linux-gnu/libkmod.so.2.3.0\n/lib/x86_64-linux-gnu/libmount.so.1.1.0\n/lib/x86_64-linux-gnu/libpam.so.0.83.1\n/lib/x86_64-linux-gnu/libpcre.so.3.13.2\n/lib/x86_64-linux-gnu/libpthread-2.23.so\n/lib/x86_64-linux-gnu/librt-2.23.so\n/lib/x86_64-linux-gnu/libseccomp.so.2.2.3\n/lib/x86_64-linux-gnu/libselinux.so.1\n/lib/x86_64-linux-gnu/libuuid.so.1.3.0\n dlopen sleep(1000)"
},
{
"answer_id": 43207568,
"author": "Shimon Doodkin",
"author_id": 466363,
"author_profile": "https://Stackoverflow.com/users/466363",
"pm_score": 2,
"selected": false,
"text": "ldd executable_name|awk '{print $3}'|xargs dpkg -S |awk -F \":\" '{print $1}'\n"
},
{
"answer_id": 46832161,
"author": "Anders Domeij",
"author_id": 8801700,
"author_profile": "https://Stackoverflow.com/users/8801700",
"pm_score": 0,
"selected": false,
"text": "#! /bin/bash\n\nrecurse ()\n# Param 1 is the nuumber of spaces that the output will be prepended with\n# Param 2 full path to library\n{\n#Use 'readelf -d' to find dependencies\ndependencies=$(readelf -d ${2} | grep NEEDED | awk '{ print $5 }' | tr -d '[]')\nfor d in $dependencies; do\n echo \"${1}${d}\"\n nm=${d##*/}\n #libstdc++ hack for the '+'-s\n nm1=${nm//\"+\"/\"\\+\"}\n # /lib /lib64 /usr/lib and /usr/lib are searched\n children=$(locate ${d} | grep -E \"(^/(lib|lib64|usr/lib|usr/lib64)/${nm1})\")\n rc=$?\n #at least locate... didn't fail\n if [ ${rc} == \"0\" ] ; then\n #we have at least one dependency\n if [ ${#children[@]} -gt 0 ]; then\n #check the dependeny's dependencies\n for c in $children; do\n recurse \" ${1}\" ${c}\n done\n else\n echo \"${1}no children found\"\n fi\n else\n echo \"${1}locate failed for ${d}\"\n fi\ndone\n}\n# Q&D -- recurse needs 2 params could/should be supplied from cmdline\nrecurse \"\" !!full path to library you want to investigate!!\n"
},
{
"answer_id": 53554914,
"author": "SoSen",
"author_id": 7098915,
"author_profile": "https://Stackoverflow.com/users/7098915",
"pm_score": 2,
"selected": false,
"text": "/proc/<pid>/maps\n cat /proc/2601/maps\n 7fb37a8f2000-7fb37a8f4000 r-xp 00000000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37a8f4000-7fb37aaf3000 ---p 00002000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37aaf3000-7fb37aaf4000 r--p 00001000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37aaf4000-7fb37aaf5000 rw-p 00002000 08:06 4065647 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/network_networkmanager.so\n7fb37aaf5000-7fb37aafe000 r-xp 00000000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37aafe000-7fb37acfd000 ---p 00009000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37acfd000-7fb37acfe000 r--p 00008000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37acfe000-7fb37acff000 rw-p 00009000 08:06 4065646 /usr/lib/x86_64-linux-gnu/libproxy/0.4.15/modules/config_gnome3.so\n7fb37acff000-7fb37ad1d000 r-xp 00000000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37ad1d000-7fb37af1d000 ---p 0001e000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37af1d000-7fb37af1e000 r--p 0001e000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37af1e000-7fb37af1f000 rw-p 0001f000 08:06 3416761 /usr/lib/x86_64-linux-gnu/libproxy.so.1.0.0\n7fb37af1f000-7fb37af21000 r-xp 00000000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n7fb37af21000-7fb37b121000 ---p 00002000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n7fb37b121000-7fb37b122000 r--p 00002000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n7fb37b122000-7fb37b123000 rw-p 00003000 08:06 4065186 /usr/lib/x86_64-linux-gnu/gio/modules/libgiolibproxy.so\n"
},
{
"answer_id": 63699024,
"author": "nomad",
"author_id": 12207627,
"author_profile": "https://Stackoverflow.com/users/12207627",
"pm_score": 2,
"selected": false,
"text": "ldd `which <executable>` # back quotes, not single quotes\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3756/"
] |
50,169 |
<p>I have a query that looks like this:</p>
<pre><code>public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
</code></pre>
<p>I need to print the information of the order and the user who created it:</p>
<pre><code>foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
</code></pre>
<p>This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?</p>
<p>Thanks</p>
<p>UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:</p>
<pre><code>public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
</code></pre>
<p>Thanks sirrocco.</p>
|
[
{
"answer_id": 56966505,
"author": "Bharat Kumar",
"author_id": 3471489,
"author_profile": "https://Stackoverflow.com/users/3471489",
"pm_score": 0,
"selected": false,
"text": "context.Cars\n .OrderBy(x => x.Id)\n .Skip(50000)\n .Take(1000)\n .ToList();\n select * from [Cars] order by [Cars].[Id] asc offset 50000 rows fetch next 1000 rows\n context.Cars\n .Where(x => context.Cars.OrderBy(y => y.Id).Select(y => y.Id).Skip(50000).Take(1000).Contains(x.Id))\n .ToList();\n exec sp_executesql N'\nselect * from [Cars]\nwhere exists\n (select 1 from\n (select [Cars].[Id] from [Cars] order by [Cars].[Id] asc offset @p__linq__0 rows fetch next @p__linq__1 rows only\n ) as [Limit1]\n where [Limit1].[Id] = [Cars].[Id]\n )\norder by [Cars].[Id] asc',N'@p__linq__0 int,@p__linq__1 int',@p__linq__0=50000,@p__linq__1=1000\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4269/"
] |
50,170 |
<p>I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.</p>
<p>My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS.</p>
<p>So the code below, which I <em>think</em> is correct according to <a href="http://www.w3.org/TR/CSS2/generate.html#markers" rel="nofollow noreferrer">the spec</a>, is like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
counter-reset: myCounter;
}
li {
counter-increment: myCounter;
}
li:before {
content: counter(myCounter)". ";
display: marker;
width: 5em;
text-align: right;
marker-offset: 1em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>The<li>
<li>quick</li>
<li>brown</li>
</ol>
<ol>
<li>fox</li>
<li>jumped</li>
<li>over</li>
</ol></code></pre>
</div>
</div>
</p>
<p>But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).</p>
<p>So, does anyone know if markers are <em>supposed</em> to work? Quirksmode.org isn't being its usual helpful self in this regard :(.</p>
|
[
{
"answer_id": 50271,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 1,
"selected": false,
"text": "inline-block li:before\n{\n content: counter(myCounter)\". \";\n display: inline-block;\n width: 2em;\n padding-right: 0.3em;\n text-align: right;\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
50,182 |
<p>Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display.</p>
<p><strong>Edit To Clarify</strong>:<br>
The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets.</p>
|
[
{
"answer_id": 50220,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 2,
"selected": false,
"text": "/dev"
},
{
"answer_id": 52266,
"author": "Thomas Kammeyer",
"author_id": 4410,
"author_profile": "https://Stackoverflow.com/users/4410",
"pm_score": 4,
"selected": true,
"text": "#include <X11/Xlib.h>"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070/"
] |
50,194 |
<p>I've got a number of non-technical users that all share a set of project files. It would be ideal to have them using version control, but I think that both subversion and git are too technical for non-technical office staff.</p>
<p>Is there any distributed source control software that would work well for normal people?</p>
|
[
{
"answer_id": 50258,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 1,
"selected": false,
"text": "svn cvs"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4767/"
] |
50,223 |
<p>We're using Mercurial where I work and I want to have a setup similar to how I used SVN:</p>
<ul>
<li>Trunk</li>
<li>Tags
<ul>
<li>Production</li>
</ul></li>
<li>Branches</li>
</ul>
<p>Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. </p>
<p>Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?</p>
|
[
{
"answer_id": 50239,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "hg transplant"
},
{
"answer_id": 50475,
"author": "Erin Dees",
"author_id": 3462,
"author_profile": "https://Stackoverflow.com/users/3462",
"pm_score": 5,
"selected": true,
"text": "hg merge .hgrc Mercurial.ini cd ~/src/development\n# hack hack hack\nhg commit -m \"Made some changes\"\ncd ../production\nhg fetch ../development\n hg update -C development\n# hack hack hack\nhg commit -m \"Made some changes\"\nhg update -C production\nhg merge development\nhg commit -m \"Merged from development\"\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/956/"
] |
50,236 |
<p>Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.</p>
|
[
{
"answer_id": 50241,
"author": "Karim",
"author_id": 2494,
"author_profile": "https://Stackoverflow.com/users/2494",
"pm_score": 5,
"selected": true,
"text": "SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); \n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] |
50,251 |
<p>I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? : </p>
<p><strong>My Main method:</strong></p>
<pre><code>static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = JSonify<Customer>
.GetJsonTable(
query,
2,
10,
"CustomerID"
,
new string[]
{
"CustomerID",
"CompanyName",
"City",
"Country",
"Orders.Count"
});
Console.WriteLine(json);
}
</code></pre>
<p><strong>JSonify class</strong></p>
<pre><code>public static class JSonify<T>
{
public static string GetJsonTable(
this IQueryable<T> query,
int pageNumber,
int pageSize,
string IDColumnName,
string[] columnNames)
{
string selectItems =
String.Format(@"
new
{
{{0}} as ID,
cell = new object[]{{{1}}}
}",
IDColumnName,
String.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows =
query
.Select(selectItems)
.Skip(pageNumber * pageSize)
.Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
// Should produce this result:
// {
// "page":2,
// "total":91,
// "rows":
// [
// {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]},
// {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]},
// {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]},
// {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]},
// {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]},
// {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]},
// {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]},
// {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]},
// {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]},
// {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]}
// ]
// }
}
}
</code></pre>
|
[
{
"answer_id": 50592,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n{\n NorthwindDataContext db = new NorthwindDataContext();\n var query = db.Customers;\n string json = query.GetJsonTable<Customer>(2, 10, \"CustomerID\", new string[] {\"CustomerID\", \"CompanyName\", \"City\", \"Country\", \"Orders.Count\" });\n } \n\npublic static class JSonify\n{\n public static string GetJsonTable<T>(\n this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)\n {\n string select = string.Format(\"new ({0} as ID, new ({1}) as cell)\", IDColumnName, string.Join(\",\", columnNames));\n var items = new\n {\n page = pageNumber,\n total = query.Count(),\n rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)\n };\n return JavaScriptConvert.SerializeObject(items);\n }\n} \n"
},
{
"answer_id": 55511,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 3,
"selected": true,
"text": "public static class JSonify\n{\n public static string GetJsonTable<T>(\n this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)\n {\n string select = string.Format(\"new ({0} as ID, \\\"CELLSTART\\\" as CELLSTART, {1}, \\\"CELLEND\\\" as CELLEND)\", IDColumnName, string.Join(\",\", columnNames));\n var items = new\n {\n page = pageNumber,\n total = query.Count(),\n rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)\n };\n string json = JavaScriptConvert.SerializeObject(items);\n json = json.Replace(\"\\\"CELLSTART\\\":\\\"CELLSTART\\\",\", \"\\\"cell\\\":[\");\n json = json.Replace(\",\\\"CELLEND\\\":\\\"CELLEND\\\"\", \"]\");\n foreach (string column in columnNames)\n {\n json = json.Replace(\"\\\"\" + column + \"\\\":\", \"\");\n }\n return json;\n }\n} \n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
] |
50,255 |
<p>I've been reading a lot lately about the next release of Java possibly supporting <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29" rel="noreferrer">closures</a>. I feel like I have a pretty firm grasp on what closures are, but I can't think of a solid example of how they would make an Object-Oriented language "better". Can anyone give me a specific use-case where a closure would be needed (or even preferred)?</p>
|
[
{
"answer_id": 54180,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "// Example #1 with closures\npublic IList<Customer> GetFilteredCustomerList(string filter) {\n //Here a closure is created around the filter parameter\n return Customers.Where( c => c.Name.Contains(filter)).ToList();\n}\n //Example #2 without closures, using just basic OO techniques\npublic IList<Customer> GetFilteredCustomerList(string filter) {\n return new Customers.Where( new CustomerNameFiltrator(filter));\n}\n... \npublic class CustomerNameFiltrator : IFilter<Customer> {\n private string _filter;\n public CustomerNameFiltrator(string filter) {\n _filter = filter;\n }\n public bool Filter(Customer customer) {\n return customer.Name.Contains( _filter);\n }\n}\n"
},
{
"answer_id": 63879,
"author": "jrudolph",
"author_id": 7647,
"author_profile": "https://Stackoverflow.com/users/7647",
"pm_score": 4,
"selected": false,
"text": "List<Integer> squareInts(List<Integer> is){\n List<Integer> result = new ArrayList<Integer>(is.size());\n for (Integer i:is)\n result.add(i*i);\n return result;\n}\n is.map({Integer i => i*i})\n void onlyStringsWithMoreThan4Chars(List<String> strings){\n List<String> result = new ArrayList<String>(str.size()); // should be enough\n for (String str:strings)\n if (str.length() > 4) result.add(str);\n return result;\n}\n strings.select({String str => str.length() > 4});\n Runnable createStringPrintingRunnable(final String str){\n return new Runnable(){\n public void run(){\n System.out.println(str); // this accesses a variable from an outer scope\n }\n };\n}\n"
},
{
"answer_id": 509851,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 2,
"selected": false,
"text": "myArray.sort( (a, b) => a.myProperty().compareTo(b.myProperty() );\n myArray.sort(new Comparator<MyClass>() {\n public int compare(MyClass a, MyClass b) {\n return a.myProperty().compareTo(b.myProperty();\n }\n});\n"
},
{
"answer_id": 716716,
"author": "cygil",
"author_id": 42076,
"author_profile": "https://Stackoverflow.com/users/42076",
"pm_score": 3,
"selected": false,
"text": "def reversecmp(x, y):\n return y - x\n\na = [4, 2, 5, 9, 11]\na.sort(cmp=reversecmp)\n a = [4, 2, 5, 9, 11]\na.sort(cmp=lambda x, y : y - x)\n class ReverseComparator implements Comparator {\n public compare(Object x, Object y) {\n return (Integer) y - (Integer) x;\n }\n\n...\n\nList<Integer> a = Arrays.asList(4, 2, 5, 9, 11);\nCollections.sort(a, new ReverseComparator());\n List<Integer> a = Arrays.asList(4, 2, 5, 9, 11);\nComparator reverse = new Comparator() {\n public Compare(Object x, Object y) {\n return (Integer) y - (Integer) x;\n }\n}\nCollections.sort(a, reverse);\n"
},
{
"answer_id": 716783,
"author": "Daniel Earwicker",
"author_id": 27423,
"author_profile": "https://Stackoverflow.com/users/27423",
"pm_score": 2,
"selected": false,
"text": "final for while do goto if"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
] |
50,280 |
<p>I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to <code>padding</code> and <code>position:relative</code>, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.</p>
<p>The main section of css that seems to be causing the problem is:</p>
<pre class="lang-css prettyprint-override"><code>#settings{
float:left;
}
#right_content{
margin-top:20px;
margin-left:440px;
width:400px;
}
</code></pre>
<p>This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.</p>
<p>The site is available at: <a href="http://frickinsweet.com/tools/Theme.mvc.aspx" rel="nofollow noreferrer">http://frickinsweet.com/tools/Theme.mvc.aspx</a> to see the source code.</p>
|
[
{
"answer_id": 50302,
"author": "Mike H",
"author_id": 4563,
"author_profile": "https://Stackoverflow.com/users/4563",
"pm_score": 1,
"selected": false,
"text": "#right_content{\n float: right;\n margin-top: 20px;\n width: 400px;\n}\n"
},
{
"answer_id": 50309,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<style> <body> <head> <a href=\"http://feeds.feedburner.com/ryanlanciaux\" style=\"position:realtive; top:-6px;\">\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] |
50,312 |
<p>I'm running some <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.</p>
<p>I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using <code>ps</code> like this:</p>
<pre><code>PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
</code></pre>
<p>...running the command every X seconds and appending the results to a text file. (for anyone wondering, <code>pmem</code> = % mem usage and <code>nlwp</code> is number of threads)</p>
<p>However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, <code>pcpu</code> is defined as:</p>
<blockquote>
<p>cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. </p>
</blockquote>
<p>In other words, <code>pcpu</code> gives me the % CPU utilization for the process for the <em>lifetime</em> of the process.</p>
<p>Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what <code>top</code> would give me
(CPU utilization of the process since the last update). </p>
<p>How can I collect this from within a shell script? </p>
|
[
{
"answer_id": 50334,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 5,
"selected": true,
"text": "top -b"
},
{
"answer_id": 14520547,
"author": "mighq",
"author_id": 1242724,
"author_profile": "https://Stackoverflow.com/users/1242724",
"pm_score": 0,
"selected": false,
"text": "top -b -n 1\n"
},
{
"answer_id": 15420777,
"author": "Bilzard",
"author_id": 2170865,
"author_profile": "https://Stackoverflow.com/users/2170865",
"pm_score": 2,
"selected": false,
"text": "top -b -n 2 |grep Cpu |tail -n 1 |awk '{print $2}' |sed 's/.[^.]*$//' top -b -n 2 |grep Cpu |tail -n 1 |awk '{print $3}' |sed 's/.[^.]*$//' top -b -n 1 |grep Cpu |tail -n 1 |awk '{print $5}' |sed 's/.[^.]*$//'"
},
{
"answer_id": 65937910,
"author": "isalgueiro",
"author_id": 1913856,
"author_profile": "https://Stackoverflow.com/users/1913856",
"pm_score": 0,
"selected": false,
"text": "-c"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
50,315 |
<p>I have a couple of solutions, but none of them work perfectly.</p>
<p><strong>Platform</strong></p>
<ol>
<li>ASP.NET / VB.NET / .NET 2.0</li>
<li>IIS 6</li>
<li>IE6 (primarily), with some IE7; Firefox not necessary, but useful</li>
</ol>
<p><em>Allowed 3rd Party Options</em></p>
<ol>
<li>Flash</li>
<li>ActiveX (would like to avoid)</li>
<li>Java (would like to avoid)</li>
</ol>
<p><strong>Current Attempts</strong></p>
<p><em>Gmail Style</em>: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.)</p>
<p><em>Flash Uploader</em>: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is <a href="http://digitarald.de/project/fancyupload/" rel="nofollow noreferrer">FancyUpload</a>, another is <a href="http://www.sitepen.com/blog/2008/09/02/the-dojo-toolkit-multi-file-uploader/" rel="nofollow noreferrer">Dojo's Multiple File Uploader</a>, yet another is one by <a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">darick_c at CodeProject</a>.) These excited me, but I quickly ran into two issues:</p>
<ol>
<li>Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal. </li>
<li>The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons.</li>
</ol>
<p><em>Java Uploader</em>: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want. </p>
<p><em>ActiveX Uploader</em>: I found <a href="http://support.persits.com/xupload/demo1.asp" rel="nofollow noreferrer">an ActiveX solution</a> as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think.</p>
<p><strong>Resolution</strong></p>
<p>I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do. </p>
<p>So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal?</p>
|
[
{
"answer_id": 240321,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 1,
"selected": true,
"text": "Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files\nIf uploads.Count > 0 Then\n UploadFiles(uploads)\nElse\n result = \"error\"\n err = \"File Not Uploaded\"\nEnd If\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106/"
] |
50,316 |
<p>I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids.</p>
<p>Edit: <a href="https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality">Someone has already asked this</a>. Thanks Joel Coohorn.</p>
|
[
{
"answer_id": 50320,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 6,
"selected": true,
"text": "<form name=\"form1\" id=\"form1\" method=\"post\" autocomplete=\"off\"\n action=\"http://www.example.com/form.cgi\">\n[...]\n</form>\n"
},
{
"answer_id": 30897967,
"author": "Jay Nielsen",
"author_id": 2561673,
"author_profile": "https://Stackoverflow.com/users/2561673",
"pm_score": 3,
"selected": false,
"text": "autocomplete=\"off\" <input type=\"password\" style=\"display: none;\" />\n<input type=\"password\" name=\"password_update\" />\n"
},
{
"answer_id": 54696260,
"author": "Jakub Fojtik",
"author_id": 1333247,
"author_profile": "https://Stackoverflow.com/users/1333247",
"pm_score": 0,
"selected": false,
"text": "<input type=\"text\" style=\"display: none;\" />\n<input type=\"password\" style=\"display: none;\" />\n<input type=\"password\" name=\"password_update\" />\n autocomplete=\"off\"\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] |
50,332 |
<p>I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:</p>
<p><em>Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))</em></p>
<p>The ItemDrag handler (where the exception takes place), looks like:</p>
<pre><code>private void treeView_ItemDrag(object sender,
System.Windows.Forms.ItemDragEventArgs e)
{
this.DoDragDrop(e.Item, DragDropEffects.Move);
}
</code></pre>
<p>Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)</p>
|
[
{
"answer_id": 52030,
"author": "Stradas",
"author_id": 5410,
"author_profile": "https://Stackoverflow.com/users/5410",
"pm_score": 1,
"selected": false,
"text": "FORMATETC FORMATETC DV DV_E_FORMATETC FORMATETC typedef struct tagFORMATETC\n{\n CLIPFORMAT cfFormat;\n DVTARGETDEVICE *ptd;\n DWORD dwAspect;\n LONG lindex;\n DWORD tymed;\n} FORMATETC, *LPFORMATETC;\n"
},
{
"answer_id": 1315206,
"author": "Joe Caffeine",
"author_id": 159770,
"author_profile": "https://Stackoverflow.com/users/159770",
"pm_score": 1,
"selected": false,
"text": " private void triggerInstanceList_DragOver(object sender, DragEventArgs e)\n {\n SetDropEffect(e);\n }\n\n private void triggerInstanceList_DragEnter(object sender, DragEventArgs e)\n {\n SetDropEffect(e);\n }\n\n private void SetDropEffect(DragEventArgs e)\n {\n if (e.Data.GetDataPresent(typeof(ListViewItem)))\n {\n ListViewItem itemToDrop = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;\n if (itemToDrop.Tag is TriggerTypeIdentifier)\n e.Effect = DragDropEffects.Copy;\n else\n e.Effect = DragDropEffects.Move;\n }\n else\n e.Effect = DragDropEffects.None;\n }\n\n private void triggerInstanceList_DragDrop(object sender, DragEventArgs e)\n {\n if (e.Data.GetDataPresent(typeof(ListViewItem)))\n {\n try\n {\n ListViewItem itemToDrop = e.Data.GetData(typeof(ListViewItem)) as ListViewItem;\n if (itemToDrop.Tag is TriggerTypeIdentifier)\n {\n ListViewItem newItem = new ListViewItem(\"<new \" + itemToDrop.Text + \">\", itemToDrop.ImageIndex);\n _triggerInstanceList.Items.Add(newItem);\n }\n else\n {\n _expiredTriggers.Items.Remove(itemToDrop);\n _triggerInstanceList.Items.Add(itemToDrop);\n }\n }\n catch (Exception ex)\n {\n Debug.WriteLine(ex);\n }\n }\n }\n"
},
{
"answer_id": 10566072,
"author": "Steve Cadwallader",
"author_id": 41693,
"author_profile": "https://Stackoverflow.com/users/41693",
"pm_score": 2,
"selected": false,
"text": " private void OnDrop(object sender, DragEventArgs e)\n {\n // Other logic...\n\n e.Handled = true;\n }\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4398/"
] |
50,373 |
<p>I'm trying to mixin the <code>MultiMap</code> trait with a <code>HashMap</code> like so:</p>
<pre><code>val children:MultiMap[Integer, TreeNode] =
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
</code></pre>
<p>The definition for the <code>MultiMap</code> trait is:</p>
<pre><code>trait MultiMap[A, B] extends Map[A, Set[B]]
</code></pre>
<p>Meaning that a <code>MultiMap</code> of types <code>A</code> & <code>B</code> is a <code>Map</code> of types <code>A</code> & <code>Set[B]</code>, or so it seems to me. However, the compiler complains:</p>
<pre><code>C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]]
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
^ one error found
</code></pre>
<p>It seems that generics are tripping me up again.</p>
|
[
{
"answer_id": 50420,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 6,
"selected": true,
"text": "scala.collection.mutable.Set HashMap[Integer, Set[TreeNode]] scala.collection.Set scala.collection. mutable .Set"
},
{
"answer_id": 64396,
"author": "Calum",
"author_id": 8434,
"author_profile": "https://Stackoverflow.com/users/8434",
"pm_score": 4,
"selected": false,
"text": "scala.collection._ HashMap new HashMap[ Integer, mutable.Set[ TreeNode ] ]\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
50,384 |
<p>I'm using <a href="http://en.wikipedia.org/wiki/Windows_Script_Host#Usage" rel="noreferrer">WScript</a> to automate some tasks, by using WScript.Shell to call external programs.</p>
<p>However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.</p>
<p>I am using code like:</p>
<pre><code>ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand
</code></pre>
<p>Is there a way to do this so it blocks until the shell executed program returns?</p>
|
[
{
"answer_id": 50395,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "Dim WshShell, oExec\nSet WshShell = CreateObject(\"WScript.Shell\")\n\nSet oExec = WshShell.Exec(ZipCommand)\n\nDo While oExec.Status = 0\n WScript.Sleep 100\nLoop\n"
},
{
"answer_id": 50458,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "ZipCommand = \"7za.exe a -r -y \" & ZipDest & BuildLabel & \".zip \" & buildSourceDir\n\nSet wshShell = WScript.CreateObject(\"Wscript.Shell\")\n\nwshShell.Run ZipCommand,1,1\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] |
50,394 |
<p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p>
<p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html" rel="noreferrer">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p>
<p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
|
[
{
"answer_id": 50413,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 0,
"selected": false,
"text": "urllib2 whois whois"
},
{
"answer_id": 55385,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 4,
"selected": true,
"text": "class Whois(object):\n _whois_by_query_cache = {}\n\n def __init__(self, query):\n \"\"\"Initializes the instance variables to defaults. See :meth:`lookup`\n for details on how to submit the query.\"\"\"\n self.query = query\n self.domain = None\n # ... other fields.\n\n def lookup(self):\n \"\"\"Submits the `whois` query and stores results internally.\"\"\"\n # ... implementation\n"
},
{
"answer_id": 2408136,
"author": "Ryan",
"author_id": 289525,
"author_profile": "https://Stackoverflow.com/users/289525",
"pm_score": -1,
"selected": false,
"text": "import socket\nsocket.gethostbyname_ex('url.com')\n"
},
{
"answer_id": 2410537,
"author": "flow",
"author_id": 256361,
"author_profile": "https://Stackoverflow.com/users/256361",
"pm_score": 0,
"selected": false,
"text": "DRWHO.whois() DRWHO.whois_providers[ '*' ] DRWHO.whois() text available ##########################################################################\nimport asyncore as _sys_asyncore\nfrom asyncore import loop as _sys_asyncore_loop\nimport socket as _sys_socket\n\n\n\n##########################################################################\nclass _Whois_request( _sys_asyncore.dispatcher_with_send, object ):\n # simple whois requester\n # original code by Frederik Lundh\n\n #-----------------------------------------------------------------------\n whoisPort = 43\n\n #-----------------------------------------------------------------------\n def __init__(self, consumer, host, provider ):\n _sys_asyncore.dispatcher_with_send.__init__(self)\n self.consumer = consumer\n self.query = host\n self.create_socket( _sys_socket.AF_INET, _sys_socket.SOCK_STREAM )\n self.connect( ( provider, self.whoisPort, ) )\n\n #-----------------------------------------------------------------------\n def handle_connect(self):\n self.send( bytes( '%s\\r\\n' % ( self.query, ), 'utf-8' ) )\n\n #-----------------------------------------------------------------------\n def handle_expt(self):\n self.close() # connection failed, shutdown\n self.consumer.abort()\n\n #-----------------------------------------------------------------------\n def handle_read(self):\n # get data from server\n self.consumer.feed( self.recv( 2048 ) )\n\n #-----------------------------------------------------------------------\n def handle_close(self):\n self.close()\n self.consumer.close()\n\n\n##########################################################################\nclass _Whois_consumer( object ):\n # original code by Frederik Lundh\n\n #-----------------------------------------------------------------------\n def __init__( self, host, provider, result ):\n self.texts_as_bytes = []\n self.host = host\n self.provider = provider\n self.result = result\n\n #-----------------------------------------------------------------------\n def feed( self, text ):\n self.texts_as_bytes.append( text.strip() )\n\n #-----------------------------------------------------------------------\n def abort(self):\n del self.texts_as_bytes[:]\n self.finalize()\n\n #-----------------------------------------------------------------------\n def close(self):\n self.finalize()\n\n #-----------------------------------------------------------------------\n def finalize( self ):\n # join bytestrings and decode them (witha a guessed encoding):\n text_as_bytes = b'\\n'.join( self.texts_as_bytes )\n self.result[ 'text' ] = text_as_bytes.decode( 'utf-8' )\n\n\n##########################################################################\nclass DRWHO:\n\n #-----------------------------------------------------------------------\n whois_providers = {\n '~isa': 'DRWHO/whois-providers',\n '*': 'whois.opensrs.net', }\n\n #-----------------------------------------------------------------------\n def whois( self, domain ):\n R = {}\n provider = self._get_whois_provider( '*' )\n self._fetch_whois( provider, domain, R )\n return R\n\n #-----------------------------------------------------------------------\n def _get_whois_provider( self, top_level_domain ):\n providers = self.whois_providers\n R = providers.get( top_level_domain, None )\n if R is None:\n R = providers[ '*' ]\n return R\n\n #-----------------------------------------------------------------------\n def _fetch_whois( self, provider, domain, pod ):\n #.....................................................................\n consumer = _Whois_consumer( domain, provider, pod )\n request = _Whois_request( consumer, domain, provider )\n #.....................................................................\n _sys_asyncore_loop() # loops until requests have been processed\n\n\n#=========================================================================\nDRWHO = DRWHO()\n\n\ndomain = 'example.com'\nwhois = DRWHO.whois( domain )\nprint( whois[ 'text' ] )\n"
},
{
"answer_id": 4078336,
"author": "Aziz",
"author_id": 494805,
"author_profile": "https://Stackoverflow.com/users/494805",
"pm_score": 3,
"selected": false,
"text": ">>> import pywhois\n>>> w = pywhois.whois('google.com')\n>>> w.expiration_date\n['14-sep-2011']\n>>> w.emails\n['[email protected]',\n '[email protected]',\n '[email protected]',\n '[email protected]']\n>>> print w\n...\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] |
50,417 |
<p>When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)</p>
|
[
{
"answer_id": 50422,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 6,
"selected": true,
"text": ";; recentf stuff\n(require 'recentf)\n(recentf-mode 1)\n(setq recentf-max-menu-items 25)\n(global-set-key \"\\C-x\\ \\C-r\" 'recentf-open-files)\n (require 'recentf)"
},
{
"answer_id": 63917973,
"author": "Glen Whitney",
"author_id": 5583443,
"author_profile": "https://Stackoverflow.com/users/5583443",
"pm_score": 2,
"selected": false,
"text": "file-name-history (savehist-mode 1) .emacs (defun dir-of-recent-files ()\n \"See the list of recently entered files in a Dired buffer.\"\n (interactive)\n (dired (cons\n \"*Recent Files*\"\n (seq-filter\n 'file-exists-p\n (delete-dups\n (mapcar (lambda (s) (string-trim-right s \"/*\"))\n file-name-history)\n ))))\n )\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
50,426 |
<p>I have a few controls that inherit from <code>ASP.NET buttons</code> and use <code>onserverclick</code>.</p>
<p>If the user clicks twice, the button fires two server side events. How can I prevent this?</p>
<p>I tried setting <code>this.disabled='true'</code> after the click (in the <code>onclick</code> attribute) via javascript, but that blocks the first postback as well.</p>
|
[
{
"answer_id": 11466704,
"author": "Andreas Krohn",
"author_id": 1521232,
"author_profile": "https://Stackoverflow.com/users/1521232",
"pm_score": 2,
"selected": false,
"text": "<script type=\"text/javascript\">\n // Using that prm reference, hook _initializeRequest\n Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequestBuchung);\n\n // Abfangen von Mehrfachklicks auf Buttons für asynchrone Postbacks im Updatepanel\n function InitializeRequestBuchung(sender, args) {\n var arrButtonIds = [\"ButtonInsert\", \"ButtonUpdate\"];\n\n // Get a reference to the PageRequestManager.\n var prm = Sys.WebForms.PageRequestManager.getInstance();\n if (prm.get_isInAsyncPostBack() & jQuery.inArray(args.get_postBackElement().id, arrButtonIds) > -1) {\n args.set_cancel(true);\n }\n }\n</script>\n"
},
{
"answer_id": 25312370,
"author": "latuya23",
"author_id": 1314273,
"author_profile": "https://Stackoverflow.com/users/1314273",
"pm_score": 1,
"selected": false,
"text": "<script type=\"text/javascript\">\n function disableFunctn(button){\n button.disabled = true;\n }\n</script>\n<asp:Button ID=\"button1\" UseSubmitBehavior=\"false\" OnClientClick=\"disableFunctn(this);\"/>\n <asp:Button ID=\"button1\" UseSubmitBehavior=\"false\" OnClientClick=\"this.disabled=true;\"/>\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50426",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
50,450 |
<p>This has been driving me crazy for a few days. Why doesn't the following work?</p>
<blockquote>
<pre><code> Dim arr(3, 3) As Integer
For y As Integer = 0 To arr.GetLength(0) - 1
For x As Integer = 0 To arr.GetLength(y) - 1
arr(y, x) = y + x
Next
Next
</code></pre>
</blockquote>
<p>Also, what if the array looked like this instead?</p>
<pre><code>{ {1, 2, 3},
{4, 5, 6, 7, 8, 9, 9, 9},
{5, 4, 3, 2}
}
</code></pre>
|
[
{
"answer_id": 50454,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "arr.GetLength(y) arr.GetLength(1)"
},
{
"answer_id": 50508,
"author": "Akira",
"author_id": 795,
"author_profile": "https://Stackoverflow.com/users/795",
"pm_score": 1,
"selected": false,
"text": "{ {1, 2, 3},\n {4, 5, 6, 7, 8, 9, 9, 9},\n {5, 4, 3, 2}\n}\n"
},
{
"answer_id": 50569,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": -1,
"selected": false,
"text": "DIM arr(3,3) As Integer Dim arr(3) as Integer()\n arr(n).Length\n"
},
{
"answer_id": 50577,
"author": "osp70",
"author_id": 2357,
"author_profile": "https://Stackoverflow.com/users/2357",
"pm_score": 0,
"selected": false,
"text": "Dim arr(3, 3) As Integer\nDim y As Integer\nDim x As Integer\n\nFor x = 0 To arr.Rank - 1\n For y = 0 To arr.GetLength(x) - 2\n arr(x, y) = x + y\n Next\nNext\n"
},
{
"answer_id": 50633,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 4,
"selected": true,
"text": " Dim arr As Integer()() = {New Integer() {1, 2, 3}, New Integer() {4, 5, 6, 7, 8, 9, 9, 9}, New Integer() {5, 4, 3, 2}}\n\n For x = 0 To arr.GetUpperBound(0)\n Console.WriteLine(\"Row \" & x & \" has \" & arr(x).GetUpperBound(0) & \" columns\")\n For y = 0 To arr(x).GetUpperBound(0)\n Console.WriteLine(\"(\" & x & \",\" & y & \") = \" & arr(x)(y))\n Next\n Next\n Row 0 has 2 columns\n(0,0) = 1\n(0,1) = 2\n(0,2) = 3\nRow 1 has 7 columns\n(1,0) = 4\n(1,1) = 5\n(1,2) = 6\n(1,3) = 7\n(1,4) = 8\n(1,5) = 9\n(1,6) = 9\n(1,7) = 9\nRow 2 has 3 columns\n(2,0) = 5\n(2,1) = 4\n(2,2) = 3\n(2,3) = 2\n"
},
{
"answer_id": 1370352,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": " static void Main(string[] args)\n {\n bool exit = false;\n int[] indices = new int[3] { 0, 0, 0 };\n string[][] vectores = new string[3][];\n\n vectores[0] = new string[] { \"A\", \"B\", \"C\" };\n vectores[1] = new string[] { \"A\", \"B\" };\n vectores[2] = new string[] { \"B\", \"D\", \"E\", \"F\" };\n\n string[] item;\n int[] tamaños = new int[3]{vectores[0].GetUpperBound(0), \n vectores[1].GetUpperBound(0), \n vectores[2].GetUpperBound(0)};\n\n while (!exit)\n {\n item = new string[]{ vectores[0][indices[0]],\n vectores[1][indices[1]],\n vectores[2][indices[2]]};\n\n Console.WriteLine(\"[{0},{1},{2}]={3}{4}{5}\", indices[0], indices[1], indices[2], item[0], item[1], item[2]);\n GetVector(tamaños, ref indices, ref exit);\n }\n Console.ReadKey();\n }\n\n public static void GetVector(int[] tamaños, ref int[] indices, ref bool exit)\n {\n for (int i = tamaños.GetUpperBound(0); i >= 0; i--)\n {\n if (tamaños[i] > indices[i])\n {\n indices[i]++;\n break;\n }\n else\n {\n //ULTIMO ITEM EN EL ARRAY, VALIDAR LAS OTRAS DIMENSIONES SI YA ESTA EN EL ULTIMO ITEM\n if (!ValidateIndexes(tamaños, indices))\n indices[i] = 0;\n else\n {\n exit = true;\n break;\n }\n }\n }\n }\n\n public static bool ValidateIndexes(int[] tamaños, int[] indices)\n {\n for (int i = 0; i < tamaños.Length; i++)\n {\n if (tamaños[i] != indices[i])\n return false;\n }\n return true;\n }\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795/"
] |
50,467 |
<p>Is there a good way to adjust the size of a <code>UITextView</code> to conform to its content? Say for instance I have a <code>UITextView</code> that contains one line of text:</p>
<pre><code>"Hello world"
</code></pre>
<p>I then add another line of text:</p>
<pre><code>"Goodbye world"
</code></pre>
<p>Is there a good way in Cocoa Touch to get the <code>rect</code> that will hold all of the lines in the text view so that I can adjust the parent view accordingly?</p>
<p>As another example, look at the notes' field for events in the Calendar application - note how the cell (and the <code>UITextView</code> it contains) expands to hold all lines of text in the notes' string.</p>
|
[
{
"answer_id": 50608,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 4,
"selected": false,
"text": "[textView sizeThatFits:textView.bounds] [textView sizeToFit]"
},
{
"answer_id": 107364,
"author": "Code Addict",
"author_id": 19514,
"author_profile": "https://Stackoverflow.com/users/19514",
"pm_score": 3,
"selected": false,
"text": "NSString -(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size"
},
{
"answer_id": 267642,
"author": "Olie",
"author_id": 34820,
"author_profile": "https://Stackoverflow.com/users/34820",
"pm_score": 3,
"selected": false,
"text": "[myTextView setDelegate: self];\n\n...\n\n- (void)textViewDidChange:(UITextView *)textView {\n if (myTextView == textView) {\n // it changed. Do resizing here.\n }\n}\n"
},
{
"answer_id": 526227,
"author": "user63934",
"author_id": 63934,
"author_profile": "https://Stackoverflow.com/users/63934",
"pm_score": 5,
"selected": false,
"text": "- (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode\n CGSize - (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size\n UITextView UITextView sizeOfFont"
},
{
"answer_id": 2464437,
"author": "Dr. Marty",
"author_id": 295891,
"author_profile": "https://Stackoverflow.com/users/295891",
"pm_score": 1,
"selected": false,
"text": "- (void)textViewDidChange:(UITextView *)textView {\n CGSize textSize = textview.contentSize;\n if (textSize != textView.frame.size)\n textView.frame.size = textSize;\n}\n"
},
{
"answer_id": 2487402,
"author": "Ronnie Liew",
"author_id": 1987,
"author_profile": "https://Stackoverflow.com/users/1987",
"pm_score": 9,
"selected": false,
"text": "UITextView UITextView contentSize CGRect frame = _textView.frame;\nframe.size.height = _textView.contentSize.height;\n_textView.frame = frame;\n contentSize UITextView addSubview frame.size sizeThatFits constant CGSize sizeThatShouldFitTheContent = [_textView sizeThatFits:_textView.frame.size];\nheightConstraint.constant = sizeThatShouldFitTheContent.height;\n heightConstraint [self.textView sizeToFit];\n CGRect _f = self.mainPostText.frame;\n_f.size.height = self.mainPostText.contentSize.height;\nself.mainPostText.frame = _f;\n"
},
{
"answer_id": 5297219,
"author": "dheeraj",
"author_id": 658572,
"author_profile": "https://Stackoverflow.com/users/658572",
"pm_score": 3,
"selected": false,
"text": "UITextView *_textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 300, 10)];\nNSString *str = @\"This is a test text view to check the auto increment of height of a text view. This is only a test. The real data is something different.\";\n_textView.text = str;\n\n[self.view addSubview:_textView];\nCGRect frame = _textView.frame;\nframe.size.height = _textView.contentSize.height;\n_textView.frame = frame;\n\nUILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 5 + frame.origin.y + frame.size.height, 300, 20)];\nlbl.text = @\"Hello!\";\n[self.view addSubview:lbl];\n"
},
{
"answer_id": 11714587,
"author": "Alejo JM",
"author_id": 545032,
"author_profile": "https://Stackoverflow.com/users/545032",
"pm_score": 2,
"selected": false,
"text": "UIFont *fontNormal = [UIFont fontWithName:FONTNAME size:FONTSIZE];\n\nNSString *dealDescription = [client objectForKey:@\"description\"];\n\n//4\nCGSize textSize = [dealDescription sizeWithFont:fontNormal constrainedToSize:CGSizeMake(containerUIView.frame.size.width, 1000)];\n\nCGRect dealDescRect = CGRectMake(10, 300, containerUIView.frame.size.width, textSize.height);\n\nUITextView *dealDesc = [[[UITextView alloc] initWithFrame:dealDescRect] autorelease];\n\ndealDesc.text = dealDescription;\n//add the subview to the container\n[containerUIView addSubview:dealDesc];\n\n//1) after adding the view\nCGRect frame = dealDesc.frame;\nframe.size.height = dealDesc.contentSize.height;\ndealDesc.frame = frame;\n"
},
{
"answer_id": 12787022,
"author": "Bill Cheswick",
"author_id": 1132993,
"author_profile": "https://Stackoverflow.com/users/1132993",
"pm_score": 2,
"selected": false,
"text": "UITextView"
},
{
"answer_id": 13048177,
"author": "Becca Royal-Gordon",
"author_id": 41222,
"author_profile": "https://Stackoverflow.com/users/41222",
"pm_score": 3,
"selected": false,
"text": "UITextView UITextView NSString * string = ...;\nCGFloat textViewWidth = ...;\nUIFont * font = ...;\n\nCGSize size = CGSizeMake(textViewWidth - 8 - 8, 100000);\nsize.height = [string sizeWithFont:font constrainedToSize:size].height + 8 + 8;\n font.leading"
},
{
"answer_id": 18651271,
"author": "Manju",
"author_id": 2720238,
"author_profile": "https://Stackoverflow.com/users/2720238",
"pm_score": 1,
"selected": false,
"text": "CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@\"SAMPLE_FONT\" size:14.0]\n constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX)];\n CGSize textViewSize = [YOURTEXTVIEW.text sizeWithFont:[UIFont fontWithName:@\"SAMPLE_FONT\" size:14.0]\n constrainedToSize:CGSizeMake(YOURTEXTVIEW.frame.size.width, FLT_MAX) lineBreakMode:NSLineBreakByTruncatingTail];\n"
},
{
"answer_id": 18837714,
"author": "phatmann",
"author_id": 201828,
"author_profile": "https://Stackoverflow.com/users/201828",
"pm_score": 5,
"selected": false,
"text": "contentSize - (void)setText:(NSString *)text\n{\n [super setText:text];\n\n if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {\n CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];\n UIEdgeInsets inset = self.textContainerInset;\n self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;\n }\n}\n"
},
{
"answer_id": 18908004,
"author": "Stian Høiland",
"author_id": 659310,
"author_profile": "https://Stackoverflow.com/users/659310",
"pm_score": 2,
"selected": false,
"text": "frame.size.height contentSize.height [textView sizeToFit]"
},
{
"answer_id": 18931531,
"author": "jhibberd",
"author_id": 1348198,
"author_profile": "https://Stackoverflow.com/users/1348198",
"pm_score": 10,
"selected": true,
"text": "- (void)textViewDidChange:(UITextView *)textView\n{\n CGFloat fixedWidth = textView.frame.size.width;\n CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];\n CGRect newFrame = textView.frame;\n newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);\n textView.frame = newFrame;\n}\n let fixedWidth = textView.frame.size.width\nlet newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))\ntextView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)\n textview.scrollEnabled = NO;\n"
},
{
"answer_id": 19084234,
"author": "madmik3",
"author_id": 291733,
"author_profile": "https://Stackoverflow.com/users/291733",
"pm_score": 0,
"selected": false,
"text": " // Code from apple developer forum - @Steve Krulewitz, @Mark Marszal, @Eric Silverberg\n- (CGFloat)measureHeight\n{\n if ([self respondsToSelector:@selector(snapshotViewAfterScreenUpdates:)])\n {\n CGRect frame = internalTextView.bounds;\n CGSize fudgeFactor;\n // The padding added around the text on iOS6 and iOS7 is different.\n fudgeFactor = CGSizeMake(10.0, 16.0);\n\n frame.size.height -= fudgeFactor.height;\n frame.size.width -= fudgeFactor.width;\n\n NSMutableAttributedString* textToMeasure;\n if(internalTextView.attributedText && internalTextView.attributedText.length > 0){\n textToMeasure = [[NSMutableAttributedString alloc] initWithAttributedString:internalTextView.attributedText];\n }\n else{\n textToMeasure = [[NSMutableAttributedString alloc] initWithString:internalTextView.text];\n [textToMeasure addAttribute:NSFontAttributeName value:internalTextView.font range:NSMakeRange(0, textToMeasure.length)];\n }\n\n if ([textToMeasure.string hasSuffix:@\"\\n\"])\n {\n [textToMeasure appendAttributedString:[[NSAttributedString alloc] initWithString:@\"-\" attributes:@{NSFontAttributeName: internalTextView.font}]];\n }\n\n // NSAttributedString class method: boundingRectWithSize:options:context is\n // available only on ios7.0 sdk.\n CGRect size = [textToMeasure boundingRectWithSize:CGSizeMake(CGRectGetWidth(frame), MAXFLOAT)\n options:NSStringDrawingUsesLineFragmentOrigin\n context:nil];\n\n return CGRectGetHeight(size) + fudgeFactor.height;\n}\nelse\n{\n return self.internalTextView.contentSize.height;\n}\n}\n"
},
{
"answer_id": 24950357,
"author": "Nikita Took",
"author_id": 2759361,
"author_profile": "https://Stackoverflow.com/users/2759361",
"pm_score": 4,
"selected": false,
"text": "updateConstraints ResizableTextView viewDidLoad CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)]; viewDidLoad contentSize.height [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {\n if (constraint.firstAttribute == NSLayoutAttributeHeight) {\n constraint.constant = contentSize.height;\n *stop = YES;\n }\n}];\n updateConstraints [super updateConstraints];\n - (void) updateConstraints {\n CGSize contentSize = [self sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];\n\n [self.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {\n if (constraint.firstAttribute == NSLayoutAttributeHeight) {\n constraint.constant = contentSize.height;\n *stop = YES;\n }\n }];\n\n [super updateConstraints];\n}\n textView [self.view layoutIfNeeded];\n // do your own text change here.\n self.infoTextView.text = [NSString stringWithFormat:@\"%@, %@\", self.infoTextView.text, self.infoTextView.text];\n [self.infoTextView setNeedsUpdateConstraints];\n [self.infoTextView updateConstraintsIfNeeded];\n [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionLayoutSubviews animations:^{\n [self.view layoutIfNeeded];\n } completion:nil];\n"
},
{
"answer_id": 26599389,
"author": "Brett Donald",
"author_id": 2518285,
"author_profile": "https://Stackoverflow.com/users/2518285",
"pm_score": 7,
"selected": false,
"text": "myTextView.scrollEnabled = @NO\n UITextView UITableViewCell UITextView UITableViewCell UITextView scrollEnabled NO UITextView viewDidLoad tableView.estimatedRowHeight = 150;\n tableView.rowHeight = UITableViewAutomaticDimension;\n UITextView UITextView textViewDidChange: UITextViewDelegate tableView - (void)textViewDidChange:(UITextView *)textView;\n {\n [tableView beginUpdates];\n [tableView endUpdates];\n }\n UITextView Storyboard tableView:cellForRowAtIndexPath:"
},
{
"answer_id": 27218598,
"author": "Gal Blank",
"author_id": 662469,
"author_profile": "https://Stackoverflow.com/users/662469",
"pm_score": 1,
"selected": false,
"text": "CGRect frame = textView.frame;\nframe.size.height = textView.contentSize.height;\n\nif(frame.size.height > textView.frame.size.height){\n CGFloat diff = frame.size.height - textView.frame.size.height;\n textView.frame = CGRectMake(0, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);\n}\nelse if(frame.size.height < textView.frame.size.height){\n CGFloat diff = textView.frame.size.height - frame.size.height;\n textView.frame = CGRectMake(0, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);\n}\n"
},
{
"answer_id": 27625246,
"author": "Gal Blank",
"author_id": 662469,
"author_profile": "https://Stackoverflow.com/users/662469",
"pm_score": -1,
"selected": false,
"text": "- (void)textViewDidChange:(UITextView *)textView{ CGRect frame = textView.frame;\nCGFloat height = [self measureHeightOfUITextView:textView];\nCGFloat insets = textView.textContainerInset.top + textView.textContainerInset.bottom;\nheight += insets;\nframe.size.height = height;\n\nif(frame.size.height > textView.frame.size.height){\n CGFloat diff = frame.size.height - textView.frame.size.height;\n textView.frame = CGRectMake(5, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);\n}\nelse if(frame.size.height < textView.frame.size.height){\n CGFloat diff = textView.frame.size.height - frame.size.height;\n textView.frame = CGRectMake(5, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);\n}\n[textView setNeedsDisplay];\n}\n"
},
{
"answer_id": 27738557,
"author": "Swaroop S",
"author_id": 2173072,
"author_profile": "https://Stackoverflow.com/users/2173072",
"pm_score": 3,
"selected": false,
"text": "[_textView sizeToFit];\n"
},
{
"answer_id": 28916825,
"author": "Fareed Alnamrouti",
"author_id": 427622,
"author_profile": "https://Stackoverflow.com/users/427622",
"pm_score": 2,
"selected": false,
"text": " let cell:MsgTableViewCell! = self.tableView.dequeueReusableCellWithIdentifier(\"MsgTableViewCell\", forIndexPath: indexPath) as? MsgTableViewCell\n cell.msgText.text = self.items[indexPath.row]\n var fixedWidth:CGFloat = cell.msgText.frame.size.width\n var size:CGSize = CGSize(width: fixedWidth,height: CGFloat.max)\n var newSize:CGSize = cell.msgText.sizeThatFits(size)\n var newFrame:CGRect = cell.msgText.frame;\n newFrame.size = CGSizeMake(CGFloat(fmaxf(Float(newSize.width), Float(fixedWidth))), newSize.height);\n cell.msgText.frame = newFrame\n cell.msgText.frame.size = newSize \n return cell\n"
},
{
"answer_id": 30215237,
"author": "Apfelsaft",
"author_id": 1447641,
"author_profile": "https://Stackoverflow.com/users/1447641",
"pm_score": 1,
"selected": false,
"text": " descriptionTxt.scrollEnabled = false\n descriptionTxt.text = yourText\n\n var contentSize = descriptionTxt.sizeThatFits(CGSizeMake(descriptionTxt.frame.size.width, CGFloat.max))\n for c in descriptionTxt.constraints() {\n if c.isKindOfClass(NSLayoutConstraint) {\n var constraint = c as! NSLayoutConstraint\n if constraint.firstAttribute == NSLayoutAttribute.Height {\n constraint.constant = contentSize.height\n break\n }\n }\n }\n"
},
{
"answer_id": 30281699,
"author": "RawMean",
"author_id": 342646,
"author_profile": "https://Stackoverflow.com/users/342646",
"pm_score": 1,
"selected": false,
"text": " let maximumLabelSize = CGSize(width: Double(textView.frame.size.width-100.0), height: DBL_MAX)\n let options = NSStringDrawingOptions.TruncatesLastVisibleLine | NSStringDrawingOptions.UsesLineFragmentOrigin\n let attribute = [NSFontAttributeName: textView.font!]\n let str = NSString(string: message)\n let labelBounds = str.boundingRectWithSize(maximumLabelSize,\n options: NSStringDrawingOptions.UsesLineFragmentOrigin,\n attributes: attribute,\n context: nil)\n let myTextHeight = CGFloat(ceilf(Float(labelBounds.height)))\n myTextHeight"
},
{
"answer_id": 30650613,
"author": "Chuck Krutsinger",
"author_id": 1256015,
"author_profile": "https://Stackoverflow.com/users/1256015",
"pm_score": 3,
"selected": false,
"text": "rowHeight UITableViewAutomaticDimension \n- (void)viewDidLoad {\n [super viewDidLoad];\n self.tableView.estimatedRowHeight = self.tableView.rowHeight;\n self.tableView.rowHeight = UITableViewAutomaticDimension;\n}\n"
},
{
"answer_id": 32894513,
"author": "Juan Boero",
"author_id": 1634890,
"author_profile": "https://Stackoverflow.com/users/1634890",
"pm_score": 6,
"selected": false,
"text": "textView.sizeToFit()\n"
},
{
"answer_id": 33275688,
"author": "Andrea",
"author_id": 395897,
"author_profile": "https://Stackoverflow.com/users/395897",
"pm_score": 0,
"selected": false,
"text": "UITextView -sizeToFit scrollingEnabled = YES UITexView -sizeToFit UITableView - tableView:cellForRowAtIndexPath: -layoutSubviews"
},
{
"answer_id": 33475313,
"author": "Bartłomiej Semańczyk",
"author_id": 2725435,
"author_profile": "https://Stackoverflow.com/users/2725435",
"pm_score": 3,
"selected": false,
"text": "UITextView UITableViewAutomaticDimension"
},
{
"answer_id": 34975206,
"author": "jithin",
"author_id": 5264832,
"author_profile": "https://Stackoverflow.com/users/5264832",
"pm_score": 0,
"selected": false,
"text": "textview.scrollEnabled = NO; -(void)adjustHeightOfTextView\n{\n //this pieces of code will helps to adjust the height of the uitextview View W.R.T content\n //This block of code work will calculate the height of the textview text content height and calculate the height for the whole content of the view to be displayed.Height --> 400 is fixed,it will change if you change anything in the storybord.\n\n\nCGSize textViewSize = [self.textview sizeThatFits:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height)];//calulcate the content width and height\n\nfloat textviewContentheight =textViewSize.height;\nself.scrollview.contentSize = CGSizeMake(self.textview.frame.size.width,textviewContentheight + 400);//height value is passed\nself.scrollview.frame =CGRectMake(self.scrollview.frame.origin.x, self.scrollview.frame.origin.y, self.scrollview.frame.size.width, textviewContentheight+400);\n\nCGRect Frame = self.contentview.frame;\nFrame.size.height = textviewContentheight + 400;\n[self.contentview setFrame:Frame];\n\nself.textview.frame =CGRectMake(self.textview.frame.origin.x, self.textview.frame.origin.y, self.textview.frame.size.width, textviewContentheight);\n[ self.textview setContentSize:CGSizeMake( self.textview.frame.size.width,textviewContentheight)];\nself.contenview_heightConstraint.constant = \n\nself.scrollview.bounds.size.height;\n NSLog(@\"%f\",self.contenview_heightConstraint.constant);\n}\n"
},
{
"answer_id": 35790169,
"author": "Kishore Kumar",
"author_id": 5105555,
"author_profile": "https://Stackoverflow.com/users/5105555",
"pm_score": 3,
"selected": false,
"text": " @property (weak, nonatomic) IBOutlet NSLayoutConstraint *txtheightconstraints;\n -(void)textViewDidChange:(UITextView *)textView\n{\n CGFloat fixedWidth = textView.frame.size.width;\n CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];\n CGRect newFrame = textView.frame;\n newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);\n NSLog(@\"this is updating height%@\",NSStringFromCGSize(newFrame.size));\n [UIView animateWithDuration:0.2 animations:^{\n _txtheightconstraints.constant=newFrame.size.height;\n }];\n\n}\n"
},
{
"answer_id": 38418756,
"author": "Alok",
"author_id": 3024579,
"author_profile": "https://Stackoverflow.com/users/3024579",
"pm_score": 7,
"selected": false,
"text": "textView.scrollEnabled = false\n"
},
{
"answer_id": 42928806,
"author": "Peter Stajger",
"author_id": 296649,
"author_profile": "https://Stackoverflow.com/users/296649",
"pm_score": 3,
"selected": false,
"text": "textView.isScrollEnabled = false\n func textViewDidChange(_ textView: UITextView) func textViewDidChange(_ textView: UITextView) {\n let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))\n textView.frame = CGRect(origin: textView.frame.origin, size: newSize)\n}\n"
},
{
"answer_id": 43137430,
"author": "Volodymyr Nazarkevych",
"author_id": 5360675,
"author_profile": "https://Stackoverflow.com/users/5360675",
"pm_score": 1,
"selected": false,
"text": "textView tableViewCell staticTableView"
},
{
"answer_id": 46398555,
"author": "iOS Flow",
"author_id": 3922498,
"author_profile": "https://Stackoverflow.com/users/3922498",
"pm_score": 1,
"selected": false,
"text": "let content = UITextView(frame: CGRect(x: 4, y: 4, width: 0, height: 0))\ncontent.text = \"what ever short or long text you wanna try\"\ncontent.textAlignment = NSTextAlignment.left\ncontent.font = UIFont.systemFont(ofSize: 13)\nlet spaceAvailable = 200 //My cell is fancy I have to calculate it...\nlet newSize = content.sizeThatFits(CGSize(width: CGFloat(spaceAvailable), height: CGFloat.greatestFiniteMagnitude))\ncontent.isEditable = false\ncontent.dataDetectorTypes = UIDataDetectorTypes.all\ncontent.isScrollEnabled = false\ncontent.backgroundColor = UIColor.clear\nbkgView.addSubview(content)\n"
},
{
"answer_id": 48188184,
"author": "ali ozkara",
"author_id": 4362167,
"author_profile": "https://Stackoverflow.com/users/4362167",
"pm_score": 3,
"selected": false,
"text": "[yourTextView setText:@\"your text\"];\n[yourTextView layoutIfNeeded];\n UIScrollView [yourScrollView layoutIfNeeded];\n\n-(void)viewDidAppear:(BOOL)animated{\n CGRect contentRect = CGRectZero;\n\n for (UIView *view in self.yourScrollView.subviews) {\n contentRect = CGRectUnion(contentRect, view.frame);\n }\n self.yourScrollView.contentSize = contentRect.size;\n}\n"
},
{
"answer_id": 51416071,
"author": "Vakas",
"author_id": 3627468,
"author_profile": "https://Stackoverflow.com/users/3627468",
"pm_score": -1,
"selected": false,
"text": "UITextView View UITextViewDelegate func textViewDidChange(_ textView: UITextView) //1. Add your UITextView in ViewDidLoad\nlet textView = UITextView()\ntextView.frame = CGRect(x: 0, y: 0, width: 200, height: 100)\ntextView.backgroundColor = .lightGray\ntextView.text = \"Here is some default text.\"\n\n\n\n//2. Add constraints\ntextView.translatesAutoresizingMaskIntoConstraints = false\n[\ntextView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),\ntextView.leadingAnchor.constraint(equalTo: view.leadingAnchor),\ntextView.trailingAnchor.constraint(equalTo: view.trailingAnchor),\ntextView.heightAnchor.constraint(equalToConstant: 50),\ntextView.widthAnchor.constraint(equalToConstant: 30)\n].forEach{ $0.isActive = true }\n\ntextView.font = UIFont.preferredFont(forTextStyle: .headline)\n\ntextView.delegate = self\ntextView.isScrollEnabled = false\n\ntextViewDidChange(textView)\n\n\n//3. Implement the delegate method.\nfunc textViewDidChange(_ textView: UITextView) {\nlet size = CGSize(width: view.frame.width, height: .infinity)\nlet estimatedSize = textView.sizeThatFits(size)\n\ntextView.constraints.forEach { (constraint) in\n if constraint.firstAttribute == .height {\n print(\"Height: \", estimatedSize.height)\n constraint.constant = estimatedSize.height\n }\n}\n}\n"
},
{
"answer_id": 57739436,
"author": "Jonathan.",
"author_id": 191463,
"author_profile": "https://Stackoverflow.com/users/191463",
"pm_score": 0,
"selected": false,
"text": "private func setup() { // Called from init or somewhere\n\n fitToContentObservations = [\n textView.observe(\\.contentSize) { _, _ in\n self.invalidateIntrinsicContentSize()\n },\n // For some reason the content offset sometimes is non zero even though the frame is the same size as the content size.\n textView.observe(\\.contentOffset) { _, _ in\n if self.contentOffset != .zero { // Need to check this to stop infinite loop\n self.contentOffset = .zero\n }\n }\n ]\n}\npublic override var intrinsicContentSize: CGSize {\n return contentSize\n}\n textView.bounds = textView.contentSize contentSize"
},
{
"answer_id": 59250215,
"author": "atereshkov",
"author_id": 5969121,
"author_profile": "https://Stackoverflow.com/users/5969121",
"pm_score": 2,
"selected": false,
"text": "func textViewDidChange(_ textView: UITextView) {\n let newSize = textView.sizeThatFits(CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude))\n textView.frame.size = CGSize(width: newSize.width, height: newSize.height)\n}\n"
},
{
"answer_id": 60439398,
"author": "f0go",
"author_id": 2543967,
"author_profile": "https://Stackoverflow.com/users/2543967",
"pm_score": 3,
"selected": false,
"text": "func textViewDidChange(_ textView: UITextView) {\n textView.sizeToFit()\n textviewHeight.constant = textView.contentSize.height\n}\n"
},
{
"answer_id": 66250012,
"author": "iOS_Mouse",
"author_id": 6748722,
"author_profile": "https://Stackoverflow.com/users/6748722",
"pm_score": 0,
"selected": false,
"text": "@IBOutlet var myAwesomeTextView: UITextView!\n@IBOutlet var myAwesomeTextViewHeight: NSLayoutConstraint!\n self.myAwesomeTextViewHeight.constant = self.myAwesomeTextView.contentSize.height\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967/"
] |
50,499 |
<p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p>
<p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a>:</p>
<ul>
<li><code>script_1.py</code> calls <code>script_2.py</code>. </li>
<li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li>
</ul>
<p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p>
<p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
|
[
{
"answer_id": 50502,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "sys.argv[0]"
},
{
"answer_id": 50505,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 3,
"selected": false,
"text": "__file__"
},
{
"answer_id": 50521,
"author": "readonly",
"author_id": 4883,
"author_profile": "https://Stackoverflow.com/users/4883",
"pm_score": 3,
"selected": false,
"text": "__file__"
},
{
"answer_id": 50905,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 9,
"selected": true,
"text": "execfile(\"p2.py\")\n import inspect, os\nprint (inspect.getfile(inspect.currentframe())) # script filename (usually with path)\nprint (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory\n"
},
{
"answer_id": 50986,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 2,
"selected": false,
"text": "inspect.stack() import inspect,os\ninspect.stack()[0] => (<frame object at 0x00AC2AC0>, 'g:\\\\Python\\\\Test\\\\_GetCurrentProgram.py', 15, '<module>', ['print inspect.stack()[0]\\n'], 0)\nos.path.abspath (inspect.stack()[0][1]) => 'g:\\\\Python\\\\Test\\\\_GetCurrentProgram.py'\n"
},
{
"answer_id": 1955163,
"author": "user13993",
"author_id": 13993,
"author_profile": "https://Stackoverflow.com/users/13993",
"pm_score": 9,
"selected": false,
"text": "__file__\n import os\n\nos.path.realpath(__file__)\n"
},
{
"answer_id": 1992378,
"author": "appusajeev",
"author_id": 242382,
"author_profile": "https://Stackoverflow.com/users/242382",
"pm_score": 3,
"selected": false,
"text": "import sys\n\nprint sys.path[0]\n"
},
{
"answer_id": 2345265,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "import inspect print inspect.stack()[-1][1] [-1] import foo __file__ inspect.getfile(inspect.currentframe()) inspect.stack()[0][1]"
},
{
"answer_id": 2665888,
"author": "WBAR",
"author_id": 320104,
"author_profile": "https://Stackoverflow.com/users/320104",
"pm_score": 2,
"selected": false,
"text": "import sys\nprint sys.argv[0]\n"
},
{
"answer_id": 5152554,
"author": "mik80",
"author_id": 224642,
"author_profile": "https://Stackoverflow.com/users/224642",
"pm_score": 0,
"selected": false,
"text": "os.path.abspath(__file__) inspect.getfile(inspect.currentframe()) sys._getframe().f_code.co_filename"
},
{
"answer_id": 6628348,
"author": "Usagi",
"author_id": 313087,
"author_profile": "https://Stackoverflow.com/users/313087",
"pm_score": 6,
"selected": false,
"text": "import inspect\nprint inspect.stack()[0][1]\n print inspect.getfile(inspect.currentframe())\n print inspect.stack()[1][1]\n"
},
{
"answer_id": 11861785,
"author": "garmoncheg",
"author_id": 809092,
"author_profile": "https://Stackoverflow.com/users/809092",
"pm_score": 4,
"selected": false,
"text": "import os,sys\nPROJECT_PATH = os.path.abspath(os.path.split(sys.argv[0])[0])\n"
},
{
"answer_id": 18168345,
"author": "vishal ekhe",
"author_id": 2068502,
"author_profile": "https://Stackoverflow.com/users/2068502",
"pm_score": 4,
"selected": false,
"text": "import os\nprint os.path.basename(__file__)\n"
},
{
"answer_id": 24390114,
"author": "Kwuite",
"author_id": 3123191,
"author_profile": "https://Stackoverflow.com/users/3123191",
"pm_score": 3,
"selected": false,
"text": "import os\nos.path.dirname(os.path.abspath(__file__))\n"
},
{
"answer_id": 28356929,
"author": "Neal Xiong",
"author_id": 1316480,
"author_profile": "https://Stackoverflow.com/users/1316480",
"pm_score": 6,
"selected": false,
"text": "import os\nos.path.dirname(__file__) # relative directory path\nos.path.abspath(__file__) # absolute file path\nos.path.basename(__file__) # the file name only\n"
},
{
"answer_id": 30831888,
"author": "Jahid",
"author_id": 3744681,
"author_profile": "https://Stackoverflow.com/users/3744681",
"pm_score": 2,
"selected": false,
"text": "import os,sys\nfilename=os.path.basename(os.path.realpath(sys.argv[0]))\ndirname=os.path.dirname(os.path.realpath(sys.argv[0]))\n"
},
{
"answer_id": 31867043,
"author": "Brian Burns",
"author_id": 243392,
"author_profile": "https://Stackoverflow.com/users/243392",
"pm_score": 7,
"selected": false,
"text": "| Python | Run statement | Filepath expression |\n|--------+---------------------+----------------------------------------|\n| 2 | execfile | os.path.abspath(inspect.stack()[0][1]) |\n| 2 | from lib import bar | __file__ |\n| 3 | exec | (wasn't able to obtain it) |\n| 3 | import lib.bar | __file__ |\n from lib import bar __init__.py execfile exec(open(<filename>).read()) import foo import lib.bar __init__.py print os.path.abspath(inspect.stack()[0][1]) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\\filepaths\\lib\n python main.py execfile('foo.py') execfile('lib/bar.py') import sys\nimport os\nimport inspect\n\nprint \"Python \" + sys.version\nprint\n\nprint __file__ # main.py\nprint sys.argv[0] # main.py\nprint inspect.stack()[0][1] # lib/bar.py\nprint sys.path[0] # C:\\filepaths\nprint\n\nprint os.path.realpath(__file__) # C:\\filepaths\\main.py\nprint os.path.abspath(__file__) # C:\\filepaths\\main.py\nprint os.path.basename(__file__) # main.py\nprint os.path.basename(os.path.realpath(sys.argv[0])) # main.py\nprint\n\nprint sys.path[0] # C:\\filepaths\nprint os.path.abspath(os.path.split(sys.argv[0])[0]) # C:\\filepaths\nprint os.path.dirname(os.path.abspath(__file__)) # C:\\filepaths\nprint os.path.dirname(os.path.realpath(sys.argv[0])) # C:\\filepaths\nprint os.path.dirname(__file__) # (empty string)\nprint\n\nprint inspect.getfile(inspect.currentframe()) # lib/bar.py\n\nprint os.path.abspath(inspect.getfile(inspect.currentframe())) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) # C:\\filepaths\\lib\nprint\n\nprint os.path.abspath(inspect.stack()[0][1]) # C:\\filepaths\\lib\\bar.py\nprint os.path.dirname(os.path.abspath(inspect.stack()[0][1])) # C:\\filepaths\\lib\nprint\n"
},
{
"answer_id": 37815779,
"author": "hayj",
"author_id": 3406616,
"author_profile": "https://Stackoverflow.com/users/3406616",
"pm_score": 0,
"selected": false,
"text": "import inspect, os\ndef getRootDirectory(_file_=None):\n \"\"\"\n Get the directory of the root execution file\n Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing\n For eclipse user with unittest or debugger, the function search for the correct folder in the stack\n You can pass __file__ (with 4 underscores) if you want the caller directory\n \"\"\"\n # If we don't have the __file__ :\n if _file_ is None:\n # We get the last :\n rootFile = inspect.stack()[-1][1]\n folder = os.path.abspath(rootFile)\n # If we use unittest :\n if (\"/pysrc\" in folder) & (\"org.python.pydev\" in folder):\n previous = None\n # We search from left to right the case.py :\n for el in inspect.stack():\n currentFile = os.path.abspath(el[1])\n if (\"unittest/case.py\" in currentFile) | (\"org.python.pydev\" in currentFile):\n break\n previous = currentFile\n folder = previous\n # We return the folder :\n return os.path.dirname(folder)\n else:\n # We return the folder according to specified __file__ :\n return os.path.dirname(os.path.realpath(_file_))\n"
},
{
"answer_id": 43890336,
"author": "pbaranski",
"author_id": 1266040,
"author_profile": "https://Stackoverflow.com/users/1266040",
"pm_score": 1,
"selected": false,
"text": " print os.path.dirname( inspect.getfile(inspect.currentframe()))\n"
},
{
"answer_id": 50760702,
"author": "Lucas Azevedo",
"author_id": 4075155,
"author_profile": "https://Stackoverflow.com/users/4075155",
"pm_score": 0,
"selected": false,
"text": "import subprocess\nsubprocess.call(['python3',<path_to_script_2.py>])\n sys.argv[0]\n execfile sys.argv[0] <string>"
},
{
"answer_id": 54832312,
"author": "Soumyajit",
"author_id": 6692537,
"author_profile": "https://Stackoverflow.com/users/6692537",
"pm_score": 3,
"selected": false,
"text": "import os\nos.path.dirname(os.path.realpath(__file__))\n"
},
{
"answer_id": 55988112,
"author": "BaiJiFeiLong",
"author_id": 5254103,
"author_profile": "https://Stackoverflow.com/users/5254103",
"pm_score": 2,
"selected": false,
"text": "print(__file__)\nprint(__import__(\"pathlib\").Path(__file__).parent)\n"
},
{
"answer_id": 56799977,
"author": "craymichael",
"author_id": 6557588,
"author_profile": "https://Stackoverflow.com/users/6557588",
"pm_score": 2,
"selected": false,
"text": "__name__ __file__ if '__file__' in globals():\n self_name = globals()['__file__']\nelif '__file__' in locals():\n self_name = locals()['__file__']\nelse:\n self_name = __name__\n self_name = globals().get('__file__', locals().get('__file__', __name__))\n"
},
{
"answer_id": 57631907,
"author": "Doug",
"author_id": 1494503,
"author_profile": "https://Stackoverflow.com/users/1494503",
"pm_score": 4,
"selected": false,
"text": "pathlib from pathlib import Path\n\ncurrent_file: Path = Path(__file__).resolve()\n .parent Path() current_path: Path = Path(__file__).parent.resolve()\n"
},
{
"answer_id": 70773078,
"author": "nichoio",
"author_id": 6312338,
"author_profile": "https://Stackoverflow.com/users/6312338",
"pm_score": 0,
"selected": false,
"text": "import builtins\nimport os\nimport sys\n\ndef current_dir():\n if \"get_ipython\" in globals() or \"get_ipython\" in dir(builtins):\n # os.getcwd() is PROBABLY the dir that hosts the active notebook script.\n # See also https://github.com/ipython/ipython/issues/10123\n return os.getcwd()\n else:\n return os.path.abspath(os.path.dirname(sys.argv[0]))\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] |
50,524 |
<p>From the Java 6 <a href="http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html" rel="noreferrer">Pattern</a> documentation:</p>
<blockquote>
<p>Special constructs (non-capturing)</p>
<p><code>(?:</code><i>X</i><code>)</code> <i>X</i>, as a non-capturing group</p>
<p>…</p>
<p><code>(?></code><i>X</i><code>)</code> <i>X</i>, as an independent, non-capturing group</p>
</blockquote>
<p>Between <code>(?:X)</code> and <code>(?>X)</code> what is the difference? What does the <strong>independent</strong> mean in this context?</p>
|
[
{
"answer_id": 394291,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "foo(?>(co)*)co"
},
{
"answer_id": 28663993,
"author": "beibichunai",
"author_id": 4434482,
"author_profile": "https://Stackoverflow.com/users/4434482",
"pm_score": -1,
"selected": false,
"text": "(?>X?) (?:X)?+ (?>X*) (?:X)*+ (?>X+) (?:X)++ (?>X?) X?+ (?>X*) X*+ (?>X+) X++"
},
{
"answer_id": 50146523,
"author": "kajibu",
"author_id": 7320818,
"author_profile": "https://Stackoverflow.com/users/7320818",
"pm_score": 4,
"selected": false,
"text": "a(bc|b)c a(?>bc|b)c a bc c b c bc b c"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50524",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4265/"
] |
50,525 |
<p>Let's take the code</p>
<pre><code>int a, b, c;
...
if ((a + b) > C)
</code></pre>
<p>If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression.</p>
|
[
{
"answer_id": 51038,
"author": "Rob Pilkington",
"author_id": 1623,
"author_profile": "https://Stackoverflow.com/users/1623",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint main()\n{\n int a, b, c;\n\n a = 2000000000;\n b = 2000000000;\n c = 2100000000;\n\n printf(\"%d + %d = %d\\n\", a, b, a+b);\n if ((a + b) > c)\n {\n printf(\"%d + %d > %d\\n\", a, b, c);\n }\n else\n {\n printf(\"%d + %d < %d\\n\", a, b, c);\n }\n return 0;\n}\n 2000000000 + 2000000000 = -294967296\n2000000000 + 2000000000 < 2100000000\n"
},
{
"answer_id": 992633,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "#if !defined(__GNUC__) || __GNUC__<2 || (__GNUC__==2 && __GNUC_MINOR__<96)\n# define unlikely(x) (x)\n#else\n# define unlikely(x) (__extension__ (__builtin_expect(!!(x), 0)))\n#endif\n\n/* ----------\n * Signed comparison (signed char, short, int, long, long long)\n * Checks for overflow off the top end of the range, in which case a+b must\n * be >c. If it overflows off the bottom, a+b < everything in the range. */\nif(a+b>c || unlikely(a>=0 && b>=0 && unlikely(a+b<0)))\n ...\n\n/* ----------\n * Unsigned comparison (unsigned char, unsigned short, unsigned, etc.)\n * Checks to see if the sum wrapped around, since the sum of any two natural\n * numbers must be >= both numbers. */\nif(a+b>c || unlikely(a+b<a))\n ...\n\n/* ----------\n * To generate code for the above only when necessary: */\nif(sizeof(long)>sizeof(int) ? ((long)a+b>c)\n : (a+b>c || unlikely(a>=0 && b>=0 && unlikely(a+b<0)))\n ...\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] |
50,528 |
<p>So I was reading those Windows Vista UI guidelines someone linked to in another question, and they mentioned that you should be able to survive a switch to 120 DPI. Well, I fire up my handy VM with my app installed, and what do we get... AAAAGH!!! MASSIVE UI FAIL!</p>
<p>Everything's all jumbled: some containers aren't big enough for their text; some controls that were positioned "next to each other" are now all squished together/spread apart; some buttons aren't tall enough; my <code>ListView</code> columns aren't wide enough... eeek.</p>
<p>It sounds like a completely different approach is in order. My previous one was basically using the VS2008 Windows Forms designer to create, I guess, a pixel-based layout. I can see that if I were to stick with Windows Forms, <code>FlowLayoutPanel</code>s would be helpful, although I've found them rather inflexible in the past. They also don't solve the problem where the containers (e.g. the form itself) aren't big enough; presumably there's a way to do that? Maybe that <code>AutoSize</code> property?</p>
<p>This might also be a sign that it's time to jump ship to WPF; I'm under the impression that it's specifically designed for this kind of thing.</p>
<p>The basic issue seems to come down to these:</p>
<ul>
<li>If I were to stick with Windows Forms, what are all the tricks to achieving a font-size-independent layout that can survive the user setting his fonts large, or setting the display to 120 DPI?</li>
<li>Does WPF have significant advantages here, and if so, can you try to convince me that it's worth the switch?</li>
<li>Are there any general "best-practices" for font-size-independent layouts, either in the .NET stack or in general?</li>
</ul>
|
[
{
"answer_id": 50729,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 5,
"selected": true,
"text": "TableLayoutPanel TableLayoutPanel"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] |
50,532 |
<p>How do I format a number in Java?<br />
What are the "Best Practices"?</p>
<p>Will I need to round a number before I format it?</p>
<blockquote>
<p><code>32.302342342342343</code> => <code>32.30</code></p>
<p><code>.7323</code> => <code>0.73</code></p>
</blockquote>
<p>etc.</p>
|
[
{
"answer_id": 50543,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "double r = 5.1234;\nSystem.out.println(r); // r is 5.1234\n\nint decimalPlaces = 2;\nBigDecimal bd = new BigDecimal(r);\n\n// setScale is immutable\nbd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);\nr = bd.doubleValue();\n\nSystem.out.println(r); // r is 5.12\n f = (float) (Math.round(n*100.0f)/100.0f);\n DecimalFormat df2 = new DecimalFormat( \"#,###,###,##0.00\" );\ndouble dd = 100.2397;\ndouble dd2dec = new Double(df2.format(dd)).doubleValue();\n\n// The value of dd2dec will be 100.24\n"
},
{
"answer_id": 50544,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 6,
"selected": false,
"text": "String.format() String.format(\"%.2f\", (double)value);\n"
},
{
"answer_id": 50556,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "/*\n * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of Sun Microsystems nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */ \n\n\nimport java.util.*;\nimport java.text.*;\n\npublic class DecimalFormatDemo {\n\n static public void customFormat(String pattern, double value ) {\n DecimalFormat myFormatter = new DecimalFormat(pattern);\n String output = myFormatter.format(value);\n System.out.println(value + \" \" + pattern + \" \" + output);\n }\n\n static public void localizedFormat(String pattern, double value, Locale loc ) {\n NumberFormat nf = NumberFormat.getNumberInstance(loc);\n DecimalFormat df = (DecimalFormat)nf;\n df.applyPattern(pattern);\n String output = df.format(value);\n System.out.println(pattern + \" \" + output + \" \" + loc.toString());\n }\n\n static public void main(String[] args) {\n\n customFormat(\"###,###.###\", 123456.789);\n customFormat(\"###.##\", 123456.789);\n customFormat(\"000000.000\", 123.78);\n customFormat(\"$###,###.###\", 12345.67);\n customFormat(\"\\u00a5###,###.###\", 12345.67);\n\n Locale currentLocale = new Locale(\"en\", \"US\");\n\n DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);\n unusualSymbols.setDecimalSeparator('|');\n unusualSymbols.setGroupingSeparator('^');\n String strange = \"#,##0.###\";\n DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);\n weirdFormatter.setGroupingSize(4);\n String bizarre = weirdFormatter.format(12345.678);\n System.out.println(bizarre);\n\n Locale[] locales = {\n new Locale(\"en\", \"US\"),\n new Locale(\"de\", \"DE\"),\n new Locale(\"fr\", \"FR\")\n };\n\n for (int i = 0; i < locales.length; i++) {\n localizedFormat(\"###,###.###\", 123456.789, locales[i]);\n }\n }\n }\n"
},
{
"answer_id": 25929742,
"author": "Nautilus",
"author_id": 3706308,
"author_profile": "https://Stackoverflow.com/users/3706308",
"pm_score": 3,
"selected": false,
"text": "String.format(\"%.2f\", 32.302342342342343);\n"
},
{
"answer_id": 45898683,
"author": "Soner from The Ottoman Empire",
"author_id": 4990642,
"author_profile": "https://Stackoverflow.com/users/4990642",
"pm_score": 2,
"selected": false,
"text": "public static void formatDouble(double myDouble){\n NumberFormat numberFormatter = new DecimalFormat(\"##.000\");\n String result = numberFormatter.format(myDouble);\n System.out.println(result);\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] |
50,539 |
<p>One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover</p>
<p>does anyone have any ideas or have created such a thing before<br>
we have a couple ideas but they involve to much database usage </p>
<p>We prefer that it be FREE!!!</p>
|
[
{
"answer_id": 50543,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "double r = 5.1234;\nSystem.out.println(r); // r is 5.1234\n\nint decimalPlaces = 2;\nBigDecimal bd = new BigDecimal(r);\n\n// setScale is immutable\nbd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);\nr = bd.doubleValue();\n\nSystem.out.println(r); // r is 5.12\n f = (float) (Math.round(n*100.0f)/100.0f);\n DecimalFormat df2 = new DecimalFormat( \"#,###,###,##0.00\" );\ndouble dd = 100.2397;\ndouble dd2dec = new Double(df2.format(dd)).doubleValue();\n\n// The value of dd2dec will be 100.24\n"
},
{
"answer_id": 50544,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 6,
"selected": false,
"text": "String.format() String.format(\"%.2f\", (double)value);\n"
},
{
"answer_id": 50556,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": false,
"text": "/*\n * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * - Neither the name of Sun Microsystems nor the names of its\n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */ \n\n\nimport java.util.*;\nimport java.text.*;\n\npublic class DecimalFormatDemo {\n\n static public void customFormat(String pattern, double value ) {\n DecimalFormat myFormatter = new DecimalFormat(pattern);\n String output = myFormatter.format(value);\n System.out.println(value + \" \" + pattern + \" \" + output);\n }\n\n static public void localizedFormat(String pattern, double value, Locale loc ) {\n NumberFormat nf = NumberFormat.getNumberInstance(loc);\n DecimalFormat df = (DecimalFormat)nf;\n df.applyPattern(pattern);\n String output = df.format(value);\n System.out.println(pattern + \" \" + output + \" \" + loc.toString());\n }\n\n static public void main(String[] args) {\n\n customFormat(\"###,###.###\", 123456.789);\n customFormat(\"###.##\", 123456.789);\n customFormat(\"000000.000\", 123.78);\n customFormat(\"$###,###.###\", 12345.67);\n customFormat(\"\\u00a5###,###.###\", 12345.67);\n\n Locale currentLocale = new Locale(\"en\", \"US\");\n\n DecimalFormatSymbols unusualSymbols = new DecimalFormatSymbols(currentLocale);\n unusualSymbols.setDecimalSeparator('|');\n unusualSymbols.setGroupingSeparator('^');\n String strange = \"#,##0.###\";\n DecimalFormat weirdFormatter = new DecimalFormat(strange, unusualSymbols);\n weirdFormatter.setGroupingSize(4);\n String bizarre = weirdFormatter.format(12345.678);\n System.out.println(bizarre);\n\n Locale[] locales = {\n new Locale(\"en\", \"US\"),\n new Locale(\"de\", \"DE\"),\n new Locale(\"fr\", \"FR\")\n };\n\n for (int i = 0; i < locales.length; i++) {\n localizedFormat(\"###,###.###\", 123456.789, locales[i]);\n }\n }\n }\n"
},
{
"answer_id": 25929742,
"author": "Nautilus",
"author_id": 3706308,
"author_profile": "https://Stackoverflow.com/users/3706308",
"pm_score": 3,
"selected": false,
"text": "String.format(\"%.2f\", 32.302342342342343);\n"
},
{
"answer_id": 45898683,
"author": "Soner from The Ottoman Empire",
"author_id": 4990642,
"author_profile": "https://Stackoverflow.com/users/4990642",
"pm_score": 2,
"selected": false,
"text": "public static void formatDouble(double myDouble){\n NumberFormat numberFormatter = new DecimalFormat(\"##.000\");\n String result = numberFormatter.format(myDouble);\n System.out.println(result);\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] |
50,558 |
<p>I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).</p>
<p>I have it declared as follows: </p>
<pre><code>float[,] _calibrationSet;
....
int calibrationRow = 0;
While (recordsToRead)
{
for (int i = 0; i < SensorCount; i++)
{
_calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
}
calibrationRow++;
}
</code></pre>
<p>This causes a NullReferenceException, so when I try to initialize it like this: </p>
<pre><code>_calibrationSet = new float[,];
</code></pre>
<p>I get an "Array creation must have array size or array initializer."</p>
<p>Thank you,
Keith</p>
|
[
{
"answer_id": 50581,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "List<float[]> _calibrationSet = new List<float[]>();\n\n// ...\n\nwhile (recordsToRead)\n{\n float[] record = new float[SensorCount];\n for (int i = 0; i < SensorCount; i++)\n {\n record[i] = calibrationArrayView.ReadFloat();\n }\n _calibrationSet.Add(record);\n}\n\n// access later: _calibrationSet[record][sensor]\n"
},
{
"answer_id": 50591,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 1,
"selected": false,
"text": " var tempCalibrationSet = new List<float[]>();\n const int SensorCount = 22;\n int calibrationRow = 0;\n\n while (recordsToRead())\n {\n tempCalibrationSet[calibrationRow] = new float[SensorCount];\n\n for (int i = 0; i < SensorCount; i++)\n {\n tempCalibrationSet[calibrationRow][i] = calibrationArrayView.ReadFloat();\n } calibrationRow++;\n }\n\n float[][] _calibrationSet = tempCalibrationSet.ToArray();\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] |
50,561 |
<p>Is it possible at runtime to programmatically check the name of the Thread that is holding the lock of a given object?</p>
|
[
{
"answer_id": 50573,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": true,
"text": "Thread.holdsLock(Object) ReentrantLock"
},
{
"answer_id": 51620,
"author": "Chris Kimpton",
"author_id": 48310,
"author_profile": "https://Stackoverflow.com/users/48310",
"pm_score": 2,
"selected": false,
"text": " Map<Thread,StackTraceElement[]> map = Thread.getAllStackTraces();\n for (Map.Entry<Thread, StackTraceElement[]> threadEntry : map.entrySet()) {\n log.info(\"Thread:\"+threadEntry.getKey().getName()+\":\"+threadEntry.getKey().getState());\n for (StackTraceElement element : threadEntry.getValue()) {\n log.info(\"--> \"+element);\n }\n }\n"
},
{
"answer_id": 1377751,
"author": "carrino",
"author_id": 128006,
"author_profile": "https://Stackoverflow.com/users/128006",
"pm_score": 4,
"selected": false,
"text": "ThreadMXBean bean = ManagementFactory.getThreadMXBean();\nThreadInfo[] ti = bean.getThreadInfo(bean.getAllThreadIds(), true, true);\n"
},
{
"answer_id": 8379402,
"author": "dac2009",
"author_id": 827272,
"author_profile": "https://Stackoverflow.com/users/827272",
"pm_score": 0,
"selected": false,
"text": "Thread holderOfLock = null;\nObject theLock = new Object();\n\npublic void doStuff()\n{\n if(holderOfLock != null)\n {\n //get and print name of holderOfLock-thread or get stacktrace etc.\n }\n\n synchronized (theLock)\n {\n holderOfLock = Thread.currentThread();\n //do stuff...\n holderOfLock = null;\n }\n}\n"
},
{
"answer_id": 15265132,
"author": "NullPointer",
"author_id": 1047104,
"author_profile": "https://Stackoverflow.com/users/1047104",
"pm_score": 1,
"selected": false,
"text": "wait() notify() llegalMonitorStateException holdsLock(Object o)"
},
{
"answer_id": 31359345,
"author": "ceph3us",
"author_id": 4669617,
"author_profile": "https://Stackoverflow.com/users/4669617",
"pm_score": 2,
"selected": false,
"text": "final ReentrantLock lock = new ReentrantLock();\nlock.isHeldByCurrentThread();\n"
},
{
"answer_id": 49549659,
"author": "petertc",
"author_id": 1271412,
"author_profile": "https://Stackoverflow.com/users/1271412",
"pm_score": 0,
"selected": false,
"text": "String findLockOwner(ReentrantLock lock) {\n String patternStr = \"\\\\[Locked by thread (\\\\S+)\\\\]\";\n Pattern pattern = Pattern.compile(patternStr);\n Matcher matcher = pattern.matcher(lock.toString());\n boolean matchFound = matcher.find();\n if (matchFound && matcher.groupCount() >= 1) {\n return matcher.group(1);\n }\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4220/"
] |
50,576 |
<p>I need to come up with an analysis of simultaneus events, when having only starttime and duration of each event.</p>
<p><strong>Details</strong></p>
<p>I've a standard CDR call detail record, that contains among others:</p>
<ul>
<li>calldate (timedate of each call start</li>
<li>duration (int, seconds of call duration)</li>
<li>channel (a string)</li>
</ul>
<p>What I need to come up with is some sort of analysys of simultaneus calls on each second, for a given timedate period. For example, a graph of simultaneous calls we had yesterday.</p>
<p>(The problem is the same if we have visitors logs with duration on a website and wish to obtain simultaneous clients for a group of web-pages)</p>
<p>What would your algoritm be?</p>
<p>I can iterate over records in the given period, and fill an array, where each bucket of the array corresponds to 1 second in the overall period. This works and seems to be fast, but if the timeperiod is big (say..1 year), I would need lots of memory (3600x24x365x4 bytes ~ 120MB aprox).</p>
<p>This is for a web-based, interactive app, so my memory footprint should be small enough. </p>
<p><strong>Edit</strong></p>
<p>By simultaneous, I mean all calls on a given second. Second would be my minimum unit. I cannot use something bigger (hour for example) becuse all calls during an hour do not need to be held at the same time.</p>
|
[
{
"answer_id": 53327,
"author": "Pablo Alsina",
"author_id": 2295,
"author_profile": "https://Stackoverflow.com/users/2295",
"pm_score": 0,
"selected": false,
"text": "SELECT temp.second, count(call.id)\nFROM call, temp\nWHERE temp.second between (call.start and call.start + call.duration)\nGROUP BY temp.second\n"
},
{
"answer_id": 169380,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "SELECT StartTime + Numbers.Number AS Second\nFROM Numbers\n"
},
{
"answer_id": 170678,
"author": "Aleksey Otrubennikov",
"author_id": 16209,
"author_profile": "https://Stackoverflow.com/users/16209",
"pm_score": 0,
"selected": false,
"text": "'simultaneous_calls' yyyymmdd Char(8),\nday_second Number, -- second of the day,\ncount Number -- count of simultaneous calls \nSelect to_char(calldate, 'yyyymmdd') yyyymmdd,\n (calldate - trunc(calldate)) * 24 * 3600 starting_second,\n duration duration\nFrom cdrs\nWhere cdrs.calldate >= Trunc(Sysdate -1)\n And cdrs.calldate \n\n\nIterates the cursor to increment 'count' field for the seconds of the call:\n\n\n For cdr in day_cdrs\nLoop \n Update simultaneos_calls\n Set count = count + 1\n Where yyyymmdd = cdr.yyyymmdd\n And day_second Between cdr.starting_second And cdr.starting_second + cdr.duration;\nEnd Loop;\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2295/"
] |
50,579 |
<p>I'm having a strange problem.</p>
<p>I have to use <code>GetPostBackEventRefence</code> to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?</p>
<p>This is what I'm missing after the postback:</p>
<pre><code><script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document.Main;
}
else {
theform = document.forms["Main"];
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
</code></pre>
|
[
{
"answer_id": 50593,
"author": "Haydar",
"author_id": 288,
"author_profile": "https://Stackoverflow.com/users/288",
"pm_score": 3,
"selected": true,
"text": "Page.ClientScript.GetPostBackClientHyperlink(controlName, \"\")\n"
},
{
"answer_id": 50663,
"author": "juan",
"author_id": 1782,
"author_profile": "https://Stackoverflow.com/users/1782",
"pm_score": 2,
"selected": false,
"text": "this.Page.RegisterClientScriptBlock(\"DUMMY\", \"<script language='javascript'>function dummy() { \" + this.Page.GetPostBackEventReference(this) + \"; } </script>\");\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
50,585 |
<p>How do you capture the mouse events, move and click over top of a Shockwave Director Object (not flash) in Firefox, via JavaScript. The code works in IE but not in FF. </p>
<p>The script works on the document body of both IE and Moz, but mouse events do not fire when mouse is over a shockwave director object embed.</p>
<p>Update: </p>
<pre><code> function displaycoordIE(){
window.status=event.clientX+" : " + event.clientY;
}
function displaycoordNS(e){
window.status=e.clientX+" : " + e.clientY;
}
function displaycoordMoz(e)
{
window.alert(e.clientX+" : " + e.clientY);
}
document.onmousemove = displaycoordIE;
document.onmousemove = displaycoordNS;
document.onclick = displaycoordMoz;
</code></pre>
<hr>
<p>Just a side note, I have also tried using an addEventListener to "mousemove".</p>
|
[
{
"answer_id": 1839458,
"author": "luna1999",
"author_id": 2573986,
"author_profile": "https://Stackoverflow.com/users/2573986",
"pm_score": 3,
"selected": true,
"text": "on mouseDown me\n gotoNetPage \"javascript:function('\" & argument & \"')\"\nend\n property pMouseLock\n\non beginsprite\n pMouseLock = _mouse.mouseLock\nend\non exitFrame \n if _mouse.mouseLock <> pMouseLock then\n gotoNetPage \"javascript:function('\" & argument & \"')\"\n pMouseLock = _mouse.mouseLock\n end if\nend\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567/"
] |
50,605 |
<p>Suppose I have the following C code.</p>
<pre><code>unsigned int u = 1234;
int i = -5678;
unsigned int result = u + i;
</code></pre>
<p>What implicit conversions are going on here, and is this code safe for all values of <code>u</code> and <code>i</code>? (Safe, in the sense that even though <em>result</em> in this example will overflow to some huge positive number, I could cast it back to an <em>int</em> and get the real result.)</p>
|
[
{
"answer_id": 50632,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 9,
"selected": true,
"text": "i UINT_MAX + 1 result u i u i i i UINT_MAX + 1 UINT_MAX #include <stdio.h>\n\nint main(void)\n{\n unsigned int plus_one = 1;\n int minus_one = -1;\n\n if(plus_one < minus_one)\n printf(\"1 < -1\");\n else\n printf(\"boring\");\n\n return 0;\n}\n UINT_MAX -1 unsigned int umax = -1; // umax set to UINT_MAX\n"
},
{
"answer_id": 50694,
"author": "Taylor Price",
"author_id": 3805,
"author_profile": "https://Stackoverflow.com/users/3805",
"pm_score": 1,
"selected": false,
"text": "int iValue, iResult;\nunsigned int uValue, uResult;\n"
},
{
"answer_id": 832772,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "unsigned int u = 1234;\nint i = -5678;\n\nunsigned int result = u + i;\n UINT_MAX + 1 - 5678 UINT_MAX + 1 - 4444"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
] |
50,618 |
<p>Syntax aside, what is the difference between</p>
<pre><code>try {
}
catch() {
}
finally {
x = 3;
}
</code></pre>
<p>and </p>
<pre><code>try {
}
catch() {
}
x = 3;
</code></pre>
<p>edit: in .NET 2.0?</p>
<hr>
<p>so</p>
<pre><code>try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
</code></pre>
<p>is behaviourally equivalent?</p>
|
[
{
"answer_id": 50649,
"author": "crashmstr",
"author_id": 1441,
"author_profile": "https://Stackoverflow.com/users/1441",
"pm_score": 0,
"selected": false,
"text": "catch(...) finally catch"
},
{
"answer_id": 50665,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 2,
"selected": false,
"text": "try\n{\n StreamReader stream = new StreamReader(\"foo.bar\");\n stream.write(\"foo\");\n}\ncatch(Exception e) { } // ignore for now\nfinally\n{\n stream.close();\n}\n StreamReader stream = null;\ntry\n{\n stream = new StreamReader(\"foo.bar\");\n stream.write(\"foo\");\n} catch(Exception e) {} // ignore\n\nif (stream != null)\n stream.close();\n"
},
{
"answer_id": 50685,
"author": "Bartosz Bierkowski",
"author_id": 3666,
"author_profile": "https://Stackoverflow.com/users/3666",
"pm_score": 3,
"selected": false,
"text": "try {\n return 0;\n} finally {\n return 2;\n}\n"
},
{
"answer_id": 50701,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 1,
"selected": false,
"text": "try\n{\nStreamReader stream = new StreamReader(\"foo.bar\");\nmySendSomethingToStream(stream);\n}\ncatch(noSomethingToSendException e) {\n //Swallow this \n logger.error(e.getMessage());\n}\ncatch(anotherTypeOfException e) {\n //More serious, throw this one back\n throw(e);\n}\nfinally\n{\nstream.close();\n}\n"
},
{
"answer_id": 52247,
"author": "Sean",
"author_id": 5446,
"author_profile": "https://Stackoverflow.com/users/5446",
"pm_score": 1,
"selected": false,
"text": "StreamReader stream = new StreamReader(\"foo.bar\"); \ntry {\n mySendSomethingToStream(stream);\n}\ncatch(noSomethingToSendException e) {\n //Swallow this \n logger.error(e.getMessage());\n}\ncatch(anotherTypeOfException e) {\n //More serious, throw this one back\n throw(e);\n}\nfinally {\n stream.close(); \n}\n"
},
{
"answer_id": 58169320,
"author": "Jacob Bruinsma",
"author_id": 930879,
"author_profile": "https://Stackoverflow.com/users/930879",
"pm_score": 1,
"selected": false,
"text": "finally stream.close() try{} finally goto finally {}"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5278/"
] |
50,702 |
<p>If I have 2 query sources how do I find ones that are in one that are not in the other?</p>
<p>example of join to find items in both:</p>
<pre><code>var results = from item1 in qs1.Items
join item2 in qs2 on item1.field1 equals item2.field2
select item1;
</code></pre>
<p>So what would the linq code be to return the items in qs1 that are not in qs2?</p>
|
[
{
"answer_id": 50719,
"author": "Bramha Ghosh",
"author_id": 3268,
"author_profile": "https://Stackoverflow.com/users/3268",
"pm_score": 2,
"selected": false,
"text": "NorthwindDataContext dc = new NorthwindDataContext();\ndc.Log = Console.Out;\nvar query =\n from c in dc.Customers\n where !(from o in dc.Orders\n select o.CustomerID)\n .Contains(c.CustomerID)\n select c;\nforeach (var c in query) Console.WriteLine( c );\n"
},
{
"answer_id": 50724,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 2,
"selected": false,
"text": "var items1 = new List<string> { \"Apple\",\"Orange\",\"Banana\" };\nvar items2 = new List<string> { \"Grapes\",\"Apple\",\"Kiwi\" };\n\nvar excluded = items1.Except(items2);\n"
},
{
"answer_id": 50728,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 0,
"selected": false,
"text": "List<string> items1 = new List<string>();\nitems1.Add(\"cake\");\nitems1.Add(\"cookie\");\nitems1.Add(\"pizza\");\n\nList<string> items2 = new List<string>();\nitems2.Add(\"pasta\");\nitems2.Add(\"pizza\");\n\nvar results = from item in items1\n where items2.Contains(item)\n select item;\n\nforeach (var item in results)\n Console.WriteLine(item); //Prints 'pizza'\n"
},
{
"answer_id": 823467,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": true,
"text": "var excluded = items1.Except(items2);\n void Main()\n{\n Random rand = new Random();\n int n = 100000;\n var randomSeq = Enumerable.Repeat(0, n).Select(i => rand.Next());\n var randomFilter = Enumerable.Repeat(0, n).Select(i => rand.Next());\n\n /* Method 1: Bramha Ghosh's/Marco Russo's method */\n (from el1 in randomSeq where !(from el2 in randomFilter select el2).Contains(el1) select el1).Dump(\"Result\");\n\n /* Method 2: Darren Kopp's method */\n randomSeq.Except(randomFilter).Dump(\"Result\");\n}\n n = 100. Method 1 takes about 0.05 seconds, Method 2 takes about 0.05 seconds\nn = 1,000. Method 1 takes about 0.6 seconds, Method 2 takes about 0.4 seconds\nn = 10,000. Method 1 takes about 2.5 seconds, Method 2 takes about 0.425 seconds\nn = 100,000. Method 1 takes about 20 seconds, Method 2 takes about 0.45 seconds\nn = 1,000,000. Method 1 takes about 3 minutes 25 seconds, Method 2 takes about 1.3 seconds\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1215/"
] |
50,704 |
<p>I'm designing an application which includes the need to log all incoming messages I receive from a Telnet connection. The text is largely plain though can include ANSI tags that provide text colour and formatting (16 colours, bold, underline, etc).</p>
<p>I'm would like to format my logs to store the text with formatting, date/time and potentially other meta data later. My first thoughts was all XML but this could impact my ability to write a fast search tool later. My current idea is Date/Time + text in one file with meta-data stored in another XML file, referenced by line number.</p>
<p>Is this a good solution? Also, where and how should I store the formatting commands? The original ANSI tags would disrupt the plain but having them in two different files might be awkward.</p>
<p>Additional: Thanks to some answers so far, though I should mention that most of the time the messages will be person to person communications rather than system messages. A more primitive IRC of sorts. Its up to my user to decide later (by adding meta data) which messages were important. This is the raw on the record log that filtered or edited logs might derive from.</p>
|
[
{
"answer_id": 50827,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 0,
"selected": false,
"text": "ls\ncd www\nls\nvi index.html\n/copyright 2007\nllllllllllllr8:wq\nexit\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
] |
50,723 |
<p>I was browsing <a href="https://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers">this thread</a>, which has good recommendation but a bit too general for me.</p>
<p>So, if anyone has a collection of nice game programming feeds,please share them. :)</p>
<p>(both general and specific topics are welcome)</p>
|
[
{
"answer_id": 50827,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 0,
"selected": false,
"text": "ls\ncd www\nls\nvi index.html\n/copyright 2007\nllllllllllllr8:wq\nexit\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5196/"
] |
50,737 |
<p>Is there a way to have TortoiseSVN (or any other tool) auto-add any new .cs files I create within a directory to my working copy so I don't have to remember which files I created at the end of the day?</p>
|
[
{
"answer_id": 50826,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": true,
"text": "dir /b /S *.cs > allcsfiles.txt\nsvn add --targets allcsfiles.txt\n"
},
{
"answer_id": 5710241,
"author": "Jet",
"author_id": 714339,
"author_profile": "https://Stackoverflow.com/users/714339",
"pm_score": 1,
"selected": false,
"text": "svn add --force --auto-props [Path to check in]\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
50,744 |
<p>What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?</p>
<p>I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the <em>file created</em> event fires before the other process has finished writing the file.</p>
<p>The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.</p>
<p>Edit: After trying out some of the solutions below, I ended up changing the <em>system</em> so that all files wrote to <code>Path.GetTempFileName()</code>, then performed a <code>File.Move()</code> to the final location. As soon as the <code>FileSystemWatcher</code> event fired, the file was already complete.</p>
|
[
{
"answer_id": 50800,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 7,
"selected": true,
"text": " /// <summary>\n /// Blocks until the file is not locked any more.\n /// </summary>\n /// <param name=\"fullPath\"></param>\n bool WaitForFile(string fullPath)\n {\n int numTries = 0;\n while (true)\n {\n ++numTries;\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite, \n FileShare.None, 100))\n {\n fs.ReadByte();\n\n // If we got this far the file is ready\n break;\n }\n }\n catch (Exception ex)\n {\n Log.LogWarning(\n \"WaitForFile {0} failed to get an exclusive lock: {1}\", \n fullPath, ex.ToString());\n\n if (numTries > 10)\n {\n Log.LogWarning(\n \"WaitForFile {0} giving up after 10 tries\", \n fullPath);\n return false;\n }\n\n // Wait for the lock to be released\n System.Threading.Thread.Sleep(500);\n }\n }\n\n Log.LogTrace(\"WaitForFile {0} returning true after {1} tries\",\n fullPath, numTries);\n return true;\n }\n"
},
{
"answer_id": 1171540,
"author": "Ralph Shillington",
"author_id": 81514,
"author_profile": "https://Stackoverflow.com/users/81514",
"pm_score": -1,
"selected": false,
"text": "private void WaitOnFile(string fileName)\n{\n FileInfo fileInfo = new FileInfo(fileName);\n for (long size = -1; size != fileInfo.Length; fileInfo.Refresh())\n {\n size = fileInfo.Length;\n System.Threading.Thread.Sleep(1000);\n }\n}\n"
},
{
"answer_id": 1247326,
"author": "user152791",
"author_id": 152791,
"author_profile": "https://Stackoverflow.com/users/152791",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.IO;\nusing System.Threading;\n\n/// <summary>\n/// This is a wrapper aroung a FileStream. While it is not a Stream itself, it can be cast to\n/// one (keep in mind that this might throw an exception).\n/// </summary>\npublic class SafeFileStream: IDisposable\n{\n #region Private Members\n private Mutex m_mutex;\n private Stream m_stream;\n private string m_path;\n private FileMode m_fileMode;\n private FileAccess m_fileAccess;\n private FileShare m_fileShare;\n #endregion//Private Members\n\n #region Constructors\n public SafeFileStream(string path, FileMode mode, FileAccess access, FileShare share)\n {\n m_mutex = new Mutex(false, String.Format(\"Global\\\\{0}\", path.Replace('\\\\', '/')));\n m_path = path;\n m_fileMode = mode;\n m_fileAccess = access;\n m_fileShare = share;\n }\n #endregion//Constructors\n\n #region Properties\n public Stream UnderlyingStream\n {\n get\n {\n if (!IsOpen)\n throw new InvalidOperationException(\"The underlying stream does not exist - try opening this stream.\");\n return m_stream;\n }\n }\n\n public bool IsOpen\n {\n get { return m_stream != null; }\n }\n #endregion//Properties\n\n #region Functions\n /// <summary>\n /// Opens the stream when it is not locked. If the file is locked, then\n /// </summary>\n public void Open()\n {\n if (m_stream != null)\n throw new InvalidOperationException(SafeFileResources.FileOpenExceptionMessage);\n m_mutex.WaitOne();\n m_stream = File.Open(m_path, m_fileMode, m_fileAccess, m_fileShare);\n }\n\n public bool TryOpen(TimeSpan span)\n {\n if (m_stream != null)\n throw new InvalidOperationException(SafeFileResources.FileOpenExceptionMessage);\n if (m_mutex.WaitOne(span))\n {\n m_stream = File.Open(m_path, m_fileMode, m_fileAccess, m_fileShare);\n return true;\n }\n else\n return false;\n }\n\n public void Close()\n {\n if (m_stream != null)\n {\n m_stream.Close();\n m_stream = null;\n m_mutex.ReleaseMutex();\n }\n }\n\n public void Dispose()\n {\n Close();\n GC.SuppressFinalize(this);\n }\n\n public static explicit operator Stream(SafeFileStream sfs)\n {\n return sfs.UnderlyingStream;\n }\n #endregion//Functions\n}\n"
},
{
"answer_id": 3677960,
"author": "mafu",
"author_id": 39590,
"author_profile": "https://Stackoverflow.com/users/39590",
"pm_score": 6,
"selected": false,
"text": "FileStream WaitForFile (string fullPath, FileMode mode, FileAccess access, FileShare share)\n{\n for (int numTries = 0; numTries < 10; numTries++) {\n FileStream fs = null;\n try {\n fs = new FileStream (fullPath, mode, access, share);\n return fs;\n }\n catch (IOException) {\n if (fs != null) {\n fs.Dispose ();\n }\n Thread.Sleep (50);\n }\n }\n\n return null;\n}\n"
},
{
"answer_id": 5441631,
"author": "Simon Mourier",
"author_id": 403671,
"author_profile": "https://Stackoverflow.com/users/403671",
"pm_score": 4,
"selected": false,
"text": "WrapSharingViolations(() => File.Delete(myFile));\n WrapSharingViolations(() => File.Copy(mySourceFile, myDestFile));\n IsSharingViolation /// <summary>\n /// Wraps sharing violations that could occur on a file IO operation.\n /// </summary>\n /// <param name=\"action\">The action to execute. May not be null.</param>\n public static void WrapSharingViolations(WrapSharingViolationsCallback action)\n {\n WrapSharingViolations(action, null, 10, 100);\n }\n\n /// <summary>\n /// Wraps sharing violations that could occur on a file IO operation.\n /// </summary>\n /// <param name=\"action\">The action to execute. May not be null.</param>\n /// <param name=\"exceptionsCallback\">The exceptions callback. May be null.</param>\n /// <param name=\"retryCount\">The retry count.</param>\n /// <param name=\"waitTime\">The wait time in milliseconds.</param>\n public static void WrapSharingViolations(WrapSharingViolationsCallback action, WrapSharingViolationsExceptionsCallback exceptionsCallback, int retryCount, int waitTime)\n {\n if (action == null)\n throw new ArgumentNullException(\"action\");\n\n for (int i = 0; i < retryCount; i++)\n {\n try\n {\n action();\n return;\n }\n catch (IOException ioe)\n {\n if ((IsSharingViolation(ioe)) && (i < (retryCount - 1)))\n {\n bool wait = true;\n if (exceptionsCallback != null)\n {\n wait = exceptionsCallback(ioe, i, retryCount, waitTime);\n }\n if (wait)\n {\n System.Threading.Thread.Sleep(waitTime);\n }\n }\n else\n {\n throw;\n }\n }\n }\n }\n\n /// <summary>\n /// Defines a sharing violation wrapper delegate.\n /// </summary>\n public delegate void WrapSharingViolationsCallback();\n\n /// <summary>\n /// Defines a sharing violation wrapper delegate for handling exception.\n /// </summary>\n public delegate bool WrapSharingViolationsExceptionsCallback(IOException ioe, int retry, int retryCount, int waitTime);\n\n /// <summary>\n /// Determines whether the specified exception is a sharing violation exception.\n /// </summary>\n /// <param name=\"exception\">The exception. May not be null.</param>\n /// <returns>\n /// <c>true</c> if the specified exception is a sharing violation exception; otherwise, <c>false</c>.\n /// </returns>\n public static bool IsSharingViolation(IOException exception)\n {\n if (exception == null)\n throw new ArgumentNullException(\"exception\");\n\n int hr = GetHResult(exception, 0);\n return (hr == -2147024864); // 0x80070020 ERROR_SHARING_VIOLATION\n\n }\n\n /// <summary>\n /// Gets the HRESULT of the specified exception.\n /// </summary>\n /// <param name=\"exception\">The exception to test. May not be null.</param>\n /// <param name=\"defaultValue\">The default value in case of an error.</param>\n /// <returns>The HRESULT value.</returns>\n public static int GetHResult(IOException exception, int defaultValue)\n {\n if (exception == null)\n throw new ArgumentNullException(\"exception\");\n\n try\n {\n const string name = \"HResult\";\n PropertyInfo pi = exception.GetType().GetProperty(name, BindingFlags.NonPublic | BindingFlags.Instance); // CLR2\n if (pi == null)\n {\n pi = exception.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance); // CLR4\n }\n if (pi != null)\n return (int)pi.GetValue(exception, null);\n }\n catch\n {\n }\n return defaultValue;\n }\n"
},
{
"answer_id": 14467767,
"author": "Bernhard Hochgatterer",
"author_id": 2001739,
"author_profile": "https://Stackoverflow.com/users/2001739",
"pm_score": -1,
"selected": false,
"text": "var watcher = new FileSystemWatcher {\n Path = @\"c:\\temp\\test\",\n Filter = \"*.xml\",\n NotifyFilter = NotifyFilters.LastWrite\n};\nwatcher.Changed += watcher_Changed; \nwatcher.EnableRaisingEvents = true;\n"
},
{
"answer_id": 22178178,
"author": "Jahmal23",
"author_id": 3380046,
"author_profile": "https://Stackoverflow.com/users/3380046",
"pm_score": -1,
"selected": false,
"text": "string fileName = MessagingBLL.BuildPropertyAttachmentFileName(currProp);\n\n //create a temporary file to send as the attachment\n string pathString = Path.Combine(Path.GetTempPath(), fileName);\n\n //dirty trick to make sure locks are released on the file.\n using (System.IO.File.Create(pathString)) { }\n\n mailItem.Subject = MessagingBLL.PropertyAttachmentSubject;\n mailItem.Attachments.Add(pathString, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);\n"
},
{
"answer_id": 42782410,
"author": "Florian K",
"author_id": 6754146,
"author_profile": "https://Stackoverflow.com/users/6754146",
"pm_score": 1,
"selected": false,
"text": "public static void CheckFileLock(string directory, string filename, Func<Task> callBack)\n{\n var watcher = new FileSystemWatcher(directory, filename);\n FileSystemEventHandler check = \n async (sender, eArgs) =>\n {\n string fullPath = Path.Combine(directory, filename);\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite,\n FileShare.None, 100))\n {\n fs.ReadByte();\n watcher.EnableRaisingEvents = false;\n // If we got this far the file is ready\n }\n watcher.Dispose();\n await callBack();\n }\n catch (IOException) { }\n };\n watcher.NotifyFilter = NotifyFilters.LastWrite;\n watcher.IncludeSubdirectories = false;\n watcher.EnableRaisingEvents = true;\n //Attach the checking to the changed method, \n //on every change it gets checked once\n watcher.Changed += check;\n //Initially do a check for the case it is already released\n check(null, null);\n}\n"
},
{
"answer_id": 67424708,
"author": "Tyrone Moodley",
"author_id": 3263578,
"author_profile": "https://Stackoverflow.com/users/3263578",
"pm_score": 0,
"selected": false,
"text": "bool WaitForFile(string fullPath)\n {\n int numTries = 0;\n while (true)\n {\n //need to add this line to prevent infinite loop\n if (!File.Exists(fullPath))\n {\n _logger.LogInformation(\"WaitForFile {0} returning true - file does not exist\", fullPath);\n break;\n }\n ++numTries;\n try\n {\n // Attempt to open the file exclusively.\n using (FileStream fs = new FileStream(fullPath,\n FileMode.Open, FileAccess.ReadWrite,\n FileShare.None, 100))\n {\n fs.ReadByte();\n\n // If we got this far the file is ready\n break;\n }\n }\n catch (Exception ex)\n {\n _logger.LogInformation(\n \"WaitForFile {0} failed to get an exclusive lock: {1}\",\n fullPath, ex.ToString());\n\n if (numTries > 10)\n {\n _logger.LogInformation(\n \"WaitForFile {0} giving up after 10 tries\",\n fullPath);\n return false;\n }\n\n // Wait for the lock to be released\n System.Threading.Thread.Sleep(500);\n }\n }\n\n _logger.LogInformation(\"WaitForFile {0} returning true after {1} tries\",\n fullPath, numTries);\n return true;\n }\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] |
50,746 |
<p>We are using VS 2008 Team System with the automated test suite, and upon running tests the test host "randomly" locks up. I actually have to kill the VSTestHost process and re-run the tests to get something to happen, otherwise all tests sit in a "pending" state.</p>
<p>Has anyone experience similar behavior and know of a fix? We have 3 developers here experiencing the same behavior.</p>
|
[
{
"answer_id": 51063,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "ntsd -p <PID>\n.dump C:\\mydump.dmp\n"
},
{
"answer_id": 888372,
"author": "Tim Long",
"author_id": 98516,
"author_profile": "https://Stackoverflow.com/users/98516",
"pm_score": 2,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\ComputerName\\ActiveComputerName\nHKEY_LOCAL_MACHINE\\System\\CurrentControlSet\\Control\\ComputerName\\ComputerName\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
] |
50,762 |
<p>I need to programmatically determine out how many sectors, heads, and cylinders are on a physical disk from Windows XP. Does anyone know the API for determining this? Where might Windows expose this information?</p>
|
[
{
"answer_id": 1724560,
"author": "µBio",
"author_id": 9796,
"author_profile": "https://Stackoverflow.com/users/9796",
"pm_score": 1,
"selected": false,
"text": "using( ManagementClass driveClass = new ManagementClass( \"Win32_DiskDrive\" ) )\n{\n using( ManagementObjectCollection physicalDrives = driveClass.GetInstances( ) )\n {\n foreach( ManagementObject drive in physicalDrives )\n {\n string cylinders = ( string )drive[\"TotalCylinders\"];\n // ... etc ...\n drive.Dispose( );\n }\n }\n}\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2171/"
] |
50,786 |
<p>How do I get ms-access to connect (through ODBC) to an ms-sql database as a different user than their Active Directory ID? </p>
<p>I don't want to specify an account in the ODBC connection, I want to do it on the ms-access side to hide it from my users. Doing it in the ODBC connection would put me right back in to the original situation I'm trying to avoid.</p>
<p>Yes, this relates to a previous question: <a href="http://www.stackoverflow.com/questions/50164/">http://www.stackoverflow.com/questions/50164/</a></p>
|
[
{
"answer_id": 73412,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 0,
"selected": false,
"text": "Table_Blablabla View_Table_Blablabla form_Open"
},
{
"answer_id": 85064,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "myTable.Connect = _\n \"ODBC;\" & _\n \"DATABASE=\" & \"MyTestDB\" & \";\" & _\n \"UID=readonly;\" & _\n \"PWD=readonly_password;\" & _\n \"DSN=\" & \"MyTestDB\" & \";\"\nmyTable.RefreshLink\n myTable.Connect = _\n \"ODBC;\" & _\n \"DATABASE=\" & \"MyTestDB\" & \";\" & _\n \"UID=readwrite;\" & _\n \"PWD=readwrite_password;\" & _\n \"DSN=\" & \"MyTestDB\" & \";\"\nmyTable.RefreshLink\n"
},
{
"answer_id": 153206,
"author": "Tim Lentine",
"author_id": 2833,
"author_profile": "https://Stackoverflow.com/users/2833",
"pm_score": 4,
"selected": true,
"text": "\"ODBC;Driver={SQL Native Client};\" &\n \"Server=MyServerName;\" & _\n \"Database=myDatabaseName;\" & _\n \"Uid=myUsername;\" & _\n \"Pwd=myPassword\"\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] |
50,794 |
<p>How does unix handle full path name with space and arguments ?<br>
In windows we quote the path and add the command-line arguments after, how is it in unix?</p>
<pre><code> "c:\foo folder with space\foo.exe" -help
</code></pre>
<p><strong>update:</strong></p>
<p>I meant how do I recognize a path from the command line arguments.</p>
|
[
{
"answer_id": 50798,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 4,
"selected": false,
"text": "/Applications/Image\\ Capture.app/Contents/MacOS/Image\\ Capture\n\n\"/Applications/Image Capture.app/Contents/MacOS/Image Capture\"\n\n/Applications/\"Image Capture.app\"/Contents/MacOS/\"Image Capture\"\n"
},
{
"answer_id": 50804,
"author": "Fernando Barrocal",
"author_id": 2274,
"author_profile": "https://Stackoverflow.com/users/2274",
"pm_score": 1,
"selected": false,
"text": "/foo\\ folder\\ with\\ space/foo.sh -help\n"
},
{
"answer_id": 50805,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 5,
"selected": false,
"text": " \"/foo folder with space/foo\" --help\n /foo\\ folder\\ with\\ space/foo --help\n"
},
{
"answer_id": 50811,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 2,
"selected": false,
"text": "\"/path/with/spaces in it/to/a/file\"\nsomecommand -spaced\\ option\nsomecommand \"-spaced option\"\nsomecommand '-spaced option'\n print(\"code sample\"); print(\"code sample\");"
},
{
"answer_id": 50830,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "$foo \\t !foo"
},
{
"answer_id": 29418681,
"author": "atwixtor",
"author_id": 435596,
"author_profile": "https://Stackoverflow.com/users/435596",
"pm_score": 0,
"selected": false,
"text": "%20 auto_smb"
},
{
"answer_id": 41442709,
"author": "PintoUbuntu",
"author_id": 3727642,
"author_profile": "https://Stackoverflow.com/users/3727642",
"pm_score": 1,
"selected": false,
"text": ">scriptName.sh arg1 arg2\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] |
50,801 |
<p>How would you find the fractional part of a floating point number in PHP?</p>
<p>For example, if I have the value <code>1.25</code>, I want to return <code>0.25</code>.</p>
|
[
{
"answer_id": 50806,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 7,
"selected": true,
"text": "$x = $x - floor($x)\n"
},
{
"answer_id": 50817,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": " $x = abs($x) - floor(abs($x));\n"
},
{
"answer_id": 51909,
"author": "Alan Storm",
"author_id": 4668,
"author_profile": "https://Stackoverflow.com/users/4668",
"pm_score": 4,
"selected": false,
"text": "$x = 22.732423423423432;\n$x = bcsub(abs($x),floor(abs($x)),20);\n $x = 22.732423423423432; \n$x = strstr ( $x, '.' );\n"
},
{
"answer_id": 7734841,
"author": "Michael Fenwick",
"author_id": 858061,
"author_profile": "https://Stackoverflow.com/users/858061",
"pm_score": 3,
"selected": false,
"text": "$x = $x - intval($x)\n"
},
{
"answer_id": 8460196,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": ".25 -.25"
},
{
"answer_id": 38701237,
"author": "Paul M",
"author_id": 933499,
"author_profile": "https://Stackoverflow.com/users/933499",
"pm_score": 1,
"selected": false,
"text": "function getDecimalPart($floatNum) {\n return abs($floatNum - intval($floatNum));\n}\n\n$decimalPart = getDecimalPart($floatNum);\n"
},
{
"answer_id": 41626638,
"author": "sanmai",
"author_id": 93540,
"author_profile": "https://Stackoverflow.com/users/93540",
"pm_score": 5,
"selected": false,
"text": "$x = fmod($x, 1);\n <?php\n$x = 25.3333;\n$x = fmod($x, 1);\nvar_dump($x);\n double(0.3333)\n"
},
{
"answer_id": 54575236,
"author": "dmvslv",
"author_id": 3328002,
"author_profile": "https://Stackoverflow.com/users/3328002",
"pm_score": 1,
"selected": false,
"text": "$y = fmod($x, 1); //$x = 1.25 $y = 0.25\n"
},
{
"answer_id": 56249728,
"author": "SirDagen",
"author_id": 11494956,
"author_profile": "https://Stackoverflow.com/users/11494956",
"pm_score": 0,
"selected": false,
"text": "$frac=($x<0) ? $x-ceil($x) : $x-floor($x);\n $frac=($x<0) ? $x-ceil($x) : $x-floor($x); $frac=fmod($x, 1); $x=sqrt(2)-0.41421356237;\n\n$time_start = microtime(true);\nfor ($i=0;$i<=9999999;$i++) {\n //$frac=fmod($x, 1); // version a\n $frac=($x<0) ? $x-ceil($x) : $x-floor($x); // version b\n}\n$time_end = microtime(true);\n\n$time = $time_end - $time_start;\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4925/"
] |
50,814 |
<p>How does Google manage to properly align the second column <em>(i.e. the ticker name)</em> in the "Get Quotes" search box suggestion drop-down in <a href="http://finance.google.com" rel="nofollow noreferrer">google finance url</a></p>
<p><strong>Example:</strong> If you enter <code>iii</code> - the second column is perfectly aligned.</p>
<p>It does not use a fixed width font - so just adding the correct numbers of spaces to the <em>ticker</em> will not work.</p>
<p>How do they do that?
</p>
|
[
{
"answer_id": 51245,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 0,
"selected": false,
"text": "span"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
50,819 |
<p>Do any editors honer C #line directives with regards to goto line features?</p>
<p><em>Context:</em>
I'm working on a code generator and need to jump to a line of the output but the line is specified relative to the the #line directives I'm adding.
I can drop them but then finding the input line is even a worse pain</p>
|
[
{
"answer_id": 50852,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 0,
"selected": false,
"text": "#line .c .i .gch"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
50,824 |
<p>I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom.</p>
<p>So my question: is it valid XML to place it at either location? For example, above the XML Declaration:</p>
<pre><code><!-- Queries used: ... -->
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
</code></pre>
<p>Or below the root node:</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
<!-- Queries used: ... -->
</code></pre>
<p>I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from <a href="http://en.wikipedia.org/wiki/Xml#Well-formed_documents:_XML_syntax" rel="noreferrer">wikipedia</a>:</p>
<blockquote>
<p>Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.</p>
</blockquote>
<p>I plan to post back if this works, but it would be nice to know if it is an official XML standard.</p>
<p><strong>UPDATE:</strong> See <a href="https://stackoverflow.com/questions/50824/can-xml-comments-go-anywhere#50976">my response below</a> for the result of my test.</p>
|
[
{
"answer_id": 50832,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 5,
"selected": true,
"text": "document ::= prolog element Misc* prolog prolog ::= XMLDecl? Misc* (doctypedecl Misc*)? Misc Misc ::= Comment | PI | S XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>' Misc*"
},
{
"answer_id": 50837,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!-- Queries used: ... -->\n<dataset>\n</dataset>\n"
},
{
"answer_id": 50850,
"author": "David Schlosnagle",
"author_id": 1750,
"author_profile": "https://Stackoverflow.com/users/1750",
"pm_score": 2,
"selected": false,
"text": "<?xml version='1.0' encoding='UTF-8'?>\n<!-- Queries used: ... -->\n<dataset>\n ...\n</dataset>\n"
},
{
"answer_id": 50976,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 2,
"selected": false,
"text": "DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\nDocumentBuilder builder = factory.newDocumentBuilder();\nDocument document = builder.parse(new File(\"/path/to/file\"));\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
50,829 |
<p>This is a bit hypothetical and grossly simplified but...</p>
<p>Assume a program that will be calling functions written by third parties. These parties can be assumed to be non-hostile but can't be assumed to be "competent". Each function will take some arguments, have side effects and return a value. They have no state while they are not running.</p>
<p>The objective is to ensure they can't cause memory leaks by logging all mallocs (and the like) and then freeing everything after the function exits.</p>
<p>Is this possible? Is this practical?</p>
<p>p.s. The important part to me is ensuring that no allocations persist so ways to remove memory leaks without doing that are not useful to me.</p>
|
[
{
"answer_id": 50842,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 2,
"selected": false,
"text": "malloc() free() #define"
},
{
"answer_id": 60252131,
"author": "Ruslan",
"author_id": 673852,
"author_profile": "https://Stackoverflow.com/users/673852",
"pm_score": 0,
"selected": false,
"text": "mtrace(3) mtrace() main() MALLOC_TRACE @ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x99e5e20 0x49\n@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x99beba0\n@ /usr/lib/tls/libnvidia-tls.so.390.116:[0xf44b795c] + 0x9a23ec0 0x10\n@ /opt/gcc-7/lib/libstdc++.so.6:(_ZdlPv+0x18)[0xf6a80f78] - 0x9a23ec0\n@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + 0x99c67c0 0x8\n@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668f14f] - 0x99c67c0\n@ /opt/Xorg/lib/video-libs/libGL.so.1:[0xf668ee49] + (nil) 0x30000000\n@ /lib/libc.so.6:[0xf677f8eb] + 0x99c21f0 0x158\n@ /lib/libc.so.6:(_IO_file_doallocate+0x91)[0xf677ee61] + 0xbfb00480 0x400\n@ /lib/libc.so.6:(_IO_setb+0x59)[0xf678d7f9] - 0xbfb00480\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
50,853 |
<p>I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?</p>
<p>Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related?</p>
|
[
{
"answer_id": 175736,
"author": "KyleLanser",
"author_id": 12923,
"author_profile": "https://Stackoverflow.com/users/12923",
"pm_score": 2,
"selected": false,
"text": "DataClasses1DataContext db = new DataClasses1DataContext();\n\nvar results = from threes in db.tableThrees\n join twos in db.tableTwos on threes.fk_tableTwo equals twos.id\n join ones in db.tableOnes on twos.fk_tableOne equals ones.id\n select new { ones, twos, threes };\n --Table One\nCREATE TABLE tableOne(\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n CONSTRAINT [PK_tableOne] PRIMARY KEY CLUSTERED \n ( [id] ASC ) WITH ( \n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n ) ON [PRIMARY];\n\n--Table Two\nCREATE TABLE tableTwo(\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n [fk_tableOne] [int] NOT NULL,\nCONSTRAINT [PK_tableTwo] PRIMARY KEY CLUSTERED \n ( [id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF,\n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n ) ON [PRIMARY];\n\nALTER TABLE tableTwo WITH CHECK \n ADD CONSTRAINT [FK_tableTwo_tableOne] \n FOREIGN KEY([fk_tableOne])\n REFERENCES tableOne ([id]);\n\nALTER TABLE tableTwo CHECK CONSTRAINT [FK_tableTwo_tableOne];\n\n\n--Table Three\nCREATE TABLE tableThree(\n [id] [int] IDENTITY(1,1) NOT NULL,\n [value] [nvarchar](50) NULL,\n [fk_tableTwo] [int] NOT NULL,\nCONSTRAINT [PK_tableThree] PRIMARY KEY CLUSTERED \n ([id] ASC ) WITH (\n PAD_INDEX = OFF, \n STATISTICS_NORECOMPUTE = OFF, \n IGNORE_DUP_KEY = OFF, \n ALLOW_ROW_LOCKS = ON, \n ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n ) ON [PRIMARY];\n\nALTER TABLE tableThree WITH CHECK \n ADD CONSTRAINT [FK_tableThree_tableTwo] \n FOREIGN KEY([fk_tableTwo])\n REFERENCES tableTwo ([id]);\n\nALTER TABLE tableThree CHECK CONSTRAINT [FK_tableThree_tableTwo];\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] |
50,900 |
<p>So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this</p>
<pre><code>if(Debug.Mode){
<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}
</code></pre>
<p>I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.</p>
|
[
{
"answer_id": 50921,
"author": "jdelator",
"author_id": 438,
"author_profile": "https://Stackoverflow.com/users/438",
"pm_score": 3,
"selected": false,
"text": "#if DEBUG\n Console.WriteLine(\"Debug mode.\") \n#else \n Console.WriteLine(\"Release mode.\") \n#endif \n"
},
{
"answer_id": 50922,
"author": "Jonathan Allen",
"author_id": 5274,
"author_profile": "https://Stackoverflow.com/users/5274",
"pm_score": 1,
"selected": false,
"text": "#If CONFIG = \"Debug\" Then\n 'do somtehing\n#Else\n 'do something else\n#EndIf\n"
},
{
"answer_id": 50966,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 6,
"selected": true,
"text": "#if (DEBUG)\n Debug Stuff\n#endif\n #if \n#else \n#elif // Else If\n#endif\n#define\n#undef // Undefine\n#warning // Causes the preprocessor to fire warning\n#error // Causes the preprocessor to fire a fatal error\n#line // Lets the preprocessor know where this source line came from\n#region // Codefolding\n#endregion \n"
},
{
"answer_id": 299152,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": " if (System.Diagnostics.Debugger.IsAttached)\n {\n // Do this\n }\n else\n {\n // Do that\n }\n"
},
{
"answer_id": 7766384,
"author": "Assassin",
"author_id": 294650,
"author_profile": "https://Stackoverflow.com/users/294650",
"pm_score": 2,
"selected": false,
"text": "HttpContext.Current.IsDebuggingEnabled\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
] |
50,931 |
<p>I'm using <a href="http://www.helicontech.com/isapi_rewrite/" rel="nofollow noreferrer">Helicon's ISAPI Rewrite 3</a>, which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:</p>
<pre><code>RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]
</code></pre>
<p>This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected?</p>
|
[
{
"answer_id": 50937,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "RewriteCond %{HTTP:Host} ^example\\.com(.*) [NC]\n"
},
{
"answer_id": 50948,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "RewriteCond %{HTTP:Host} ^[^.]+\\.[a-z]{2,5}$ [NC]\n"
},
{
"answer_id": 51039,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 1,
"selected": false,
"text": "<unless header=\"Host\" match=\"^www\\.\">\n <if url=\"^(https?://)[^/]*(.*)$\">\n <redirect to=\"$1www.domain.tld$2\"/>\n </if>\n <redirect url=\"^(.*)$\" to=\"http://www.domain.tld$1\"/>\n</unless>\n"
},
{
"answer_id": 51075,
"author": "Josh Hunt",
"author_id": 2592,
"author_profile": "https://Stackoverflow.com/users/2592",
"pm_score": 0,
"selected": false,
"text": "ServerName: www.example.com\nServerAlias: example.com\n"
},
{
"answer_id": 51079,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "^example\\.com$ ^example\\.com(.*)"
},
{
"answer_id": 52578,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "^[^.]+\\.[^.]\\+$"
},
{
"answer_id": 52919,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "RewriteCond %{HTTP:Host} (example.com|example.net|example.org) [NC]\n"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2614/"
] |
50,945 |
<p>If I had 20 directories under trunk/ with lots of files in each and only needed 3 of those directories, would it be possible to do a Subversion checkout with only those 3 directories under trunk?</p>
|
[
{
"answer_id": 50956,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": -1,
"selected": false,
"text": "svn co file:///.../trunk/foo file:///.../trunk/bar file:///.../trunk/hum\n"
},
{
"answer_id": 50980,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 8,
"selected": false,
"text": "svn checkout --depth empty http://svnserver/trunk/proj\nsvn update --set-depth infinity proj/foo\nsvn update --set-depth infinity proj/bar\nsvn update --set-depth infinity proj/baz\n --depth immediates empty trunk/proj svn checkout --non-recursive http://svnserver/trunk/proj\nsvn update trunk/foo\nsvn update trunk/bar\nsvn update trunk/baz\n"
},
{
"answer_id": 6686476,
"author": "kostmo",
"author_id": 105137,
"author_profile": "https://Stackoverflow.com/users/105137",
"pm_score": 3,
"selected": false,
"text": "#!/usr/bin/env python\n\n'''\nThis script makes a sparse checkout of an SVN tree in the current working directory.\n\nGiven a list of paths in an SVN repository, it will:\n1. Checkout the common root directory\n2. Update with depth=empty for intermediate directories\n3. Update with depth=infinity for the leaf directories\n'''\n\nimport os\nimport getpass\nimport pysvn\n\n__author__ = \"Karl Ostmo\"\n__date__ = \"July 13, 2011\"\n\n# =============================================================================\n\n# XXX The os.path.commonprefix() function does not behave as expected!\n# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html\n# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html\n# and here (what ever happened?): http://bugs.python.org/issue400788\nfrom itertools import takewhile\ndef allnamesequal(name):\n return all(n==name[0] for n in name[1:])\n\ndef commonprefix(paths, sep='/'):\n bydirectorylevels = zip(*[p.split(sep) for p in paths])\n return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))\n\n# =============================================================================\ndef getSvnClient(options):\n\n password = options.svn_password\n if not password:\n password = getpass.getpass('Enter SVN password for user \"%s\": ' % options.svn_username)\n\n client = pysvn.Client()\n client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)\n return client\n\n# =============================================================================\ndef sparse_update_with_feedback(client, new_update_path):\n revision_list = client.update(new_update_path, depth=pysvn.depth.empty)\n\n# =============================================================================\ndef sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):\n\n path_segments = sparse_path.split(os.sep)\n path_segments.reverse()\n\n # Update the middle path segments\n new_update_path = local_checkout_root\n while len(path_segments) > 1:\n path_segment = path_segments.pop()\n new_update_path = os.path.join(new_update_path, path_segment)\n sparse_update_with_feedback(client, new_update_path)\n if options.verbose:\n print \"Added internal node:\", path_segment\n\n # Update the leaf path segment, fully-recursive\n leaf_segment = path_segments.pop()\n new_update_path = os.path.join(new_update_path, leaf_segment)\n\n if options.verbose:\n print \"Will now update with 'recursive':\", new_update_path\n update_revision_list = client.update(new_update_path)\n\n if options.verbose:\n for revision in update_revision_list:\n print \"- Finished updating %s to revision: %d\" % (new_update_path, revision.number)\n\n# =============================================================================\ndef group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):\n\n if not sparse_path_list:\n print \"Nothing to do!\"\n return\n\n checkout_path = None\n if len(sparse_path_list) > 1:\n checkout_path = commonprefix(sparse_path_list)\n else:\n checkout_path = sparse_path_list[0].split(os.sep)[0]\n\n\n\n root_checkout_url = os.path.join(repo_url, checkout_path).replace(\"\\\\\", \"/\")\n revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)\n\n checkout_path_segments = checkout_path.split(os.sep)\n for sparse_path in sparse_path_list:\n\n # Remove the leading path segments\n path_segments = sparse_path.split(os.sep)\n start_segment_index = 0\n for i, segment in enumerate(checkout_path_segments):\n if segment == path_segments[i]:\n start_segment_index += 1\n else:\n break\n\n pruned_path = os.sep.join(path_segments[start_segment_index:])\n sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)\n\n# =============================================================================\nif __name__ == \"__main__\":\n\n from optparse import OptionParser\n usage = \"\"\"%prog [path2] [more paths...]\"\"\"\n\n default_repo_url = \"http://svn.example.com/MyRepository\"\n default_checkout_path = \"sparse_trunk\"\n\n parser = OptionParser(usage)\n parser.add_option(\"-r\", \"--repo_url\", type=\"str\", default=default_repo_url, dest=\"repo_url\", help='Repository URL (default: \"%s\")' % default_repo_url)\n parser.add_option(\"-l\", \"--local_path\", type=\"str\", default=default_checkout_path, dest=\"local_path\", help='Local checkout path (default: \"%s\")' % default_checkout_path)\n\n default_username = getpass.getuser()\n parser.add_option(\"-u\", \"--username\", type=\"str\", default=default_username, dest=\"svn_username\", help='SVN login username (default: \"%s\")' % default_username)\n parser.add_option(\"-p\", \"--password\", type=\"str\", dest=\"svn_password\", help=\"SVN login password\")\n\n parser.add_option(\"-v\", \"--verbose\", action=\"store_true\", default=False, dest=\"verbose\", help=\"Verbose output\")\n (options, args) = parser.parse_args()\n\n client = getSvnClient(options)\n group_sparse_checkout(\n options,\n client,\n options.repo_url,\n map(os.path.relpath, args),\n options.local_path)\n"
},
{
"answer_id": 53920270,
"author": "Feng Weiwei",
"author_id": 6320442,
"author_profile": "https://Stackoverflow.com/users/6320442",
"pm_score": 1,
"selected": false,
"text": "--set-depth svn update --set-depth=exclude www\n set-depth --set-depth svn update --set-depth=infinity www\n"
},
{
"answer_id": 74054522,
"author": "Zac",
"author_id": 971443,
"author_profile": "https://Stackoverflow.com/users/971443",
"pm_score": 0,
"selected": false,
"text": "Choose items..."
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] |
50,983 |
<p>I liked the discussion at <a href="https://stackoverflow.com/questions/31693/differences-in-generics">Differences in Generics</a>, and was wondering whether there were any languages that used this feature particularly well.</p>
<p>I really dislike Java's <code>List<? extends Foo></code> for a <code>List</code> of things that are Liskov-substitutable for <code>Foo</code>. Why can't <code>List<Foo></code> cover that?</p>
<p>And honestly, <code>Comparable<? super Bar></code>?</p>
<p>I also can't remember for the life of my why you should never return an Array of generics:</p>
<pre><code>public T[] getAll<T>() { ... }
</code></pre>
<p>I never liked templates in C++, but that was mostly because none of the compilers could ever spit out a remotely meaningful error message for them. One time I actually did a <code>make realclean && make</code> 17 times to get something to compile; I never did figure out why the 17th time was the charm.</p>
<p>So, who actually <em>likes</em> using generics in their pet language?</p>
|
[
{
"answer_id": 50997,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 1,
"selected": false,
"text": "Dim Cars as List(Of Car)\nDim Car as Car\n\nFor Each Car in Cars\n...\nNext\n"
},
{
"answer_id": 51014,
"author": "Jay Conrod",
"author_id": 1891,
"author_profile": "https://Stackoverflow.com/users/1891",
"pm_score": 3,
"selected": false,
"text": "List<Foo> List<? extends Foo> Foo Bar List<Foo> List<Bar> List<Foo> List<Bar> Bar Foo[] Bar[] List<? super Foo>"
}
] |
2008/09/08
|
[
"https://Stackoverflow.com/questions/50983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] |
50,995 |
<p>I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.</p>
<p>I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument</p>
<p>I have 2 questions, the second regarding a workaround due to my inability to figure out the first.</p>
<p>1: Ideal solution</p>
<p>I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death</p>
<pre><code>Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
</code></pre>
<p>I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.</p>
<p>2: Cludgy workaround</p>
<p>Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.</p>
<p>I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.</p>
<p>Any thoughts or assistance greatly appreciated</p>
|
[
{
"answer_id": 51312,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": -1,
"selected": false,
"text": "<dict>\n <key>Author</key>\n <string>William Shakespeare</string>\n <key>Title</key>\n <string>Romeo et</string>\n <key>ISBN</key>\n <string>?????</string>\n</dict>\n"
},
{
"answer_id": 796938,
"author": "CoderDennis",
"author_id": 69527,
"author_profile": "https://Stackoverflow.com/users/69527",
"pm_score": 3,
"selected": false,
"text": "Dim Elements = New Dictionary(Of String, String)\nElements.Add(\"Key1\", \"Value1\")\nElements.Add(\"Key2\", \"Value2\")\nElements.Add(\"Key3\", \"Value3\")\n\nDim xConnections = <Connections>\n <%= From elem In Elements _\n Select <<%= elem.Key %>><%= elem.Value %></> %>\n </Connections>\n </> <%= %> <Connections>\n <Key1>Value1</Key1>\n <Key2>Value2</Key2>\n <Key3>Value3</Key3>\n</Connections>\n"
},
{
"answer_id": 1028596,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "Dim conns = connections.AsList()\nIf conns IsNot Nothing AndAlso conns.length > 0 Then\n Dim index = 0\n Dim xConnections = _\n <Connections>\n <%= From kvp As KeyValuePair(Of String, String) In conns (System.Threading.Interlocked.Increment(index)).DecompiledElements() _\n Select XElement.Parse(\"<\" & <%= kvp.Key %> & \">\" & <%= kvp.Value %> & \"</\" & <%= kvp.Key %> & \">\") _\n %>\n </Connections>\n Return xConnections.ToString()\nEnd If\n"
}
] |
2008/09/09
|
[
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] |
51,007 |
<p>One of the things I miss the most in ActionScript is the lack of operator overloading, in particular ==. I kind of work around this issue by adding a "Compare" method to my classes, but that doesn't help in many cases, like when you want to use things like the built in Dictionary.</p>
<p>Is there a good way to work around this problem?</p>
|
[
{
"answer_id": 51310,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 5,
"selected": true,
"text": "equals == ==="
}
] |
2008/09/09
|
[
"https://Stackoverflow.com/questions/51007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815/"
] |
51,010 |
<p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
|
[
{
"answer_id": 51023,
"author": "chryss",
"author_id": 5169,
"author_profile": "https://Stackoverflow.com/users/5169",
"pm_score": 3,
"selected": false,
"text": ">>> import datetime as dt\n>>> t1 = dt.time(23, 5, 5, 5)\n>>> t2 = dt.time(10, 5, 5, 5)\n>>> dt1 = dt.timedelta(hours=t1.hour, minutes=t1.minute, seconds=t1.second, microseconds=t1.microsecond)\n>>> dt2 = dt.timedelta(hours=t2.hour, minutes=t2.minute, seconds=t2.second, microseconds=t2.microsecond)\n>>> print(dt1-dt2)\n13:00:00\n>>> print(dt2-dt1)\n-1 day, 11:00:00\n>>> print(abs(dt2-dt1))\n13:00:00\n >>> dt2 < dt1\nTrue\n>>> t2 < t1\nTrue\n"
},
{
"answer_id": 51029,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": -1,
"selected": true,
"text": "t1, t2 = datetime.time(...), datetime.time(...)\n\nt1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond\nt2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond\n\ndelta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])\n"
},
{
"answer_id": 51042,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "datetime.datetime.combine >>> import datetime\n>>> t1 = datetime.time(2,3,4)\n>>> t2 = datetime.time(18,20,59)\n>>> dummydate = datetime.date(2000,1,1)\n>>> datetime.datetime.combine(dummydate,t2) - datetime.datetime.combine(dummydate,t1)\ndatetime.timedelta(0, 58675)\n"
}
] |
2008/09/09
|
[
"https://Stackoverflow.com/questions/51010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] |
51,013 |
<p>I have some HTML that is generated via a Rich Text Editor outside of my Flex application but would like to display it inside Flex. </p>
<p>The HTML is simple HTML tags, things like styles, anchors, and possibly image tags, is there a control that would let me render this HTML in flex or am I going to have to roll up my sleeves and roll my own?</p>
<p>Any ideas appreciated...Thanks.</p>
|
[
{
"answer_id": 51302,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "mx.controls.Label flash.text.TextField Text Label TextField Text htmlText <img> Label align=\"left\""
},
{
"answer_id": 9993803,
"author": "Adrian Pirvulescu",
"author_id": 129270,
"author_profile": "https://Stackoverflow.com/users/129270",
"pm_score": 1,
"selected": false,
"text": "<!---\n A basic example application showing how to embed a local html page in a Flex application.\n\n @author Alistair Rutherford\n-->\n<mx:Application xmlns:mx=\"http://www.adobe.com/2006/mxml\" \n xmlns:flexiframe=\"http://code.google.com/p/flex-iframe/\"\n horizontalAlign=\"center\"\n verticalAlign=\"middle\"\n viewSourceURL=\"srcview/index.html\">\n\n <!-- Example project presentation -->\n <mx:ApplicationControlBar dock=\"true\">\n <mx:Text selectable=\"false\">\n <mx:htmlText><![CDATA[<font color=\"#000000\" size=\"12\"><b>flex-iframe - Simple html example</b><br>This example shows how to embed a simple Html page in a Flex application.</font>]]></mx:htmlText>\n </mx:Text>\n </mx:ApplicationControlBar>\n\n <!-- HTML content stored in a String -->\n <mx:String id=\"iFrameHTMLContent\">\n <![CDATA[\n <html>\n <head>\n <title>About</title>\n </head>\n <body>\n <div>About</div>\n <p>Simple HTML Test application. This test app loads a page of html locally.</p>\n <div>Credits</div>\n <p> </p>\n <p>IFrame.as is based on the work of</p>\n <ul>\n <li><a href=\"http://coenraets.org/\" target=\"_top\">Christophe Coenraets</a></li>\n <li><a href=\"http://www.deitte.com/\" target=\"_top\">Brian Deitte</a></li>\n </ul>\n </body>\n </html>\n ]]>\n </mx:String>\n\n <!-- Example using the 'source' property -->\n <mx:Panel title=\"A simple Html page embedded with the 'source' property\"\n width=\"80%\"\n height=\"80%\">\n\n <flexiframe:IFrame id=\"iFrameBySource\"\n width=\"100%\"\n height=\"100%\"\n source=\"about.html\"/>\n </mx:Panel>\n\n <!-- Example using the 'content' property -->\n <mx:Panel title=\"A simple Html page embedded with the 'content' property\"\n width=\"80%\"\n height=\"80%\">\n\n <flexiframe:IFrame id=\"iFrameByContent\"\n width=\"100%\"\n height=\"100%\"\n content=\"{iFrameHTMLContent}\"/>\n </mx:Panel>\n\n</mx:Application>\n"
}
] |
2008/09/09
|
[
"https://Stackoverflow.com/questions/51013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
51,017 |
<p>How can you determine the performance consequences of your PHP code if you are not familiar with the internals? Are there ways to figure out how your code is being executed (besides simply load testing it)? I am looking for things like memory usage, the execution time for algorithms.</p>
<p>Perhaps Joel would say, "learn C, then read the internals", but I really don't have time to learn C right now (though I'd love to, actually). </p>
|
[
{
"answer_id": 2227253,
"author": "StasM",
"author_id": 214196,
"author_profile": "https://Stackoverflow.com/users/214196",
"pm_score": 0,
"selected": false,
"text": "microtime() memory_get_usage() -T php-cgi -T 100 yourscript.php"
}
] |
2008/09/09
|
[
"https://Stackoverflow.com/questions/51017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.