qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
18,685
<p>Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?</p>
[ { "answer_id": 18693, "author": "Niyaz", "author_id": 184, "author_profile": "https://Stackoverflow.com/users/184", "pm_score": 7, "selected": true, "text": "<p>Here is the php code for the same:</p>\n\n<pre><code>function time_since($since) {\n $chunks = array(\n array(60 * 60...
2008/08/20
[ "https://Stackoverflow.com/questions/18685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?
Here is the php code for the same: ``` function time_since($since) { $chunks = array( array(60 * 60 * 24 * 365 , 'year'), array(60 * 60 * 24 * 30 , 'month'), array(60 * 60 * 24 * 7, 'week'), array(60 * 60 * 24 , 'day'), array(60 * 60 , 'hour'), array(60 , 'minute'), array(1 , 'second') ); for ($i = 0, $j = count($chunks); $i < $j; $i++) { $seconds = $chunks[$i][0]; $name = $chunks[$i][1]; if (($count = floor($since / $seconds)) != 0) { break; } } $print = ($count == 1) ? '1 '.$name : "$count {$name}s"; return $print; } ``` The function takes the number of seconds as input and outputs text such as: * 10 seconds * 1 minute etc
18,754
<p>I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run:</p> <pre><code>markdown-batch ./*.markdown </code></pre> <p>Any ideas?</p>
[ { "answer_id": 18775, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": -1, "selected": false, "text": "<p>I use this in a .bat file:</p>\n\n<pre><code>@echo off\nfor %i in (*.txt) python markdown.py \"%i\"\n</code></pre>\n"...
2008/08/20
[ "https://Stackoverflow.com/questions/18754", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2185/" ]
I'm writing some documentation in Markdown, and creating a separate file for each section of the doc. I would like to be able to convert all the files to HTML in one go, but I can't find anyone else who has tried the same thing. I'm on a Mac, so I would think a simple bash script should be able to handle it, but I've never done anything in bash and haven't had any luck. It seems like it should be simple to write something so I could just run: ``` markdown-batch ./*.markdown ``` Any ideas?
This is how you would do it in Bash. ``` for i in ./*.markdown; do perl markdown.pl --html4tags $i > $i.html; done; ``` Of course, you need the [Markdown script](http://daringfireball.net/projects/markdown/).
18,757
<p>The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both.</p> <p>However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData.</p> <p>So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null?<br> Should I include the operation in the view data as an enum?<br> Should I surround all the subtle differences with <em>&lt;% if( ViewData.Model.Op == Ops.Editing ) { %></em> ?</p> <p>Or is there a better way?</p>
[ { "answer_id": 18876, "author": "Andrew Rimmer", "author_id": 1982, "author_profile": "https://Stackoverflow.com/users/1982", "pm_score": 2, "selected": false, "text": "<p>I don't like the Views to become too complex, and so far I have tended to have separate views for Edit and Add. I us...
2008/08/20
[ "https://Stackoverflow.com/questions/18757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1851/" ]
The Add view and the Edit view are often incredibly similar that it is unwarranted to write 2 views. As the app evolves you would be making the same changes to both. However, there are usually subtle differences. For instance, a field might be read-only once it's been added, and if that field is a DropDownList you no longer need that List in the ViewData. So, should I create a view data class which contains all the information for both views, where, depending on the operation you're performing, certain properties will be null? Should I include the operation in the view data as an enum? Should I surround all the subtle differences with *<% if( ViewData.Model.Op == Ops.Editing ) { %>* ? Or is there a better way?
It's pretty easy really. Let's assume you're editing a blog post. Here's your 2 actions for new/edit: ``` public class BlogController : Controller { public ActionResult New() { var post = new Post(); return View("Edit", post); } public ActionResult Edit(int id) { var post = _repository.Get(id); return View(post); } .... } ``` And here's the view: ``` <% using(Html.Form("save")) { %> <%= Html.Hidden("Id") %> <label for="Title">Title</label> <%= Html.TextBox("Title") %> <label for="Body">Body</label> <%= Html.TextArea("Body") %> <%= Html.Submit("Submit") %> <% } %> ``` And here's the Save action that the view submits to: ``` public ActionResult Save(int id, string title, string body) { var post = id == 0 ? new Post() : _repository.Get(id); post.Title = title; post.Body = body; _repository.Save(post); return RedirectToAction("list"); } ```
18,764
<p>Since both a <code>Table Scan</code> and a <code>Clustered Index Scan</code> essentially scan all records in the table, why is a Clustered Index Scan supposedly better?</p> <p>As an example - what's the performance difference between the following when there are many records?:</p> <pre><code>declare @temp table( SomeColumn varchar(50) ) insert into @temp select 'SomeVal' select * from @temp ----------------------------- declare @temp table( RowID int not null identity(1,1) primary key, SomeColumn varchar(50) ) insert into @temp select 'SomeVal' select * from @temp </code></pre>
[ { "answer_id": 18782, "author": "DrPizza", "author_id": 2131, "author_profile": "https://Stackoverflow.com/users/2131", "pm_score": -1, "selected": false, "text": "<p>A table scan has to examine every single row of the table. The clustered index scan only needs to scan the index. It do...
2008/08/20
[ "https://Stackoverflow.com/questions/18764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
Since both a `Table Scan` and a `Clustered Index Scan` essentially scan all records in the table, why is a Clustered Index Scan supposedly better? As an example - what's the performance difference between the following when there are many records?: ``` declare @temp table( SomeColumn varchar(50) ) insert into @temp select 'SomeVal' select * from @temp ----------------------------- declare @temp table( RowID int not null identity(1,1) primary key, SomeColumn varchar(50) ) insert into @temp select 'SomeVal' select * from @temp ```
In a table without a clustered index (a heap table), data pages are not linked together - so traversing pages requires a [lookup into the Index Allocation Map](http://msdn.microsoft.com/en-us/library/ms188270.aspx). A clustered table, however, has it's [data pages linked in a doubly linked list](http://msdn.microsoft.com/en-us/library/ms177443.aspx) - making sequential scans a bit faster. Of course, in exchange, you have the overhead of dealing with keeping the data pages in order on `INSERT`, `UPDATE`, and `DELETE`. A heap table, however, requires a second write to the IAM. If your query has a `RANGE` operator (e.g.: `SELECT * FROM TABLE WHERE Id BETWEEN 1 AND 100`), then a clustered table (being in a guaranteed order) would be more efficient - as it could use the index pages to find the relevant data page(s). A heap would have to scan all rows, since it cannot rely on ordering. And, of course, a clustered index lets you do a CLUSTERED INDEX SEEK, which is pretty much optimal for performance...a heap with no indexes would always result in a table scan. So: * For your example query where you select all rows, the only difference is the doubly linked list a clustered index maintains. This should make your clustered table just a tiny bit faster than a heap with a large number of rows. * For a query with a `WHERE` clause that can be (at least partially) satisfied by the clustered index, you'll come out ahead because of the ordering - so you won't have to scan the entire table. * For a query that is not satisified by the clustered index, you're pretty much even...again, the only difference being that doubly linked list for sequential scanning. In either case, you're suboptimal. * For `INSERT`, `UPDATE`, and `DELETE` a heap may or may not win. The heap doesn't have to maintain order, but does require a second write to the IAM. I think the relative performance difference would be negligible, but also pretty data dependent. Microsoft has a [whitepaper](http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/clusivsh.mspx) which compares a clustered index to an equivalent non-clustered index on a heap (not exactly the same as I discussed above, but close). Their conclusion is basically to put a clustered index on all tables. I'll do my best to summarize their results (again, note that they're really comparing a non-clustered index to a clustered index here - but I think it's relatively comparable): * `INSERT` performance: clustered index wins by about 3% due to the second write needed for a heap. * `UPDATE` performance: clustered index wins by about 8% due to the second lookup needed for a heap. * `DELETE` performance: clustered index wins by about 18% due to the second lookup needed and the second delete needed from the IAM for a heap. * single `SELECT` performance: clustered index wins by about 16% due to the second lookup needed for a heap. * range `SELECT` performance: clustered index wins by about 29% due to the random ordering for a heap. * concurrent `INSERT`: heap table wins by 30% under load due to page splits for the clustered index.
18,765
<p>I'm currently working on creating a new C# project that needs to interact with an older C++ application. There is an error enumeration that already exists in the C++ app that I need to use in the C# app.</p> <p><em>I don't want to just re declare the enumeration in C# because that could cause sync issues down the line if the files aren't updated together</em>. </p> <p>All that being said my question is this: Is there a way for me to taken an enumeration declared like so:</p> <pre><code>typedef enum { eDEVICEINT_ERR_FATAL = 0x10001 ... } eDeviceIntErrCodes; </code></pre> <p>and use it in a C# program like so:</p> <pre><code>eDeviceIntErrCodes.eDEVICEINT_ERR_FATAL </code></pre>
[ { "answer_id": 18774, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 2, "selected": false, "text": "<p>Simple answer is going to be no. Sorry, you are going to have to re-declare.</p>\n\n<p>I have, in the past however, writ...
2008/08/20
[ "https://Stackoverflow.com/questions/18765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2191/" ]
I'm currently working on creating a new C# project that needs to interact with an older C++ application. There is an error enumeration that already exists in the C++ app that I need to use in the C# app. *I don't want to just re declare the enumeration in C# because that could cause sync issues down the line if the files aren't updated together*. All that being said my question is this: Is there a way for me to taken an enumeration declared like so: ``` typedef enum { eDEVICEINT_ERR_FATAL = 0x10001 ... } eDeviceIntErrCodes; ``` and use it in a C# program like so: ``` eDeviceIntErrCodes.eDEVICEINT_ERR_FATAL ```
Check out the PInvoke Interop Assistant tool <http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120>. Its a useful tool for generating PInvoke signatures for native methods. If I feed it your enum it generates this code. There is a command line version of the tool included so you could potentially build an automated process to keep the C# definition of the enum up to date whenever the C++ version changes. ``` public enum eDeviceIntErrCodes { /// eDEVICEINT_ERR_FATAL -> 0x10001 eDEVICEINT_ERR_FATAL = 65537, } ```
18,787
<p>When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following:</p> <pre><code>return View("Message", new { DisplayMessage = "This is a test" }); </code></pre> <p>and on my Message control I had this:</p> <pre><code>&lt;%= ViewData["DisplayMessage"] %&gt; </code></pre> <p>I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control:</p> <pre><code>public class MessageControl : ViewUserControl&lt;MessageData&gt; </code></pre> <p>and now this call works:</p> <pre><code>return View("Message", new MessageData() { DisplayMessage = "This is a test" }); </code></pre> <p>and can be displayed like this:</p> <pre><code>&lt;%= ViewData.Model.DisplayMessage %&gt; </code></pre> <p>Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"?</p>
[ { "answer_id": 18830, "author": "Ryan Eastabrook", "author_id": 105, "author_profile": "https://Stackoverflow.com/users/105", "pm_score": 2, "selected": false, "text": "<p>Of course after I create this question I immediately find the answer after a few more searches on Google</p>\n\n<p><...
2008/08/20
[ "https://Stackoverflow.com/questions/18787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/105/" ]
When a controller renders a view based on a model you can get the properties from the ViewData collection using the indexer (ie. ViewData["Property"]). However, I have a shared user control that I tried to call using the following: ``` return View("Message", new { DisplayMessage = "This is a test" }); ``` and on my Message control I had this: ``` <%= ViewData["DisplayMessage"] %> ``` I would think this would render the DisplayMessage correctly, however, null is being returned. After a heavy dose of tinkering around, I finally created a "MessageData" class in order to strongly type my user control: ``` public class MessageControl : ViewUserControl<MessageData> ``` and now this call works: ``` return View("Message", new MessageData() { DisplayMessage = "This is a test" }); ``` and can be displayed like this: ``` <%= ViewData.Model.DisplayMessage %> ``` Why wouldn't the DisplayMessage property be added to the ViewData (ie. ViewData["DisplayMessage"]) collection without strong typing the user control? Is this by design? Wouldn't it make sense that ViewData would contain a key for "DisplayMessage"?
The method ``` ViewData.Eval("DisplayMessage") ``` should work for you.
18,836
<p>I'm looking for shell scripts files installed on my system, but <strong>find</strong> doesn't work:</p> <pre><code>$ find /usr -name *.sh </code></pre> <p>But I know there are a ton of scripts out there. For instance:</p> <pre><code>$ ls /usr/local/lib/*.sh /usr/local/lib/tclConfig.sh /usr/local/lib/tkConfig.sh </code></pre> <p>Why doesn't <strong>find</strong> work?</p>
[ { "answer_id": 18837, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 7, "selected": true, "text": "<p>Try quoting the wildcard:</p>\n\n<pre><code>$ find /usr -name \\*.sh\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>$ find ...
2008/08/20
[ "https://Stackoverflow.com/questions/18836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1438/" ]
I'm looking for shell scripts files installed on my system, but **find** doesn't work: ``` $ find /usr -name *.sh ``` But I know there are a ton of scripts out there. For instance: ``` $ ls /usr/local/lib/*.sh /usr/local/lib/tclConfig.sh /usr/local/lib/tkConfig.sh ``` Why doesn't **find** work?
Try quoting the wildcard: ``` $ find /usr -name \*.sh ``` or: ``` $ find /usr -name '*.sh' ``` If you happen to have a file that matches **\*.sh** in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the **find** command would expand to: ``` $ find /usr -name tkConfig.sh ``` which would only find files named tkConfig.sh. If you had more than one file that matches **\*.sh**, you'd get a syntax error from **find**: ``` $ cd /usr/local/lib $ find /usr -name *.sh find: bad option tkConfig.sh find: path-list predicate-list ``` Again, the reason is that the wildcard expands to both files: ``` $ find /usr -name tclConfig.sh tkConfig.sh ``` Quoting the wildcard prevents it from being prematurely expanded. Another possibility is that /usr or one of its subdirectories is a symlink. **find** doesn't normally follow links, so you might need the **-follow** option: ``` $ find /usr -follow -name '*.sh' ```
18,858
<p>Does anyone here know of good batch file code indenters or beautifiers?</p> <p>Specifically for PHP, JS and SGML-languages.</p> <p>Preferably with options as to style.</p>
[ { "answer_id": 18837, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 7, "selected": true, "text": "<p>Try quoting the wildcard:</p>\n\n<pre><code>$ find /usr -name \\*.sh\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>$ find ...
2008/08/20
[ "https://Stackoverflow.com/questions/18858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118/" ]
Does anyone here know of good batch file code indenters or beautifiers? Specifically for PHP, JS and SGML-languages. Preferably with options as to style.
Try quoting the wildcard: ``` $ find /usr -name \*.sh ``` or: ``` $ find /usr -name '*.sh' ``` If you happen to have a file that matches **\*.sh** in the current working directory, the wildcard will be expanded before find sees it. If you happen to have a file named tkConfig.sh in your working directory, the **find** command would expand to: ``` $ find /usr -name tkConfig.sh ``` which would only find files named tkConfig.sh. If you had more than one file that matches **\*.sh**, you'd get a syntax error from **find**: ``` $ cd /usr/local/lib $ find /usr -name *.sh find: bad option tkConfig.sh find: path-list predicate-list ``` Again, the reason is that the wildcard expands to both files: ``` $ find /usr -name tclConfig.sh tkConfig.sh ``` Quoting the wildcard prevents it from being prematurely expanded. Another possibility is that /usr or one of its subdirectories is a symlink. **find** doesn't normally follow links, so you might need the **-follow** option: ``` $ find /usr -follow -name '*.sh' ```
18,861
<p>So I am writing a registration form and I need the display name to be only numbers, letters and underscores. </p> <p>Have a look at my code and tell me what I'm doing wrong.</p> <pre><code>&lt;form method="post" action="/" onsubmit="return check_form()"&gt; &lt;input type="text" id="display-name" name="display-name" maxlength="255" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; &lt;!-- var name_regex = /^([a-zA-Z0-9_])+/ function check_form() { if (!name_regex.test(document.forms[0].elements[0].value)) { document.forms[0].elements[0].focus() alert("Your display name may only contain letters, numbers and underscores") return false } } --&gt; &lt;/script&gt; </code></pre> <p>It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.</p>
[ { "answer_id": 18874, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 3, "selected": false, "text": "<p>My regexp would go along the lines of: <code>/^[a-zA-Z0-9_]+$/</code></p>\n\n<p>edit: I think it's the lack of a line end...
2008/08/20
[ "https://Stackoverflow.com/questions/18861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
So I am writing a registration form and I need the display name to be only numbers, letters and underscores. Have a look at my code and tell me what I'm doing wrong. ``` <form method="post" action="/" onsubmit="return check_form()"> <input type="text" id="display-name" name="display-name" maxlength="255" /> <input type="submit" /> </form> <script type="text/javascript"> <!-- var name_regex = /^([a-zA-Z0-9_])+/ function check_form() { if (!name_regex.test(document.forms[0].elements[0].value)) { document.forms[0].elements[0].focus() alert("Your display name may only contain letters, numbers and underscores") return false } } --> </script> ``` It's obviously been trimmed down to not include anything not related to the problem but even this snippet doesn't work.
Your regex ``` /^([a-zA-Z0-9_])+/ ``` Looks for 1. Start of string(check), followed by 2. 1 or more letters, numbers, or underscore (check) And then whatever comes after it doesn't matter. This regex will match anything at all so long as it begins with a letter, number, or underscore If you put a `$` at the end, then it will work - `$` matches 'end of string', so the only way it can match is if there are *only* numbers, letters, and underscores between the start and end of the string. ``` /^([a-zA-Z0-9_])+$/ ``` Secondly, I'd suggest using `document.getElementById('display-name').value` instead of `document.forms` as it won't break if you rearrange the HTML, and is more 'the commonly accepted standard of what to do'
18,912
<p>I know in JavaScript, <em>objects</em> double as hashes, but I have been unable to find a built-in function to get the keys:</p> <pre><code>var h = {a:'b', c:'d'}; </code></pre> <p>I want something like</p> <pre><code>var k = h.keys() ; // k = ['a', 'c']; </code></pre> <p>It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that?</p> <p>I keep feeling it must be a simple built in function that I missed but I can't find it!</p>
[ { "answer_id": 18929, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 4, "selected": false, "text": "<p>This is the best you can do, as far as I know...</p>\n\n<pre><code>var keys = [];\nfor (var k in h)keys.push(k);\n</code></pr...
2008/08/20
[ "https://Stackoverflow.com/questions/18912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/238/" ]
I know in JavaScript, *objects* double as hashes, but I have been unable to find a built-in function to get the keys: ``` var h = {a:'b', c:'d'}; ``` I want something like ``` var k = h.keys() ; // k = ['a', 'c']; ``` It is simple to write a function myself to iterate over the items and add the keys to an array that I return, but is there a standard cleaner way to do that? I keep feeling it must be a simple built in function that I missed but I can't find it!
There is function in modern JavaScript (ECMAScript 5) called [`Object.keys`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys) performing this operation: ``` var obj = { "a" : 1, "b" : 2, "c" : 3}; alert(Object.keys(obj)); // will output ["a", "b", "c"] ``` Compatibility details can be found [here](http://kangax.github.com/es5-compat-table/). On the [Mozilla site](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys) there is also a snippet for backward compatibility: ``` if(!Object.keys) Object.keys = function(o){ if (o !== Object(o)) throw new TypeError('Object.keys called on non-object'); var ret=[],p; for(p in o) if(Object.prototype.hasOwnProperty.call(o,p)) ret.push(p); return ret; } ```
18,918
<p>Im testing an ASP.NEt site. When I execute it, it starts the ASP.NET Development Server and opens up a page.</p> <p>Now I want to test it in the intranet I have. </p> <ol> <li><p>Can I use this server or I need to configure IIS in this machine? </p></li> <li><p>Do I need to configure something for it to work?</p></li> </ol> <p>I've changed the localhost to the correct IP and I opened up the firewall.</p> <p>Thanks</p>
[ { "answer_id": 18919, "author": "Jason", "author_id": 1338, "author_profile": "https://Stackoverflow.com/users/1338", "pm_score": 1, "selected": false, "text": "<p>I believe the built in ASP.NET server only works on localhost. You'll have to use IIS.</p>\n" }, { "answer_id": 189...
2008/08/20
[ "https://Stackoverflow.com/questions/18918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013/" ]
Im testing an ASP.NEt site. When I execute it, it starts the ASP.NET Development Server and opens up a page. Now I want to test it in the intranet I have. 1. Can I use this server or I need to configure IIS in this machine? 2. Do I need to configure something for it to work? I've changed the localhost to the correct IP and I opened up the firewall. Thanks
**Yes you can! And you don't need IIS** Just use a simple Java TCP tunnel. Download this Java app & just tunnel the traffic back. <http://jcbserver.uwaterloo.ca/cs436/software/tgui/tcpTunnelGUI.shtml> In command prompt, you'd then run the java app like this... Let's assume you want external access on port 80 and your standard debug environment runs on port 1088... ``` java -jar tunnel.jar 80 localhost 1088 ``` (Also answered here: [Accessing asp. net development server external to VM](https://stackoverflow.com/questions/1555058/accessing-asp-net-development-server-external-to-vm/7394823#7394823))
18,920
<p>When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine <code>(file:///)</code> then where should the <code>css</code> file be for the browser to find it?</p> <pre><code>&lt;link href="/temp/test.css" rel="stylesheet" type="text/css" /&gt; </code></pre>
[ { "answer_id": 18924, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": 3, "selected": true, "text": "<p>It depends on what browser you use, but Internet Explorer, for example, would take you to the root directory of your harddrive...
2008/08/20
[ "https://Stackoverflow.com/questions/18920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1858/" ]
When opening a file from your hard drive into your browser, where is the document root? To illustrate, given the following HTML code, if the page is opened from the local machine `(file:///)` then where should the `css` file be for the browser to find it? ``` <link href="/temp/test.css" rel="stylesheet" type="text/css" /> ```
It depends on what browser you use, but Internet Explorer, for example, would take you to the root directory of your harddrive (eg. `C:/`), while browsers such as Firefox does nothing.
18,932
<p>I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows).</p> <p>The rows, of course, will not be perfect duplicates because of the existence of the <code>RowID</code> identity field.</p> <p><strong>MyTable</strong></p> <pre><code>RowID int not null identity(1,1) primary key, Col1 varchar(20) not null, Col2 varchar(2048) not null, Col3 tinyint not null </code></pre> <p>How can I do this?</p>
[ { "answer_id": 18934, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 7, "selected": false, "text": "<p>There's a good article on <a href=\"http://support.microsoft.com/kb/139444\" rel=\"noreferrer\">removing duplicates</a> on ...
2008/08/20
[ "https://Stackoverflow.com/questions/18932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
I need to remove duplicate rows from a fairly large SQL Server table (i.e. 300,000+ rows). The rows, of course, will not be perfect duplicates because of the existence of the `RowID` identity field. **MyTable** ``` RowID int not null identity(1,1) primary key, Col1 varchar(20) not null, Col2 varchar(2048) not null, Col3 tinyint not null ``` How can I do this?
Assuming no nulls, you `GROUP BY` the unique columns, and `SELECT` the `MIN (or MAX)` RowId as the row to keep. Then, just delete everything that didn't have a row id: ``` DELETE FROM MyTable LEFT OUTER JOIN ( SELECT MIN(RowId) as RowId, Col1, Col2, Col3 FROM MyTable GROUP BY Col1, Col2, Col3 ) as KeepRows ON MyTable.RowId = KeepRows.RowId WHERE KeepRows.RowId IS NULL ``` In case you have a GUID instead of an integer, you can replace ``` MIN(RowId) ``` with ``` CONVERT(uniqueidentifier, MIN(CONVERT(char(36), MyGuidColumn))) ```
18,955
<p>Is there a way to disable entering multi-line entries in a Text Box (i.e., I'd like to stop my users from doing ctrl-enter to get a newline)?</p>
[ { "answer_id": 18972, "author": "Mauro", "author_id": 2208, "author_profile": "https://Stackoverflow.com/users/2208", "pm_score": 0, "selected": false, "text": "<p>not entirely sure about that one, you should be able to remove the line breaks when you render the content though, or even r...
2008/08/20
[ "https://Stackoverflow.com/questions/18955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/685/" ]
Is there a way to disable entering multi-line entries in a Text Box (i.e., I'd like to stop my users from doing ctrl-enter to get a newline)?
I was able to do it on using KeyPress event. Here's the code example: ``` Private Sub SingleLineTextBox_ KeyPress(ByRef KeyAscii As Integer) If KeyAscii = 10 _ or KeyAscii = 13 Then '10 -> Ctrl-Enter. AKA ^J or ctrl-j '13 -> Enter. AKA ^M or ctrl-m KeyAscii = 0 'clear the the KeyPress End If End Sub ```
18,984
<p>What are your opinions on developing for the command line first, then adding a GUI on after the fact by simply calling the command line methods?</p> <p>eg.</p> <blockquote> <p>W:\ todo AddTask "meeting with John, re: login peer review" "John's office" "2008-08-22" "14:00" </p> </blockquote> <p>loads <code>todo.exe</code> and calls a function called <code>AddTask</code> that does some validation and throws the meeting in a database. </p> <p>Eventually you add in a screen for this: </p> <pre> ============================================================ Event: [meeting with John, re: login peer review] Location: [John's office] Date: [Fri. Aug. 22, 2008] Time: [ 2:00 PM] [Clear] [Submit] ============================================================ </pre> <p>When you click submit, it calls the same AddTask function.</p> <p>Is this considered: </p> <ul> <li>a good way to code</li> <li>just for the newbies</li> <li>horrendous!.</li> </ul> <p><strong>Addendum:</strong> </p> <p>I'm noticing a trend here for "shared library called by both the GUI and CLI executables." Is there some compelling reason why they would have to be separated, other than maybe the size of the binaries themselves? </p> <p>Why not just call the same executable in different ways:</p> <ul> <li><code>"todo /G"</code> when you want the full-on graphical interface</li> <li><code>"todo /I"</code> for an interactive prompt <em>within</em> <code>todo.exe</code> (scripting, etc)</li> <li>plain old <code>"todo &lt;function&gt;"</code> when you just want to do one thing and be done with it.</li> </ul> <p><strong>Addendum 2:</strong> </p> <p>It was mentioned that "the way [I've] described things, you [would] need to spawn an executable every time the GUI needs to do something." </p> <p>Again, this wasn't my intent. When I mentioned that the example GUI called "the same <code>AddTask</code> function," I didn't mean the GUI called the command line program each time. I agree that would be totally nasty. I had intended (see first addendum) that this all be held in a single executable, since it was a tiny example, but I don't think my phrasing necessarily precluded a shared library.</p> <p>Also, I'd like to thank all of you for your input. This is something that keeps popping back in my mind and I appreciate the wisdom of your experience.</p>
[ { "answer_id": 18990, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 3, "selected": false, "text": "<p>Put the shared functionality in a library, then write a command-line and a GUI front-end for it. That way your layer transition ...
2008/08/20
[ "https://Stackoverflow.com/questions/18984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1588/" ]
What are your opinions on developing for the command line first, then adding a GUI on after the fact by simply calling the command line methods? eg. > > W:\ todo AddTask "meeting with John, re: login peer review" "John's office" "2008-08-22" "14:00" > > > loads `todo.exe` and calls a function called `AddTask` that does some validation and throws the meeting in a database. Eventually you add in a screen for this: ``` ============================================================ Event: [meeting with John, re: login peer review] Location: [John's office] Date: [Fri. Aug. 22, 2008] Time: [ 2:00 PM] [Clear] [Submit] ============================================================ ``` When you click submit, it calls the same AddTask function. Is this considered: * a good way to code * just for the newbies * horrendous!. **Addendum:** I'm noticing a trend here for "shared library called by both the GUI and CLI executables." Is there some compelling reason why they would have to be separated, other than maybe the size of the binaries themselves? Why not just call the same executable in different ways: * `"todo /G"` when you want the full-on graphical interface * `"todo /I"` for an interactive prompt *within* `todo.exe` (scripting, etc) * plain old `"todo <function>"` when you just want to do one thing and be done with it. **Addendum 2:** It was mentioned that "the way [I've] described things, you [would] need to spawn an executable every time the GUI needs to do something." Again, this wasn't my intent. When I mentioned that the example GUI called "the same `AddTask` function," I didn't mean the GUI called the command line program each time. I agree that would be totally nasty. I had intended (see first addendum) that this all be held in a single executable, since it was a tiny example, but I don't think my phrasing necessarily precluded a shared library. Also, I'd like to thank all of you for your input. This is something that keeps popping back in my mind and I appreciate the wisdom of your experience.
I would go with building a library with a command line application that links to it. Afterwards, you can create a GUI that links to the same library. Calling a command line from a GUI spawns external processes for each command and is more disruptive to the OS. Also, with a library you can easily do unit tests for the functionality. But even as long as your functional code is separate from your command line interpreter, then you can just re-use the source for a GUI without having the two kinds at once to perform an operation.
18,985
<p>I am writing a batch script in order to beautify JavaScript code. It needs to work on both <strong>Windows</strong> and <strong>Linux</strong>. </p> <p>How can I beautify JavaScript code using the command line tools? </p>
[ { "answer_id": 27343, "author": "Alan Storm", "author_id": 2838, "author_profile": "https://Stackoverflow.com/users/2838", "pm_score": 7, "selected": true, "text": "<p>First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at <a href=\"http://jsbeautifier.o...
2008/08/20
[ "https://Stackoverflow.com/questions/18985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/486/" ]
I am writing a batch script in order to beautify JavaScript code. It needs to work on both **Windows** and **Linux**. How can I beautify JavaScript code using the command line tools?
First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at [<http://jsbeautifier.org/>](http://jsbeautifier.org/), because it's what I found first. Downloads its file <https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js> Second, download and install The Mozilla group's Java based Javascript engine, [Rhino](https://www.mozilla.org/rhino/). "Install" is a little bit misleading; Download the zip file, extract everything, place js.jar in your Java classpath (or Library/Java/Extensions on OS X). You can then run scripts with an invocation similar to this ``` java -cp js.jar org.mozilla.javascript.tools.shell.Main name-of-script.js ``` Use the Pretty Print/Beautifier from step 1 to write a small shell script that will read in your javascript file and run it through the Pretty Print/Beautifier from step one. For example ``` //original code (function() { ... js_beautify code ... }()); //new code print(global.js_beautify(readFile(arguments[0]))); ``` Rhino gives javascript a few extra useful functions that don't necessarily make sense in a browser context, but do in a console context. The function print does what you'd expect, and prints out a string. The function readFile accepts a file path string as an argument and returns the contents of that file. You'd invoke the above something like ``` java -cp js.jar org.mozilla.javascript.tools.shell.Main beautify.js file-to-pp.js ``` You can mix and match Java and Javascript in your Rhino run scripts, so if you know a little Java it shouldn't be too hard to get this running with text-streams as well.
19,014
<p>I want to use Lucene (in particular, Lucene.NET) to search for email address domains.</p> <p>E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address.</p> <p>Running a Lucene query for "*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word.</p> <p>How can I do this?</p>
[ { "answer_id": 20468, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 5, "selected": true, "text": "<p>No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accom...
2008/08/20
[ "https://Stackoverflow.com/questions/19014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/536/" ]
I want to use Lucene (in particular, Lucene.NET) to search for email address domains. E.g. I want to search for "@gmail.com" to find all emails sent to a gmail address. Running a Lucene query for "\*@gmail.com" results in an error, asterisks cannot be at the start of queries. Running a query for "@gmail.com" doesn't return any matches, because "foo@gmail.com" is seen as a whole word, and you cannot search for just parts of a word. How can I do this?
No one gave a satisfactory answer, so we started poking around Lucene documentation and discovered we can accomplish this using custom Analyzers and Tokenizers. The answer is this: create a WhitespaceAndAtSymbolTokenizer and a WhitespaceAndAtSymbolAnalyzer, then recreate your index using this analyzer. Once you do this, a search for "@gmail.com" will return all gmail addresses, because it's seen as a separate word thanks to the Tokenizer we just created. Here's the source code, it's actually very simple: ``` class WhitespaceAndAtSymbolTokenizer : CharTokenizer { public WhitespaceAndAtSymbolTokenizer(TextReader input) : base(input) { } protected override bool IsTokenChar(char c) { // Make whitespace characters and the @ symbol be indicators of new words. return !(char.IsWhiteSpace(c) || c == '@'); } } internal class WhitespaceAndAtSymbolAnalyzer : Analyzer { public override TokenStream TokenStream(string fieldName, TextReader reader) { return new WhitespaceAndAtSymbolTokenizer(reader); } } ``` That's it! Now you just need to rebuild your index and do all searches using this new Analyzer. For example, to write documents to your index: ``` IndexWriter index = new IndexWriter(indexDirectory, new WhitespaceAndAtSymbolAnalyzer()); index.AddDocument(myDocument); ``` Performing searches should use the analyzer as well: ``` IndexSearcher searcher = new IndexSearcher(indexDirectory); Query query = new QueryParser("TheFieldNameToSearch", new WhitespaceAndAtSymbolAnalyzer()).Parse("@gmail.com"); Hits hits = query.Search(query); ```
19,030
<p>I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme..</p> <p>Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths.</p> <p>Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code.</p> <p>The current code can be found <a href="http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py" rel="nofollow noreferrer">here</a></p> <p>I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. </p> <p>How could I write this system in a more expandable way?</p> <p>The rules it needs to check would be..</p> <ul> <li>File is in the format <code>Show Name - [01x23] - Episode Name.avi</code> or <code>Show Name - [01xSpecial02] - Special Name.avi</code> or <code>Show Name - [01xExtra01] - Extra Name.avi</code></li> <li>If filename is in the format <code>Show Name - [01x23].avi</code> display it a 'missing episode name' section of the output</li> <li>The path should be in the format <code>Show Name/season 2/the_file.avi</code> (where season 2 should be the correct season number in the filename)</li> <li>each <code>Show Name/season 1/</code> folder should contain "folder.jpg"</li> </ul> <p>.any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things..</p> <p>The only thought I had was a list of dicts in the format:</p> <pre><code>checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets } </code></pre>
[ { "answer_id": 19389, "author": "sven", "author_id": 46, "author_profile": "https://Stackoverflow.com/users/46", "pm_score": 0, "selected": false, "text": "<p>maybe you should take the approach of defaulting to: \"the filename is correct\" and work from there to disprove that statement:<...
2008/08/20
[ "https://Stackoverflow.com/questions/19030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
I have a bunch of files (TV episodes, although that is fairly arbitrary) that I want to check match a specific naming/organisation scheme.. Currently: I have three arrays of regex, one for valid filenames, one for files missing an episode name, and one for valid paths. Then, I loop though each valid-filename regex, if it matches, append it to a "valid" dict, if not, do the same with the missing-ep-name regexs, if it matches this I append it to an "invalid" dict with an error code (2:'missing epsiode name'), if it matches neither, it gets added to invalid with the 'malformed name' error code. The current code can be found [here](http://github.com/dbr/checktveps/tree/8a6dc68ad61e684c8d8f0ca1dc37a22d1c51aa82/2checkTvEps.py) I want to add a rule that checks for the presence of a folder.jpg file in each directory, but to add this would make the code substantially more messy in it's current state.. How could I write this system in a more expandable way? The rules it needs to check would be.. * File is in the format `Show Name - [01x23] - Episode Name.avi` or `Show Name - [01xSpecial02] - Special Name.avi` or `Show Name - [01xExtra01] - Extra Name.avi` * If filename is in the format `Show Name - [01x23].avi` display it a 'missing episode name' section of the output * The path should be in the format `Show Name/season 2/the_file.avi` (where season 2 should be the correct season number in the filename) * each `Show Name/season 1/` folder should contain "folder.jpg" .any ideas? While I'm trying to check TV episodes, this concept/code should be able to apply to many things.. The only thought I had was a list of dicts in the format: ``` checker = [ { 'name':'valid files', 'type':'file', 'function':check_valid(), # runs check_valid() on all files 'status':0 # if it returns True, this is the status the file gets } ```
> > I want to add a rule that checks for > the presence of a folder.jpg file in > each directory, but to add this would > make the code substantially more messy > in it's current state.. > > > This doesn't look bad. In fact your current code does it very nicely, and Sven mentioned a good way to do it as well: 1. Get a list of all the files 2. Check for "required" files You would just have have add to your dictionary a list of required files: ``` checker = { ... 'required': ['file', 'list', 'for_required'] } ``` As far as there being a better/extensible way to do this? I am not exactly sure. I could only really think of a way to possibly drop the "multiple" regular expressions and build off of Sven's idea for using a delimiter. So my strategy would be defining a dictionary as follows (and I'm sorry I don't know Python syntax and I'm a tad to lazy to look it up but it should make sense. The /regex/ is shorthand for a regex): ``` check_dict = { 'delim' : /\-/, 'parts' : [ 'Show Name', 'Episode Name', 'Episode Number' ], 'patterns' : [/valid name/, /valid episode name/, /valid number/ ], 'required' : ['list', 'of', 'files'], 'ignored' : ['.*', 'hidden.txt'], 'start_dir': '/path/to/dir/to/test/' } ``` 1. Split the filename based on the delimiter. 2. Check each of the parts. Because its an ordered list you can determine what parts are missing and if a section doesn't match any pattern it is malformed. Here the `parts` and `patterns` have a 1 to 1 ratio. Two arrays instead of a dictionary enforces the order. Ignored and required files can be listed. The `.` and `..` files should probably be ignored automatically. The user should be allowed to input "globs" which can be shell expanded. I'm thinking here of `svn:ignore` properties, but globbing is natural for listing files. Here `start_dir` would be default to the current directory but if you wanted a single file to run automated testing of a bunch of directories this would be useful. The real loose end here is the path template and along the same lines what path is required for "valid files". I really couldn't come up with a solid idea without writing one large regular expression and taking groups from it... to build a template. It felt a lot like writing a TextMate language grammar. But that starts to stray on the ease of use. The real problem was that the path template was not composed of `parts`, which makes sense but adds complexity. Is this strategy in tune with what you were thinking of?
19,035
<p>I am working with both <a href="http://activemq.apache.org/ajax.html" rel="nofollow noreferrer">amq.js</a> (ActiveMQ) and <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps</a>. I load my scripts in this order</p> <pre><code>&lt;head&gt; &lt;meta http-equiv="content-type" content="text/html;charset=UTF-8" /&gt; &lt;title&gt;AMQ &amp; Maps Demo&lt;/title&gt; &lt;!-- Stylesheet --&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt;&lt;/link&gt; &lt;!-- Google APIs --&gt; &lt;script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"&gt;&lt;/script&gt; &lt;!-- Active MQ --&gt; &lt;script type="text/javascript" src="amq/amq.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt;amq.uri='amq';&lt;/script&gt; &lt;!-- Application --&gt; &lt;script type="text/javascript" src="application.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. <strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong> </p> <p>Google has this nice function call <code>google.setOnLoadCallback(initialize);</code> which works great. I'm not sure amq.js has something like this.</p>
[ { "answer_id": 19067, "author": "maxsilver", "author_id": 1477, "author_profile": "https://Stackoverflow.com/users/1477", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p><strong>Is there a way to make sure both scripts load before I use them?</strong></p>\n</blockquote>\n\n...
2008/08/20
[ "https://Stackoverflow.com/questions/19035", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1992/" ]
I am working with both [amq.js](http://activemq.apache.org/ajax.html) (ActiveMQ) and [Google Maps](http://code.google.com/apis/maps/documentation/reference.html). I load my scripts in this order ``` <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <title>AMQ & Maps Demo</title> <!-- Stylesheet --> <link rel="stylesheet" type="text/css" href="style.css"></link> <!-- Google APIs --> <script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"></script> <!-- Active MQ --> <script type="text/javascript" src="amq/amq.js"></script> <script type="text/javascript">amq.uri='amq';</script> <!-- Application --> <script type="text/javascript" src="application.js"></script> </head> ``` However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. **Is there a way to make sure both scripts load before I use them in my application.js?** Google has this nice function call `google.setOnLoadCallback(initialize);` which works great. I'm not sure amq.js has something like this.
> > **Is there a way to make sure both scripts load before I use them in my application.js?** > > > JavaScript files should load sequentially *and block* so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files. [Non-blocking JavaScript Downloads](http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/) has some information about how scripts load (and discusses some techniques to subvert the blocking).
19,047
<p>After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available.</p> <p>When attempting to run it manually, I get this error:</p> <pre><code>The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail </code></pre> <p>The application log shows this</p> <pre><code>Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll". Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found. Please use sxstrace.exe for detailed diagnosis. </code></pre>
[ { "answer_id": 19053, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 4, "selected": true, "text": "<p>I remembered I'd seen this thing before just after posting to SO</p>\n\n<p>It seems that later versions of TortoiseSVN ...
2008/08/20
[ "https://Stackoverflow.com/questions/19047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234/" ]
After upgrading to the latest version of TortoiseSVN (1.5.2.13595), it's context menu is no longer available. When attempting to run it manually, I get this error: ``` The application has failed to start because its side-by-side configuration is incorrect. Please see the application event log for more detail ``` The application log shows this ``` Activation context generation failed for "C:\Program Files\TortoiseSVN\bin\TortoiseSVN.dll". Dependent Assembly Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.30411.0" could not be found. Please use sxstrace.exe for detailed diagnosis. ```
I remembered I'd seen this thing before just after posting to SO It seems that later versions of TortoiseSVN are built with Visual Studio 2008 SP1 (hence the 9.0.30411.0 build number) Installing the [VC2008 SP1 Redistributable](http://www.microsoft.com/downloads/details.aspx?familyid=A5C84275-3B97-4AB7-A40D-3802B2AF5FC2&displaylang=en) fixes it
19,058
<p>Example:</p> <pre><code>select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') </code></pre> <p>and </p> <pre><code>select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') </code></pre> <p>return different results</p>
[ { "answer_id": 19061, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 7, "selected": true, "text": "<p><a href=\"http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519...
2008/08/20
[ "https://Stackoverflow.com/questions/19058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
Example: ``` select ename from emp where hiredate = todate('01/05/81','dd/mm/yy') ``` and ``` select ename from emp where hiredate = todate('01/05/81','dd/mm/rr') ``` return different results
<http://oracle.ittoolbox.com/groups/technical-functional/oracle-dev-l/difference-between-yyyy-and-rrrr-format-519525> > > YY allows you to retrieve just two digits of a year, for example, the 99 in > 1999. The other digits (19) are automatically assigned to the current > century. RR converts two-digit years into four-digit years by rounding. > > > 50-99 are stored as 1950-1999, and dates ending in 00-49 are stored as > 2000-2049. RRRR accepts a four-digit input (although not required), and > converts two-digit dates as RR does. YYYY accepts 4-digit inputs butdoesn't > do any date converting > > > Essentially, your first example will assume that 81 is 2081 whereas the RR one assumes 1981. So the first example should not return any rows as you most likely did not hire any guys after May 1 2081 yet :-)
19,089
<p>I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage.</p> <p>So far I have this (simplified):</p> <pre><code>DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName </code></pre> <p>The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist.</p> <p>Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option).</p> <p>I'm using SQL Server 2005.</p> <p><strong>Edit: @Lee:</strong> Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL.</p> <p><strong>Edit: @BCS:</strong> I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.</p>
[ { "answer_id": 19097, "author": "AlexCuse", "author_id": 794, "author_profile": "https://Stackoverflow.com/users/794", "pm_score": 1, "selected": false, "text": "<p>To get a real \"upsert\" type of query you need to use an if exists... type of thing, and this unfortunately means using a ...
2008/08/20
[ "https://Stackoverflow.com/questions/19089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/233/" ]
I have a view that has a list of jobs in it, with data like who they're assigned to and the stage they are in. I need to write a stored procedure that returns how many jobs each person has at each stage. So far I have this (simplified): ``` DECLARE @ResultTable table ( StaffName nvarchar(100), Stage1Count int, Stage2Count int ) INSERT INTO @ResultTable (StaffName, Stage1Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage1 = 1 GROUP BY StaffName INSERT INTO @ResultTable (StaffName, Stage2Count) SELECT StaffName, COUNT(*) FROM ViewJob WHERE InStage2 = 1 GROUP BY StaffName ``` The problem with that is that the rows don't combine. So if a staff member has jobs in stage1 and stage2 there's two rows in @ResultTable. What I would really like to do is to update the row if one exists for the staff member and insert a new row if one doesn't exist. Does anyone know how to do this, or can suggest a different approach? I would really like to avoid using cursors to iterate on the list of users (but that's my fall back option). I'm using SQL Server 2005. **Edit: @Lee:** Unfortunately the InStage1 = 1 was a simplification. It's really more like WHERE DateStarted IS NOT NULL and DateFinished IS NULL. **Edit: @BCS:** I like the idea of doing an insert of all the staff first so I just have to do an update every time. But I'm struggling to get those UPDATE statements correct.
IIRC there is some sort of "On Duplicate" (name might be wrong) syntax that lets you update if a row exists (MySQL) Alternately some form of: ``` INSERT INTO @ResultTable (StaffName, Stage1Count, Stage2Count) SELECT StaffName,0,0 FROM ViewJob GROUP BY StaffName UPDATE @ResultTable Stage1Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage1 = 1 @ResultTable.StaffName = StaffName) UPDATE @ResultTable Stage2Count= ( SELECT COUNT(*) AS count FROM ViewJob WHERE InStage2 = 1 @ResultTable.StaffName = StaffName) ```
19,122
<p>Does anyone know how bash handles sending data through pipes?</p> <pre><code>cat file.txt | tail -20 </code></pre> <p>Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? </p> <p>The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20".</p> <p>EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: <a href="http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation</a> which did have the information I was looking for.</p> <hr> <p>I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state.</p> <p>What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism?</p>
[ { "answer_id": 19134, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "<p>cat will just print the data to standard out, which happens to be redirected to the standard in of tail. This can be see...
2008/08/21
[ "https://Stackoverflow.com/questions/19122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/306/" ]
Does anyone know how bash handles sending data through pipes? ``` cat file.txt | tail -20 ``` Does this command print all the contents of file.txt into a buffer, which is then read by tail? Or does this command, say, print the contents of file.txt line by line, and then pause at each line for tail to process, and then ask for more data? The reason I ask is that I'm writing a program on an embedded device that basically performs a sequence of operations on some chunk of data, where the output of one operation is send off as the input of the next operation. I would like to know how linux (bash) handles this so please give me a general answer, not specifically what happens when I run "cat file.txt | tail -20". EDIT: Shog9 pointed out a relevant Wikipedia Article, this didn't lead me directly to the article but it helped me find this: <http://en.wikipedia.org/wiki/Pipeline_%28Unix%29#Implementation> which did have the information I was looking for. --- I'm sorry for not making myself clear. Of course you're using a pipe and of course you're using stdin and stdout of the respective parts of the command. I had assumed that was too obvious to state. What I'm asking is how this is handled/implemented. Since both programs cannot run at once, how is data sent from stdin to stdout? What happens if the first program generates data significantly faster than the second program? Does the system just run the first command until either it's terminated or it's stdout buffer is full, and then move on to the next program, and so on in a loop until no more data is left to be processed or is there a more complicated mechanism?
I decided to write a slightly more detailed explanation. The "magic" here lies in the operating system. Both programs do start up at roughly the same time, and run at the same time (the operating system assigns them slices of time on the processor to run) as every other simultaneously running process on your computer (including the terminal application and the kernel). So, before any data gets passed, the processes are doing whatever initialization necessary. In your example, tail is parsing the '-20' argument and cat is parsing the 'file.txt' argument and opening the file. At some point tail will get to the point where it needs input and it will tell the operating system that it is waiting for input. At some other point (either before or after, it doesn't matter) cat will start passing data to the operating system using stdout. This goes into a buffer in the operating system. The next time tail gets a time slice on the processor after some data has been put into the buffer by cat, it will retrieve some amount of that data (or all of it) which leaves the buffer on the operating system. When the buffer is empty, at some point tail will have to wait for cat to output more data. If cat is outputting data much faster than tail is handling it, the buffer will expand. cat will eventually be done outputting data, but tail will still be processing, so cat will close and tail will process all remaining data in the buffer. The operating system will signal tail when their is no more incoming data with an EOF. Tail will process the remaining data. In this case, tail is probably just receiving all the data into a circular buffer of 20 lines, and when it is signalled by the operating system that there is no more incoming data, it then dumps the last twenty lines to its own stdout, which just gets displayed in the terminal. Since tail is a much simpler program than cat, it will likely spend most of the time waiting for cat to put data into the buffer. On a system with multiple processors, the two programs will not just be sharing alternating time slices on the same processor core, but likely running at the same time on separate cores. To get into a little more detail, if you open some kind of process monitor (operating system specific) like 'top' in Linux you will see a whole list of running processes, most of which are effectively using 0% of the processor. Most applications, unless they are crunching data, spend most of their time doing nothing. This is good, because it allows other processes to have unfettered access to the processor according to their needs. This is accomplished in basically three ways. A process could get to a sleep(n) style instruction where it basically tells the kernel to wait n milliseconds before giving it another time slice to work with. Most commonly a program needs to wait for something from another program, like 'tail' waiting for more data to enter the buffer. In this case the operating system will wake up the process when more data is available. Lastly, the kernel can preempt a process in the middle of execution, giving some processor time slices to other processes. 'cat' and 'tail' are simple programs. In this example, tail spends most of it's time waiting for more data on the buffer, and cat spends most of it's time waiting for the operating system to retrieve data from the harddrive. The bottleneck is the speed (or slowness) of the physical medium that the file is stored on. That perceptible delay you might detect when you run this command for the first time is the time it takes for the read heads on the disk drive to seek to the position on the harddrive where 'file.txt' is. If you run the command a second time, the operating system will likely have the contents of file.txt cached in memory, and you will not likely see any perceptible delay (unless file.txt is very large, or the file is no longer cached.) Most operations you do on your computer are IO bound, which is to say that you are usually waiting for data to come from your harddrive, or from a network device, etc.
19,132
<p>I'm asking with regards to c#, but I assume its the same in most other languages.</p> <p>Does anyone have a good definition of <em>expressions</em> and <em>statements</em> and what the differences are?</p>
[ { "answer_id": 19138, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "<p>Expressions can be evaluated to get a value, whereas statements don't return a value (they're of type <em>void</em>).<...
2008/08/21
[ "https://Stackoverflow.com/questions/19132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm asking with regards to c#, but I assume its the same in most other languages. Does anyone have a good definition of *expressions* and *statements* and what the differences are?
**Expression:** Something which evaluates to a value. Example: *1+2/x* **Statement:** A line of code which does something. Example: *GOTO 100* In the earliest general-purpose programming languages, like FORTRAN, the distinction was crystal-clear. In FORTRAN, a statement was one unit of execution, a thing that you did. The only reason it wasn't called a "line" was because sometimes it spanned multiple lines. An expression on its own couldn't do anything... you had to assign it to a variable. ``` 1 + 2 / X ``` is an error in FORTRAN, because it doesn't do anything. You had to do something with that expression: ``` X = 1 + 2 / X ``` FORTRAN didn't have a grammar as we know it today—that idea was invented, along with Backus-Naur Form (BNF), as part of the definition of Algol-60. At that point the *semantic* distinction ("have a value" versus "do something") was enshrined in *syntax*: one kind of phrase was an expression, and another was a statement, and the parser could tell them apart. Designers of later languages blurred the distinction: they allowed syntactic expressions to do things, and they allowed syntactic statements that had values. The earliest popular language example that still survives is C. The designers of C realized that no harm was done if you were allowed to evaluate an expression and throw away the result. In C, every syntactic expression can be a made into a statement just by tacking a semicolon along the end: ``` 1 + 2 / x; ``` is a totally legit statement even though absolutely nothing will happen. Similarly, in C, an expression can have *side-effects*—it can change something. ``` 1 + 2 / callfunc(12); ``` because `callfunc` might just do something useful. Once you allow any expression to be a statement, you might as well allow the assignment operator (=) inside expressions. That's why C lets you do things like ``` callfunc(x = 2); ``` This evaluates the expression x = 2 (assigning the value of 2 to x) and then passes that (the 2) to the function `callfunc`. This blurring of expressions and statements occurs in all the C-derivatives (C, C++, C#, and Java), which still have some statements (like `while`) but which allow almost any expression to be used as a statement (in C# only assignment, call, increment, and decrement expressions may be used as statements; see [Scott Wisniewski's answer](https://stackoverflow.com/a/20771/8554766)). Having two "syntactic categories" (which is the technical name for the sort of thing statements and expressions are) can lead to duplication of effort. For example, C has two forms of conditional, the statement form ``` if (E) S1; else S2; ``` and the expression form ``` E ? E1 : E2 ``` And sometimes people *want* duplication that isn't there: in standard C, for example, only a statement can declare a new local variable—but this ability is useful enough that the GNU C compiler provides a GNU extension that enables an expression to declare a local variable as well. Designers of other languages didn't like this kind of duplication, and they saw early on that if expressions can have side effects as well as values, then the *syntactic* distinction between statements and expressions is not all that useful—so they got rid of it. Haskell, Icon, Lisp, and ML are all languages that don't have syntactic statements—they only have expressions. Even the class structured looping and conditional forms are considered expressions, and they have values—but not very interesting ones.
19,147
<p>Using C# and WPF under .NET (rather than <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="noreferrer">Windows Forms</a> or console), what is the correct way to create an application that can only be run as a single instance?</p> <p>I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are.</p> <p>The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.</p>
[ { "answer_id": 19165, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 7, "selected": false, "text": "<p>From <a href=\"http://www.albahari.com/threading/part2.html#_MutexSingleAppInstance\" rel=\"noreferrer\">here</a>.</p>...
2008/08/21
[ "https://Stackoverflow.com/questions/19147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/483/" ]
Using C# and WPF under .NET (rather than [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) or console), what is the correct way to create an application that can only be run as a single instance? I know it has something to do with some mythical thing called a mutex, rarely can I find someone that bothers to stop and explain what one of these are. The code needs to also inform the already-running instance that the user tried to start a second one, and maybe also pass any command-line arguments if any existed.
Here is a very good [article](http://sanity-free.org/143/csharp_dotnet_single_instance_application.html) regarding the Mutex solution. The approach described by the article is advantageous for two reasons. First, it does not require a dependency on the Microsoft.VisualBasic assembly. If my project already had a dependency on that assembly, I would probably advocate using the approach [shown in another answer](https://stackoverflow.com/a/19326/3195477). But as it is, I do not use the Microsoft.VisualBasic assembly, and I'd rather not add an unnecessary dependency to my project. Second, the article shows how to bring the existing instance of the application to the foreground when the user tries to start another instance. That's a very nice touch that the other Mutex solutions described here do not address. --- ### UPDATE As of 8/1/2014, the article I linked to above is still active, but the blog hasn't been updated in a while. That makes me worry that eventually it might disappear, and with it, the advocated solution. I'm reproducing the content of the article here for posterity. The words belong solely to the blog owner at [Sanity Free Coding](http://sanity-free.org/). > > Today I wanted to refactor some code that prohibited my application > from running multiple instances of itself. > > > Previously I had use [System.Diagnostics.Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process(v=vs.110).aspx) to search for an > instance of my myapp.exe in the process list. While this works, it > brings on a lot of overhead, and I wanted something cleaner. > > > Knowing that I could use a mutex for this (but never having done it > before) I set out to cut down my code and simplify my life. > > > In the class of my application main I created a static named [Mutex](http://msdn.microsoft.com/en-us/library/system.threading.mutex(v=vs.110).aspx): > > > ``` static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] ... } ``` > > Having a named mutex allows us to stack synchronization across > multiple threads and processes which is just the magic I'm looking > for. > > > [Mutex.WaitOne](http://msdn.microsoft.com/en-us/library/58195swd(v=vs.110).aspx) has an overload that specifies an amount of time for us > to wait. Since we're not actually wanting to synchronizing our code > (more just check if it is currently in use) we use the overload with > two parameters: [Mutex.WaitOne(Timespan timeout, bool exitContext)](http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx). > Wait one returns true if it is able to enter, and false if it wasn't. > In this case, we don't want to wait at all; If our mutex is being > used, skip it, and move on, so we pass in TimeSpan.Zero (wait 0 > milliseconds), and set the exitContext to true so we can exit the > synchronization context before we try to aquire a lock on it. Using > this, we wrap our Application.Run code inside something like this: > > > ``` static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { MessageBox.Show("only one instance at a time"); } } } ``` > > So, if our app is running, WaitOne will return false, and we'll get a > message box. > > > Instead of showing a message box, I opted to utilize a little Win32 to > notify my running instance that someone forgot that it was already > running (by bringing itself to the top of all the other windows). To > achieve this I used [PostMessage](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644944(v=vs.85).aspx) to broadcast a custom message to every > window (the custom message was registered with [RegisterWindowMessage](http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947(v=vs.85).aspx) > by my running application, which means only my application knows what > it is) then my second instance exits. The running application instance > would receive that notification and process it. In order to do that, I > overrode [WndProc](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.wndproc(v=vs.110).aspx) in my main form and listened for my custom > notification. When I received that notification I set the form's > TopMost property to true to bring it up on top. > > > Here is what I ended up with: > > > * Program.cs > > > ``` static class Program { static Mutex mutex = new Mutex(true, "{8F6F0AC4-B9A1-45fd-A8CF-72F04E6BDE8F}"); [STAThread] static void Main() { if(mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); mutex.ReleaseMutex(); } else { // send our Win32 message to make the currently running instance // jump on top of all the other windows NativeMethods.PostMessage( (IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); } } } ``` > > * NativeMethods.cs > > > ``` // this class just wraps some Win32 stuff that we're going to use internal class NativeMethods { public const int HWND_BROADCAST = 0xffff; public static readonly int WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); [DllImport("user32")] public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); [DllImport("user32")] public static extern int RegisterWindowMessage(string message); } ``` > > * Form1.cs (front side partial) > > > ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } protected override void WndProc(ref Message m) { if(m.Msg == NativeMethods.WM_SHOWME) { ShowMe(); } base.WndProc(ref m); } private void ShowMe() { if(WindowState == FormWindowState.Minimized) { WindowState = FormWindowState.Normal; } // get our current "TopMost" value (ours will always be false though) bool top = TopMost; // make our form jump to the top of everything TopMost = true; // set it back to whatever it was TopMost = top; } } ```
19,151
<p>How would one create an iterative function (or iterator object) in python?</p>
[ { "answer_id": 19152, "author": "akdom", "author_id": 145, "author_profile": "https://Stackoverflow.com/users/145", "pm_score": 7, "selected": false, "text": "<p>First of all the <a href=\"https://docs.python.org/3/library/itertools.html\" rel=\"noreferrer\">itertools module</a> is incre...
2008/08/21
[ "https://Stackoverflow.com/questions/19151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145/" ]
How would one create an iterative function (or iterator object) in python?
Iterator objects in python conform to the iterator protocol, which basically means they provide two methods: `__iter__()` and `__next__()`. * The `__iter__` returns the iterator object and is implicitly called at the start of loops. * The `__next__()` method returns the next value and is implicitly called at each loop increment. This method raises a StopIteration exception when there are no more value to return, which is implicitly captured by looping constructs to stop iterating. Here's a simple example of a counter: ``` class Counter: def __init__(self, low, high): self.current = low - 1 self.high = high def __iter__(self): return self def __next__(self): # Python 2: def next(self) self.current += 1 if self.current < self.high: return self.current raise StopIteration for c in Counter(3, 9): print(c) ``` This will print: ``` 3 4 5 6 7 8 ``` This is easier to write using a generator, as covered in a previous answer: ``` def counter(low, high): current = low while current < high: yield current current += 1 for c in counter(3, 9): print(c) ``` The printed output will be the same. Under the hood, the generator object supports the iterator protocol and does something roughly similar to the class Counter. David Mertz's article, [Iterators and Simple Generators](https://www.ibm.com/developerworks/library/l-pycon/), is a pretty good introduction.
19,185
<p>There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is <a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&amp;SiteID=1" rel="nofollow noreferrer">detected by checking for keyboard and mouse events</a>. I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away.</p> <p>As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?</p>
[ { "answer_id": 19187, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 1, "selected": false, "text": "<p><strong>Managed code</strong></p>\n\n<p>Check position of the mouse every second. If there are new messages for user, ho...
2008/08/21
[ "https://Stackoverflow.com/questions/19185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
There is some documentation on the internet that shows that Windows changes the behavior of the NotifyIcon.BalloonTipShown command if the user is currently idle and this is [detected by checking for keyboard and mouse events](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=343411&SiteID=1). I am currently working on an application that spends most of its time in the system tray, but pop-ups up multiple balloon tips from time to time and I would like to prevent the user from missing any of them if they are currently away from the system. Since any currently displayed balloon tips are destroyed if a new one is displayed, I want to hold off on displaying them if the user is away. As such, is there any way to check to see if the user is currently idle if the application is minimized to the system tray?
How about the Win32 [LASTINPUTINFO](http://www.codeproject.com/KB/cs/GetIdleTimeWithCS.aspx) function? ``` using System.Runtime.InteropServices; [DllImport("User32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO plii); struct LASTINPUTINFO { public uint cbSize; public uint dwTime; } ```
19,193
<p>How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this:</p> <pre><code>#include &lt;iostream&gt; #include &lt;tree&gt; using namespace std; int main() { tree&lt;int&gt; myTree; tree&lt;int&gt;::iterator i = myTree.root(); *i = 42; tree&lt;int&gt;::iterator j = i.add_child(); *j = 777; j = j.parent(); if (i == myTree.root() &amp;&amp; i == j) cout &lt;&lt; "i and j are both pointing to the root\n"; return 0; } </code></pre> <hr> <p>Thank you, tree.hh seems to be just what I was looking for.</p> <blockquote> <p>If this is for gaining the benefit of a data-structure holding arbitrary index types, optimized for searching and good at insertion then consider using a map.</p> <p>A map is an associative container that has performance guarantees identical to those of a tree: logarithmic searching, logarithmic insertion, logarithmic deletion, linear space. Internally they are often implemented as red-black trees, although that is not a guarantee. Still, as an STL user all you should care about is the performance guarantees of the STL algorithms and data-structures. Whether they're implemented as trees or little green men shouldn't matter to you.</p> </blockquote> <p>I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.</p>
[ { "answer_id": 19204, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 2, "selected": false, "text": "<p>Why would you want to do that? If this is for learning purposes then you can write your own tree data structure. If th...
2008/08/21
[ "https://Stackoverflow.com/questions/19193", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2222/" ]
How do I make a tree data structure in C++ that uses iterators instead of pointers? I couldn't find anything in the STL that can do this. What I would like to do is to be able to create and manipulate trees like this: ``` #include <iostream> #include <tree> using namespace std; int main() { tree<int> myTree; tree<int>::iterator i = myTree.root(); *i = 42; tree<int>::iterator j = i.add_child(); *j = 777; j = j.parent(); if (i == myTree.root() && i == j) cout << "i and j are both pointing to the root\n"; return 0; } ``` --- Thank you, tree.hh seems to be just what I was looking for. > > If this is for gaining the benefit of > a data-structure holding arbitrary > index types, optimized for searching > and good at insertion then consider > using a map. > > > A map is an associative container that > has performance guarantees identical > to those of a tree: logarithmic > searching, logarithmic insertion, > logarithmic deletion, linear space. > Internally they are often implemented > as red-black trees, although that is > not a guarantee. Still, as an STL user > all you should care about is the > performance guarantees of the STL > algorithms and data-structures. > Whether they're implemented as trees > or little green men shouldn't matter > to you. > > > I'm not sure if a map is what I need, but thanks for the info. I will remember to use maps whenever possible instead of implementing trees.
Here is [tree.hh](http://www.aei.mpg.de/~peekas/tree/) which is a bit close to what you want to do, though a bit different. Here is a piece of code extracted from its website. ``` int main(int, char **) { tree<string> tr; tree<string>::iterator top, one, two, loc, banana; top=tr.begin(); one=tr.insert(top, "one"); two=tr.append_child(one, "two"); tr.append_child(two, "apple"); banana=tr.append_child(two, "banana"); tr.append_child(banana,"cherry"); tr.append_child(two, "peach"); tr.append_child(one,"three"); loc=find(tr.begin(), tr.end(), "two"); if(loc!=tr.end()) { tree<string>::sibling_iterator sib=tr.begin(loc); while(sib!=tr.end(loc)) { cout << (*sib) << endl; ++sib; } cout << endl; tree<string>::iterator sib2=tr.begin(loc); tree<string>::iterator end2=tr.end(loc); while(sib2!=end2) { for(int i=0; i<tr.depth(sib2)-2; ++i) cout << " "; cout << (*sib2) << endl; ++sib2; } } } ``` Now what's different? Your implementation is simpler when it comes to append a node to the tree. Though your version is indiscutably simpler, the dev of this lib probably wanted to have some info accessible without browsing the tree, such as the size of the tree for instance. I also assume he didn't want to store the root on all nodes for performance reason. So if you want to implement it your way, I suggest you keep most of the logic and add the link to the parent tree in the iterator and rewrite append a bit.
19,236
<p>I'm working on a internal web based tool for my company. Part of this tool is another application (The Cruise Control Dashboard) that runs in its own Virtual Directory under my root application.</p> <p>I wanted to limit access to this internal application by setting up Forms Authentication on it, and having a login form in the root application.</p> <p>I put the following into the root applications web.config:</p> <pre><code>&lt;location path="ccnet"&gt; &lt;system.web&gt; &lt;authentication mode="Forms"&gt; &lt;forms loginUrl="/default.aspx" timeout="5000"/&gt; &lt;/authentication&gt; &lt;authorization&gt; &lt;allow users="?"/&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p>However, the Forms Authentication does not appear to be working, it does not redirect back to the login page when I access that application directly.</p> <p>I have a feeling I have the &lt;allow&gt; and &lt;deny&gt; tags set wrong. Can someone clarify?</p>
[ { "answer_id": 19239, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>you are allowing all unauthenticated. You might be looking for something like this</p>\n\n<pre><code>&lt;deny users=\"?\"/...
2008/08/21
[ "https://Stackoverflow.com/questions/19236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I'm working on a internal web based tool for my company. Part of this tool is another application (The Cruise Control Dashboard) that runs in its own Virtual Directory under my root application. I wanted to limit access to this internal application by setting up Forms Authentication on it, and having a login form in the root application. I put the following into the root applications web.config: ``` <location path="ccnet"> <system.web> <authentication mode="Forms"> <forms loginUrl="/default.aspx" timeout="5000"/> </authentication> <authorization> <allow users="?"/> <deny users="?"/> </authorization> </system.web> </location> ``` However, the Forms Authentication does not appear to be working, it does not redirect back to the login page when I access that application directly. I have a feeling I have the <allow> and <deny> tags set wrong. Can someone clarify?
You might also need to put path="/" in the <forms tag(s) I think. Sorry, its been a while since i've done this
19,294
<p>In my code behind I wire up my events like so:</p> <pre><code>protected override void OnInit(EventArgs e) { base.OnInit(e); btnUpdateUser.Click += btnUpateUserClick; } </code></pre> <p>I've done it this way because that's what I've seen in examples. </p> <ul> <li>Does the base.OnInit() method need to be called? </li> <li>Will it be implicitly be called? </li> <li>Is it better to call it at the beginning of the method or at the end? </li> <li>What would be an example where confusion over the base method can get you in trouble? </li> </ul>
[ { "answer_id": 19296, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 0, "selected": false, "text": "<p>In this case, if you don't call the base OnInit, then the Init even will not fire.</p>\n\n<p>In general, it is best pr...
2008/08/21
[ "https://Stackoverflow.com/questions/19294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1894/" ]
In my code behind I wire up my events like so: ``` protected override void OnInit(EventArgs e) { base.OnInit(e); btnUpdateUser.Click += btnUpateUserClick; } ``` I've done it this way because that's what I've seen in examples. * Does the base.OnInit() method need to be called? * Will it be implicitly be called? * Is it better to call it at the beginning of the method or at the end? * What would be an example where confusion over the base method can get you in trouble?
I should clarify: The guidelines recommend that firing an event should involve calling a virtual "On*EventName*" method, but they also say that if a derived class overrides that method and forgets to call the base method, the event should still fire. See the "Important Note" about halfway down [this page](http://msdn.microsoft.com/en-us/library/ms229011.aspx): > > Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called. > > >
19,295
<p>I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution.</p> <p>I'm specifically refering to something that would work with the jstl tags such as</p> <pre><code>&lt;fmt:setlocale&gt; &lt;fmt:bundle&gt; &lt;fmt:setBundle&gt; &lt;fmt:message&gt; </code></pre> <p>I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.</p>
[ { "answer_id": 19308, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 3, "selected": true, "text": "<p>Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 s...
2008/08/21
[ "https://Stackoverflow.com/questions/19295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
I'd like to use a database to store i18n key/value pairs so we can modify / reload the i18n data at runtime. Has anyone done this? Or does anyone have an idea of how to implement this? I've read several threads on this, but I haven't seen a workable solution. I'm specifically refering to something that would work with the jstl tags such as ``` <fmt:setlocale> <fmt:bundle> <fmt:setBundle> <fmt:message> ``` I think this will involve extending ResourceBundle, but when I tried this I ran into problems that had to do with the way the jstl tags get the resource bundle.
Are you just asking how to store UTF-8/16 characters in a DB? in mysql it's just a matter of making sure you build with UTF8 support and setting that as the default, or specifying it at the column or table level. I've done this in oracle and mysql before. Create a table and cut and paste some i18n data into it and see what happens... you might be set already.. or am I completely missing your point? edit: to be more explicit... I usually implement a three column table... language, key, value... where "value" contains potentially foreign language words or phrases... "language" contains some language key and "key" is an english key (i.e. login.error.password.dup)... language and key are indexed... I've then built interfaces on a structure like this that shows each key with all its translations (values)... it can get fancy and include audit trails and "dirty" markers and all the other stuff you need to enable translators and data entry folk to make use of it.. Edit 2: Now that you added the info about the JSTL tags, I understand a bit more... I've never done that myself.. but I found this old info on [theserverside](http://www.theserverside.com/discussions/thread.tss?thread_id=27390)... ``` HttpSession session = .. [get hold of the session] ResourceBundle bundle = new PropertyResourceBundle(toInputStream(myOwnProperties)) [toInputStream just stores the properties into an inputstream] Locale locale = .. [get hold of the locale] javax.servlet.jsp.jstl.core.Config.set(session, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle ,locale)); ```
19,318
<p>I have an ASP.NET webservice with along the lines of:</p> <pre><code>[WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService : WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { // ... do stuff } } </code></pre> <p>I am calling the web service from ASP using something like:</p> <pre><code>provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl" Set service = CreateObject("MSSOAP.SoapClient30") service.ClientProperty("ServerHTTPRequest") = True Call service.MSSoapInit(provWSDL) xmlMessage = "&lt;request&gt;&lt;task&gt;....various xml&lt;/task&gt;&lt;/request&gt;" result = service.ProcessMessage(xmlMessage) </code></pre> <p>The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see:</p> <pre><code>&lt;request xmlns="http://internalservice.net/messageprocessing"&gt; &lt;task&gt;....various xml&lt;/task&gt; &lt;/request&gt; </code></pre> <p>When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the .NET WS client. The SOAP toolkit sends:</p> <pre><code>&lt;SOAP-ENV:Envelope xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;SOAP-ENV:Body&gt; &lt;ProcessMessage xmlns="http://internalservice.net/messageprocessing"&gt; &lt;message xmlns:SOAPSDK4="http://internalservice.net/messageprocessing"&gt; &lt;request&gt; &lt;task&gt;...stuff to do&lt;/task&gt; &lt;/request&gt; &lt;/message&gt; &lt;/ProcessMessage&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>Whilst the .NET client sends:</p> <pre><code>&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;ProcessMessage xmlns="http://internalservice.net/messageprocessing"&gt; &lt;message&gt; &lt;request xmlns=""&gt; &lt;task&gt;...stuff to do&lt;/task&gt; &lt;/request&gt; &lt;/message&gt; &lt;/ProcessMessage&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre> <p>It's been so long since I used the ASP/SOAP toolkit to call into .NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this.</p> <p>Any ideas? One solution is to knock up a COM callable .NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.</p>
[ { "answer_id": 19324, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p>I take it you have access to the Services code, not just the consuming client right?</p>\n\n<p>Just pull the namespace out...
2008/08/21
[ "https://Stackoverflow.com/questions/19318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
I have an ASP.NET webservice with along the lines of: ``` [WebService(Namespace = "http://internalservice.net/messageprocessing")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] public class ProvisioningService : WebService { [WebMethod] public XmlDocument ProcessMessage(XmlDocument message) { // ... do stuff } } ``` I am calling the web service from ASP using something like: ``` provWSDL = "http://servername:12011/MessageProcessor.asmx?wsdl" Set service = CreateObject("MSSOAP.SoapClient30") service.ClientProperty("ServerHTTPRequest") = True Call service.MSSoapInit(provWSDL) xmlMessage = "<request><task>....various xml</task></request>" result = service.ProcessMessage(xmlMessage) ``` The problem I am encountering is that when the XML reaches the ProcessMessage method, the web service plumbing has added a default namespace along the way. i.e. if I set a breakpoint inside ProcessMessage(XmlDocument message) I see: ``` <request xmlns="http://internalservice.net/messageprocessing"> <task>....various xml</task> </request> ``` When I capture packets on the wire I can see that the XML sent by the SOAP toolkit is slightly different from that sent by the .NET WS client. The SOAP toolkit sends: ``` <SOAP-ENV:Envelope xmlns:SOAPSDK1="http://www.w3.org/2001/XMLSchema" xmlns:SOAPSDK2="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAPSDK3="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <ProcessMessage xmlns="http://internalservice.net/messageprocessing"> <message xmlns:SOAPSDK4="http://internalservice.net/messageprocessing"> <request> <task>...stuff to do</task> </request> </message> </ProcessMessage> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ``` Whilst the .NET client sends: ``` <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <ProcessMessage xmlns="http://internalservice.net/messageprocessing"> <message> <request xmlns=""> <task>...stuff to do</task> </request> </message> </ProcessMessage> </soap:Body> </soap:Envelope> ``` It's been so long since I used the ASP/SOAP toolkit to call into .NET webservices, I can't remember all the clever tricks/SOAP-fu I used to pull to get around stuff like this. Any ideas? One solution is to knock up a COM callable .NET proxy that takes the XML as a string param and calls the WS on my behalf, but it's an extra layer of complexity/work I hoped not to do.
I solved this: The SOAP client *request* node was picking up the default namespace from: ``` <ProcessMessage xmlns="http://internalservice.net/messageprocessing"> ``` Adding an empty default namespace to the XML sent by the ASP client overrides this behaviour: ``` xmlMessage = "<request xmlns=''><task>....various xml</task></request>" ```
19,339
<p>I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.</p> <p><strong>For example:</strong></p> <pre><code>original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) </code></pre> <p>Is there a builtin function that does that?</p>
[ { "answer_id": 19343, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 11, "selected": true, "text": "<p><a href=\"http://docs.python.org/library/functions.html#zip\" rel=\"noreferrer\"><code>zip</code></a> is its own inverse! Pr...
2008/08/21
[ "https://Stackoverflow.com/questions/19339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item. **For example:** ``` original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4]) ``` Is there a builtin function that does that?
[`zip`](http://docs.python.org/library/functions.html#zip) is its own inverse! Provided you use the special \* operator. ``` >>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] ``` The way this works is by calling `zip` with the arguments: ``` zip(('a', 1), ('b', 2), ('c', 3), ('d', 4)) ``` … except the arguments are passed to `zip` directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.
19,355
<p>In a .NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). </p> <p>How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers).</p> <p><hr /> Edit: Can the "<code>file</code>" method suggested by @Jonathon be somehow used with the <code>connectionStrings</code> section?</p>
[ { "answer_id": 19359, "author": "Scott Muc", "author_id": 1894, "author_profile": "https://Stackoverflow.com/users/1894", "pm_score": 0, "selected": false, "text": "<p>I always make templates for my config files. </p>\n\n<p>As an example I use NAnt for the building of my projects. I have...
2008/08/21
[ "https://Stackoverflow.com/questions/19355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/708/" ]
In a .NET project, say you have a configuration setting - like a connection string - stored in a app.config file, which is different for each developer on your team (they may be using a local SQL Server, or a specific server instance, or using a remote server, etc). How can you structure your solution so that each developer can have their own development "preferences" (i.e. not checked into source control), but provide a default connection string that is checked into source control (thereby supplying the correct defaults for a build process or new developers). --- Edit: Can the "`file`" method suggested by @Jonathon be somehow used with the `connectionStrings` section?
AppSettings can be overridden with a local file: ``` <appSettings file="localoveride.config"/> ``` This allows for each developer to keep their own local settings. As far as the connection string, in a perfect world all developers should connect to a test DB, not run SQL Server each. However, I've found it best to keep a file named Web.Config.Prd in source control, and use that for build deployments. If someone modifies web.config, they must also add the change to the .PRD file...There is no good automation there :(
19,388
<p>I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing?</p> <p>I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "<code>GOTO 10</code>"-like command...</p>
[ { "answer_id": 19398, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 2, "selected": false, "text": "<p>Granted, I am not a PHP programmer, and I don't know what PHP's exact implementation of GOTO will look like, but here...
2008/08/21
[ "https://Stackoverflow.com/questions/19388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2238/" ]
I've heard rumors that PHP is planning on introducing a "goto" command. What is it supposed to be doing? I've tried searching a bit, but haven't found anything awfully descriptive. I understand that it won't be a "`GOTO 10`"-like command...
They are not adding a real GOTO, but extending the BREAK keyword to use static labels. Basically, it will be enhancing the ability to break out of ~~switch~~ nested if statements. Here's the concept example I found: ``` <?php for ($i = 0; $i < 9; $i++) { if (true) { break blah; } echo "not shown"; blah: echo "iteration $i\n"; } ?> ``` Of course, once the GOTO "rumor" was out, there was nothing to stop some evil guys to propagate an additional **COMEFROM** joke. Be on your toes. See also: <http://www.php.net/~derick/meeting-notes.html#adding-goto>
19,409
<p>This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this:</p> <pre><code># count.s: print the numbers from 0 to 100. .text string: .asciz "%d\n" .globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end: </code></pre> <p>All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem.</p> <p>(The formatting's a little messed up, but nothing major).</p>
[ { "answer_id": 19411, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 3, "selected": false, "text": "<p>I'm not too familiar with _printf, but could it be that it modifies eax? Printf should return the number of chars ...
2008/08/21
[ "https://Stackoverflow.com/questions/19409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
This is kinda oddball, but I was poking around with the GNU assembler today (I want to be able to at least read the syntax), and was trying to get this little contrived example of mine to work. Namely I just want to go from 0 to 100, printing out numbers all the while. So a few minutes later I come up with this: ``` # count.s: print the numbers from 0 to 100. .text string: .asciz "%d\n" .globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end: ``` All I get from this is 3 printed over and over again. Like I said, just a little contrived example, so don't worry too much about it, it's not a life or death problem. (The formatting's a little messed up, but nothing major).
You can't trust what any called procedure does to any of the registers. Either push the registers onto the stack and pop them back off after calling printf or have the increment and end point values held in memory and read/written into registers as you need them. I hope the following works. I'm assuming that pushl has an equivalant popl and you can push an extra couple of numbers onto the stack. ``` # count.s: print the numbers from 0 to 100. .text string: .asciz "%d\n" .globl _main _main: movl $0, %eax # The starting point/current value. movl $100, %ebx # The ending point. _loop: # Remember your registers. pushl %eax pushl %ebx # Display the current value. pushl %eax pushl $string call _printf addl $8, %esp # reinstate registers. popl %ebx popl %eax # Check against the ending value. cmpl %eax, %ebx je _end # Increment the current value. incl %eax jmp _loop _end: ```
19,412
<p>How can I request a random row (or as close to truly random as is possible) in pure SQL?</p>
[ { "answer_id": 19414, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": false, "text": "<p>I don't know how efficient this is, but I've used it before:</p>\n\n<pre><code>SELECT TOP 1 * FROM MyTable ORDER BY ne...
2008/08/21
[ "https://Stackoverflow.com/questions/19412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/473/" ]
How can I request a random row (or as close to truly random as is possible) in pure SQL?
See this post: [SQL to Select a random row from a database table](http://www.petefreitag.com/item/466.cfm). It goes through methods for doing this in MySQL, PostgreSQL, Microsoft SQL Server, IBM DB2 and Oracle (the following is copied from that link): Select a random row with MySQL: ``` SELECT column FROM table ORDER BY RAND() LIMIT 1 ``` Select a random row with PostgreSQL: ``` SELECT column FROM table ORDER BY RANDOM() LIMIT 1 ``` Select a random row with Microsoft SQL Server: ``` SELECT TOP 1 column FROM table ORDER BY NEWID() ``` Select a random row with IBM DB2 ``` SELECT column, RAND() as IDX FROM table ORDER BY IDX FETCH FIRST 1 ROWS ONLY ``` Select a random record with Oracle: ``` SELECT column FROM ( SELECT column FROM table ORDER BY dbms_random.value ) WHERE rownum = 1 ```
19,436
<p>I have a datalist with a OnDeleteCommand="Delete_Command".</p> <p>I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete_Command event.</p> <p>If I use DataKeyField I'm limited to only one key. Any workarounds for this?</p>
[ { "answer_id": 19447, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": true, "text": "<p>You can access all of the keys:</p>\n\n<pre><code>gridView.DataKeys[rowNum][dataKeyName]\n</code></pre>\n\n<p>where rowNum is e....
2008/08/21
[ "https://Stackoverflow.com/questions/19436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1013/" ]
I have a datalist with a OnDeleteCommand="Delete\_Command". I want the delete a record with multiple primary Keys but I do not know how to access it from the Delete\_Command event. If I use DataKeyField I'm limited to only one key. Any workarounds for this?
You can access all of the keys: ``` gridView.DataKeys[rowNum][dataKeyName] ``` where rowNum is e.RowIndex from the gridView\_RowDeleting event handler, and dataKeyName is the key you want to get: ``` <asp:GridView ID="gridView" runat="server" DataKeyNames="userid, id1, id2, id3" OnRowDeleting="gridView_RowDeleting"> protected void gridView_RowDeleting(object sender, GridViewDeleteEventArgs e) { gridView.DataKeys[e.RowIndex]["userid"]... gridView.DataKeys[e.RowIndex]["id1"]... gridView.DataKeys[e.RowIndex]["id2"]... gridView.DataKeys[e.RowIndex]["id3"]... } ```
19,442
<p>How can I create this file in a directory in windows 2003 SP2:</p> <pre><code>.hgignore </code></pre> <p>I get error: You must type a file name.</p>
[ { "answer_id": 19443, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 6, "selected": true, "text": "<p>That's a \"feature\" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) a...
2008/08/21
[ "https://Stackoverflow.com/questions/19442", "https://Stackoverflow.com", "https://Stackoverflow.com/users/479/" ]
How can I create this file in a directory in windows 2003 SP2: ``` .hgignore ``` I get error: You must type a file name.
That's a "feature" of Windows Explorer. Try to create your files from a command line (or from a batch/program you wrote) and it should work fine. Try this from a dos prompt: ``` echo Hello there! > .hgignore ```
19,454
<p>Following on from my recent question on <a href="https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result">Large, Complex Objects as a Web Service Result</a>. I have been thinking about how I can ensure all future child classes are serializable to XML.</p> <p>Now, obviously I could implement the <a href="http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx" rel="noreferrer">IXmlSerializable</a> interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a <em>string</em> so I may just write my own.</p> <p>However, to serialize to XML, I am simply decorating the class and its members with the <em>Xml???</em> attributes ( <em>XmlRoot</em> , <em>XmlElement</em> etc.) and then passing it to the <em>XmlSerializer</em> and a <em>StringWriter</em> to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc.</p> <p>The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time.</p> <p><strong>Is there any way to enforce attribute decoration? Can this be done with FxCop?</strong> (I have not used FxCop yet)</p> <h3>UPDATE:</h3> <p>Sorry for the delay in getting this close off guys, lots to do!</p> <p>Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455">Fredrik Kalseth's answer</a> was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself!</p> <p>+1 to the other guys for similar suggestions :)</p>
[ { "answer_id": 19455, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 5, "selected": true, "text": "<p>I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is d...
2008/08/21
[ "https://Stackoverflow.com/questions/19454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
Following on from my recent question on [Large, Complex Objects as a Web Service Result](https://stackoverflow.com/questions/17725/large-complex-objects-as-a-web-service-result). I have been thinking about how I can ensure all future child classes are serializable to XML. Now, obviously I could implement the [IXmlSerializable](http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx) interface and then chuck a reader/writer to it but I would like to avoid that since it then means I need to instantiate a reader/writer whenever I want to do it, and 99.99% of the time I am going to be working with a *string* so I may just write my own. However, to serialize to XML, I am simply decorating the class and its members with the *Xml???* attributes ( *XmlRoot* , *XmlElement* etc.) and then passing it to the *XmlSerializer* and a *StringWriter* to get the string. Which is all good. I intend to put the method to return the string into a generic utility method so I don't need to worry about type etc. The this that concerns me is this: If I do not decorate the class(es) with the required attributes an error is not thrown until run time. **Is there any way to enforce attribute decoration? Can this be done with FxCop?** (I have not used FxCop yet) ### UPDATE: Sorry for the delay in getting this close off guys, lots to do! Definitely like the idea of using reflection to do it in a test case rather than resorting to FxCop (like to keep everything together).. [Fredrik Kalseth's answer](https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods#19455) was fantastic, thanks for including the code as it probably would have taken me a bit of digging to figure out how to do it myself! +1 to the other guys for similar suggestions :)
I'd write a unit/integration test that verifies that any class matching some given criteria (ie subclassing X) is decorated appropriately. If you set up your build to run with tests, you can have the build fail when this test fails. UPDATE: You said, "Looks like I will just have to roll my sleeves up and make sure that the unit tests are collectively maintained" - you don't have to. Just write a general test class that uses reflection to find all classes that needs to be asserted. Something like this: ``` [TestClass] public class When_type_inherits_MyObject { private readonly List<Type> _types = new List<Type>(); public When_type_inherits_MyObject() { // lets find all types that inherit from MyObject, directly or indirectly foreach(Type type in typeof(MyObject).Assembly.GetTypes()) { if(type.IsClass && typeof(MyObject).IsAssignableFrom(type)) { _types.Add(type); } } } [TestMethod] public void Properties_have_XmlElement_attribute { foreach(Type type in _types) { foreach(PropertyInfo property in type.GetProperties()) { object[] attribs = property.GetCustomAttributes(typeof(XmlElementAttribute), false); Assert.IsTrue(attribs.Count > 0, "Missing XmlElementAttribute on property " + property.Name + " in type " + type.FullName); } } } } ```
19,461
<p>I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function.</p> <p>The coordinates need to be relative to the image top and left.</p>
[ { "answer_id": 19464, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 3, "selected": false, "text": "<p>I think you're talking about:</p>\n\n<pre><code>&lt;input id=\"info\" type=\"image\"&gt;\n</code></pre>\n\n<p>When submitte...
2008/08/21
[ "https://Stackoverflow.com/questions/19461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
I have a standard HTML image tag with an image in it, 100 by 100 pixels in size. I want people to be able to click the image and for that to pass the X and Y that they click into a function. The coordinates need to be relative to the image top and left.
I think you're talking about: ``` <input id="info" type="image"> ``` When submitted, there are form values for the x and y coordinate based on the input element id (`info.x` and `info.y` in this case). <http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.4.1>
19,466
<p>How can I check <code>file permissions</code>, without having to run operating system specific command via <code>passthru()</code> or <code>exec()</code>?</p>
[ { "answer_id": 19469, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 0, "selected": false, "text": "<p>What do you want to do by checking file permissions?</p>\n\n<p>When writing secure code, it's almost always incorrect t...
2008/08/21
[ "https://Stackoverflow.com/questions/19466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
How can I check `file permissions`, without having to run operating system specific command via `passthru()` or `exec()`?
Use [fileperms()](http://php.net/fileperms) function ``` clearstatcache(); echo substr(sprintf('%o', fileperms('/etc/passwd')), -4); ```
19,516
<p>Here is a simplification of my database:</p> <pre>Table: Property Fields: ID, Address Table: Quote Fields: ID, PropertyID, BespokeQuoteFields... Table: Job Fields: ID, PropertyID, BespokeJobFields...</pre> <p>Then we have other tables that relate to the <strong>Quote</strong> and <strong>Job</strong> tables individually.</p> <p>I now need to add a <strong>Message</strong> table where users can record telephone messages left by customers regarding Jobs and Quotes.</p> <p>I could create two identical tables (<strong>QuoteMessage</strong> and <strong>JobMessage</strong>), but this violates the DRY principal and seems messy.</p> <p>I could create one <strong>Message</strong> table:</p> <pre>Table: Message Fields: ID, RelationID, RelationType, OtherFields...</pre> <p>But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on.</p> <p>Is there an elegant solution to this problem, or am I ultimately going to have to hack something together?</p> <p>Burns</p>
[ { "answer_id": 19521, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 3, "selected": true, "text": "<p>Create one Message table, containing a unique MessageId and the various properties you need to store for a message.</p>\...
2008/08/21
[ "https://Stackoverflow.com/questions/19516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366/" ]
Here is a simplification of my database: ``` Table: Property Fields: ID, Address Table: Quote Fields: ID, PropertyID, BespokeQuoteFields... Table: Job Fields: ID, PropertyID, BespokeJobFields... ``` Then we have other tables that relate to the **Quote** and **Job** tables individually. I now need to add a **Message** table where users can record telephone messages left by customers regarding Jobs and Quotes. I could create two identical tables (**QuoteMessage** and **JobMessage**), but this violates the DRY principal and seems messy. I could create one **Message** table: ``` Table: Message Fields: ID, RelationID, RelationType, OtherFields... ``` But this stops me from using constraints to enforce my referential integrity. I can also forsee it creating problems with the devlopment side using Linq to SQL later on. Is there an elegant solution to this problem, or am I ultimately going to have to hack something together? Burns
Create one Message table, containing a unique MessageId and the various properties you need to store for a message. ``` Table: Message Fields: Id, TimeReceived, MessageDetails, WhateverElse... ``` Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message. ``` Table: QuoteMessage Fields: QuoteId, MessageId Table: JobMessage Fields: JobId, MessageId ``` In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the *same* message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).
19,517
<p>I was reading the example chapter from <a href="http://www.manning.com/rahien/" rel="nofollow noreferrer">the book by Ayende</a> and on the website of <a href="http://boo.codehaus.org/" rel="nofollow noreferrer">the Boo language</a> I saw a reference to the <a href="http://specter.sourceforge.net/" rel="nofollow noreferrer">Specter BDD Framework</a>.</p> <p>I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings.</p> <p>Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment.</p> <hr> <p>A few year later visiting this question. I think we can safely assume <a href="http://www.specflow.org/" rel="nofollow noreferrer">Specflow</a> and some others like <a href="http://nspec.org/" rel="nofollow noreferrer">NSpec</a> became the tools we are using.</p>
[ { "answer_id": 19521, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 3, "selected": true, "text": "<p>Create one Message table, containing a unique MessageId and the various properties you need to store for a message.</p>\...
2008/08/21
[ "https://Stackoverflow.com/questions/19517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4367/" ]
I was reading the example chapter from [the book by Ayende](http://www.manning.com/rahien/) and on the website of [the Boo language](http://boo.codehaus.org/) I saw a reference to the [Specter BDD Framework](http://specter.sourceforge.net/). I am wondering if anybody is using it in their project, how that works out and if there are more examples and/or suggested readings. Just in case you are wondering, I'm a C# developer and so I plan to use it in a C#/.NET environment. --- A few year later visiting this question. I think we can safely assume [Specflow](http://www.specflow.org/) and some others like [NSpec](http://nspec.org/) became the tools we are using.
Create one Message table, containing a unique MessageId and the various properties you need to store for a message. ``` Table: Message Fields: Id, TimeReceived, MessageDetails, WhateverElse... ``` Create two link tables - QuoteMessage and JobMessage. These will just contain two fields each, foreign keys to the Quote/Job and the Message. ``` Table: QuoteMessage Fields: QuoteId, MessageId Table: JobMessage Fields: JobId, MessageId ``` In this way you have defined the data properties of a Message in one place only (making it easy to extend, and to query across all messages), but you also have the referential integrity linking Quotes and Jobs to any number of messages. Indeed, both a Quote and Job could be linked to the *same* message (I'm not sure if that is appropriate to your business model, but at least the data model gives you the option).
19,553
<p>I have a "Status" class in C#, used like this:</p> <pre><code>Status MyFunction() { if(...) // something bad return new Status(false, "Something went wrong") else return new Status(true, "OK"); } </code></pre> <p>You get the idea. All callers of MyFunction <em>should</em> check the returned Status:</p> <pre><code>Status myStatus = MyFunction(); if ( ! myStatus.IsOK() ) // handle it, show a message,... </code></pre> <p>Lazy callers however can ignore the Status.</p> <pre><code>MyFunction(); // call function and ignore returned Status </code></pre> <p>or </p> <pre><code>{ Status myStatus = MyFunction(); } // lose all references to myStatus, without calling IsOK() on it </code></pre> <p>Is it possible to make this impossible? e.g. an throw exception</p> <p><strong>In general</strong>: is it possible to write a C# class on which you <em>have</em> to call a certain function?</p> <p>In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the <em>destructor</em> and ring some bells when someone doesn't check this instance.</p> <p>What is the equivalent option in C#? I read somewhere that "You don't want a destructor in your C# class"</p> <p>Is the Dispose method of the IDisposable interface an option?</p> <p>In this case there are no unmanaged resources to free. Additionally, it is not determined <em>when</em> the GC will dispose the object. When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance? The "using" keyword does help, but again, it is not <em>required</em> for lazy callers.</p>
[ { "answer_id": 19560, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 3, "selected": false, "text": "<p>I know this doesn't answer your question directly, but if \"something went wrong\" within your function (unexpected cir...
2008/08/21
[ "https://Stackoverflow.com/questions/19553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1163/" ]
I have a "Status" class in C#, used like this: ``` Status MyFunction() { if(...) // something bad return new Status(false, "Something went wrong") else return new Status(true, "OK"); } ``` You get the idea. All callers of MyFunction *should* check the returned Status: ``` Status myStatus = MyFunction(); if ( ! myStatus.IsOK() ) // handle it, show a message,... ``` Lazy callers however can ignore the Status. ``` MyFunction(); // call function and ignore returned Status ``` or ``` { Status myStatus = MyFunction(); } // lose all references to myStatus, without calling IsOK() on it ``` Is it possible to make this impossible? e.g. an throw exception **In general**: is it possible to write a C# class on which you *have* to call a certain function? In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the *destructor* and ring some bells when someone doesn't check this instance. What is the equivalent option in C#? I read somewhere that "You don't want a destructor in your C# class" Is the Dispose method of the IDisposable interface an option? In this case there are no unmanaged resources to free. Additionally, it is not determined *when* the GC will dispose the object. When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance? The "using" keyword does help, but again, it is not *required* for lazy callers.
I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following: ``` using System; public class Example { public class Toy { private bool inCupboard = false; public void Play() { Console.WriteLine("Playing."); } public void PutAway() { inCupboard = true; } public bool IsInCupboard { get { return inCupboard; } } } public delegate void ToyUseCallback(Toy toy); public class Parent { public static void RequestToy(ToyUseCallback callback) { Toy toy = new Toy(); callback(toy); if (!toy.IsInCupboard) { throw new Exception("You didn't put your toy in the cupboard!"); } } } public class Child { public static void Play() { Parent.RequestToy(delegate(Toy toy) { toy.Play(); // Oops! Forgot to put the toy away! }); } } public static void Main() { Child.Play(); Console.ReadLine(); } } ``` In the very simple example, you get an instance of Toy by calling Parent.RequestToy, *and passing it a delegate*. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all "something went wrong" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request.
19,589
<p>Using C# .NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to).</p> <p>The obvious way is to use <code>ConfigurationManager</code> to load the configuration section and write out the data I need.</p> <pre><code>var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel"); </code></pre> <p>Appears to always return null.</p> <pre><code>var serviceModelSection = ConfigurationManager.GetSection("appSettings"); </code></pre> <p>Works perfectly.</p> <p>The configuration section is present in the App.config but for some reason <code>ConfigurationManager</code> refuses to load the <code>system.ServiceModel</code> section.</p> <p>I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack.</p> <p>Any suggestions?</p>
[ { "answer_id": 19594, "author": "DavidWhitney", "author_id": 1297, "author_profile": "https://Stackoverflow.com/users/1297", "pm_score": 6, "selected": false, "text": "<p><a href=\"http://mostlytech.blogspot.com/2007/11/programmatically-enumerate-wcf.html\" rel=\"noreferrer\">http://most...
2008/08/21
[ "https://Stackoverflow.com/questions/19589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1297/" ]
Using C# .NET 3.5 and WCF, I'm trying to write out some of the WCF configuration in a client application (the name of the server the client is connecting to). The obvious way is to use `ConfigurationManager` to load the configuration section and write out the data I need. ``` var serviceModelSection = ConfigurationManager.GetSection("system.serviceModel"); ``` Appears to always return null. ``` var serviceModelSection = ConfigurationManager.GetSection("appSettings"); ``` Works perfectly. The configuration section is present in the App.config but for some reason `ConfigurationManager` refuses to load the `system.ServiceModel` section. I want to avoid manually loading the xxx.exe.config file and using XPath but if I have to resort to that I will. Just seems like a bit of a hack. Any suggestions?
The [`<system.serviceModel>`](http://msdn.microsoft.com/en-us/library/ms731354%28v=vs.90%29.aspx) element is for a configuration section **group**, not a section. You'll need to use [`System.ServiceModel.Configuration.ServiceModelSectionGroup.GetSectionGroup()`](http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.servicemodelsectiongroup.getsectiongroup%28v=vs.90%29.aspx) to get the whole group.
19,656
<p>I have an Interface called <code>IStep</code> that can do some computation (See "<a href="http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html" rel="nofollow noreferrer">Execution in the Kingdom of Nouns</a>"). At runtime, I want to select the appropriate implementation by class name.</p> <pre> // use like this: IStep step = GetStep(sName); </pre>
[ { "answer_id": 19658, "author": "Ian Nelson", "author_id": 2084, "author_profile": "https://Stackoverflow.com/users/2084", "pm_score": 2, "selected": false, "text": "<p>If the implementation has a parameterless constructor, you can do this using the System.Activator class. You will need ...
2008/08/21
[ "https://Stackoverflow.com/questions/19656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I have an Interface called `IStep` that can do some computation (See "[Execution in the Kingdom of Nouns](http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html)"). At runtime, I want to select the appropriate implementation by class name. ``` // use like this: IStep step = GetStep(sName); ```
Your question is very confusing... If you want to find types that implement IStep, then do this: ``` foreach (Type t in Assembly.GetCallingAssembly().GetTypes()) { if (!typeof(IStep).IsAssignableFrom(t)) continue; Console.WriteLine(t.FullName + " implements " + typeof(IStep).FullName); } ``` If you know already the name of the required type, just do this ``` IStep step = (IStep)Activator.CreateInstance(Type.GetType("MyNamespace.MyType")); ```
19,708
<p>To grab the inode of a file in PHP, you can use this:</p> <pre><code>$fs = stat($file); echo $fs['ino']; </code></pre> <p>The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it?</p>
[ { "answer_id": 19716, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": true, "text": "<p>You could use <a href=\"http://php.net/fileinode\" rel=\"nofollow noreferrer\"><code>fileinode()</code></a> but you should...
2008/08/21
[ "https://Stackoverflow.com/questions/19708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/497/" ]
To grab the inode of a file in PHP, you can use this: ``` $fs = stat($file); echo $fs['ino']; ``` The problem with this is EVERYWHERE says it's slow and you should avoid it. So the question becomes what's the fast(er) way to do it?
You could use [`fileinode()`](http://php.net/fileinode) but you should run benchmarks if you think it is slow.
19,725
<p>Right, initially ran:</p> <pre><code>c:\regsvr32 Amazing.dll </code></pre> <p>then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know <em>now</em> I should've run:</p> <pre><code>c:\regsvr32 /u Amazing.dll </code></pre> <p>beforehand - but hey! I forgot.</p> <p>To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running <code>regsvr32 /u</code> removes one of the references, the second time - does nothing...</p> <p>How do I get rid of these references? Am I looking at a regedit scenario? - If so - what <em>exactly</em> happens if I delete one of the keys???</p> <p>Cheers</p>
[ { "answer_id": 19730, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 0, "selected": false, "text": "<p>I've got myself into a horrible mess with COM before. I had to pick my way though the registry deleting each referenc...
2008/08/21
[ "https://Stackoverflow.com/questions/19725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2266/" ]
Right, initially ran: ``` c:\regsvr32 Amazing.dll ``` then, (accidentally - I might add) I must have run it again, and (indeed) again when new versions of 'Amazing.dll' were released. Yes - I know *now* I should've run: ``` c:\regsvr32 /u Amazing.dll ``` beforehand - but hey! I forgot. To cut to the chase, when add the COM reference in VS, I can see 3 instances of 'Amazing' all pointing to the same location (c:\Amazing.dll), running `regsvr32 /u` removes one of the references, the second time - does nothing... How do I get rid of these references? Am I looking at a regedit scenario? - If so - what *exactly* happens if I delete one of the keys??? Cheers
Your object's GUID's should not be changing. In other words, once you register the COM object, re-registering shouldn't be adding anything additional to the registry. Unless you added additional COM interfaces or objects to the project. In any case, if this is a one time deal (and it sounds like it is), open regedit and delete the unneeded keys manually.
19,786
<p>I am maintaining an app for a client that is used in two locations. One in England and one in Poland.</p> <p>The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format.</p> <p>My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace , or . ?</p> <p>BTW I have looked at CCur, but not sure if that will do what I want. </p>
[ { "answer_id": 19810, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 0, "selected": false, "text": "<p>What database are you using? And what data type is the amount stored in?</p>\n\n<p>As long as you are always converting from ...
2008/08/21
[ "https://Stackoverflow.com/questions/19786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1075/" ]
I am maintaining an app for a client that is used in two locations. One in England and one in Poland. The database is stored in England and uses the format £1000.00 for currency, but the information is being gathered locally in Poland where 1000,00 is the format. My question is, in VB6 is there a function that takes a currency string in a local format and converts to another, or will I just have to parse the string and replace , or . ? BTW I have looked at CCur, but not sure if that will do what I want.
The data is not actually stored as the string `"£1000.00"`; it's stored in some numeric format. > > **Sidebar:** Usually databases are set up to store money amounts using either the **decimal** data type (also called **money** in some DBs), or as a floating point number (also called **double**). > > > The difference is that when it's stored as **decimal** certain numbers like 0.01 are represented exactly whereas in **double** those numbers can only be stored approximately, causing rounding errors. > > > The database *appears* to be storing the number as `"£1000.00"` because something is formatting it for display. In VB6, there's a function `FormatCurrency` which would take a number like 1000 and return a string like `"£1000.00"`. You'll notice that the `FormatCurrency` function does not take an argument specifying what type of currency to use. That's because it, along with all the other locale-specific functions in VB, figures out the currency from the current locale of the system (from the Windows Control Panel). That means that on my system, ``` Debug.Print FormatCurrency(1000) ``` will print `$1,000.00`, but if I run that same program on a Windows computer set to the UK locale, it will probably print `£1,000.00`, which, of course, is something completely different. Similarly, you've got some code, somewhere, I can't tell where, in Poland, it seems, that is responsible for parsing the user's string and converting it to a number. And if that code is in Visual Basic, again, it's relying on the control panel to decide whether "." or "," is the thousands separator and whether "," or "." is the decimal point. The function `CDbl` converts its argument to a number. So for example on my system in the US ``` Debug.Print CDbl("1.200") ``` produces the number one point two, on a system with the Control Panel set to European formatting, it would produce the number one thousand, two hundred. It's possible that the problem is that you have someone sitting a computer with the regional control panel set to use "." as the decimal separator, but they're typing "," as the decimal separator.
19,787
<p>Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)?</p> <p>I want to see if a <code>.bat</code> file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this.</p> <p>The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this?</p>
[ { "answer_id": 19798, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 2, "selected": false, "text": "<p>I assume you are using the SVN command line client. Give TortoiseSVN a try. Its \"Show Log\" dialog allows searching for co...
2008/08/21
[ "https://Stackoverflow.com/questions/19787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/277/" ]
Is it possible to look back through the history of a Subversion repository for files of a certain name (even better would be for them to have a wildcard search)? I want to see if a `.bat` file has been committed to the repository at some point in the past but has since been removed in later updates. Even a dump of the file history at each revision would work, as I could just grep the output. I have looked through the manual but could not see a good way to do this. The logs for each commit are descriptive, so I cannot just look through the log messages to see what modifications were done. I presume Subversion does have a way of retrieving this?
TortoiseSVN can search the logs very easily, and on my system I can enter ".plg" in the search box and find all adds, modifies, and deletes for those files. Without Tortoise, the only way I can think of doing that would be to grep the full logs or parse the logs and do your own searching for 'A' and 'D' indicators on the file you are looking for (use `svn log --verbose` to get file paths). ``` svn log --verbose | grep .bat ```
19,838
<p>I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C.</p> <p>One easy way to implement closures is to pass a <code>void*</code> to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block.</p> <pre><code>loop do break i if (i &gt;= 4000) i *= 2 end </code></pre> <p>I think one of the closures proposals for Java works like this also.</p> <p>So, how would you implement Ruby-blocks/Java-closures in C?</p>
[ { "answer_id": 20154, "author": "wvdschel", "author_id": 2018, "author_profile": "https://Stackoverflow.com/users/2018", "pm_score": 4, "selected": true, "text": "<p>The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, ...
2008/08/21
[ "https://Stackoverflow.com/questions/19838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2148/" ]
I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C. One easy way to implement closures is to pass a `void*` to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block. ``` loop do break i if (i >= 4000) i *= 2 end ``` I think one of the closures proposals for Java works like this also. So, how would you implement Ruby-blocks/Java-closures in C?
The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed. The way this is done by interpreters or virtual machines is to have a `context` structure or something similar, and not use the stack and registers directly. This structure keeps track of a stack and optionally some registers, if you're designing a register based VM. At least, that's the simplest way to do it (though slightly less performant than actually mapping things correctly).
19,843
<p>My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code:</p> <pre><code>Class test&lt;T&gt;{ int method1(Obj Parameter1){ //in here I want to do something which I would explain as T.TryParse(Parameter1); //my problem is that it does not work ... I get an error. //just to explain: if I declare test&lt;int&gt; (with type Integer) //I want my sample code to call int.TryParse(). If it were String //it should have been String.TryParse() } } </code></pre> <p>So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you!</p> <hr /> <p>Edit: Thank you all for your answers!</p> <p>Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch.</p> <p>This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn)</p> <hr /> <p>Though if you have some other suggestion I am still waiting (and willing to participate)</p>
[ { "answer_id": 19862, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<p>The problem is that TryParse isn't defined on an interface or base class anywhere, so you can't make an assumption that t...
2008/08/21
[ "https://Stackoverflow.com/questions/19843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2275/" ]
My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code: ``` Class test<T>{ int method1(Obj Parameter1){ //in here I want to do something which I would explain as T.TryParse(Parameter1); //my problem is that it does not work ... I get an error. //just to explain: if I declare test<int> (with type Integer) //I want my sample code to call int.TryParse(). If it were String //it should have been String.TryParse() } } ``` So thank you guys for your answers (By the way the question is: how would I solve this problem without getting an error). This probably quite an easy question for you! --- Edit: Thank you all for your answers! Though I think the try - catch phrase is the most elegant, I know from my experience with vb that it can really be a bummer. I used it once and it took about 30 minutes to run a program, which later on only took 2 minutes to compute just because I avoided try - catch. This is why I chose the switch statement as the best answer. It makes the code more complicated but on the other hand I imagine it to be relatively fast and relatively easy to read. (Though I still think there should be a more elegant way ... maybe in the next language I learn) --- Though if you have some other suggestion I am still waiting (and willing to participate)
One more way to do it, this time some reflection in the mix: ``` static class Parser { public static bool TryParse<TType>( string str, out TType x ) { // Get the type on that TryParse shall be called Type objType = typeof( TType ); // Enumerate the methods of TType foreach( MethodInfo mi in objType.GetMethods() ) { if( mi.Name == "TryParse" ) { // We found a TryParse method, check for the 2-parameter-signature ParameterInfo[] pi = mi.GetParameters(); if( pi.Length == 2 ) // Find TryParse( String, TType ) { // Build a parameter list for the call object[] paramList = new object[2] { str, default( TType ) }; // Invoke the static method object ret = objType.InvokeMember( "TryParse", BindingFlags.InvokeMethod, null, null, paramList ); // Get the output value from the parameter list x = (TType)paramList[1]; return (bool)ret; } } } // Maybe we should throw an exception here, because we were unable to find the TryParse // method; this is not just a unable-to-parse error. x = default( TType ); return false; } } ``` The next step would be trying to implement ``` public static TRet CallStaticMethod<TRet>( object obj, string methodName, params object[] args ); ``` With full parameter type matching etc.
19,852
<p>I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc).</p> <p>Does anybody know the maximum length that I can expect a content-type to be?</p>
[ { "answer_id": 136592, "author": "Walden Leverich", "author_id": 2673770, "author_profile": "https://Stackoverflow.com/users/2673770", "pm_score": 1, "selected": false, "text": "<p>We run an SaaS system that allows users to upload files. We'd originally designed it to store MIME Types up...
2008/08/21
[ "https://Stackoverflow.com/questions/19852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2084/" ]
I'm just designing the schema for a database table which will hold details of email attachments - their size in bytes, filename and content-type (i.e. "image/jpg", "audio/mp3", etc). Does anybody know the maximum length that I can expect a content-type to be?
I hope I havn't misread, but it looks like the length is max 127/127 or **255 total**. [RFC 4288](http://www.ietf.org/rfc/rfc4288.txt?number=4288) has a reference in 4.2 (page 6): ``` Type and subtype names MUST conform to the following ABNF: type-name = reg-name subtype-name = reg-name reg-name = 1*127reg-name-chars reg-name-chars = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "." / "+" / "-" / "^" / "_" ``` It is not clear to me if the +suffix can add past the 127, but it appears not.
19,952
<p>The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M.</p> <p>Thinking C is the .class and J is the .java file of which we need to calculate RFC.</p> <pre> class J{ a(){} b(){} c(){ e1.e(); e1.f(); e1.g(); } h(){ i.k(); i.j(); } m(){} n(){ i.o(); i.p(); i.p(); i.p(); } } </pre> <p>here M=6 and R=9 (Don't worry about call inside a loop. It's considered as a single call)</p> <p>Calculating M is easy. Load C using classloader and use reflection to get the count of methods.</p> <p>Calculating R is not direct. We need to count the number of method calls from the class. First level only. </p> <p>For calculating R I must use regex. Usually format would be (calls without using . are not counted)</p> <pre> [variable_name].[method_name]([zero or more parameters]); </pre> <p>or</p> <pre> [variable_name].[method_name]([zero or more parameters]) </pre> <p>with out semicolon when call return is directly becomes parameter to another method. or </p> <pre> [variable_name].[method_name]([zero or more parameters]).method2(); </pre> <p>this becomes two method calls</p> <p>What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R.</p> <hr> <p><strong>UPDATE:</strong><br> <a href="https://stackoverflow.com/questions/19952/rfc-calculation-in-java-need-help-with-algorithm#19983" title="@McDowell">@McDowell</a> Looks like using BCEL I can simplify the whole process. Let me try it.</p>
[ { "answer_id": 19967, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 0, "selected": false, "text": "<p>You should find your answer in the <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html\" rel=\"nofo...
2008/08/21
[ "https://Stackoverflow.com/questions/19952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/482/" ]
The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M. Thinking C is the .class and J is the .java file of which we need to calculate RFC. ``` class J{ a(){} b(){} c(){ e1.e(); e1.f(); e1.g(); } h(){ i.k(); i.j(); } m(){} n(){ i.o(); i.p(); i.p(); i.p(); } } ``` here M=6 and R=9 (Don't worry about call inside a loop. It's considered as a single call) Calculating M is easy. Load C using classloader and use reflection to get the count of methods. Calculating R is not direct. We need to count the number of method calls from the class. First level only. For calculating R I must use regex. Usually format would be (calls without using . are not counted) ``` [variable_name].[method_name]([zero or more parameters]); ``` or ``` [variable_name].[method_name]([zero or more parameters]) ``` with out semicolon when call return is directly becomes parameter to another method. or ``` [variable_name].[method_name]([zero or more parameters]).method2(); ``` this becomes two method calls What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R. --- **UPDATE:** [@McDowell](https://stackoverflow.com/questions/19952/rfc-calculation-in-java-need-help-with-algorithm#19983 "@McDowell") Looks like using BCEL I can simplify the whole process. Let me try it.
You could use the [Byte Code Engineering Library](http://jakarta.apache.org/bcel/index.html) with binaries. You can use a [DescendingVisitor](http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/DescendingVisitor.html) to visit a class' members and references. I've used it to [find class dependencies](http://illegalargumentexception.blogspot.com/2008/04/java-finding-binary-class-dependencies.html). Alternatively, you could reuse some model of the source files. I'm pretty sure the Java editor in the [Eclipse JDT](http://www.eclipse.org/jdt/) is backed by some form of model.
20,047
<p>We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database.</p> <p>I attached the profiler, set up a trace profile using <a href="http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/" rel="noreferrer">this excellent article on troubleshooting deadlocks</a>, and captured a bunch of examples. The weird thing is that <strong>the deadlocking write is <em>always</em> the same</strong>:</p> <pre><code>UPDATE [dbo].[Posts] SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3 WHERE [Id] = @p0 </code></pre> <p>The other deadlocking statement varies, but it's usually some kind of trivial, simple <strong>read</strong> of the posts table. This one always gets killed in the deadlock. Here's an example</p> <pre><code>SELECT [t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount], [t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId], [t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason], [t0].[LastActivityDate], [t0].[LastActivityUserId] FROM [dbo].[Posts] AS [t0] WHERE [t0].[ParentId] = @p0 </code></pre> <p>To be perfectly clear, we are not seeing write / write deadlocks, but read / write.</p> <p>We have a mixture of LINQ and parameterized SQL queries at the moment. We have added <code>with (nolock)</code> to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems!</p> <p>Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write.</p> <p>The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's <em>only</em> executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app.</p> <p>I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date?</p> <p>Using NOLOCK with Linq is a bit more difficult as <a href="http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx" rel="noreferrer">Scott Hanselman discusses here</a>.</p> <p>We are flirting with the idea of using</p> <pre><code>SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED </code></pre> <p>on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly.</p> <p>I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but <em>reads?</em> We're not running a banking site here, we don't need perfect accuracy every time.</p> <p>Ideas? Thoughts?</p> <hr> <blockquote> <p>Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls?</p> </blockquote> <p>Jeremy, we are sharing one static datacontext in the base Controller for the most part:</p> <pre><code>private DBContext _db; /// &lt;summary&gt; /// Gets the DataContext to be used by a Request's controllers. /// &lt;/summary&gt; public DBContext DB { get { if (_db == null) { _db = new DBContext() { SessionName = GetType().Name }; //_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"); } return _db; } } </code></pre> <p>Do you recommend we create a new context for every Controller, or per Page, or .. more often?</p>
[ { "answer_id": 20056, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>Will you care if your user profile is a few seconds out of date?</p>\n</blockquote>\n\n<p>Nope - that's p...
2008/08/21
[ "https://Stackoverflow.com/questions/20047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
We're seeing some pernicious, but rare, deadlock conditions in the Stack Overflow SQL Server 2005 database. I attached the profiler, set up a trace profile using [this excellent article on troubleshooting deadlocks](http://www.simple-talk.com/sql/learn-sql-server/how-to-track-down-deadlocks-using-sql-server-2005-profiler/), and captured a bunch of examples. The weird thing is that **the deadlocking write is *always* the same**: ``` UPDATE [dbo].[Posts] SET [AnswerCount] = @p1, [LastActivityDate] = @p2, [LastActivityUserId] = @p3 WHERE [Id] = @p0 ``` The other deadlocking statement varies, but it's usually some kind of trivial, simple **read** of the posts table. This one always gets killed in the deadlock. Here's an example ``` SELECT [t0].[Id], [t0].[PostTypeId], [t0].[Score], [t0].[Views], [t0].[AnswerCount], [t0].[AcceptedAnswerId], [t0].[IsLocked], [t0].[IsLockedEdit], [t0].[ParentId], [t0].[CurrentRevisionId], [t0].[FirstRevisionId], [t0].[LockedReason], [t0].[LastActivityDate], [t0].[LastActivityUserId] FROM [dbo].[Posts] AS [t0] WHERE [t0].[ParentId] = @p0 ``` To be perfectly clear, we are not seeing write / write deadlocks, but read / write. We have a mixture of LINQ and parameterized SQL queries at the moment. We have added `with (nolock)` to all the SQL queries. This may have helped some. We also had a single (very) poorly-written badge query that I fixed yesterday, which was taking upwards of 20 seconds to run every time, and was running every minute on top of that. I was hoping this was the source of some of the locking problems! Unfortunately, I got another deadlock error about 2 hours ago. Same exact symptoms, same exact culprit write. The truly strange thing is that the locking write SQL statement you see above is part of a very specific code path. It's *only* executed when a new answer is added to a question -- it updates the parent question with the new answer count and last date/user. This is, obviously, not that common relative to the massive number of reads we are doing! As far as I can tell, we're not doing huge numbers of writes anywhere in the app. I realize that NOLOCK is sort of a giant hammer, but most of the queries we run here don't need to be that accurate. Will you care if your user profile is a few seconds out of date? Using NOLOCK with Linq is a bit more difficult as [Scott Hanselman discusses here](http://www.hanselman.com/blog/GettingLINQToSQLAndLINQToEntitiesToUseNOLOCK.aspx). We are flirting with the idea of using ``` SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED ``` on the base database context so that all our LINQ queries have this set. Without that, we'd have to wrap every LINQ call we make (well, the simple reading ones, which is the vast majority of them) in a 3-4 line transaction code block, which is ugly. I guess I'm a little frustrated that trivial reads in SQL 2005 can deadlock on writes. I could see write/write deadlocks being a huge issue, but *reads?* We're not running a banking site here, we don't need perfect accuracy every time. Ideas? Thoughts? --- > > Are you instantiating a new LINQ to SQL DataContext object for every operation or are you perhaps sharing the same static context for all your calls? > > > Jeremy, we are sharing one static datacontext in the base Controller for the most part: ``` private DBContext _db; /// <summary> /// Gets the DataContext to be used by a Request's controllers. /// </summary> public DBContext DB { get { if (_db == null) { _db = new DBContext() { SessionName = GetType().Name }; //_db.ExecuteCommand("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED"); } return _db; } } ``` Do you recommend we create a new context for every Controller, or per Page, or .. more often?
According to MSDN: <http://msdn.microsoft.com/en-us/library/ms191242.aspx> > > When either the > READ COMMITTED SNAPSHOT or > ALLOW SNAPSHOT ISOLATION database > options are ON, logical copies > (versions) are maintained for all data > modifications performed in the > database. Every time a row is modified > by a specific transaction, the > instance of the Database Engine stores > a version of the previously committed > image of the row in tempdb. Each > version is marked with the transaction > sequence number of the transaction > that made the change. The versions of > modified rows are chained using a link > list. The newest row value is always > stored in the current database and > chained to the versioned rows stored > in tempdb. > > > For short-running transactions, a > version of a modified row may get > cached in the buffer pool without > getting written into the disk files of > the tempdb database. If the need for > the versioned row is short-lived, it > will simply get dropped from the > buffer pool and may not necessarily > incur I/O overhead. > > > There appears to be a slight performance penalty for the extra overhead, but it may be negligible. We should test to make sure. Try setting this option and REMOVE all NOLOCKs from code queries unless it’s really necessary. NOLOCKs or using global methods in the database context handler to combat database transaction isolation levels are Band-Aids to the problem. NOLOCKS will mask fundamental issues with our data layer and possibly lead to selecting unreliable data, where automatic select / update row versioning appears to be the solution. ``` ALTER Database [StackOverflow.Beta] SET READ_COMMITTED_SNAPSHOT ON ```
20,061
<p>I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played.</p> <p>My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application?</p> <hr> <p>Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;). I'm used to building web applications and for those, text files are generally frowned upon.</p> <p>So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?</p>
[ { "answer_id": 20086, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 3, "selected": false, "text": "<p>A database may be overkill - have you thought about just storing the scores in a file?</p>\n\n<p>If you decide to go with a ...
2008/08/21
[ "https://Stackoverflow.com/questions/20061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/271/" ]
I've recently taken up learning some C# and wrote a Yahtzee clone. My next step (now that the game logic is in place and functioning correctly) is to integrate some method of keeping stats across all the games played. My question is this, how should I go about storing this information? My first thought would be to use a database and I have a feeling that's the answer I'll get... if that's the case, can you point me to a good resource for creating and accessing a database from a C# application? --- Storing in an XML file actually makes more sense to me, but I thought if I suggested that I'd get torn apart ;). I'm used to building web applications and for those, text files are generally frowned upon. So, going with an XML file, what classes should I be looking at that would allow for easy manipulation?
Here is one idea: use Xml Serialization. Design your GameStats data structure and optionally use Xml attributes to influence the schema as you like. I like to use this method for small data sets because its quick and easy and all I need to do is design and manipulate the data structure. ``` using (FileStream fs = new FileStream(....)) { // Read in stats XmlSerializer xs = new XmlSerializer(typeof(GameStats)); GameStats stats = (GameStats)xs.Deserialize(fs); // Manipulate stats here ... // Write out game stats XmlSerializer xs = new XmlSerializer(typeof(GameStats)); xs.Serialize(fs, stats); fs.Close(); } ```
20,063
<p>What's the <strong>easiest</strong>, <strong>tersest</strong>, and most <strong>flexible</strong> method or library for parsing Python command line arguments?</p>
[ { "answer_id": 20065, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 4, "selected": false, "text": "<p>Use <code>optparse</code> which comes with the standard library. For example:</p>\n\n<pre><code>#!/usr/bin/env python\nimpor...
2008/08/21
[ "https://Stackoverflow.com/questions/20063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1335/" ]
What's the **easiest**, **tersest**, and most **flexible** method or library for parsing Python command line arguments?
**This answer suggests `optparse` which is appropriate for older Python versions. For Python 2.7 and above, `argparse` replaces `optparse`. See [this answer](https://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse) for more information.** As other people pointed out, you are better off going with optparse over getopt. getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use. optparse, while being a bit more verbose, is much better structured and simpler to extend later on. Here's a typical line to add an option to your parser: ``` parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") ``` It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it. It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option. Usually you parse your arguments with: ``` options, args = parser.parse_args() ``` This will, by default, parse the standard arguments passed to the script (sys.argv[1:]) options.query will then be set to the value you passed to the script. You create a parser simply by doing ``` parser = optparse.OptionParser() ``` These are all the basics you need. Here's a complete Python script that shows this: ``` import optparse parser = optparse.OptionParser() parser.add_option('-q', '--query', action="store", dest="query", help="query string", default="spam") options, args = parser.parse_args() print 'Query string:', options.query ``` 5 lines of python that show you the basics. Save it in sample.py, and run it once with ``` python sample.py ``` and once with ``` python sample.py --query myquery ``` Beyond that, you will find that optparse is very easy to extend. In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily. It uses optparse heavily to chain commands together. It's not something I can easily explain in a few lines, but feel free to [browse around in my repository](https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py) for the main class, as well as [a class that uses it and the option parser](https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py)
20,081
<p>I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together.</p> <p>The logic is written as a <a href="http://www.oreillynet.com/lpt/a/3136" rel="nofollow noreferrer">pipelined table function</a>, following the pattern from the linked article. The table function uses a <code>PRAGMA AUTONOMOUS_TRANSACTION</code> declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values.</p> <p>I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive).</p> <p>My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing?</p> <p>Every time I touch PL/SQL I get the impression that I'm typing way too much.</p> <p><strong>Update:</strong> I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example:</p> <pre><code>| EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns... | 1 | 10 | A | 10-JAN-2008 | | 2 | 11 | A | 13-JAN-2008 | | 1 | 12 | A | 20-JAN-2008 | | 2 | 11 | T | 01-FEB-2008 | | 1 | 10 | T | 02-FEB-2008 | | 2 | 11 | A | 20-FEB-2008 | </code></pre> <p>Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any <code>EMP_ID</code>s passed in though the cursor. Passing in <code>EMP_ID</code>s 1 and 2 would produce the following:</p> <pre><code>| EMP_ID | JOB_ID | START_DATE | END_DATE | | 1 | 10 | 10-JAN-2008 | 02-FEB-2008 | | 2 | 11 | 13-JAN-2008 | 01-FEB-2008 | | 1 | 12 | 20-JAN-2008 | | | 2 | 11 | 20-FEB-2008 | | </code></pre> <p>(<code>END_DATE</code> allows <code>NULL</code>s for jobs that don't have a predetermined termination date.)</p> <p>As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it.</p>
[ { "answer_id": 22033, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 1, "selected": false, "text": "<p>Rather than having the input parameter as a cursor, I would have a table variable (don't know if Oracle has such...
2008/08/21
[ "https://Stackoverflow.com/questions/20081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/726/" ]
I've written PL/SQL code to denormalize a table into a much-easer-to-query form. The code uses a temporary table to do some of its work, merging some rows from the original table together. The logic is written as a [pipelined table function](http://www.oreillynet.com/lpt/a/3136), following the pattern from the linked article. The table function uses a `PRAGMA AUTONOMOUS_TRANSACTION` declaration to permit the temporary table manipulation, and also accepts a cursor input parameter to restrict the denormalization to certain ID values. I then created a view to query the table function, passing in all possible ID values as a cursor (other uses of the function will be more restrictive). My question: is this all really necessary? Have I completely missed a much more simple way of accomplishing the same thing? Every time I touch PL/SQL I get the impression that I'm typing way too much. **Update:** I'll add a sketch of the table I'm dealing with to give everyone an idea of the denormalization that I'm talking about. The table stores a history of employee jobs, each with an activation row, and (possibly) a termination row. It's possible for an employee to have multiple simultaneous jobs, as well as the same job over and over again in non-contiguous date ranges. For example: ``` | EMP_ID | JOB_ID | STATUS | EFF_DATE | other columns... | 1 | 10 | A | 10-JAN-2008 | | 2 | 11 | A | 13-JAN-2008 | | 1 | 12 | A | 20-JAN-2008 | | 2 | 11 | T | 01-FEB-2008 | | 1 | 10 | T | 02-FEB-2008 | | 2 | 11 | A | 20-FEB-2008 | ``` Querying that to figure out who is working when in what job is non-trivial. So, my denormalization function populates the temporary table with just the date ranges for each job, for any `EMP_ID`s passed in though the cursor. Passing in `EMP_ID`s 1 and 2 would produce the following: ``` | EMP_ID | JOB_ID | START_DATE | END_DATE | | 1 | 10 | 10-JAN-2008 | 02-FEB-2008 | | 2 | 11 | 13-JAN-2008 | 01-FEB-2008 | | 1 | 12 | 20-JAN-2008 | | | 2 | 11 | 20-FEB-2008 | | ``` (`END_DATE` allows `NULL`s for jobs that don't have a predetermined termination date.) As you can imagine, this denormalized form is much, much easier to query, but creating it--so far as I can tell--requires a temporary table to store the intermediate results (e.g., job records for which the activation row has been found, but not the termination...yet). Using the pipelined table function to populate the temporary table and then return its rows is the only way I've figured out how to do it.
I think a way to approach this is to use analytic functions... I set up your test case using: ``` create table employee_job ( emp_id integer, job_id integer, status varchar2(1 char), eff_date date ); insert into employee_job values (1,10,'A',to_date('10-JAN-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'A',to_date('13-JAN-2008','DD-MON-YYYY')); insert into employee_job values (1,12,'A',to_date('20-JAN-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'T',to_date('01-FEB-2008','DD-MON-YYYY')); insert into employee_job values (1,10,'T',to_date('02-FEB-2008','DD-MON-YYYY')); insert into employee_job values (2,11,'A',to_date('20-FEB-2008','DD-MON-YYYY')); commit; ``` I've used the **lead** function to get the next date and then wrapped it all as a sub-query just to get the "A" records and add the end date if there is one. ``` select emp_id, job_id, eff_date start_date, decode(next_status,'T',next_eff_date,null) end_date from ( select emp_id, job_id, eff_date, status, lead(eff_date,1,null) over (partition by emp_id, job_id order by eff_date, status) next_eff_date, lead(status,1,null) over (partition by emp_id, job_id order by eff_date, status) next_status from employee_job ) where status = 'A' order by start_date, emp_id, job_id ``` I'm sure there's some use cases I've missed but you get the idea. Analytic functions are your friend :) ``` EMP_ID JOB_ID START_DATE END_DATE 1 10 10-JAN-2008 02-FEB-2008 2 11 13-JAN-2008 01-FEB-2008 2 11 20-FEB-2008 1 12 20-JAN-2008 ```
20,084
<p>Following on from my <a href="https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods">previous question</a> I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!).</p> <p>The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types.</p> <p>I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case!</p> <p>So I have done some digging on Google and I now understand <em>why</em> it's not working. In that <strong>the <code>XmlSerializer</code> is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to</strong>. Fine.</p> <p>I did come across <a href="http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx" rel="noreferrer">this page</a> on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible.</p> <p>One thing I should also add is that I <strong>DO NOT</strong> want to go down the <code>XmlInclude</code> route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!</p>
[ { "answer_id": 20097, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "<p>I've done things similar to this. What I normally do is make sure all the XML serialization attributes are on the c...
2008/08/21
[ "https://Stackoverflow.com/questions/20084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
Following on from my [previous question](https://stackoverflow.com/questions/19454/enforce-attribute-decoration-of-classesmethods) I have been working on getting my object model to serialize to XML. But I have now run into a problem (quelle surprise!). The problem I have is that I have a collection, which is of a abstract base class type, which is populated by the concrete derived types. I thought it would be fine to just add the XML attributes to all of the classes involved and everything would be peachy. Sadly, thats not the case! So I have done some digging on Google and I now understand *why* it's not working. In that **the `XmlSerializer` is in fact doing some clever reflection in order to serialize objects to/from XML, and since its based on the abstract type, it cannot figure out what the hell it's talking to**. Fine. I did come across [this page](http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx) on CodeProject, which looks like it may well help a lot (yet to read/consume fully), but I thought I would like to bring this problem to the StackOverflow table too, to see if you have any neat hacks/tricks in order to get this up and running in the quickest/lightest way possible. One thing I should also add is that I **DO NOT** want to go down the `XmlInclude` route. There is simply too much coupling with it, and this area of the system is under heavy development, so the it would be a real maintenance headache!
Problem Solved! --------------- OK, so I finally got there (admittedly with a **lot** of help from [here](http://www.codeproject.com/KB/XML/xmlserializerforunknown.aspx)!). So summarise: ### Goals: * I didn't want to go down the *XmlInclude* route due to the maintenence headache. * Once a solution was found, I wanted it to be quick to implement in other applications. * Collections of Abstract types may be used, as well as individual abstract properties. * I didn't really want to bother with having to do "special" things in the concrete classes. ### Identified Issues/Points to Note: * *XmlSerializer* does some pretty cool reflection, but it is *very* limited when it comes to abstract types (i.e. it will only work with instances of the abstract type itself, not subclasses). * The Xml attribute decorators define how the XmlSerializer treats the properties its finds. The physical type can also be specified, but this creates a **tight coupling** between the class and the serializer (not good). * We can implement our own XmlSerializer by creating a class that implements *IXmlSerializable* . The Solution ------------ I created a generic class, in which you specify the generic type as the abstract type you will be working with. This gives the class the ability to "translate" between the abstract type and the concrete type since we can hard-code the casting (i.e. we can get more info than the XmlSerializer can). I then implemented the *IXmlSerializable* interface, this is pretty straight forward, but when serializing we need to ensure we write the type of the concrete class to the XML, so we can cast it back when de-serializing. It is also important to note it must be **fully qualified** as the assemblies that the two classes are in are likely to differ. There is of course a little type checking and stuff that needs to happen here. Since the XmlSerializer cannot cast, we need to provide the code to do that, so the implicit operator is then overloaded (I never even knew you could do this!). The code for the AbstractXmlSerializer is this: ``` using System; using System.Collections.Generic; using System.Text; using System.Xml.Serialization; namespace Utility.Xml { public class AbstractXmlSerializer<AbstractType> : IXmlSerializable { // Override the Implicit Conversions Since the XmlSerializer // Casts to/from the required types implicitly. public static implicit operator AbstractType(AbstractXmlSerializer<AbstractType> o) { return o.Data; } public static implicit operator AbstractXmlSerializer<AbstractType>(AbstractType o) { return o == null ? null : new AbstractXmlSerializer<AbstractType>(o); } private AbstractType _data; /// <summary> /// [Concrete] Data to be stored/is stored as XML. /// </summary> public AbstractType Data { get { return _data; } set { _data = value; } } /// <summary> /// **DO NOT USE** This is only added to enable XML Serialization. /// </summary> /// <remarks>DO NOT USE THIS CONSTRUCTOR</remarks> public AbstractXmlSerializer() { // Default Ctor (Required for Xml Serialization - DO NOT USE) } /// <summary> /// Initialises the Serializer to work with the given data. /// </summary> /// <param name="data">Concrete Object of the AbstractType Specified.</param> public AbstractXmlSerializer(AbstractType data) { _data = data; } #region IXmlSerializable Members public System.Xml.Schema.XmlSchema GetSchema() { return null; // this is fine as schema is unknown. } public void ReadXml(System.Xml.XmlReader reader) { // Cast the Data back from the Abstract Type. string typeAttrib = reader.GetAttribute("type"); // Ensure the Type was Specified if (typeAttrib == null) throw new ArgumentNullException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because no 'type' attribute was specified in the XML."); Type type = Type.GetType(typeAttrib); // Check the Type is Found. if (type == null) throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because the type specified in the XML was not found."); // Check the Type is a Subclass of the AbstractType. if (!type.IsSubclassOf(typeof(AbstractType))) throw new InvalidCastException("Unable to Read Xml Data for Abstract Type '" + typeof(AbstractType).Name + "' because the Type specified in the XML differs ('" + type.Name + "')."); // Read the Data, Deserializing based on the (now known) concrete type. reader.ReadStartElement(); this.Data = (AbstractType)new XmlSerializer(type).Deserialize(reader); reader.ReadEndElement(); } public void WriteXml(System.Xml.XmlWriter writer) { // Write the Type Name to the XML Element as an Attrib and Serialize Type type = _data.GetType(); // BugFix: Assembly must be FQN since Types can/are external to current. writer.WriteAttributeString("type", type.AssemblyQualifiedName); new XmlSerializer(type).Serialize(writer, _data); } #endregion } } ``` So, from there, how do we tell the XmlSerializer to work with our serializer rather than the default? We must pass our type within the Xml attributes type property, for example: ``` [XmlRoot("ClassWithAbstractCollection")] public class ClassWithAbstractCollection { private List<AbstractType> _list; [XmlArray("ListItems")] [XmlArrayItem("ListItem", Type = typeof(AbstractXmlSerializer<AbstractType>))] public List<AbstractType> List { get { return _list; } set { _list = value; } } private AbstractType _prop; [XmlElement("MyProperty", Type=typeof(AbstractXmlSerializer<AbstractType>))] public AbstractType MyProperty { get { return _prop; } set { _prop = value; } } public ClassWithAbstractCollection() { _list = new List<AbstractType>(); } } ``` Here you can see, we have a collection and a single property being exposed, and all we need to do is add the *type* named parameter to the Xml declaration, easy! :D **NOTE: If you use this code, I would really appreciate a shout-out. It will also help drive more people to the community :)** Now, but unsure as to what to do with answers here since they all had their pro's and con's. I'll upmod those that I feel were useful (no offence to those that weren't) and close this off once I have the rep :) Interesting problem and good fun to solve! :)
20,107
<p>This line in YUI's <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Reset CSS</a> is causing trouble for me:</p> <pre class="lang-css prettyprint-override"><code>address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } </code></pre> <p>It makes my <code>em</code> not italic and my <code>strong</code> not bold. Which is okay. I know how to override that in my own stylesheet.</p> <pre class="lang-css prettyprint-override"><code>strong, b { font-weight: bold; } em, i { font-style: italic; } </code></pre> <p>The problem comes in when I have text that's both <code>em</code> and <code>strong</code>. </p> <pre><code>&lt;strong&gt;This is bold, &lt;em&gt;and this is italic, but not bold&lt;/em&gt;&lt;/strong&gt; </code></pre> <p>My rule for <code>strong</code> makes it bold, but YUI's rule for <code>em</code> makes it normal again. How do I fix that? </p>
[ { "answer_id": 20118, "author": "palmsey", "author_id": 521, "author_profile": "https://Stackoverflow.com/users/521", "pm_score": 5, "selected": true, "text": "<p>If your strong declaration comes after YUI's yours should override it. You can force it like this:</p>\n\n<pre><code>strong, ...
2008/08/21
[ "https://Stackoverflow.com/questions/20107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/437/" ]
This line in YUI's [Reset CSS](http://developer.yahoo.com/yui/reset/) is causing trouble for me: ```css address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } ``` It makes my `em` not italic and my `strong` not bold. Which is okay. I know how to override that in my own stylesheet. ```css strong, b { font-weight: bold; } em, i { font-style: italic; } ``` The problem comes in when I have text that's both `em` and `strong`. ``` <strong>This is bold, <em>and this is italic, but not bold</em></strong> ``` My rule for `strong` makes it bold, but YUI's rule for `em` makes it normal again. How do I fix that?
If your strong declaration comes after YUI's yours should override it. You can force it like this: ``` strong, b, strong *, b * { font-weight: bold; } em, i, em *, i * { font-style: italic; } ``` If you still support IE7 you'll need to add `!important`. ``` strong, b, strong *, b * { font-weight: bold !important; } em, i, em *, i * { font-style: italic !important; } ``` This works - see for yourself: ```css /*YUI styles*/ address,caption,cite,code,dfn,em,strong,th,var { font-style: normal; font-weight: normal; } /*End YUI styles =*/ strong, b, strong *, b * { font-weight: bold; } em, i, em *, i * { font-style: italic; } ``` ```html <strong>Bold</strong> - <em>Italic</em> - <strong>Bold and <em>Italic</em></strong> ```
20,146
<p>I'm looking for something like the <code>tempfile</code> module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too...</p> <p>It seems, .NET does not have the &quot;batteries included&quot; features of the <code>tempfile</code> module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (<code>mkstemp()</code> I think): <a href="https://docs.python.org/library/tempfile.html" rel="nofollow noreferrer">https://docs.python.org/library/tempfile.html</a></p> <hr /> <p>Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...</p>
[ { "answer_id": 20150, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 0, "selected": false, "text": "<p>I don't know of any built in (within the framework) classes to do this, but I imagine it wouldn't be too much of an issue...
2008/08/21
[ "https://Stackoverflow.com/questions/20146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I'm looking for something like the `tempfile` module in Python: A (preferably) secure way to open a file for writing to. This should be easy to delete when I'm done too... It seems, .NET does not have the "batteries included" features of the `tempfile` module, which not only creates the file, but returns the file descriptor (old school, I know...) to it along with the path. At the same time, it makes sure only the creating user can access the file and whatnot (`mkstemp()` I think): <https://docs.python.org/library/tempfile.html> --- Ah, yes, I can see that. But GetTempFileName does have a drawback: There is a race condition between when the file was created (upon call to GetTempFileName a 0-Byte file gets created) and when I get to open it (after return of GetTempFileName). This might be a security issue, although not for my current application...
I've also had the same requirement before, and I've created a small class to solve it: ``` public sealed class TemporaryFile : IDisposable { public TemporaryFile() : this(Path.GetTempPath()) { } public TemporaryFile(string directory) { Create(Path.Combine(directory, Path.GetRandomFileName())); } ~TemporaryFile() { Delete(); } public void Dispose() { Delete(); GC.SuppressFinalize(this); } public string FilePath { get; private set; } private void Create(string path) { FilePath = path; using (File.Create(FilePath)) { }; } private void Delete() { if (FilePath == null) return; File.Delete(FilePath); FilePath = null; } } ``` It creates a temporary file in a folder you specify or in the system temporary folder. It's a disposable class, so at the end of its life (either `Dispose` or the destructor), it deletes the file. You get the name of the file created (and path) through the `FilePath` property. You can certainly extend it to also open the file for writing and return its associated `FileStream`. An example usage: ``` using (var tempFile = new TemporaryFile()) { // use the file through tempFile.FilePath... } ```
20,148
<p>I'm working on a projects which involves a lot of database writes, I'd say (<em>70% inserts and 30% reads</em>). This ratio would also include updates which I consider to be one read and one write. The reads can be dirty (e.g. I don't need 100% accurate information at the time of read).<br> The task in question will be doing over 1 million database transactions an hour. </p> <p>I've read a bunch of stuff on the web about the differences between MyISAM and InnoDB, and MyISAM seems like the obvious choice to me for the particular database/tables that I'll be using for this task. From what I seem to be reading, InnoDB is good if transactions are needed since row level locking is supported.</p> <p>Does anybody have any experience with this type of load (or higher)? Is MyISAM the way to go?</p>
[ { "answer_id": 22733, "author": "rix0rrr", "author_id": 2474, "author_profile": "https://Stackoverflow.com/users/2474", "pm_score": 8, "selected": false, "text": "<p>I'm not a database expert, and I do not speak from experience. However:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refma...
2008/08/21
[ "https://Stackoverflow.com/questions/20148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2013/" ]
I'm working on a projects which involves a lot of database writes, I'd say (*70% inserts and 30% reads*). This ratio would also include updates which I consider to be one read and one write. The reads can be dirty (e.g. I don't need 100% accurate information at the time of read). The task in question will be doing over 1 million database transactions an hour. I've read a bunch of stuff on the web about the differences between MyISAM and InnoDB, and MyISAM seems like the obvious choice to me for the particular database/tables that I'll be using for this task. From what I seem to be reading, InnoDB is good if transactions are needed since row level locking is supported. Does anybody have any experience with this type of load (or higher)? Is MyISAM the way to go?
I have briefly [discussed](http://developer99.blogspot.com/2011/07/mysql-innodb-vs-myisam.html) this question in a table so you can conclude whether to go with **InnoDB** or **MyISAM**. Here is a small overview of which db storage engine you should use in which situation: ``` MyISAM InnoDB ---------------------------------------------------------------- Required full-text search Yes 5.6.4 ---------------------------------------------------------------- Require transactions Yes ---------------------------------------------------------------- Frequent select queries Yes ---------------------------------------------------------------- Frequent insert, update, delete Yes ---------------------------------------------------------------- Row locking (multi processing on single table) Yes ---------------------------------------------------------------- Relational base design Yes ``` **Summary** * In almost all circumstances, **InnoDB** is the best way to go * But, frequent reading, almost no writing, use **MyISAM** * Full-text search in MySQL <= 5.5, use **MyISAM**
20,156
<p>Is there an easy way in C# to create <a href="http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29" rel="noreferrer">Ordinals</a> for a number? For example:</p> <ul> <li>1 returns 1st</li> <li>2 returns 2nd</li> <li>3 returns 3rd</li> <li>...etc</li> </ul> <p>Can this be done through <code>String.Format()</code> or are there any functions available to do this?</p>
[ { "answer_id": 20166, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 4, "selected": false, "text": "<p>You'll have to roll your own. From the top of my head:</p>\n\n<pre><code>public static string Ordinal(this int number)\n{\n var...
2008/08/21
[ "https://Stackoverflow.com/questions/20156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
Is there an easy way in C# to create [Ordinals](http://en.wikipedia.org/wiki/Ordinal_numbers_%28linguistics%29) for a number? For example: * 1 returns 1st * 2 returns 2nd * 3 returns 3rd * ...etc Can this be done through `String.Format()` or are there any functions available to do this?
This page gives you a complete listing of all custom numerical formatting rules: [Custom numeric format strings](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings) As you can see, there is nothing in there about ordinals, so it can't be done using `String.Format`. However its not really that hard to write a function to do it. ``` public static string AddOrdinal(int num) { if( num <= 0 ) return num.ToString(); switch(num % 100) { case 11: case 12: case 13: return num + "th"; } switch(num % 10) { case 1: return num + "st"; case 2: return num + "nd"; case 3: return num + "rd"; default: return num + "th"; } } ``` Update: Technically Ordinals don't exist for <= 0, so I've updated the code above. Also removed the redundant `ToString()` methods. Also note, this is not internationalized. I've no idea what ordinals look like in other languages.
20,185
<p>I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. </p> <p>Is there any way to hide a constructor from all code except a parent class.</p> <p>I'd like to do this basically</p> <pre><code>public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } } public class ConcreteClassA : AbstractClass { } public class ConcreteClassB : AbstractClass { } </code></pre> <p>But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this?</p> <p><strong>UPDATE</strong><br> I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class.</p> <p>To me, the simplest solution is to <a href="https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200">make child classes as samjudson mentioned</a>. I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization.</p> <p>I guess there's no easy solution to this...</p>
[ { "answer_id": 20199, "author": "Vaibhav", "author_id": 380, "author_profile": "https://Stackoverflow.com/users/380", "pm_score": 1, "selected": false, "text": "<p>No, I don't think we can do that.</p>\n" }, { "answer_id": 20200, "author": "samjudson", "author_id": 1908, ...
2008/08/21
[ "https://Stackoverflow.com/questions/20185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I have a collection of classes that inherit from an abstract class I created. I'd like to use the abstract class as a factory for creating instances of concrete implementations of my abstract class. Is there any way to hide a constructor from all code except a parent class. I'd like to do this basically ``` public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } } public class ConcreteClassA : AbstractClass { } public class ConcreteClassB : AbstractClass { } ``` But I want to prevent anyone from directly instantiating the 2 concrete classes. I want to ensure that only the MakeAbstractClass() method can instantiate the base classes. Is there any way to do this? **UPDATE** I don't need to access any specific methods of ConcreteClassA or B from outside of the Abstract class. I only need the public methods my Abstract class provides. I don't really need to prevent the Concrete classes from being instantiated, I'm just trying to avoid it since they provide no new public interfaces, just different implementations of some very specific things internal to the abstract class. To me, the simplest solution is to [make child classes as samjudson mentioned](https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20200). I'd like to avoid this however since it would make my abstract class' file a lot bigger than I'd like it to be. I'd rather keep classes split out over a few files for organization. I guess there's no easy solution to this...
You can make the sub classes child classes, something like this: ``` public abstract class AbstractClass { public static AbstractClass MakeAbstractClass(string args) { if (args == "a") return new ConcreteClassA(); if (args == "b") return new ConcreteClassB(); } private class ConcreteClassA : AbstractClass { } private class ConcreteClassB : AbstractClass { } } ``` [@Vaibhav](https://stackoverflow.com/questions/20185/is-there-a-way-to-make-a-constructor-only-visible-to-a-parent-class-in-c#20220) This does indeed mean that the classes are also hidden. But this is as far as I am aware the only way to completely hide the constructor. Edit: As others have mentioned the same thing can be accomplished using Reflection, which might actually be closer to what you would like to be the case - for example the above method replies on the concrete classes being inside the same file as the Abstract class, which probably isn't very convenient. Having said that this way is a nice 'Hack', and good if the number and complexity of the concrete classes is low.
20,227
<p>Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string?</p> <p>I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far:</p> <p>** note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle.</p> <pre><code>public class TripleDESTest { public static void main(String[] args) { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); System.out.println(decodedtext); } public byte[] encrypt(String message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j &lt; 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText); return cipherText; } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} return null; } public String decrypt(byte[] message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j &lt; 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); //final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return plainText.toString(); } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } </code></pre>
[ { "answer_id": 20670, "author": "Boris Terzic", "author_id": 1996, "author_profile": "https://Stackoverflow.com/users/1996", "pm_score": 7, "selected": true, "text": "<p>Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not...
2008/08/21
[ "https://Stackoverflow.com/questions/20227", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
Every method I write to encode a string in Java using 3DES can't be decrypted back to the original string. Does anyone have a simple code snippet that can just encode and then decode the string back to the original string? I know I'm making a very silly mistake somewhere in this code. Here's what I've been working with so far: \*\* note, I am not returning the BASE64 text from the encrypt method, and I am not base64 un-encoding in the decrypt method because I was trying to see if I was making a mistake in the BASE64 part of the puzzle. ``` public class TripleDESTest { public static void main(String[] args) { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); System.out.println(decodedtext); } public byte[] encrypt(String message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); final String encodedCipherText = new sun.misc.BASE64Encoder().encode(cipherText); return cipherText; } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} return null; } public String decrypt(byte[] message) { try { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9".getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); //final byte[] encData = new sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return plainText.toString(); } catch (java.security.InvalidAlgorithmParameterException e) { System.out.println("Invalid Algorithm"); } catch (javax.crypto.NoSuchPaddingException e) { System.out.println("No Such Padding"); } catch (java.security.NoSuchAlgorithmException e) { System.out.println("No Such Algorithm"); } catch (java.security.InvalidKeyException e) { System.out.println("Invalid Key"); } catch (BadPaddingException e) { System.out.println("Invalid Key");} catch (IllegalBlockSizeException e) { System.out.println("Invalid Key");} catch (UnsupportedEncodingException e) { System.out.println("Invalid Key");} catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } } ```
Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the **contents**). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string: ``` import java.security.MessageDigest; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class TripleDESTest { public static void main(String[] args) throws Exception { String text = "kyle boon"; byte[] codedtext = new TripleDESTest().encrypt(text); String decodedtext = new TripleDESTest().decrypt(codedtext); System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array System.out.println(decodedtext); // This correctly shows "kyle boon" } public byte[] encrypt(String message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9" .getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, key, iv); final byte[] plainTextBytes = message.getBytes("utf-8"); final byte[] cipherText = cipher.doFinal(plainTextBytes); // final String encodedCipherText = new sun.misc.BASE64Encoder() // .encode(cipherText); return cipherText; } public String decrypt(byte[] message) throws Exception { final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest("HG58YZ3CR9" .getBytes("utf-8")); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } final SecretKey key = new SecretKeySpec(keyBytes, "DESede"); final IvParameterSpec iv = new IvParameterSpec(new byte[8]); final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding"); decipher.init(Cipher.DECRYPT_MODE, key, iv); // final byte[] encData = new // sun.misc.BASE64Decoder().decodeBuffer(message); final byte[] plainText = decipher.doFinal(message); return new String(plainText, "UTF-8"); } } ```
20,245
<p>I am doing an e-commerce solution in ASP.NET which uses <a href="https://www.paypal.com/IntegrationCenter/ic_standard_home.html" rel="noreferrer">PayPal's Website Payments Standard</a> service. Together with that I use a service they offer (<a href="https://www.paypal.com/IntegrationCenter/ic_pdt.html" rel="noreferrer">Payment Data Transfer</a>) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form :</p> <blockquote> <p>SUCCESS<br> first_name=Jane+Doe<br> last_name=Smith<br> payment_status=Completed<br> payer_email=janedoesmith%40hotmail.com<br> payment_gross=3.99<br> mc_currency=USD<br> custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham</p> </blockquote> <p>Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.</p>
[ { "answer_id": 20256, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 0, "selected": false, "text": "<p>If I'm reading your question right, I think you're looking for the <a href=\"http://msdn.microsoft.com/en-us/library/syst...
2008/08/21
[ "https://Stackoverflow.com/questions/20245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801/" ]
I am doing an e-commerce solution in ASP.NET which uses [PayPal's Website Payments Standard](https://www.paypal.com/IntegrationCenter/ic_standard_home.html) service. Together with that I use a service they offer ([Payment Data Transfer](https://www.paypal.com/IntegrationCenter/ic_pdt.html)) that sends you back order information after a user has completed a payment. The final thing I need to do is to parse the POST request from them and persist the info in it. The HTTP request's content is in this form : > > SUCCESS > > first\_name=Jane+Doe > > last\_name=Smith > > payment\_status=Completed > > payer\_email=janedoesmith%40hotmail.com > > payment\_gross=3.99 > > mc\_currency=USD > > custom=For+the+purchase+of+the+rare+book+Green+Eggs+%26+Ham > > > Basically I want to parse this information and do something meaningful, like send it through e-mail or save it in DB. My question is what is the right approach to do parsing raw HTTP data in ASP.NET, not how the parsing itself is done.
Something like this placed in your onload event. ``` if (Request.RequestType == "POST") { using (StreamReader sr = new StreamReader(Request.InputStream)) { if (sr.ReadLine() == "SUCCESS") { /* Do your parsing here */ } } } ``` Mind you that they might want some special sort of response to (ie; not your full webpage), so you might do something like this after you're done parsing. ``` Response.Clear(); Response.ContentType = "text/plain"; Response.Write("Thanks!"); Response.End(); ``` Update: this should be done in a Generic Handler (.ashx) file in order to avoid a great deal of overhead from the page model. Check out [this article](http://www.aspcode.net/Creating-an-ASHX-handler-in-ASPNET.aspx) for more information about .ashx files
20,249
<p>We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use <code>ClientScript.RegisterClientScriptResource</code> and these are 404-ing after the merge (These worked before the merge).</p> <p>For example one of our controls would look like</p> <pre><code>namespace Company.WebControls { public class ControlA: CompositeControl, INamingContainer { protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js"); } } } </code></pre> <p>It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following:</p> <pre><code>[assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")] </code></pre> <p>After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): <code>"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll</code></p>
[ { "answer_id": 20380, "author": "John Hoven", "author_id": 1907, "author_profile": "https://Stackoverflow.com/users/1907", "pm_score": 3, "selected": true, "text": "<p>OK - I got this working. It looks like the primary assembly was the only one whose assembly attributes were being copie...
2008/08/21
[ "https://Stackoverflow.com/questions/20249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1907/" ]
We're attemtping to merge our DLL's into one for deployment, thus ILMerge. Almost everything seems to work great. We have a couple web controls that use `ClientScript.RegisterClientScriptResource` and these are 404-ing after the merge (These worked before the merge). For example one of our controls would look like ``` namespace Company.WebControls { public class ControlA: CompositeControl, INamingContainer { protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); this.Page.ClientScript.RegisterClientScriptResource(typeof(ControlA), "Company.WebControls.ControlA.js"); } } } ``` It would be located in Project WebControls, assembly Company.WebControls. Underneath would be ControlA.cs and ControlA.js. ControlA.js is marked as an embedded resource. In the AssemblyInfo.cs I include the following: ``` [assembly: System.Web.UI.WebResource("Company.WebControls.ControlA.js", "application/x-javascript")] ``` After this is merged into CompanyA.dll, what is the proper way to reference this web resource? The ILMerge command line is as follows (from the bin directory after the build): `"C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../CompanySK.snk /wildcards:True /copyattrs:True /out:Company.dll Company.*.dll`
OK - I got this working. It looks like the primary assembly was the only one whose assembly attributes were being copied. With copyattrs set, the last one in would win, not a merge (as far as I can tell). I created a dummy project to reference the other DLL's and included all the web resources from those projects in the dummy assembly info - now multiple resources from multiple projects are all loading correctly. Final post-build command line for dummy project: "C:\Program Files\Microsoft\ILMerge\ILMerge.exe" /keyfile:../../Company.snk /wildcards:True /out:Company.dll Company.Merge.dll Company.\*.dll
20,272
<p>In a macro for Visual Studio 6, I wanted to run an external program, so I typed:</p> <pre><code>shell("p4 open " + ActiveDocument.FullName) </code></pre> <p>Which gave me a type mismatch runtime error. What I ended up having to type was this:</p> <pre><code>Dim wshShell Set wshShell = CreateObject("WScript.Shell") strResult = wshShell.Run("p4 open " + ActiveDocument.FullName) </code></pre> <p>What is going on here? Is that nonsense really necessary or have I missed something?</p>
[ { "answer_id": 20304, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 1, "selected": false, "text": "<p>VBScript isn't Visual Basic.</p>\n" }, { "answer_id": 20353, "author": "Bryan Roth", "author_id": 2...
2008/08/21
[ "https://Stackoverflow.com/questions/20272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1105/" ]
In a macro for Visual Studio 6, I wanted to run an external program, so I typed: ``` shell("p4 open " + ActiveDocument.FullName) ``` Which gave me a type mismatch runtime error. What I ended up having to type was this: ``` Dim wshShell Set wshShell = CreateObject("WScript.Shell") strResult = wshShell.Run("p4 open " + ActiveDocument.FullName) ``` What is going on here? Is that nonsense really necessary or have I missed something?
As [lassevk](https://stackoverflow.com/questions/20272/why-doesnt-shell-work-in-vbscript-in-vs6#20304) pointed out, VBScript is not Visual Basic. I believe the only built in object in VBScript is the WScript object. ``` WScript.Echo "Hello, World!" ``` From the docs > > The WScript object is the root object of the Windows Script Host > object model hierarchy. It never needs to be instantiated before invoking its > properties and methods, and it is always available from any script file. > > > Everything else must be created via the CreateObject call. Some of those objects are [listed here](http://msdn.microsoft.com/en-us/library/f51wc7hz(VS.85).aspx). The Shell object is one of the *other* objects that you need to create if you want to call methods on it. One caveat, is that RegExp is *sort of* built in, in that you can instantiate a RegExp object like so in VBScript: ``` Dim r as New RegExp ```
20,298
<p>I have something like this:</p> <pre> barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration))); </pre> <p>Now, how would you stop that animation (the <code>DoubleAnimation</code>)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...</p>
[ { "answer_id": 20306, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 8, "selected": true, "text": "<p>To stop it, call <code>BeginAnimation</code> again with the second argument set to <code>null</code>.</p>\n" }, ...
2008/08/21
[ "https://Stackoverflow.com/questions/20298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2260/" ]
I have something like this: ``` barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation( barProgress.Value, dNextProgressValue, new Duration(TimeSpan.FromSeconds(dDuration))); ``` Now, how would you stop that animation (the `DoubleAnimation`)? The reason I want to do this, is because I would like to start new animations (this seems to work, but it's hard to tell) and eventually stop the last animation...
To stop it, call `BeginAnimation` again with the second argument set to `null`.
20,326
<p>I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced.</p> <p>I have checked and checked the code, and I can't find the cause.</p> <p>Here are both call stacks which end in a page_load</p> <p>First postback (generated by teh ComboBox's autopostback)</p> <p><a href="http://www.juanformoso.com.ar/images/callstack1.jpg" rel="nofollow noreferrer">Postback call stack</a> (broken)</p> <p>Second postback (this is what I want to find why it's happening)</p> <p><a href="http://www.juanformoso.com.ar/images/callstack2.jpg" rel="nofollow noreferrer">alt text</a> (broken)</p> <p>Any suggestion? What can I check?</p>
[ { "answer_id": 20348, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 0, "selected": false, "text": "<p>First thing I would look for is that you don't have the second ComboBox's AutoPostBack property set to true. If you...
2008/08/21
[ "https://Stackoverflow.com/questions/20326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I have a ASP.NET 1.1 application, and I'm trying to find out why when I change a ComboBox which value is used to fill another one (parent-child relation), two postbacks are produced. I have checked and checked the code, and I can't find the cause. Here are both call stacks which end in a page\_load First postback (generated by teh ComboBox's autopostback) [Postback call stack](http://www.juanformoso.com.ar/images/callstack1.jpg) (broken) Second postback (this is what I want to find why it's happening) [alt text](http://www.juanformoso.com.ar/images/callstack2.jpg) (broken) Any suggestion? What can I check?
It's a very specific problem with this code, I doubt it will be useful for someone else, but here it goes: A check was added to the combo's `onchange` with an if, if the condition was met, an explicit call to the postback function was made. If the combo was set to `AutoPostback`, asp.net added the postback call again, producing the two postbacks... The generated html was like this: ``` [select onchange="javascript: if (CustomFunction()){__doPostBack('name','')}; __doPostBack('name','')"] ```
20,346
<p>What are attributes in .NET, what are they good for, and how do I create my own attributes?</p>
[ { "answer_id": 20351, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "<p>An attribute is a class that contains some bit of functionality that you can apply to objects in your code. To crea...
2008/08/21
[ "https://Stackoverflow.com/questions/20346", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595/" ]
What are attributes in .NET, what are they good for, and how do I create my own attributes?
Metadata. Data about your objects/methods/properties. For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriately. ``` public class DisplayWrapper { private UnderlyingClass underlyingObject; public DisplayWrapper(UnderlyingClass u) { underlyingObject = u; } [DisplayOrder(1)] public int SomeInt { get { return underlyingObject .SomeInt; } } [DisplayOrder(2)] public DateTime SomeDate { get { return underlyingObject .SomeDate; } } } ``` Thereby ensuring that SomeInt is always displayed before SomeDate when working with my custom GUI components. However, you'll see them most commonly used outside of the direct coding environment. For example the Windows Designer uses them extensively so it knows how to deal with custom made objects. Using the BrowsableAttribute like so: ``` [Browsable(false)] public SomeCustomType DontShowThisInTheDesigner { get{/*do something*/} } ``` Tells the designer not to list this in the available properties in the Properties window at design time for example. You *could* also use them for code-generation, pre-compile operations (such as Post-Sharp) or run-time operations such as Reflection.Emit. For example, you could write a bit of code for profiling that transparently wrapped every single call your code makes and times it. You could "opt-out" of the timing via an attribute that you place on particular methods. ``` public void SomeProfilingMethod(MethodInfo targetMethod, object target, params object[] args) { bool time = true; foreach (Attribute a in target.GetCustomAttributes()) { if (a.GetType() is NoTimingAttribute) { time = false; break; } } if (time) { StopWatch stopWatch = new StopWatch(); stopWatch.Start(); targetMethod.Invoke(target, args); stopWatch.Stop(); HandleTimingOutput(targetMethod, stopWatch.Duration); } else { targetMethod.Invoke(target, args); } } ``` Declaring them is easy, just make a class that inherits from Attribute. ``` public class DisplayOrderAttribute : Attribute { private int order; public DisplayOrderAttribute(int order) { this.order = order; } public int Order { get { return order; } } } ``` And remember that when you use the attribute you can omit the suffix "attribute" the compiler will add that for you. **NOTE:** Attributes don't do anything by themselves - there needs to be some other code that uses them. Sometimes that code has been written for you but sometimes you have to write it yourself. For example, the C# compiler cares about some and certain frameworks frameworks use some (e.g. NUnit looks for [TestFixture] on a class and [Test] on a test method when loading an assembly). So when creating your own custom attribute be aware that it will not impact the behaviour of your code at all. You'll need to write the other part that checks attributes (via reflection) and act on them.
20,386
<p>What are all the possible ways in which we can get memory leaks in .NET?</p> <p>I know of two:</p> <ol> <li>Not properly un-registering <a href="http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx" rel="nofollow noreferrer">Event Handlers/Delegates</a>.</li> <li>Not disposing dynamic child controls in Windows Forms:</li> </ol> <p>Example:</p> <pre><code>// Causes Leaks Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); // Correct Code Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); label.Dispose(); </code></pre> <p><strong>Update</strong>: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.</p> <hr> <p>Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.</p> <p>In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).</p> <p><strong>So, what are the various possible ways in which such a memory leak can happen?</strong></p>
[ { "answer_id": 20393, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 4, "selected": false, "text": "<p>There's no way to provide a comprehensive list... this is very much like asking \"How can you get wet?\"</p>\n\n<p>That s...
2008/08/21
[ "https://Stackoverflow.com/questions/20386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/380/" ]
What are all the possible ways in which we can get memory leaks in .NET? I know of two: 1. Not properly un-registering [Event Handlers/Delegates](http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx). 2. Not disposing dynamic child controls in Windows Forms: Example: ``` // Causes Leaks Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); // Correct Code Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); label.Dispose(); ``` **Update**: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++. --- Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks. In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question). **So, what are the various possible ways in which such a memory leak can happen?**
Block the finalizer thread. No other objects will be garbage collected until the finalizer thread is unblocked. Thus the amount of memory used will grow and grow. Further reading: <http://dotnetdebug.net/2005/06/22/blocked-finalizer-thread/>
20,391
<p>I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share?</p> <p>I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.</p>
[ { "answer_id": 20408, "author": "Jedi Master Spooky", "author_id": 1154, "author_profile": "https://Stackoverflow.com/users/1154", "pm_score": 2, "selected": false, "text": "<p>svnadmin dump C:\\SVNRepositorio\\Repositorio > \\\\Backups\\BkTmpSubversion\\subversiontemp.dump</p>\n\n<p>Try...
2008/08/21
[ "https://Stackoverflow.com/questions/20391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1946/" ]
I have a svn repo on my machine (Windows). Anyone have a script to back it up to a network share? I'm using the repo locally since I'm disconnected a lot. The network share is on a server with a backup strategy. I'm a perfect candidate for git/hg but I don't want to give up my VS integration just yet.
I wrote a batch file to do this for a bunch of repos, you could just hook that batch file up to windows scheduler and run it on a schedule. ``` svnadmin hotcopy m:\Source\Q4Press\Repo m:\SvnOut\Q4Press ``` I use the hotcopy but the svn dump would work just as well.
20,426
<p>I have a tree encoded in a MySQL database as edges:</p> <pre><code>CREATE TABLE items ( num INT, tot INT, PRIMARY KEY (num) ); CREATE TABLE tree ( orig INT, term INT FOREIGN KEY (orig,term) REFERENCES items (num,num) ) </code></pre> <p>For each leaf in the tree, <code>items.tot</code> is set by someone. For interior nodes, <code>items.tot</code> needs to be the sum of it's children. Running the following query repeatedly would generate the desired result.</p> <pre><code>UPDATE items SET tot = ( SELECT SUM(b.tot) FROM tree JOIN items AS b ON tree.term = b.num WHERE tree.orig=items.num) WHERE EXISTS (SELECT * FROM tree WHERE orig=items.num) </code></pre> <p>(note this actually doesn't work but that's beside the point)</p> <p>Assume that the database exists and the invariant are already satisfied. </p> <p>The question is:</p> <blockquote> <p><strong>What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of <code>tot</code> on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree.</strong></p> </blockquote> <p>Some thoughts I have had:</p> <ul> <li>Full Invalidation, after any update, recompute everything (Um... No)</li> <li>Set a trigger on the items table to update the parent of any row that is updated <ul> <li>This would be recursive (updates trigger updates, trigger updates, ...)</li> <li>Doesn't work, MySQL can't update the table that kicked off the trigger</li> </ul></li> <li>Set a trigger to schedule an update of the parent of any row that is updated <ul> <li>This would be iterative (get an item from the schedule, processing it schedules more items)</li> <li>What kicks this off? Trust client code to get it right?</li> <li>An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own.</li> </ul></li> </ul> <p>An ideal solution would generalize to other "aggregating invariants"</p> <p>FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it. :-)</p>
[ { "answer_id": 21019, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 3, "selected": false, "text": "<p>Xcode has refactoring for C and Objective-C built in. Just select what you'd like to refactor, choose \"Refactor...\" ...
2008/08/21
[ "https://Stackoverflow.com/questions/20426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
I have a tree encoded in a MySQL database as edges: ``` CREATE TABLE items ( num INT, tot INT, PRIMARY KEY (num) ); CREATE TABLE tree ( orig INT, term INT FOREIGN KEY (orig,term) REFERENCES items (num,num) ) ``` For each leaf in the tree, `items.tot` is set by someone. For interior nodes, `items.tot` needs to be the sum of it's children. Running the following query repeatedly would generate the desired result. ``` UPDATE items SET tot = ( SELECT SUM(b.tot) FROM tree JOIN items AS b ON tree.term = b.num WHERE tree.orig=items.num) WHERE EXISTS (SELECT * FROM tree WHERE orig=items.num) ``` (note this actually doesn't work but that's beside the point) Assume that the database exists and the invariant are already satisfied. The question is: > > **What is the most practical way to update the DB while maintaining this requirement? Updates may move nodes around or alter the value of `tot` on leaf nodes. It can be assumed that leaf nodes will stay as leaf nodes, interior nodes will stay as interior nodes and the whole thing will remain as a proper tree.** > > > Some thoughts I have had: * Full Invalidation, after any update, recompute everything (Um... No) * Set a trigger on the items table to update the parent of any row that is updated + This would be recursive (updates trigger updates, trigger updates, ...) + Doesn't work, MySQL can't update the table that kicked off the trigger * Set a trigger to schedule an update of the parent of any row that is updated + This would be iterative (get an item from the schedule, processing it schedules more items) + What kicks this off? Trust client code to get it right? + An advantage is that if the updates are ordered correctly fewer sums need to be computer. But that ordering is a complication in and of it's own. An ideal solution would generalize to other "aggregating invariants" FWIW I know this is "a bit overboard", but I'm doing this for fun (Fun: verb, Finding the impossible by doing it. :-)
You sound as if you're looking for three major things: code templates, refactoring tools, and auto-completion. The good news is that Xcode 3 and later come with superb auto-completion and template support. By default, you have to explicitly request completion by hitting the escape key. (This actually works in all `NSTextView`s; try it!) If you want to have the completions appear automatically, you can go to **Preferences** -> **Code Sense** and set the pop-up to appear automatically after a few seconds. You should find good completions for C and Objective-C code, and pretty good completions for C++. Xcode also has a solid template/skeleton system that you can use. You can see what templates are available by default by going to Edit -> Insert Text Macro. Of course, you don't want to insert text macros with the mouse; that defeats the point. Instead, you have two options: 1. Back in **Preferences**,go to **Key Bindings**, and then, under **Menu Key Bindings**, assign a specific shortcut to macros you use often. I personally don't bother doing this, but I know plenty of great Mac devs who do 2. Use the `CompletionPrefix`. By default, nearly all of the templates have a special prefix that, if you type and then hit the escape key, will result in the template being inserted. You can use Control-/ to move between the completion fields. You can see [a full list of Xcode's default macros and their associated `CompletionPrefix`es](http://crookedspin.com/2005/06/10/xcode-macros/) at [Crooked Spin](http://crookedspin.com). You can also add your own macros, or modify the defaults. To do so, edit the file `/Developer/Library/Xcode/Specifications/{C,HTML}.xctxtmacro`. The syntax should be self-explanatory, if not terribly friendly. Unfortunately, if you're addicted to R#, you will be disappointed by your refactoring options. Basic refactoring is provided within Xcode through the context menu or by hitting Shift-Apple-J. From there, you can extract and rename methods, promote and demote them through the class hierarchy, and a few other common operations. Unfortunately, neither Xcode nor any third-party utilities offer anything approaching Resharper, so on that front, you're currently out of luck. Thankfully, Apple has already demonstrated versions of Xcode in the works that have vastly improved refactoring capabilities, so hopefully you won't have to wait too long before the situation starts to improve.
20,450
<p>I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information.</p> <p>The command used to paste into Word will be something like: oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard)</p> <pre><code>{\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl ;\red255\green255\blue140;} \viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par </code></pre> <p>Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do.</p>
[ { "answer_id": 20498, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "<p>You can strip out the tags with regular expressions. Just make sure that your expressions will not filter tags that we...
2008/08/21
[ "https://Stackoverflow.com/questions/20450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1508/" ]
I'd like to take some RTF input and clean it to remove all RTF formatting except \ul \b \i to paste it into Word with minor format information. The command used to paste into Word will be something like: oWord.ActiveDocument.ActiveWindow.Selection.PasteAndFormat(0) (with some RTF text already in the Clipboard) ``` {\rtf1\ansi\deff0{\fonttbl{\f0\fnil\fcharset0 Courier New;}} {\colortbl ;\red255\green255\blue140;} \viewkind4\uc1\pard\highlight1\lang3084\f0\fs18 The company is a global leader in responsible tourism and was \ul the first major hotel chain in North America\ulnone to embrace environmental stewardship within its daily operations\highlight0\par ``` Do you have any idea on how I can clean up the RTF safely with some regular expressions or something? I am using VB.NET to do the processing but any .NET language sample will do.
I would use a hidden RichTextBox, set the Rtf member, then retrieve the Text member to sanitize the RTF in a well-supported way. Then I would use manually inject the desired formatting afterwards.
20,465
<p>I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly.</p> <p>The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception:</p> <blockquote> <p>ListObject cannot be bound because it cannot be resized to fit the data. The ListObject failed to add new rows. This can be caused because of inability to move objects below of the list object.</p> <blockquote> <p>Inner exception: "Insert method of Range class failed"<br> Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject</p> </blockquote> </blockquote> <p>I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail.</p> <p>Basic code structure:</p> <pre><code>//at startup DataTable tbl = //get from database listObj1.SetDataBinding(tbl); DataTable tbl2 = //get from database listObj2.SetDataBinding(tbl2); //in buttonClick event handler DataTable tbl = //get different info from database //have tried with and without unbinding old source listObj1.SetDataBinding(tbl); &lt;-- exception here DataTable tbl2 = //get different info from database listObj2.SetDataBinding(tbl2); </code></pre> <p>Note that this exception occurs even when the ListObject is shrinking, and not only when it grows.</p>
[ { "answer_id": 23735, "author": "Guy", "author_id": 1463, "author_profile": "https://Stackoverflow.com/users/1463", "pm_score": 0, "selected": false, "text": "<p>Just an idea of something to try to see if it gives you more info: Try resizes the list object before the exception line and s...
2008/08/21
[ "https://Stackoverflow.com/questions/20465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940/" ]
I'm developing an Excel 2007 add-in using Visual Studio Tools for Office (2008). I have one sheet with several ListObjects on it, which are being bound to datatables on startup. When they are bound, they autosize correctly. The problem comes when they are re-bound. I have a custom button on the ribbon bar which goes back out to the database and retrieves different information based on some criteria that the user inputs. This new data comes back and is re-bound to the ListObjects - however, this time they are not resized and I get an exception: > > ListObject cannot be bound because it > cannot be resized to fit the data. The > ListObject failed to add new rows. > This can be caused because of > inability to move objects below of the > list object. > > > > > > > Inner exception: "Insert method of Range class failed" > > > > Reason: Microsoft.Office.Tools.Excel.FailureReason.CouldNotResizeListObject > > > > > > > > > I was not able to find anything very meaningful on this error on Google or MSDN. I have been trying to figure this out for a while, but to no avail. Basic code structure: ``` //at startup DataTable tbl = //get from database listObj1.SetDataBinding(tbl); DataTable tbl2 = //get from database listObj2.SetDataBinding(tbl2); //in buttonClick event handler DataTable tbl = //get different info from database //have tried with and without unbinding old source listObj1.SetDataBinding(tbl); <-- exception here DataTable tbl2 = //get different info from database listObj2.SetDataBinding(tbl2); ``` Note that this exception occurs even when the ListObject is shrinking, and not only when it grows.
If anyone else is having this problem, I have found the cause of this exception. ListObjects will automatically re-size on binding, as long as they do not affect any other objects on the sheet. Keep in mind that ListObjects can only affect the Ranges which they wrap around. In my case, the list object which was above the other one had fewer columns than the one below it. Let's say the top ListObject had 2 columns, and the bottom ListObject had 3 columns. When the top ListObject changed its number of rows, it had no ability to make any changes to the third column since it wasn't in it's underlying Range. This means that it couldn't shift any cells in the third column, and so the second ListObject couldn't be properly moved, resulting in my exception above. Changing the positions of the ListObjects to place the wider one above the smaller one works fine. Following the logic above, this now means that the wider ListObject can shift all of the columns of the second ListObject, and since there is nothing below the smaller one it can also shift any cells necessary. The reason I wasn't having any trouble on the initial binding is that both ListObjects were a single cell. Since this is not optimal in my case, I will probably use empty columns or try to play around with invisible columns if that's possible, but at least the cause is now clear.
20,467
<p>Are there any automatic methods for trimming a path string in .NET?</p> <p>For example:</p> <pre><code>C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx </code></pre> <p>becomes</p> <pre><code>C:\Documents...\demo data.emx </code></pre> <p>It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!</p>
[ { "answer_id": 20492, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>What you are thinking on the label is that it will put ... if it is longer than the width (not set to auto size), but that...
2008/08/21
[ "https://Stackoverflow.com/questions/20467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1490/" ]
Are there any automatic methods for trimming a path string in .NET? For example: ``` C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx ``` becomes ``` C:\Documents...\demo data.emx ``` It would be particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!
Use **TextRenderer.DrawText** with **TextFormatFlags.PathEllipsis** flag ``` void label_Paint(object sender, PaintEventArgs e) { Label label = (Label)sender; TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); } ``` > > Your code is 95% there. The only > problem is that the trimmed text is > drawn on top of the text which is > already on the label. > > > Yes thanks, I was aware of that. My intention was only to demonstrate use of `DrawText` method. I didn't know whether you want to manually create event for each label or just override `OnPaint()` method in inherited label. Thanks for sharing your final solution though.
20,484
<p>Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain.</p> <p>I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such:</p> <pre><code>SELECT Id, Name, Description FROM dbo.Card WHERE Description LIKE '%warrior%' OR Description LIKE '%fiend%' OR Description LIKE '%damage%' </code></pre> <p>But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this:</p> <pre><code>SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId </code></pre> <p>I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this:</p> <pre><code>SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%' </code></pre> <p>Is this possible/recommended?</p> <p>Is there a better way to do something like this?</p> <hr> <p>The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts.</p> <p>I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? </p> <p>Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?</p>
[ { "answer_id": 20513, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 1, "selected": false, "text": "<p>It seems like you are looking for full-text search. Because you want to query a set of keywords against the card descrip...
2008/08/21
[ "https://Stackoverflow.com/questions/20484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
Can/Should I use a LIKE criteria as part of an INNER JOIN when building a stored procedure/query? I'm not sure I'm asking the right thing, so let me explain. I'm creating a procedure that is going to take a list of keywords to be searched for in a column that contains text. If I was sitting at the console, I'd execute it as such: ``` SELECT Id, Name, Description FROM dbo.Card WHERE Description LIKE '%warrior%' OR Description LIKE '%fiend%' OR Description LIKE '%damage%' ``` But a trick I picked up a little while go to do "strongly typed" list parsing in a stored procedure is to parse the list into a table variable/temporary table, converting it to the proper type and then doing an INNER JOIN against that table in my final result set. This works great when sending say a list of integer IDs to the procedure. I wind up having a final query that looks like this: ``` SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblExclusiveCard ON dbo.Card.Id = @tblExclusiveCard.CardId ``` I want to use this trick with a list of strings. But since I'm looking for a particular keyword, I am going to use the LIKE clause. So ideally I'm thinking I'd have my final query look like this: ``` SELECT Id, Name, Description FROM dbo.Card INNER JOIN @tblKeyword ON dbo.Card.Description LIKE '%' + @tblKeyword.Value + '%' ``` Is this possible/recommended? Is there a better way to do something like this? --- The reason I'm putting wildcards on both ends of the clause is because there are "archfiend", "beast-warrior", "direct-damage" and "battle-damage" terms that are used in the card texts. I'm getting the impression that depending on the performance, I can either use the query I specified or use a full-text keyword search to accomplish the same task? Other than having the server do a text index on the fields I want to text search, is there anything else I need to do?
Your first query will work but will require a full table scan because any index on that column will be ignored. You will also have to do some dynamic SQL to generate all your LIKE clauses. Try a full text search if your using SQL Server or check out one of the [Lucene](http://lucene.apache.org/java/docs/index.html) implementations. Joel talked about his success with it recently.
20,510
<p>I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method)</p> <p>I am currently doing this by exposing the following JavaScript method:</p> <pre><code>function doScript(js){ eval(js);} </code></pre> <p>I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app):</p> <pre><code>ExternalInterface.call("doScript","alert('foo')); </code></pre> <p>My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side...</p> <p>Is there a better way to do this?</p>
[ { "answer_id": 20532, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>As far as I know, and I'm definately not a hacker, you are completely fine. Really, if someone wanted to, they could explo...
2008/08/21
[ "https://Stackoverflow.com/questions/20510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
I have a flex application that needs the ability to generate and execute JavaScript. When I say this, I mean I need to execute raw JavaScript that I create in my Flex application (not just an existing JavaScript method) I am currently doing this by exposing the following JavaScript method: ``` function doScript(js){ eval(js);} ``` I can then do something like this in Flex (note: I am doing something more substantial then an alert box in the real Flex app): ``` ExternalInterface.call("doScript","alert('foo')); ``` My question is does this impose any security risk, I am assuming it's not since the Flex and JasvaScript all run client side... Is there a better way to do this?
There's no need for the JavaScript function, the first argument to `ExternalInterface` can be any JavaScript code, it doesn't have to be a function name (the documentation says so, but it is wrong). Try this: ``` ExternalInterface.call("alert('hello')"); ```
20,586
<p>I'm trying to bind a list of custom objects to a WPF Image like this:</p> <pre><code>&lt;Image&gt; &lt;Image.Source&gt; &lt;BitmapImage UriSource="{Binding Path=ImagePath}" /&gt; &lt;/Image.Source&gt; &lt;/Image&gt; </code></pre> <p>But it doesn't work. This is the error I'm getting:</p> <p><em>"Property 'UriSource' or property 'StreamSource' must be set."</em></p> <p>What am I missing?</p>
[ { "answer_id": 20617, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 3, "selected": false, "text": "<p>You need to have an implementation of <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconve...
2008/08/21
[ "https://Stackoverflow.com/questions/20586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373/" ]
I'm trying to bind a list of custom objects to a WPF Image like this: ``` <Image> <Image.Source> <BitmapImage UriSource="{Binding Path=ImagePath}" /> </Image.Source> </Image> ``` But it doesn't work. This is the error I'm getting: *"Property 'UriSource' or property 'StreamSource' must be set."* What am I missing?
WPF has built-in converters for certain types. If you bind the Image's `Source` property to a `string` or `Uri` value, under the hood WPF will use an [ImageSourceConverter](https://msdn.microsoft.com/en-us/library/system.windows.media.imagesourceconverter(v=vs.110).aspx) to convert the value to an `ImageSource`. So ``` <Image Source="{Binding ImageSource}"/> ``` would work if the ImageSource property was a string representation of a valid URI to an image. You can of course roll your own Binding converter: ```cs public class ImageConverter : IValueConverter { public object Convert( object value, Type targetType, object parameter, CultureInfo culture) { return new BitmapImage(new Uri(value.ToString())); } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } ``` and use it like this: ``` <Image Source="{Binding ImageSource, Converter={StaticResource ImageConverter}}"/> ```
20,587
<p>I want to get the results of a stored procedure and place them into a CSV file onto an FTP location.</p> <p>The catch though is that I cannot create a local/temporary file that I can then FTP over.</p> <p>The approach I was taking was to use an SSIS package to create a temporary file and then have a FTP Task within the pack to FTP the file over, but our DBA's do not allow temporary files to be created on any servers.</p> <h2><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20596">in reply to Yaakov Ellis</a></h2> <p>I think we will need to convince the DBA's to let me use at least a share on a server that they do not operate, or ask them how they would do it.</p> <h2><a href="https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689">in reply to Kev</a></h2> <p>I like the idea of the CLR integration, but I don't think our DBA's even know what that is <em>lol</em> and they would probably not allow it either. But I will probably be able to do this within a Script Task in an SSIS package that can be scheduled.</p>
[ { "answer_id": 20593, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 0, "selected": false, "text": "<p>Try using a CLR stored procedure. You might be able to come up with something, but without first creating a temporar...
2008/08/21
[ "https://Stackoverflow.com/questions/20587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1950/" ]
I want to get the results of a stored procedure and place them into a CSV file onto an FTP location. The catch though is that I cannot create a local/temporary file that I can then FTP over. The approach I was taking was to use an SSIS package to create a temporary file and then have a FTP Task within the pack to FTP the file over, but our DBA's do not allow temporary files to be created on any servers. [in reply to Yaakov Ellis](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20596) ----------------------------------------------------------------------------------------------------------------------------------------------------------- I think we will need to convince the DBA's to let me use at least a share on a server that they do not operate, or ask them how they would do it. [in reply to Kev](https://stackoverflow.com/questions/20587/execute-stored-procedure-sql-2005-and-place-results-into-a-csv-file-on-a-ftp-lo#20689) -------------------------------------------------------------------------------------------------------------------------------------------------- I like the idea of the CLR integration, but I don't think our DBA's even know what that is *lol* and they would probably not allow it either. But I will probably be able to do this within a Script Task in an SSIS package that can be scheduled.
This step-by-step example is for others who might stumble upon this question. This example uses *Windows Server 2008 R2 server* and *SSIS 2008 R2*. Even though, the example uses *SSIS 2008 R2*, the logic used is applicable to *SSIS 2005* as well. Thanks to `@Kev` for the *FTPWebRequest* code. Create an SSIS package ([Steps to create an SSIS package](http://learnbycoding.com/2011/07/creating-a-simple-ssis-package-using-bids/)). I have named the package in the format YYYYMMDD\_hhmm in the beginning followed by *SO* stands for Stack Overflow, followed by the *SO question id*, and finally a description. I am not saying that you should name your package like this. This is for me to easily refer this back later. Note that I also have two Data Sources namely *Adventure Works* and *Practice DB*. I will be using *Adventure Works* data source, which points to *AdventureWorks* database downloaded from [this link](http://msftdbprodsamples.codeplex.com/). Refer screenshot **#1** at the bottom of the answer. In the *AdventureWorks* database, create a stored procedure named *dbo.GetCurrency* using the below given script. ``` CREATE PROCEDURE [dbo].[GetCurrency] AS BEGIN SET NOCOUNT ON; SELECT TOP 10 CurrencyCode , Name , ModifiedDate FROM Sales.Currency ORDER BY CurrencyCode END GO ``` On the package’s Connection Manager section, right-click and select *New Connection From Data Source*. On the *Select Data Source* dialog, select *Adventure Works* and click *OK*. You should now see the Adventure Works data source under the Connection Managers section. Refer screenshot **#2**, **#3** and **#4**. On the package, create the following variables. Refer screenshot **#5**. * *ColumnDelimiter*: This variable is of type String. This will be used to separate the column data when it is written to the file. In this example, we will be using comma (,) and the code is written to handle only displayable characters. For non-displayable characters like tab (\t), you might need to change the code used in this example accordingly. * *FileName*: This variable is of type String. It will contain the name of the file. In this example, I have named the file as Currencies.csv because I am going to export list of currency names. * *FTPPassword*: This variable is of type String. This will contain the password to the FTP website. Ideally, the package should be encrypted to hide sensitive information. * *FTPRemotePath*: This variable is of type String. This will contain the FTP folder path to which the file should be uploaded to. For example if the complete FTP URI is <ftp://myFTPSite.com/ssis/samples/uploads>, then the RemotePath would be /ssis/samples/uploads. * *FTPServerName*: This variable is of type String. This will contain the FTP site root URI. For example if the complete FTP URI is <ftp://myFTPSite.com/ssis/samples/uploads>, then the FTPServerName would contain <ftp://myFTPSite.com>. You can combine FTPRemotePath with this variable and have a single variable. It is up to your preference. * *FTPUserName*:This variable is of type String. This will contain the user name that will be used to connect to the FTP website. * *ListOfCurrencies*: This variable is of type Object. This will contain the result set from the stored procedure and it will be looped through in the Script Task. * *ShowHeader*: This variable is of type Boolean. This will contain values true/false. True indicates that the first row in the file will contain Column names and False indicates that the first row will not contain Column names. * *SQLGetData*: This variable is of type String. This will contain the Stored Procedure execution statement. This example uses the value EXEC dbo.GetCurrency On the package’s *Control Flow* tab, place an *Execute SQL Task* and name it as *Get Data*. Double-click on the Execute SQL Task to bring the *Execute SQL Task Editor*. On the *General* section of the *Execute SQL Task Editor*, set the *ResultSet* to `Full result set`, the *Connection* to `Adventure Works`, the *SQLSourceType* to `Variable` and the *SourceVariable* to `User::SQLGetData`. On the Result Set section, click Add button. Set the Result Name to `0`, this indicates the index and the Variable to `User::ListOfCurrencies`. The output of the stored procedure will be saved to this object variable. Click *OK*. Refer screenshot **#6** and **#7**. On the package’s *Control Flow* tab, place a Script Task below the Execute SQL Task and name it as *Save to FTP*. Double-click on the Script Task to bring the *Script Task Editor*. On the Script section, click the `Edit Script…` button. Refer screenshot **#8**. This will bring up the Visual Studio Tools for Applications (VSTA) editor. Replace the code within the class `ScriptMain` in the editor with the code given below. Also, make sure that you add the using statements to the namespaces `System.Data.OleDb`, `System.IO`, `System.Net`, `System.Text`. Refer screenshot **#9** that highlights the code changes. Close the VSTA editor and click Ok to close the Script Task Editor. Script code takes the object variable ListOfCurrencies and stores it into a DataTable with the help of OleDbDataAdapter because we are using OleDb connection. The code then loops through each row and if the variable ShowHeader is set to true, the code will include the Column names in the first row written to the file. The result is stored in a stringbuilder variable. After the string builder variable is populated with all the data, the code creates an FTPWebRequest object and connects to the FTP Uri by combining the variables FTPServerName, FTPRemotePath and FileName using the credentials provided in the variables FTPUserName and FTPPassword. Then the full string builder variable contents are written to the file. The method WriteRowData is created to loop through columns and provide the column names or data information based on the parameters passed. ``` using System; using System.Data; using Microsoft.SqlServer.Dts.Runtime; using System.Windows.Forms; using System.Data.OleDb; using System.IO; using System.Net; using System.Text; namespace ST_7033c2fc30234dae8086558a88a897dd.csproj { [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")] public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { #region VSTA generated code enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; #endregion public void Main() { Variables varCollection = null; Dts.VariableDispenser.LockForRead("User::ColumnDelimiter"); Dts.VariableDispenser.LockForRead("User::FileName"); Dts.VariableDispenser.LockForRead("User::FTPPassword"); Dts.VariableDispenser.LockForRead("User::FTPRemotePath"); Dts.VariableDispenser.LockForRead("User::FTPServerName"); Dts.VariableDispenser.LockForRead("User::FTPUserName"); Dts.VariableDispenser.LockForRead("User::ListOfCurrencies"); Dts.VariableDispenser.LockForRead("User::ShowHeader"); Dts.VariableDispenser.GetVariables(ref varCollection); OleDbDataAdapter dataAdapter = new OleDbDataAdapter(); DataTable currencies = new DataTable(); dataAdapter.Fill(currencies, varCollection["User::ListOfCurrencies"].Value); bool showHeader = Convert.ToBoolean(varCollection["User::ShowHeader"].Value); int rowCounter = 0; string columnDelimiter = varCollection["User::ColumnDelimiter"].Value.ToString(); StringBuilder sb = new StringBuilder(); foreach (DataRow row in currencies.Rows) { rowCounter++; if (rowCounter == 1 && showHeader) { WriteRowData(currencies, row, columnDelimiter, true, ref sb); } WriteRowData(currencies, row, columnDelimiter, false, ref sb); } string ftpUri = string.Concat(varCollection["User::FTPServerName"].Value, varCollection["User::FTPRemotePath"].Value, varCollection["User::FileName"].Value); FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpUri); ftp.Method = WebRequestMethods.Ftp.UploadFile; string ftpUserName = varCollection["User::FTPUserName"].Value.ToString(); string ftpPassword = varCollection["User::FTPPassword"].Value.ToString(); ftp.Credentials = new System.Net.NetworkCredential(ftpUserName, ftpPassword); using (StreamWriter sw = new StreamWriter(ftp.GetRequestStream())) { sw.WriteLine(sb.ToString()); sw.Flush(); } Dts.TaskResult = (int)ScriptResults.Success; } public void WriteRowData(DataTable currencies, DataRow row, string columnDelimiter, bool isHeader, ref StringBuilder sb) { int counter = 0; foreach (DataColumn column in currencies.Columns) { counter++; if (isHeader) { sb.Append(column.ColumnName); } else { sb.Append(row[column].ToString()); } if (counter != currencies.Columns.Count) { sb.Append(columnDelimiter); } } sb.Append(System.Environment.NewLine); } } } ``` Once the tasks have been configured, the package’s Control Flow should look like as shown in screenshot **#10**. Screenshot **#11** shows the output of the stored procedure execution statement EXEC dbo.GetCurrency. Execute the package. Screenshot **#12** shows successful execution of the package. Using the *FireFTP* add-on available in *FireFox* browser, I logged into the FTP website and verified that the file has been successfully uploaded to the FTP website. Refer screenshot #**13**. Examining the contents by opening the file in Notepad++ shows that it matches with the stored procedure output. Refer screenshot #**14**. Thus, the example demonstrated how to write results from database to an FTP website without having to use temporary/local files. Hope that helps someone. **Screenshots:** **#1**: Solution\_Explorer ![Solution_Explorer](https://i.stack.imgur.com/1C8VG.png) **#2**: New\_Connection\_From\_Data\_Source ![New_Connection_From_Data_Source](https://i.stack.imgur.com/hYZqX.png) **#3**: Select\_Data\_Source ![Select_Data_Source](https://i.stack.imgur.com/ccxdu.png) **#4**: Connection\_Managers ![Connection_Managers](https://i.stack.imgur.com/Rw8xv.png) **#5**: Variables ![Variables](https://i.stack.imgur.com/Ov6Ac.png) **#6**: Execute\_SQL\_Task\_Editor\_General ![Execute_SQL_Task_Editor_General](https://i.stack.imgur.com/sMP6f.png) **#7**: Execute\_SQL\_Task\_Editor\_Result\_Set ![Execute_SQL_Task_Editor_Result_Set](https://i.stack.imgur.com/D7iKl.png) **#8**: Script\_Task\_Editor ![Script_Task_Editor](https://i.stack.imgur.com/Yz20f.png) **#9**: Script\_Task\_VSTA\_Code ![Script_Task_VSTA_Code](https://i.stack.imgur.com/C39Xc.png) **#10**: Control\_Flow\_Tab ![Control_Flow_Tab](https://i.stack.imgur.com/kFLeF.png) **#11**: Query\_Results ![Query_Results](https://i.stack.imgur.com/t3aGT.png) **#12**: Package\_Execution\_Successful ![Package_Execution_Successful](https://i.stack.imgur.com/tYKwu.png) **#13**: File\_In\_FTP ![File_In_FTP](https://i.stack.imgur.com/Yt8fD.png) **#14**: File\_Contents ![File_Contents](https://i.stack.imgur.com/nuf2M.png)
20,598
<p>I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?</p>
[ { "answer_id": 20605, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": true, "text": "<p>Converting from timestamp to format:</p>\n\n<pre><code>date('Y-m-d', $timestamp);\n</code></pre>\n\n<p>Converting from formatt...
2008/08/21
[ "https://Stackoverflow.com/questions/20598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I'm interested in doing comparisons between the date string and the MySQL timestamp. However, I'm not seeing an easy conversion. Am I overlooking something obvious?
Converting from timestamp to format: ``` date('Y-m-d', $timestamp); ``` Converting from formatted to timestamp: ``` mktime(0, 0, 0, $month, $day, $year, $is_dst); ``` See [date](http://www.php.net/manual/en/function.date.php) and [mktime](http://www.php.net/manual/en/function.mktime.php) for further documentation. When it comes to storing it's up to you whether to use the MySQL DATE format for stroing as a formatted date; as an integer for storing as a UNIX timestamp; or you can use MySQL's TIMESTAMP format which converts a numeric timestamp into a readable format. [Check the MySQL Doc](http://dev.mysql.com/doc/refman/5.0/en/datetime.html) for TIMESTAMP info.
20,611
<p>The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says:</p> <p><strong>The node to be removed is not a child of this node.</strong></p> <p>Does anyone know the proper way to do this?</p> <pre><code>public void DeleteProject (string projectName) { string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"]; XmlDocument configDoc = new XmlDocument(); configDoc.Load(ccConfigPath); XmlNodeList projectNodes = configDoc.GetElementsByTagName("project"); for (int i = 0; i &lt; projectNodes.Count; i++) { if (projectNodes[i].Attributes["name"] != null) { if (projectName == projectNodes[i].Attributes["name"].InnerText) { configDoc.RemoveChild(projectNodes[i]); configDoc.Save(ccConfigPath); } } } } </code></pre> <p><strong>UPDATE</strong></p> <p>Fixed. I did two things:</p> <pre><code>XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']"); </code></pre> <p>Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach.</p> <p>The actual fix was:</p> <pre><code>project.ParentNode.RemoveChild(project); </code></pre> <p>Thanks Pat and Chuck for this suggestion.</p>
[ { "answer_id": 20614, "author": "Greg Hurlman", "author_id": 35, "author_profile": "https://Stackoverflow.com/users/35", "pm_score": 1, "selected": false, "text": "<p>Is it possible that the project nodes aren't child nodes, but grandchildren or lower? GetElementsByTagName will give you...
2008/08/21
[ "https://Stackoverflow.com/questions/20611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
The following code should find the appropriate project tag and remove it from the XmlDocument, however when I test it, it says: **The node to be removed is not a child of this node.** Does anyone know the proper way to do this? ``` public void DeleteProject (string projectName) { string ccConfigPath = ConfigurationManager.AppSettings["ConfigPath"]; XmlDocument configDoc = new XmlDocument(); configDoc.Load(ccConfigPath); XmlNodeList projectNodes = configDoc.GetElementsByTagName("project"); for (int i = 0; i < projectNodes.Count; i++) { if (projectNodes[i].Attributes["name"] != null) { if (projectName == projectNodes[i].Attributes["name"].InnerText) { configDoc.RemoveChild(projectNodes[i]); configDoc.Save(ccConfigPath); } } } } ``` **UPDATE** Fixed. I did two things: ``` XmlNode project = configDoc.SelectSingleNode("//project[@name='" + projectName + "']"); ``` Replaced the For loop with an XPath query, which wasn't for fixing it, just because it was a better approach. The actual fix was: ``` project.ParentNode.RemoveChild(project); ``` Thanks Pat and Chuck for this suggestion.
Instead of ``` configDoc.RemoveChild(projectNodes[i]); ``` try ``` projectNodes[i].parentNode.RemoveChild(projectNodes[i]); ```
20,674
<p>Other than <code>self.class.send :method, args...</code>, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code.</p> <hr> <p><strong>UPDATE:</strong> </p> <p>@Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that <code>private</code> doesn't work on class methods, though this will declare a private class method:</p> <pre><code>class Foo class &lt;&lt;self private def bar puts 'bar' end end end Foo.bar # =&gt; NoMethodError: private method 'bar' called for Foo:Class </code></pre>
[ { "answer_id": 20690, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": -1, "selected": false, "text": "<p>Unless I'm misunderstanding, don't you just need something like this:</p>\n\n<pre><code>class Foo\n private\n def Foo....
2008/08/21
[ "https://Stackoverflow.com/questions/20674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
Other than `self.class.send :method, args...`, of course. I'd like to make a rather complex method available at both the class and instance level without duplicating the code. --- **UPDATE:** @Jonathan Branam: that was my assumption, but I wanted to make sure nobody else had found a way around. Visibility in Ruby is very different from that in Java. You're also quite right that `private` doesn't work on class methods, though this will declare a private class method: ``` class Foo class <<self private def bar puts 'bar' end end end Foo.bar # => NoMethodError: private method 'bar' called for Foo:Class ```
Here is a code snippet to go along with the question. Using "private" in a class definition does not apply to class methods. You need to use "private\_class\_method" as in the following example. ``` class Foo def self.private_bar # Complex logic goes here puts "hi" end private_class_method :private_bar class <<self private def another_private_bar puts "bar" end end public def instance_bar self.class.private_bar end def instance_bar2 self.class.another_private_bar end end f=Foo.new f=instance_bar # NoMethodError: private method `private_bar' called for Foo:Class f=instance_bar2 # NoMethodError: private method `another_private_bar' called for Foo:Class ``` I don't see a way to get around this. The documentation says that you cannot specify the receive of a private method. Also you can only access a private method from the same instance. The class Foo is a different object than a given instance of Foo. Don't take my answer as final. I'm certainly not an expert, but I wanted to provide a code snippet so that others who attempt to answer will have properly private class methods.
20,696
<p>In E (specman) I want to declare variables that are lists, and I want to fix their lengths.</p> <p>It's easy to do for a member of a struct:</p> <pre><code>thread[2] : list of thread_t; </code></pre> <p>while for a "regular" variable in a function the above doesn't work, and I have to do something like:</p> <pre><code>var warned : list of bool; gen warned keeping { it.size() == 5; }; </code></pre> <p>Is there a better way to declare a list of fixed size?</p>
[ { "answer_id": 28801, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": -1, "selected": false, "text": "<p>I know nothing of specman, but a fixed sized list is an array, so that might point you somewhere.</p>\n" }, { ...
2008/08/21
[ "https://Stackoverflow.com/questions/20696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084/" ]
In E (specman) I want to declare variables that are lists, and I want to fix their lengths. It's easy to do for a member of a struct: ``` thread[2] : list of thread_t; ``` while for a "regular" variable in a function the above doesn't work, and I have to do something like: ``` var warned : list of bool; gen warned keeping { it.size() == 5; }; ``` Is there a better way to declare a list of fixed size?
A hard keep like you have is only going to fix the size at initialization but elements could still be added or dropped later, are you trying to guard against this condition? The only way I can think of to guarantee that elements aren't added or dropped later is emitting an event synced on the size != the predetermined amount: ``` event list_size_changed is true (wanted.size() != 5) @clk; ``` The only other thing that I can offer is a bit of syntactic sugar for the hard keep: ``` var warned : list of bool; keep warned.size() == 5; ```
20,722
<p>How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of <a href="http://silverlight.net/" rel="nofollow noreferrer">Silverlight</a> currently running on the browser?</p>
[ { "answer_id": 20729, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p>Look in silverlight.js:</p>\n\n<p><a href=\"http://forums.asp.net/p/1135746/1997617.aspx#1997617\" rel=\"nofollow noreferrer\">h...
2008/08/21
[ "https://Stackoverflow.com/questions/20722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/375/" ]
How can I efficiently and effectively detect the version and, for that matter, any available information about the instance of [Silverlight](http://silverlight.net/) currently running on the browser?
The Silverlight control only has an [IsVersionSupported function](http://msdn.microsoft.com/en-us/library/system.windows.interop.silverlighthost.isversionsupported(VS.95).aspx), which returns true / false when you give it a version number, e.g.: ``` if(slPlugin.isVersionSupported("2.0")) { alert("I haz some flavour of Silverlight 2"); ``` You can be as specific as you want when checking the build, since the version string can include all of the following: * major - the major number * minor - the minor number * build - the build number * revision - the revision number So we can check for a specific build number as follows: ``` if(slPlugin.isVersionSupported("2.0.30523")) { alert("I haz Silverlight 2.0.30523, but could be any revision."); ``` [Silverlight 1.0 Beta included a control.settings.version property, which was replaced with the isVersionSupported() method](http://msdn.microsoft.com/en-us/library/bb693297.aspx#replace_version). The idea is that you shouldn't be programming against specific versions of Silverlight. Rather, you should be checking if the client has *at least* verion 1.0, or 2.0, etc. That being said, you can get the Silverlight version number in Firefox by checking the Silverlight plugin description: ``` alert(navigator.plugins["Silverlight Plug-In"].description); ``` Shows '2.0.30523.8' on my computer. Note that it is possible to brute force it by iterating through all released version numbers. [Presumably that's what BrowserHawk does](http://pages.citebite.com/w3o7qsydtr) - they'll report which version of Silverlight the client has installed.
20,731
<p>I've tried several things already,</p> <pre><code>std::stringstream m; m.empty(); m.clear(); </code></pre> <p>both of which don't work.</p>
[ { "answer_id": 20732, "author": "CodingWithoutComments", "author_id": 25, "author_profile": "https://Stackoverflow.com/users/25", "pm_score": 5, "selected": false, "text": "<pre><code>m.str(\"\");\n</code></pre>\n\n<p>seems to work.</p>\n" }, { "answer_id": 20792, "author": "...
2008/08/21
[ "https://Stackoverflow.com/questions/20731", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25/" ]
I've tried several things already, ``` std::stringstream m; m.empty(); m.clear(); ``` both of which don't work.
For all the standard library types the member function `empty()` is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents". The `clear()` member function is inherited from `ios` and is used to clear the error state of the stream, e.g. if a file stream has the error state set to `eofbit` (end-of-file), then calling `clear()` will set the error state back to `goodbit` (no error). For clearing the contents of a `stringstream`, using: ``` m.str(""); ``` is correct, although using: ``` m.str(std::string()); ``` is technically more efficient, because you avoid invoking the `std::string` constructor that takes `const char*`. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.
20,744
<p>Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue.</p>
[ { "answer_id": 20781, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 2, "selected": false, "text": "<p>No, you cannot reposition the view report button in the ReportViewer control.</p>\n\n<p>However, you could create your ow...
2008/08/21
[ "https://Stackoverflow.com/questions/20744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215/" ]
Using the viewer control for display of SQL Reporting Services reports on web page (Microsoft.ReportViewer.WebForms), can you move the View Report button? It defaults to the very right side of the report, which means you have to scroll all the way across before the button is visible. Not a problem for reports that fit the window width, but on very wide reports that is quickly an issue.
It's kind of a hack, but you can move it in JavaScript. Just see what HTML the ReportViewer generates, and write the appropriate JavaScript code to move the button. I used JavaScript to hide the button (because we wanted our own View Report button). Any JavaScript code that manipulates the generated ReportViewer's HTML must come after the ReportViewer control in the .aspx page. Here's my code for hiding the button, to give you an idea of what you'd do: ``` function getRepViewBtn() { return document.getElementsByName("ReportViewer1$ctl00$ctl00")[0]; } function hideViewReportButton() { // call this where needed var btn = getRepViewBtn(); btn.style.display = 'none'; } ```
20,762
<p>Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML?</p> <p>Note: </p> <ul> <li>The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point.</li> <li>The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character.</li> </ul> <p><em>Background:</em></p> <p>I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification.</p> <p>In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.</p>
[ { "answer_id": 20777, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 7, "selected": true, "text": "<p>It <strong>may not be perfect</strong> (emphasis added since people missing this disclaimer), but what I've done in tha...
2008/08/21
[ "https://Stackoverflow.com/questions/20762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2029/" ]
Is there any easy/general way to clean an XML based data source prior to using it in an XmlReader so that I can gracefully consume XML data that is non-conformant to the hexadecimal character restrictions placed on XML? Note: * The solution needs to handle XML data sources that use character encodings other than UTF-8, e.g. by specifying the character encoding at the XML document declaration. Not mangling the character encoding of the source while stripping invalid hexadecimal characters has been a major sticking point. * The removal of invalid hexadecimal characters should only remove hexadecimal encoded values, as you can often find href values in data that happens to contains a string that would be a string match for a hexadecimal character. *Background:* I need to consume an XML-based data source that conforms to a specific format (think Atom or RSS feeds), but want to be able to consume data sources that have been published which contain invalid hexadecimal characters per the XML specification. In .NET if you have a Stream that represents the XML data source, and then attempt to parse it using an XmlReader and/or XPathDocument, an exception is raised due to the inclusion of invalid hexadecimal characters in the XML data. My current attempt to resolve this issue is to parse the Stream as a string and use a regular expression to remove and/or replace the invalid hexadecimal characters, but I am looking for a more performant solution.
It **may not be perfect** (emphasis added since people missing this disclaimer), but what I've done in that case is below. You can adjust to use with a stream. ``` /// <summary> /// Removes control characters and other non-UTF-8 characters /// </summary> /// <param name="inString">The string to process</param> /// <returns>A string with no control characters or entities above 0x00FD</returns> public static string RemoveTroublesomeCharacters(string inString) { if (inString == null) return null; StringBuilder newString = new StringBuilder(); char ch; for (int i = 0; i < inString.Length; i++) { ch = inString[i]; // remove any characters outside the valid UTF-8 range as well as all control characters // except tabs and new lines //if ((ch < 0x00FD && ch > 0x001F) || ch == '\t' || ch == '\n' || ch == '\r') //if using .NET version prior to 4, use above logic if (XmlConvert.IsXmlChar(ch)) //this method is new in .NET 4 { newString.Append(ch); } } return newString.ToString(); } ```
20,778
<p>I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport.</p> <p>What I've got right now is</p> <pre><code>byte[] buffer = ...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore </code></pre> <p>Does anyone know how to convert binary to String and back without data loss?</p> <p>Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem.</p> <p>EDIT: Just for the sake of completeness, I used the <a href="http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html" rel="noreferrer">Base64</a> class from the <a href="http://commons.apache.org/" rel="noreferrer">Apache Commons</a> <a href="http://commons.apache.org/codec/" rel="noreferrer">Codec</a> package to solve this problem.</p>
[ { "answer_id": 20779, "author": "Sam", "author_id": 428, "author_profile": "https://Stackoverflow.com/users/428", "pm_score": 5, "selected": true, "text": "<p>If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data...
2008/08/21
[ "https://Stackoverflow.com/questions/20778", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
I have binary data in a file that I can read into a byte array and process with no problem. Now I need to send parts of the data over a network connection as elements in an XML document. My problem is that when I convert the data from an array of bytes to a String and back to an array of bytes, the data is getting corrupted. I've tested this on one machine to isolate the problem to the String conversion, so I now know that it isn't getting corrupted by the XML parser or the network transport. What I've got right now is ``` byte[] buffer = ...; // read from file // a few lines that prove I can process the data successfully String element = new String(buffer); byte[] newBuffer = element.getBytes(); // a few lines that try to process newBuffer and fail because it is not the same data anymore ``` Does anyone know how to convert binary to String and back without data loss? Answered: Thanks Sam. I feel like an idiot. I had this answered yesterday because my SAX parser was complaining. For some reason when I ran into this seemingly separate issue, it didn't occur to me that it was a new symptom of the same problem. EDIT: Just for the sake of completeness, I used the [Base64](http://commons.apache.org/codec/apidocs/org/apache/commons/codec/binary/Base64.html) class from the [Apache Commons](http://commons.apache.org/) [Codec](http://commons.apache.org/codec/) package to solve this problem.
If you encode it in base64, this will turn any data into ascii safe text, but base64 encoded data is larger than the orignal data
20,794
<p>If I call <code>os.stat()</code> on a broken <code>symlink</code>, python throws an <code>OSError</code> exception. This makes it useful for finding them. However, there are a few other reasons that <code>os.stat()</code> might throw a similar exception. Is there a more precise way of detecting broken <code>symlinks</code> with Python under Linux?</p>
[ { "answer_id": 20843, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "<p>Can I mention testing for hardlinks without python? /bin/test has the FILE1 -ef FILE2 condition that is true when files sha...
2008/08/21
[ "https://Stackoverflow.com/questions/20794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
If I call `os.stat()` on a broken `symlink`, python throws an `OSError` exception. This makes it useful for finding them. However, there are a few other reasons that `os.stat()` might throw a similar exception. Is there a more precise way of detecting broken `symlinks` with Python under Linux?
A common Python saying is that it's easier to ask forgiveness than permission. While I'm not a fan of this statement in real life, it does apply in a lot of cases. Usually you want to avoid code that chains two system calls on the same file, because you never know what will happen to the file in between your two calls in your code. **A typical mistake is to write something like**: ``` if os.path.exists(path): os.unlink(path) ``` The second call (os.unlink) may fail if something else deleted it after your if test, raise an Exception, and stop the rest of your function from executing. (You might think this doesn't happen in real life, but we just fished another bug like that out of our codebase last week - and it was the kind of bug that left a few programmers scratching their head and claiming 'Heisenbug' for the last few months) So, in your particular case, I would probably do: ``` try: os.stat(path) except OSError, e: if e.errno == errno.ENOENT: print 'path %s does not exist or is a broken symlink' % path else: raise e ``` The annoyance here is that stat returns the same error code for a symlink that just isn't there and a broken symlink. So, I guess you have no choice than to break the atomicity, and do something like ``` if not os.path.exists(os.readlink(path)): print 'path %s is a broken symlink' % path ```
20,797
<p>I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this:</p> <pre><code>byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); </code></pre> <p><code>smallPortion</code> would equal 1,2,3,4<br> <code>largeBytes</code> would equal 5,6,7,8,9</p>
[ { "answer_id": 20826, "author": "Stu", "author_id": 414, "author_profile": "https://Stackoverflow.com/users/414", "pm_score": 0, "selected": false, "text": "<p>You can't. What you might want is keep a starting point and number of items; in essence, build iterators. If this is C++, you ca...
2008/08/21
[ "https://Stackoverflow.com/questions/20797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
I have a byte array in memory, read from a file. I would like to split the byte array at a certain point (index) without having to just create a new byte array and copy each byte at a time, increasing the in memory foot print of the operation. What I would like is something like this: ``` byte[] largeBytes = [1,2,3,4,5,6,7,8,9]; byte[] smallPortion; smallPortion = split(largeBytes, 3); ``` `smallPortion` would equal 1,2,3,4 `largeBytes` would equal 5,6,7,8,9
This is how I would do that: ``` using System; using System.Collections; using System.Collections.Generic; class ArrayView<T> : IEnumerable<T> { private readonly T[] array; private readonly int offset, count; public ArrayView(T[] array, int offset, int count) { this.array = array; this.offset = offset; this.count = count; } public int Length { get { return count; } } public T this[int index] { get { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else return this.array[offset + index]; } set { if (index < 0 || index >= this.count) throw new IndexOutOfRangeException(); else this.array[offset + index] = value; } } public IEnumerator<T> GetEnumerator() { for (int i = offset; i < offset + count; i++) yield return array[i]; } IEnumerator IEnumerable.GetEnumerator() { IEnumerator<T> enumerator = this.GetEnumerator(); while (enumerator.MoveNext()) { yield return enumerator.Current; } } } class Program { static void Main(string[] args) { byte[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; ArrayView<byte> p1 = new ArrayView<byte>(arr, 0, 5); ArrayView<byte> p2 = new ArrayView<byte>(arr, 5, 5); Console.WriteLine("First array:"); foreach (byte b in p1) { Console.Write(b); } Console.Write("\n"); Console.WriteLine("Second array:"); foreach (byte b in p2) { Console.Write(b); } Console.ReadKey(); } } ```
20,840
<p>Why should I or shouldn't I use dirty reads:</p> <pre><code>set transaction isolation level read uncommitted </code></pre> <p>in SQL Server?</p>
[ { "answer_id": 20879, "author": "Tokabi", "author_id": 315, "author_profile": "https://Stackoverflow.com/users/315", "pm_score": 3, "selected": false, "text": "<p>Generally when you need to do a sizeable (or frequent) queries to busy tables, where read committed would possibly be blocked...
2008/08/21
[ "https://Stackoverflow.com/questions/20840", "https://Stackoverflow.com", "https://Stackoverflow.com/users/357/" ]
Why should I or shouldn't I use dirty reads: ``` set transaction isolation level read uncommitted ``` in SQL Server?
From [MSDN](http://msdn.microsoft.com/en-us/library/aa259216(SQL.80).aspx): > > When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. > > > Simply put, when you are using this isolation level, and you are performing multiple queries on an active table as part of one transaction, there is no guarantee that the information returned to you within different parts of the transaction will remain the same. You could query the same data twice within one transaction and get different results (this might happen in the case where a different user was updating the same data in the midst of your transaction). This can obviously have severe ramifications for parts of your application that rely on data integrity.
20,850
<p>I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes.</p> <p>Basically, I have an external disk with two volumes: </p> <p>One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes.</p> <p>So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. </p> <p>What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far:</p> <ul> <li>I've tried going through options in Disk Utility</li> <li>I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking.</li> <li>I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings.</li> </ul> <p>Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick).</p> <p>EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.</p>
[ { "answer_id": 21101, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 1, "selected": false, "text": "<p>This is not directly an answer, but</p>\n\n<blockquote>\n <p>The thing is that to remove the disk you have to eject t...
2008/08/21
[ "https://Stackoverflow.com/questions/20850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1120/" ]
I'm a bit newbieish when it comes to the deeper parts of OSX configuration and am having to put up with a fairly irritating niggle which while I can put up with it, I know under Windows I could have sorted in minutes. Basically, I have an external disk with two volumes: One is an HFS+ volume which I use for TimeMachine backups. The other, an NTFS volume that I use for general file copying etc on Mac and Windows boxes. So what happens is that whenever I plug in the disk into my Mac USB, OSX goes off and mounts both volumes and shows an icon on the desktop for each. The thing is that to remove the disk you have to eject the volume and in this case do it for both volumes, which causes an annoying warning dialog to be shown every time. What I'd prefer is some way to prevent the NTFS volume from auto-mounting altogether. I've done some hefty googling and here's a list of things I've tried so far: * I've tried going through options in Disk Utility * I've tried setting AutoMount to No in /etc/hostconfig but that is a bit too global for my liking. * I've also tried the suggested approach to putting settings in fstab but it appears the OSX (10.5) is ignoring these settings. Any other suggestions would be welcomed. Just a little dissapointed that I can't just tick a box somewhere (or untick). EDIT: Thanks heaps to hop for the answer it worked a treat. For the record it turns out that it wasn't OSX not picking up the settings I actually had "msdos" instead of "ntfs" in the fs type column.
The following entry in `/etc/fstab` will do what you want, even on 10.5 (Leopard): ``` LABEL=VolumeName none ntfs noauto ``` If the file is not already there, just create it. Do not use `/etc/fstab.hd`! No reloading of `diskarbitrationd` needed. If this still doesn't work for you, maybe you can find a hint in the syslog.
20,856
<p>I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully?</p> <p>Am I missing a best practice for tags?</p>
[ { "answer_id": 20871, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 10, "selected": true, "text": "<p>Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, w...
2008/08/21
[ "https://Stackoverflow.com/questions/20856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/459/" ]
I've heard of a few ways to implement tagging; using a mapping table between TagID and ItemID (makes sense to me, but does it scale?), adding a fixed number of possible TagID columns to ItemID (seems like a bad idea), Keeping tags in a text column that's comma separated (sounds crazy but could work). I've even heard someone recommend a sparse matrix, but then how do the tag names grow gracefully? Am I missing a best practice for tags?
Three tables (one for storing all items, one for all tags, and one for the relation between the two), properly indexed, with foreign keys set running on a proper database, should work well and scale properly. ``` Table: Item Columns: ItemID, Title, Content Table: Tag Columns: TagID, Title Table: ItemTag Columns: ItemID, TagID ```
20,876
<p>I'm new to SQL Server Reporting Services, and was wondering the best way to do the following:</p> <blockquote> <ul> <li>Query to get a list of popular IDs</li> <li>Subquery on each item to get properties from another table</li> </ul> </blockquote> <p>Ideally, the final report columns would look like this:</p> <pre><code>[ID] [property1] [property2] [SELECT COUNT(*) FROM AnotherTable WHERE ForeignID=ID] </code></pre> <p>There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.</p>
[ { "answer_id": 20895, "author": "Bryan Roth", "author_id": 299, "author_profile": "https://Stackoverflow.com/users/299", "pm_score": 3, "selected": true, "text": "<p>I would recommend using a <a href=\"http://msdn.microsoft.com/en-us/library/ms160348.aspx\" rel=\"nofollow noreferrer\">Su...
2008/08/21
[ "https://Stackoverflow.com/questions/20876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
I'm new to SQL Server Reporting Services, and was wondering the best way to do the following: > > * Query to get a list of popular IDs > * Subquery on each item to get properties from another table > > > Ideally, the final report columns would look like this: ``` [ID] [property1] [property2] [SELECT COUNT(*) FROM AnotherTable WHERE ForeignID=ID] ``` There may be ways to construct a giant SQL query to do this all in one go, but I'd prefer to compartmentalize it. Is the recommended approach to write a VB function to perform the subquery for each row? Thanks for any help.
I would recommend using a [SubReport](http://msdn.microsoft.com/en-us/library/ms160348.aspx). You would place the SubReport in a table cell.
20,923
<p>I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0.</p> <p>Ideally I would like to adsutil.vbs to update the metabase. How do I do this?</p>
[ { "answer_id": 20953, "author": "Chris Miller", "author_id": 206, "author_profile": "https://Stackoverflow.com/users/206", "pm_score": 2, "selected": false, "text": "<p>I found the following script <a href=\"http://www.diablopup.net/post/Set-an-IIS-Object%27s-ASPNET-Version-Using-VBScrip...
2008/08/21
[ "https://Stackoverflow.com/questions/20923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/636/" ]
I need to script the creation of app pools and websites on IIS 6.0. I have been able to create these using adsutil.vbs and iisweb.vbs, but don't know how to set the version of ASP.NET for the sites I have just created to 2.0.50727.0. Ideally I would like to adsutil.vbs to update the metabase. How do I do this?
@[Chris](https://stackoverflow.com/questions/20923/vbscriptiis-how-do-i-automatically-set-aspnet-version-for-a-particular-website#20953) beat me to the punch on the ADSI way You can do this using the aspnet\_regiis.exe tool. There is one of these tools per version of ASP.NET installed on the machine. You could shell out to - This configures ASP.NET 1.1 ``` %windir%\microsoft.net\framework\v1.1.4322\aspnet_regiis -s W3SVC/[iisnumber]/ROOT ``` This configures ASP.NET 2.0 ``` %windir%\microsoft.net\framework\v2.0.50727\aspnet_regiis -s W3SVC/[iisnumber]/ROOT ``` You probably already know this, but if you have multiple 1.1 and 2.0 sites on your machine, just remember to switch the website you're changing ASP.NET versions on to compatible app pool. ASP.NET 1.1 and 2.0 sites don't mix in the same app pool.
20,926
<p>Today I was working on a tab navigation for a webpage. I tried the <a href="http://www.alistapart.com/articles/slidingdoors2/" rel="noreferrer">Sliding Doors</a> approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). </p> <p>I wanted to use a nested anchor, which didn't work because it is <a href="http://www.w3.org/TR/html4/struct/links.html#h-12.2.2" rel="noreferrer">not</a> allowed. Then I saw the tab- navigation at <a href="http://www.pageflakes.com" rel="noreferrer">Pageflakes</a>, which was actually working (including nested hyperlinks). Why?</p>
[ { "answer_id": 20944, "author": "Yaakov Ellis", "author_id": 51, "author_profile": "https://Stackoverflow.com/users/51", "pm_score": 4, "selected": true, "text": "<p>They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested...
2008/08/21
[ "https://Stackoverflow.com/questions/20926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2078/" ]
Today I was working on a tab navigation for a webpage. I tried the [Sliding Doors](http://www.alistapart.com/articles/slidingdoors2/) approach which worked fine. Then I realized that I must include an option to delete a tab (usually a small X in the right corner of each tab). I wanted to use a nested anchor, which didn't work because it is [not](http://www.w3.org/TR/html4/struct/links.html#h-12.2.2) allowed. Then I saw the tab- navigation at [Pageflakes](http://www.pageflakes.com), which was actually working (including nested hyperlinks). Why?
They must be doing some really crazy stuff with JavaScript to get it to work (notice how neither the parent nor the nested anchor tags have a name or href attribute - all functionality is done through the class name and JS). Here is what the html looks like: ``` <a class="page_tab page_tab"> <div class="page_title" title="Click to rename this page.">Click & Type Page Name</div> <a class="delete_page" title="Click to delete this page" style="display: block;">X</a> </a> ```
20,927
<p>I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code:</p> <pre><code>def save(self): super(Attachment, self).save() self.message.updated = self.updated </code></pre> <p>Will this work, and if you can explain it to me, why? If not, how would I accomplish this?</p>
[ { "answer_id": 20983, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 5, "selected": true, "text": "<p>You would also need to then save the message. Then it that should work.</p>\n" }, { "answer_id": 72359, "author":...
2008/08/21
[ "https://Stackoverflow.com/questions/20927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1914/" ]
I've got two models: Message and Attachment. Each attachment is attached to a specific message, using a ForeignKey on the Attachment model. Both models have an auto\_now DateTimeField called updated. I'm trying to make it so that when any attachment is saved, it also sets the updated field on the associated message to now. Here's my code: ``` def save(self): super(Attachment, self).save() self.message.updated = self.updated ``` Will this work, and if you can explain it to me, why? If not, how would I accomplish this?
You would also need to then save the message. Then it that should work.