input
stringlengths
51
42.3k
output
stringlengths
18
55k
Is there a c# library for wrapping multiple SCM provider's APIs? <p>The project I'm working on requires access to the users source control. To do this we are wrapping the Perforce API and the Subversion API ( using P4.NET and SubversionSharp respectively ). </p> <p>We would like to support as many as we can depending on user requirements and I've tried googling for an existing library but no luck. Does a C# library that wraps multiple SCM applications exist?</p>
<p>You propably search for Microsoft Source Code Control Provider ( MSSCCI ). I know, the Source Safe, Team Foundation Server, Subversion, Evolution, ( and some next others ) source control products has this interface implemented.</p>
What do 1.#INF00, -1.#IND00 and -1.#IND mean? <p>I'm messing around with some C code using floats and I'm getting 1.#INF00, -1.#IND00 and -1.#IND when I try to print floats in the screen. What does those values mean? I believe that 1.#INF00 means positive infinity, but what about -1.#IND00 and -1.#IND? I also saw sometimes this value: 1.$NaN which is Not a Number but what causes those strange values and how can those help me with debugging?</p> <p>I'm using MingW which I believe uses IEEE 754 representation for float points.</p> <p>Can someone list all those invalid values and what they mean?</p>
<p>From <a href="http://www.johndcook.com/IEEE_exceptions_in_cpp.html">IEEE floating-point exceptions in C++</a> :</p> <blockquote> <p>This page will answer the following questions.</p> <ul> <li>My program just printed out 1.#IND or 1.#INF (on Windows) or nan or inf (on Linux). What happened?</li> <li>How can I tell if a number is really a number and not a NaN or an infinity?</li> <li>How can I find out more details at runtime about kinds of NaNs and infinities?</li> <li>Do you have any sample code to show how this works?</li> <li>Where can I learn more?</li> </ul> <p>These questions have to do with floating point exceptions. If you get some strange non-numeric output where you're expecting a number, you've either exceeded the finite limits of floating point arithmetic or you've asked for some result that is undefined. To keep things simple, I'll stick to working with the double floating point type. Similar remarks hold for float types.</p> <p><strong>Debugging 1.#IND, 1.#INF, nan, and inf</strong></p> <p>If your operation would generate a larger positive number than could be stored in a double, the operation will return 1.#INF on Windows or inf on Linux. Similarly your code will return -1.#INF or -inf if the result would be a negative number too large to store in a double. Dividing a positive number by zero produces a positive infinity and dividing a negative number by zero produces a negative infinity. Example code at the end of this page will demonstrate some operations that produce infinities.</p> <p>Some operations don't make mathematical sense, such as taking the square root of a negative number. (Yes, this operation makes sense in the context of complex numbers, but a double represents a real number and so there is no double to represent the result.) The same is true for logarithms of negative numbers. Both sqrt(-1.0) and log(-1.0) would return a NaN, the generic term for a "number" that is "not a number". Windows displays a NaN as -1.#IND ("IND" for "indeterminate") while Linux displays nan. Other operations that would return a NaN include 0/0, 0*∞, and ∞/∞. See the sample code below for examples. </p> <p>In short, if you get 1.#INF or inf, look for overflow or division by zero. If you get 1.#IND or nan, look for illegal operations. Maybe you simply have a bug. If it's more subtle and you have something that is difficult to compute, see Avoiding Overflow, Underflow, and Loss of Precision. That article gives tricks for computing results that have intermediate steps overflow if computed directly.</p> </blockquote>
iPhone and OpenCV <p>I know that <a href="http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port">OpenCV was ported to Mac OS X</a>, however I did not find any info about a port to the iPhone.</p> <p>I am not a Mac developer, so that I do not know whether a Mac OS X port is enough for the iPhone.</p> <p>Does anyone know better than me? </p> <p>Edit: Thanks for the informed answer Adam. </p>
<p>OpenCV does indeed work on the iphone. Use the configure script here to compile the library: <a href="http://lambdajive.wordpress.com/2008/12/20/cross-compiling-for-iphone/" rel="nofollow">cross compiling for iphone</a></p> <p>You just have to cross-compile just as you do your apps.</p>
Ensuring Users are Authenticated in Java Web App <p>My web app has a secure area which users log in to via a JSP. The JSP posts the user name and password to a servlet, which then checks to see if the users credentials are valid. If they are valid then the user is directed to the secure resource. How can I ensure that users can't just navigate to the secure resource without validating first?</p>
<p>A common approach is to set a token in the user's session i.e.,</p> <p><code>session.setAttribute("loggedIn", "true");</code></p> <p>or even</p> <p><code>session.setAttribute("loggedInUser", "someUserName");</code></p> <p>and check that on any page that should be secured. A good strategy is to perform the check using a servlet filter that you attach to any page to be secured. If they don't pass the check, the filter can redirect to the login page. Also see here: <a href="http://java.sun.com/products/servlet/Filters.html" rel="nofollow">http://java.sun.com/products/servlet/Filters.html</a></p> <p>This is a good article on using filters for authentication also: <a href="http://www.developer.com/java/ent/article.php/3467801" rel="nofollow">http://www.developer.com/java/ent/article.php/3467801</a></p>
Reusing a connection while polling a database in JDBC? <p>Have a use case wherein need to maintain a connection open to a database open to execute queries periodically. </p> <p>Is it advisable to close connection after executing the query and then reopen it after the period interval (10 minutes). I would guess no since opening a connection to database is expensive.</p> <p>Is connection pooling the alternative and keep using the connections?</p>
<p>You should use connection pooling. Write your application code to request a connection from the pool, use the connection, then return the connection back to the pool. This keeps your code clean. Then you rely on the pool implementation to determine the most efficient way to manage the connections (for example, keeping them open vs closing them).</p> <p>Generally it is "expensive" to open a connection, typically due to the overhead of setting up a TCP/IP connection, authentication, etc. However, it can also be expensive to keep a connection open "too long", because the database (probably) has reserved resources (like memory) for use by the connection. So keeping a connection open can tie-up those resources.</p> <p>You don't want to pollute your application code managing these types of efficiency trade-offs, so use a connection pool.</p>
How to undo 'git add' before commit? <p>I mistakenly added files using the command:</p> <pre><code>git add myfile.txt </code></pre> <p>I have not yet run <code>git commit</code>. Is there a way to undo this, so these files won't be included in the commit?</p>
<p>You can undo <code>git add</code> before commit with</p> <pre><code>git reset &lt;file&gt; </code></pre> <p>which will remove it from the current index (the "about to be committed" list) without changing anything else.</p> <p>You can use</p> <pre><code>git reset </code></pre> <p>without any file name to unstage all due changes. This can come in handy when there are too many files to be listed one by one in a reasonable amount of time.</p> <p>In old versions of Git, the above commands are equivalent to <code>git reset HEAD &lt;file&gt;</code> and <code>git reset HEAD</code> respectively, and will fail if <code>HEAD</code> is undefined (because you haven't yet made any commits in your repo) or ambiguous (because you created a branch called <code>HEAD</code>, which is a stupid thing that you shouldn't do). This <a href="https://git.kernel.org/cgit/git/git.git/tree/Documentation/RelNotes/1.8.2.txt#n179">was changed in Git 1.8.2</a>, though, so in modern versions of Git you can use the commands above even prior to making your first commit:</p> <blockquote> <p>"git reset" (without options or parameters) used to error out when you do not have any commits in your history, but it now gives you an empty index (to match non-existent commit you are not even on).</p> </blockquote>
Essential Firefox Plugins/Extensions? <p>What firefox plugins could you not live without, as relates to webdev?</p> <p>My list would be:</p> <ul> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/3227" rel="nofollow">DBGBar</a></li> <li><a href="https://addons.mozilla.org/nl/firefox/addon/6622" rel="nofollow">Dom Inspector</a></li> <li>Firebug</li> <li><a href="https://addons.mozilla.org/en-US/firefox/addon/6683" rel="nofollow">Firecookie</a></li> <li>Google toolbar (useful for seo)</li> <li>Live HTTP</li> <li><a href="https://addons.mozilla.org/nl/firefox/addon/115" rel="nofollow">ReloadEvery</a></li> <li>TamperData</li> <li>Web Developer</li> </ul> <p>I am always on the lookout for new ones though, so I wonder if anyone knows of any great ones that I may have missed?</p>
<p><a href="http://getfirebug.com/">Firebug</a> is the main one I use.</p>
Fastest javascript page search <p>I am writing a Firefox extension. I would like to search the current webpage for a set of words, and count how many times each occurs. This activity is only performed when the user asks, but it must still happen reasonably quickly.</p> <p>I am currently using indexOf on the BODY tag's innerHTML element, but am finding it too slow to run repeatedly in the following manner:</p> <pre><code>function wordcount(doc, match) { var count = 0; var pos = 0; for(;;) { len=doc.indexOf(match, pos); if(len == -1) { break; } pos = len + match.length; count++; } return count; } var html = content.document.body.innerHTML.toLowerCase() for(var i=0; i&lt;keywords.length; i++) { var kw = keywords[i]; myDump(kw + ": " + wordcount(html, kw)); } </code></pre> <p>With 100 keywords, this takes approximately 10 to 20 seconds to run. There is some scope to reduce the number of keywords, but it will still need to run much quicker.</p> <p>Is there a more obvious way to do this? What is the most efficient method? I have some ideas, but am reluctant to code each up without some idea of the performance I can expect:</p> <ul> <li>Navigate the DOM rather than using innerHTML. Will this be likely quicker or slower? It would have the benefit of only searching textual content.</li> <li>Loop through the document word by word, accumulating a count of each word's occurence simultaneously. With this method I would have to do a bit more work parsing the HTML.</li> </ul> <p><em>Edit: Turns out that the slowest part was the myDump function writing to the error console. Duh! Nevertheless, there some interesting more efficient alternatives have been presented, which I am intending to use.</em></p>
<p>I could not find hasItem, setItem or getItem in prototypes Hash like tvanfosson suggested, but used set and get and wrote a hasItem based on get. But profiling showed that it is slower to use prototypes Hash compared to javascripts native object.</p> <p>If you have an array with keywords, convert it to an hash object with the keywords as the key and a value of 0: </p> <pre><code>function prepareCount(words) { var result = {}; for (var i=0,len=words.length; i &lt; len; i++) { result[words[i]] = 0; } return result; } </code></pre> <p>Instead of splitting the string and go through it with a for statement, you could use a function as a parameter to replace. In the tests I did this was much faster. In the regexp I choosed to match everything but white space. You probably want to add other separators like parentheses, comma, dot and dash and so on, or if you know the text is ASCII only, you can use a-z instead. </p> <pre><code>function countKeywords(text,wordcount) { text.replace(/[^\s]+/g,function(s) { if (wordcount[s]!==undefined) { ++wordcount[s];} return ""; }); return wordcount; } </code></pre> <p>To use it:</p> <pre><code>var wordcount = countKeywords(document.documentElement.textContent.toLowerCase(),prepareCount(["my","key","words"])); </code></pre> <p><strong>Update:</strong></p> <p>Use this regexp to exclude all delimiters in ASCII but underscore (allows non ASCII characters):</p> <pre><code>/[^\s\x00-\x2F\x3A-\x40\x5B-\x5E\x60\x7B-\x7F]+/g </code></pre> <p>if you know that your text with keywords are ASCII only, you can instead use: /[a-z]+</p>
In C++ is it possible to have a defined purely virtual function? <p>Here's the deal. I have a big class hierarchy and I have this one method that is extended all the way through. The method always has to look at one or two more variable at each new level and these variable depend on the actual class in the hierarchy. What I want to do is check those two extra variables then call the superclass's version of that same function. I want to be able to define this function as all it's immediate children will use it, but I want to force any children of that class to have to redefine that method (because they will have to look at their new data members)</p> <p>So how would I write this? I usually use =0; in the .h file, but I assume I can't use that and define it...</p>
<p>Actually you can declare a function as purely virtual and still define an implementation for it in the base class.</p> <pre><code>class Abstract { public: virtual void pure_virtual(int x) = 0; }; void Abstract::pure_virtual(int x) { // do something } class Child : public Abstract { virtual void pure_virtual(int x); }; void Child::pure_virtual(int x) { // do something with x Abstract::pure_virtual(); } </code></pre>
Domain Logic and Data Access of MVC at Remote API/Web Service Layer <p>In our system, we have a Remote API layer (e.g. SOAP, XML-RPC, REST, etc.) to handle the domain logic and data access for web application and any client applications that're developed on top of it. Unlike in the past, I do not have business logic code and DB connectivity at the web application, all user actions are translated to be invoking the methods of the layer.</p> <p>My concerns are, say for the rendering of a page, it requires making quite a number of calls to grab the data, e.g. a user dashboard with reports, recent history, some portlets, etc. With my current design (of delegating logic and DA to the Remote layer), what're the disadvantages that you are seeing? I see that establishing and transmitting text-based data via HTTP are heavier and more expensive than DB access. Besides, optimization has to be done at the Remote layer instead (given business logic &amp; DA code at the web app, you have more flexibility in optimizing).</p> <p>I am now thinking if I shall create a remote "Helper" service that allows me to squeeze all calls into one, i.e. instead of making multiple calls, I send one single call with a collection of method names and arguments. It looks a bit ugly and that's why I'm still skeptical of doing it now.</p> <p>I would like to know your opinions about this architecture and if you had developed a web appplication using the similar way, what're the approaches you had taken in the past to guarantee good performance? If there're any other concerns that I should really be worried about, please share it with me as well.</p> <p>Thanks!</p> <p>yc</p>
<p>If you use output caching in asp.net mvc properly then performance will be increased a lot.</p>
Sort an Array by keys based on another Array? <p>Is it possible in PHP to do something like this? How would you go about writing a function? Here is an example. The order is the most important thing.</p> <pre><code>$customer['address'] = '123 fake st'; $customer['name'] = 'Tim'; $customer['dob'] = '12/08/1986'; $customer['dontSortMe'] = 'this value doesnt need to be sorted'; </code></pre> <p>And I'd like to do something like </p> <pre><code>$properOrderedArray = sortArrayByArray($customer, array('name', 'dob', 'address')); </code></pre> <p>Because at the end I use a foreach() and they're not in the right order (because I append the values to a string which needs to be in the correct order and I don't know in advance all of the array keys/values).</p> <p>I've looked through PHP's internal array functions but it seems you can only sort alphabetically or numerically. </p>
<p>Just use <code>array_merge</code> or <code>array_replace</code>. <code>Array_merge</code> works by starting with the array you give it (in the proper order) and overwriting/adding the keys with data from your actual array:</p> <pre><code>$customer['address'] = '123 fake st'; $customer['name'] = 'Tim'; $customer['dob'] = '12/08/1986'; $customer['dontSortMe'] = 'this value doesnt need to be sorted'; $properOrderedArray = array_merge(array_flip(array('name', 'dob', 'address')), $customer); //Or: $properOrderedArray = array_replace(array_flip(array('name', 'dob', 'address')), $customer); //$properOrderedArray -&gt; array('name' =&gt; 'Tim', 'address' =&gt; '123 fake st', 'dob' =&gt; '12/08/1986', 'dontSortMe' =&gt; 'this value doesnt need to be sorted') </code></pre> <p>ps - I'm answering this 'stale' question, because I think all the loops given as previous answers are overkill.</p>
Make enter key behave like tab key on form <p>Is there an easy way to move around controls on a form exactly the same way as the tab key? This includes moving around cells on a datagridview etc.</p>
<p>using winforms you should set the Form KeyPreview property to true</p> <p>and in the keypress event for the form you should have </p> <pre><code>private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == 13) GetNextControl(ActiveControl, true).Focus(); } </code></pre>
Show tooltip when selecting item on asp:DropDownList <p>I have an asp:DropDownList on a page that, due to the 1024x768 development standard can truncate some of the text values in the dropdown (not enough of them, apparently, to redesign the layout ), so I need to display a tooltip of the selected value <em>when</em> a dropdown item is being selected (i.e. when the dropdown is shown and an item is being hovered over), preferably only when the text for that item is being truncated.</p> <p>Is this possible by default, javascript hacking or only my imagination?</p>
<pre><code>foreach (ListItem _listItem in this.DropDownList1.Items) { _listItem.Attributes.Add("title", _listItem.Text); } </code></pre> <p>// add a tooltip for the selected item also</p> <pre><code>DropDownList1.Attributes.Add("onmouseover", this.title=this.options[this.selectedIndex].title"); </code></pre>
How can I download all emails with attachments from Gmail? <p>How do I connect to Gmail and determine which messages have attachments? I then want to download each attachment, printing out the Subject: and From: for each message as I process it.</p>
<p>Hard one :-)</p> <pre><code>import email, getpass, imaplib, os detach_dir = '.' # directory where to save attachments (default: current) user = raw_input("Enter your GMail username:") pwd = getpass.getpass("Enter your password: ") # connecting to the gmail imap server m = imaplib.IMAP4_SSL("imap.gmail.com") m.login(user,pwd) m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead # use m.list() to get all the mailboxes resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp) items = items[0].split() # getting the mails id for emailid in items: resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc email_body = data[0][1] # getting the mail content mail = email.message_from_string(email_body) # parsing the mail content to get a mail object #Check if any attachments at all if mail.get_content_maintype() != 'multipart': continue print "["+mail["From"]+"] :" + mail["Subject"] # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach for part in mail.walk(): # multipart are just containers, so we skip them if part.get_content_maintype() == 'multipart': continue # is this part an attachment ? if part.get('Content-Disposition') is None: continue filename = part.get_filename() counter = 1 # if there is no filename, we create one with a counter to avoid duplicates if not filename: filename = 'part-%03d%s' % (counter, 'bin') counter += 1 att_path = os.path.join(detach_dir, filename) #Check if its already there if not os.path.isfile(att_path) : # finally write the stuff fp = open(att_path, 'wb') fp.write(part.get_payload(decode=True)) fp.close() </code></pre> <p>Wowww! That was something. ;-) But try the same in Java, just for fun!</p> <p>By the way, I tested that in a shell, so some errors likely remain.</p> <p>Enjoy</p> <p><strong>EDIT:</strong></p> <p>Because mail-box names can change from one country to another, I recommend doing <code>m.list()</code> and picking an item in it before <code>m.select("the mailbox name")</code> to avoid this error:</p> <blockquote> <p>imaplib.error: command SEARCH illegal in state AUTH, only allowed in states SELECTED</p> </blockquote>
Getting raw HTTP request from CFHTTPMessageRef <p>I am working with a wrapper class for <code>CFHTTPMessage</code>, which contains a <code>CFHTTPMessageRef</code> object to which is added the method (GET), the URL of the web application server, and a few custom headers containing the date and an authentication nonce.</p> <p>I'm having some problems getting the method and URL to return certain data. I think I've worked out the authentication nonce. </p> <p>I'd like to troubleshoot this by looking at the raw request going to the web application, and making sure everything is formatted properly. </p> <p>My question is: If I have a <code>CFHTTPMessageRef</code> object (e.g. <code>messageRef</code>), is there a way to log the raw HTTP request that comes out of this message?</p> <p>I've tried the following but I get a <code>EXC_BAD_ACCESS</code> signal when I try to access its bytes:</p> <pre><code>CFDataRef messageData = CFHTTPMessageCopyBody(messageRef); </code></pre> <p>Thanks for any advice.</p> <p>As an alternative, is it possible to use a packet sniffer on a switched network? I can run <code>ettercap</code> on a laptop device, but don't know how to sniff what my iPhone is doing on the local wireless network.</p>
<p>The following worked well:</p> <pre><code>NSData *d = (NSData *)CFHTTPMessageCopySerializedMessage(messageRef); NSLog(@"%@",[[[NSString alloc] initWithBytes:[d bytes] length:[d length] encoding:NSUTF8StringEncoding] autorelease]); </code></pre> <p>Hope this is helpful to others.</p>
Comparing dates in Lingo <p>How do I compare two dates in Lingo? To be specific, I want to know if today's date is after some fixed date. I know I can create the fixed date by using:</p> <pre><code>date("20090101") </code></pre> <p>and I can get the current date using:</p> <pre><code>_system.date() </code></pre> <p>but I can't seem to directly compare the two. Do I have to parse the _system.date() to determine if it's after my fixed date? I tried:</p> <pre><code>if(_system.date() &gt; date("20090101") then --do something end if </code></pre> <p>but that doesn't seem to work. Any ideas?</p>
<p>Instead of _system.date(), try _movie.systemDate(), it will return a date object that you can safely compare with another one.</p> <p>if _movie.systemDate() > date("20090101") then</p> <pre><code>--do something </code></pre> <p>end if</p> <p>regards</p>
Why is there "class" in "template <class x>"? <p>What does the "class" part of a template statement do?</p> <p>Example:</p> <pre><code>template &lt;class T&gt; class Something { public: Something(const T &amp;something); } </code></pre> <p>And what else can go there? I usually only see "class".</p>
<p>The <code>class</code> keyword means the same thing as the <code>typename</code> keyword for the most part. They both indicates that T is a type.</p> <p>The only difference between the keywords <code>class</code> and <code>typename</code> is that <code>class</code> can be used to provide class template template arguments to a template, whereas <code>typename</code> can't. Consider:</p> <pre><code>template&lt;template &lt;class T&gt; class U&gt; // must be "class" std::string to_string(const U&lt;char&gt;&amp; u) { return std::string(u.begin(),u.end()); } </code></pre> <p>The only other thing you can put in place of the <code>class</code> or <code>typename</code> keywords is an integral type. For example:</p> <pre><code>template&lt;std::size_t max&gt; class Foo{...}; ... Foo&lt;10&gt; f; </code></pre> <p>For a concrete example of this, take a look at <code>std::bitset&lt;N&gt;</code> in the standard library.</p>
Getting the time zone as a UTC offset on windows and linux <p>What is the simplest way to get the machine's time zone as a positive or negative UTC offset, preferably using some time of shell command?</p>
<p>For all Unix-ish operating systems, when using the GNU date command:</p> <p><code>date +%z</code></p> <p>Example, for Eastern European Time (my timezone):</p> <pre> [moocha@helium ~]$ date +%z +0200 </pre>
Code Coverage tools for PHP <p>Is there any code coverage tool available for PHP? I wish to check the code coverage of my code and API's written in PHP, but have not been able to lay my hands on any code coverage tool for PHP, as it is more of a server side language and dynamic in nature.</p> <p>Does anyone know of a method by which code coverage for PHP can be executed?</p>
<p><a href="http://www.xdebug.org/" rel="nofollow">xdebug</a> has <a href="http://www.xdebug.org/docs/code_coverage" rel="nofollow">Code Coverage Analysis</a>.</p> <p>Check <a href="https://phpunit.de/manual/current/en/code-coverage-analysis.html" rel="nofollow">this chapter</a> of the PHPUnit Manual</p>
Getting week number off a date in MS SQL Server 2005? <p>Is it possible to create an sql statement that selects the week number (NOT the day of week - or the day number in a week). I'm creating a view to select this extra information along with a couple of other fields and thus can not use a stored procedure. I'm aware that it's possible to create a UDF to do the trick, but if at all possible i'd rather only have to add a view to this database, than both a view and a function.</p> <p>Any ideas? Also where i come from, the week starts monday and week 1 is the first week of the year with atleast 4 days.</p> <h3>Related:</h3> <blockquote> <p><a href="http://stackoverflow.com/questions/274861/how-do-i-calculate-the-week-number-given-a-date">How do I calculate the week number given a date?</a></p> </blockquote>
<p>Be aware that there are differences in what is regarded the correct week number, depending on the culture. Week numbers depend on a couple of assumptions that differ from country to country, see <a href="http://en.wikipedia.org/wiki/Week#Week_number" rel="nofollow">Wikipedia article on the matter</a>. There is an <a href="http://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow">ISO standard</a> (ISO 8601) that applies to week numbers.</p> <p>The SQL server integrated <code>DATEPART()</code> function does not necessarily do The Right Thing. SQL Server assumes day 1 of week 1 would be January 1, for many applications that's wrong.</p> <p>Calculating week numbers correctly is non-trivial, and different implementations can be found on the web. For example, there's an UDF that calculates the <a href="http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=60510" rel="nofollow">ISO week numbers from 1930-2030</a>, being one among many others. You'll have to check what works for you.</p> <p>This one is from <a href="https://msdn.microsoft.com/library/ms186755.aspx#sectionToggle8" rel="nofollow">Books Online</a> (though you probably want to use <a href="http://stackoverflow.com/a/348945/18771">the one from Jonas Lincoln's answer</a>, the BOL version seems to be incorrect):</p> <pre><code>CREATE FUNCTION ISOweek (@DATE DATETIME) RETURNS INT AS BEGIN DECLARE @ISOweek INT SET @ISOweek = DATEPART(wk,@DATE) +1 -DATEPART(wk,CAST(DATEPART(yy,@DATE) AS CHAR(4))+'0104') -- Special cases: Jan 1-3 may belong to the previous year IF (@ISOweek=0) SET @ISOweek = dbo.ISOweek(CAST(DATEPART(yy,@DATE) - 1 AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1 -- Special case: Dec 29-31 may belong to the next year IF ((DATEPART(mm,@DATE)=12) AND ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))&gt;= 28)) SET @ISOweek=1 RETURN(@ISOweek) END GO </code></pre>
Another LINQ Pivot Problem - Convert SQL Script to LINQ <p>There are a few questions on SO already regarding LINQ pivots and while a couple of them outline my exact problem, I can't successfully translate them to a working solution. I feel that this is mostly due to a join in my tables.</p> <p>So for the benefit of all the LINQ junkies out there who love a problem, here's another puzzle for you to work out. Please help me out (and earn some reputation points and much respect from me) by converting the following SQL stored proc script to LINQ:</p> <pre><code>ALTER PROCEDURE [dbo].[GetTimesheetForWeekById] @timesheetid int, @begindate VarChar(20), @enddate VarChar(20) AS BEGIN SELECT T.TaskName, SUM( case DATEPART(weekday, TE.StartTime) WHEN 1 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Sunday, SUM( case DATEPART(weekday, TE.StartTime) when 2 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Monday, SUM( case DATEPART(weekday, TE.StartTime) when 3 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Tuesday, SUM( case DATEPART(weekday, TE.StartTime) when 4 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Wednesday, SUM( case DATEPART(weekday, TE.StartTime) when 5 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Thursday, SUM( case DATEPART(weekday, TE.StartTime) when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Friday, SUM( case DATEPART(weekday, TE.StartTime) when 6 THEN DATEDIFF(minute, TE.StartTime, TE.EndTime) ELSE 0 END ) AS Saturday FROM Tasks T INNER JOIN TimeEntries TE on T.TaskID = TE.TaskID WHERE TE.StartTime BETWEEN (CONVERT(datetime, @begindate, 103)) AND (CONVERT(datetime, @enddate, 103)) AND TE.TimesheetID = @timesheetid GROUP BY T.TaskName END </code></pre>
<p>Well, assuming that the foreign key has an object representation, something like:</p> <pre><code> int timesheetId = ... DateTime start = ..., end = ... var qry = from timeEntry in ctx.TimeEntries let date = timeEntry.StartTime.Date where timeEntry.TimesheetId == timesheetId &amp;&amp; date &gt;= start &amp;&amp; date &lt;= end group timeEntry by timeEntry.Task.TaskName into grp select new { TaskName = grp.Key, Monday = grp.Where(x =&gt; x.StartTime.DayOfWeek == DayOfWeek.Monday).Count(), Tuesday = grp.Where(x =&gt; x.StartTime.DayOfWeek == DayOfWeek.Tuesday).Count(), Wednesday = grp.Where(x =&gt; x.StartTime.DayOfWeek == DayOfWeek.Wednesday).Count(), Thursday = grp.Where(x =&gt; x.StartTime.DayOfWeek == DayOfWeek.Thursday).Count(), Friday = grp.Where(x =&gt; x.StartTime.DayOfWeek == DayOfWeek.Friday).Count() }; </code></pre> <p>Unfortunately, some of the specifics depend on the SQL provider - i.e. which functions (like DayOfWeek etc) it can map successfully as TSQL. Let me know if you get problems...</p>
member control through admin account using php <p>I am new to php. I made a member registration on login page and adm too. So inside admin I wanted to get the list of the members and delete the members I dont want. So I took the a code from a sample code for phone book from <a href="http://localhost/xamp" rel="nofollow">http://localhost/xamp</a> and editted it to my requirement I am able to retrieve the members but unable to delete the members. See the code below:</p> <p> <pre><code>require_once('../config.php'); //Array to store validation errors $errmsg_arr = array(); //Validation error flag $errflag = false; //Connect to mysql server $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } //Select database $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } </code></pre> <p>?> </p> <pre><code>&lt;body&gt; &amp;nbsp;&lt;p&gt; &lt;h2&gt;&lt;?php echo "User list"; ?&gt;&lt;/h2&gt; &lt;table border="0" cellpadding="0" cellspacing="0"&gt; &lt;tr bgcolor="#f87820"&gt; &lt;td&gt;&lt;img src="img/blank.gif" alt="" width="10" height="25"&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="150" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo $TEXT['phonebook-attrib1']; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="150" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo $TEXT['phonebook-attrib2']; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="150" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo $TEXT['phonebook-attrib3']; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td class="tabhead"&gt;&lt;img src="img/blank.gif" alt="" width="50" height="6"&gt;&lt;br&gt;&lt;b&gt;&lt;?php echo $TEXT['phonebook-attrib4']; ?&gt;&lt;/b&gt;&lt;/td&gt; &lt;td&gt;&lt;img src="img/blank.gif" alt="" width="10" height="25"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php $firstname=$_REQUEST['firstname']; $lastname=$_REQUEST['lastname']; $phone=$_REQUEST['phone']; if($_REQUEST['action']=="del") { $result=mysql_query("DELETE FROM members WHERE member_id={$_REQUEST['member_id']}"); } $result=mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname"); $i = 0; while($row = mysql_fetch_array($result)) { if ($i &gt; 0) { echo "&lt;tr valign='bottom'&gt;"; echo "&lt;td bgcolor='#ffffff' height='1' style='background-image:url(img/strichel.gif)' colspan='6'&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; } echo "&lt;tr valign='middle'&gt;"; echo "&lt;td class='tabval'&gt;&lt;img src='img/blank.gif' alt='' width='10' height='20'&gt;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;&lt;b&gt;".$row['lastname']."&lt;/b&gt;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;".$row['firstname']."&amp;nbsp;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;".$row['member_id']."&amp;nbsp;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;&lt;a onclick=\"return confirm('".$TEXT['userlist-sure']."');\" href='userlist.php?action=del&amp;amp;member_1d=".$row['member_id']."'&gt;&lt;span class='red'&gt;[".$TEXT['userlist-button1']."]&lt;/span&gt;&lt;/a&gt;&lt;/td&gt;"; echo "&lt;td class='tabval'&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; $i++; } echo "&lt;tr valign='bottom'&gt;"; echo "&lt;td bgcolor='#fb7922' colspan='6'&gt;&lt;img src='img/blank.gif' alt='' width='1' height='8'&gt;&lt;/td&gt;"; echo "&lt;/tr&gt;"; ?&gt; &lt;/table&gt; &lt;/body&gt; </code></pre> <p></p> <p>I haven't editted it that properly and the looks in all.</p> <p>Please help me in making it able to delete the members also.</p> <p>I didn't understand what .$TEXT['userlist-button1'].,'".$TEXT['userlist-sure']. variables are? I also want to include an approved and disapproved radio button in table for each members.</p> <p>How can I do that?</p> <p>Please if you can help me.</p>
<ol> <li>This should be a POST via a FORM not a href link (GET).</li> <li>$TEXT is obviously an array holding the text you want printed.</li> <li>You need to replace <code>&amp;amp;member_1d</code> in the href with a real &amp; and a real i as <code>&amp;member_id</code>.</li> </ol>
I don't want a "close window" menu item in the task bar context menu for my WPF window <p>I don't want a "close window" menu item in the task bar context menu for my WPF window. My intention is to annoy the user.</p> <p>Thank you!</p>
<p>An easier option would be to do this:</p> <pre><code>&lt;Window ShowInTaskbar="False" ... /&gt; </code></pre>
Calculating a LookAt matrix <p>I'm in the midst of writing a 3d engine and I've come across the LookAt algorithm described in the DirectX documentation:</p> <pre><code>zaxis = normal(At - Eye) xaxis = normal(cross(Up, zaxis)) yaxis = cross(zaxis, xaxis) xaxis.x yaxis.x zaxis.x 0 xaxis.y yaxis.y zaxis.y 0 xaxis.z yaxis.z zaxis.z 0 -dot(xaxis, eye) -dot(yaxis, eye) -dot(zaxis, eye) l </code></pre> <p>Now I get how it works on the rotation side, but what I don't quite get is why it puts the translation component of the matrix to be those dot products. Examining it a bit it seems that it's adjusting the camera position by a small amount based on a projection of the new basis vectors onto the position of the eye/camera.</p> <p>The question is why does it need to do this? What does it accomplish?</p>
<p><strong>Note the example given is a left-handed, row major matrix</strong>.</p> <p>So the operation is: Translate to the origin first (move by -<em>eye</em>), then rotate so that the vector from <em>eye</em> to <em>At</em> lines up with +z:</p> <p>Basically you get the same result if you pre-multiply the rotation matrix by a translation -<em>eye</em>:</p> <pre> [ 1 0 0 0 ] [ xaxis.x yaxis.x zaxis.x 0 ] [ 0 1 0 0 ] * [ xaxis.y yaxis.y zaxis.y 0 ] [ 0 0 1 0 ] [ xaxis.z yaxis.z zaxis.z 0 ] [ -eye.x -eye.y -eye.z 1 ] [ 0 0 0 1 ] [ xaxis.x yaxis.x zaxis.x 0 ] = [ xaxis.y yaxis.y zaxis.y 0 ] [ xaxis.z yaxis.z zaxis.z 0 ] [ dot(xaxis,-eye) dot(yaxis,-eye) dot(zaxis,-eye) 1 ] </pre> <h3>Additional notes:</h3> <p>Note that a viewing transformation is (intentionally) <strong>inverted</strong>: you multiply every vertex by this matrix to "move the world" so that the portion you want to see ends up in the canonical view volume.</p> <p>Also note that the rotation matrix (call it <em>R</em>) component of the LookAt matrix is an <em>inverted change of basis</em> matrix where the rows of <em>R</em> are the new basis vectors in terms of the old basis vectors (hence the variable names xaxis.x, .. xaxis is the <em>new</em> x axis after the change of basis occurs). Because of the inversion, however, the rows and columns are transposed.</p>
Report section style list numbering in CSS? <p>Now I know about the "normal" CSS list styles (roman, latin, etc) and certainly in years past they were somewhat inflexible in not allowing things like:</p> <p>(a)</p> <p>or </p> <p>a)</p> <p>only</p> <p>a.</p> <p>Now I believe that you can get an effect like the above with the :before and :after pseudo-elements. Is that correct? And whats the browser compatibility like if you can?</p> <p>My main question however is that I want to have report style numbering:</p> <ol> <li>Introduction 1.1 Objectives 1.2 Assumptions 1.3 Limitations 1.3.1 ...</li> <li>New Section ...</li> </ol> <p>and so on.</p> <p>Can CSS do this and, if so, whats the browser compatibility like?</p>
<p>See <a href="http://www.w3.org/TR/CSS2/generate.html">Generated content, automatic numbering, and lists</a>.</p> <blockquote> <p>This example shows a way to number chapters and sections with "Chapter 1", "1.1", "1.2", etc.</p> </blockquote> <pre><code>H1:before { content: "Chapter " counter(chapter) ". "; counter-increment: chapter; /* Add 1 to chapter */ counter-reset: section; /* Set section to 0 */ } H2:before { content: counter(chapter) "." counter(section) " "; counter-increment: section; } </code></pre> <p>Edit: <a href="http://www.quirksmode.org/css/contents.html">quirksmode.org</a> has a better table of css supports on browsers. Almost all browsers, except pre IE8b2 IEs. So yes, totally useless.</p>
How long before ASP.NET MVC becomes widely used in industry? <p>I am trying to decide whether to learn ASP.NET MVC (or to spend the time learning another technology that interests me). I know that it is an elegant framework, but I am trying to assess my future job opportunities if I invest in this skill. In your estimation, how long is it going to be before demand for ASP.NET MVC developers rivals that for developers in the other top web dev frameworks? Is it a matter of a year? 2 years? 3+? On a related note, do you see use of ASP.NET MVC surpassing classic ASP.NET in the foreseeable future? Scott Guthrie says the two will exist side by side, but I'm curious just how much of the mind share ASP.NET MVC is expected to grab.</p> <p>I know this is a speculative question; I'm just interested in your subjective hunches.</p>
<p>For mainstream adoption, I wouldn't expect it will really take off until after RTM. Initially work will be limited to new projects, which I suspect there may be fewer of with the economy being as it is. The real increase in jobs will come when there are more established projects requiring maintenance. </p> <p>As for surpassing the original ASP.NET, that will happen when more older projects are decommissioned, either in one hit, or by sections being replaced by new MVC functionality. </p> <p>Personally, I would learn at least the basics now, so as to be ready for an increase after RTM.</p>
how to display xml in javascript? <p>As the question says, it just escaped my memory how to display xml in javascript, I want to display some source xml within an div on a page, that sits next to the processed result of the xml in another div.</p> <p>Can't remember if there was an equivalent to javascript's escape to convert entities on the client </p> <p><strong>Note</strong>: the xml files are served as is from the server, so I need a client side solution</p> <p><strong>Note</strong>: the main problem is XML doesn't render correctly in most browsers, all the brackets and attributes disappear, leaving you with text that doesn't look like xml</p>
<p>Fetch your XML using Ajax and simply put the result in a <code>textarea</code>. Style the textarea any way you want.</p>
MySQL tool or query that suggests table structure <p>I used a query a few weeks ago in MySQL that described a table and suggested possible improvements to its structure. For example, if I have an int field but only the numbers 1-3 in that field, it will suggest set(1,2,3) as the type.</p> <p>I think I was using phpMyAdmin but I've been through all the functions I can find - Analyze, Describe, Explain, Optimize, etc - to no avail. I can't for the life of me remember what the query was!</p>
<p>This is what phpMyAdmin gives me:</p> <pre><code>SELECT * FROM `table_name` PROCEDURE ANALYSE ( ) </code></pre>
.net architecture: Creating a IRepository<T> generically <p>I am using a generic repository interface which allows me to add, find, update and delete objects of different types. I have then implemented two concrete repositories and can switch them around without changing the application. Everything is wonderfully disconnected. But I have hit a snag. The code inside my repository methods just feels wrong and I cannot figure out how to do it better. Here is a snippet of my code:</p> <pre><code>public class OracleRepository&lt;T&gt; : IRepository&lt;T&gt; where T : new() { public IQueryable&lt;T&gt; GetAll() { if (typeof(T) == typeof(Object1)) { return (IQueryable&lt;T&gt;)DataAccess.GetAllObject1().AsQueryable(); } if (typeof(T) == typeof(Object2)) { return (IQueryable&lt;T&gt;)DataAccess.GetAllObject2().AsQueryable(); } throw new NotImplementedException(); } } </code></pre> <p>The problem is that my DataAccess (creates objects from a datareader) is not generic and has specific methods for each type of object that it supports. </p> <p>Can I rewrite the above so that I avoid the list of if-then-elseif using generics or otherwise?</p>
<p>One common pattern is to use a dictionary from type to a function of the relevant type. For instance:</p> <pre><code>private static readonly IDictionary&lt;Type, Func&lt;object&gt;&gt; Fetchers = new Dictionary&lt;Type, Func&lt;object&gt;&gt;(); { (typeof(Object1), () =&gt; DataAccess.GetAllObject1().AsQueryable()), (typeof(Object2), () =&gt; DataAccess.GetAllObject2().AsQueryable()), // etc }; public IQueryable&lt;T&gt; GetAll() { Func&lt;object&gt; func = Fetchers[typeof(T)]; if (func == null) { throw new NotImplementedException(); } return (IQueryable&lt;T&gt;) func(); } </code></pre> <p>The cast is there because you can't really express the type relationship in the dictionary, but at least it's slightly easier to add new types etc.</p> <p>You may be able to move the call to <code>AsQueryable()</code> to <code>GetAll()</code> depending on what <code>GetAllObject1()</code> etc return.</p>
Version control of MDF files <p>I'm working on a web app (it is in asp.net mvc framework beta in visual studio 2008) and want to version control it. How do I version control the database files (*.mdf, binary) in the App_Data folder. </p> <p>Is there a way to just store the tables-and-whatever definition of the database or do I really need to version control it's contents?</p>
<p>Export the database structure as creation scripts, and potentially export some table (reference) data as insert scripts, then check those into source control.</p> <p>Definitely do NOT attempt to put the database binaries (*.mdf) into source control.</p>
How can I convert a REG_BINARY value from the registry into a string ? (vb.net) <p>I have a registry value which is stored as a binary value (REG_BINARY) holding information about a filepath. The value is read out into an byte array. But how can I transform it into a readable string?</p> <p>I have read about system.text.encoding.ASCII.GetString(value) but this does not work. As far as I got to know the registry value is arbitrary binary data and not ASCII which is the reason for the method to produce useless data.</p> <p>Does anybody know how I can convert the data? </p> <p>Sample: (A piece of the entry)</p> <pre><code>01 00 00 00 94 00 00 00 14 00 00 00 63 00 3A 00 5C 00 70 00 72 00 6F 00 67 00 72 00 61 00 6D 00 6d 00 65 00 5C 00 67 00 65 00 6D 00 65 00 69 00 6E 00 73 00 61 00 6D 00 65 00 20 00 64 00 61 00 74 00 65 00 69 00 65 00 6E 00 5C </code></pre> <p>Due to the regedit this is supposed to be:</p> <pre><code>............c.:.\.p.r.o.g.r.a.m.m.e.\.g.e.m.e.i.n.s.a.m.e. .d.a.t.e.i.e.n.\ </code></pre> <p>The entry itself was created from Outlook. It's an entry for an disabled addin item (resiliency)</p>
<p>Well, it's not <em>arbitrary</em> binary data - it's text data in <em>some</em> kind of encoding. You need to find out what the encoding is.</p> <p>I wouldn't be surprised if <code>Encoding.Unicode.GetString(value)</code> worked - but if that doesn't, please post a sample (in hex) and I'll see what I can do. What does the documentation of whatever's put the data in there say?</p> <p>EDIT: It looks like Encoding.Unicode is your friend, but starting from byte 12. Use</p> <pre><code>Encoding.Unicode.GetString(bytes, 12, bytes.Length-12) </code></pre>
SQL statement problem <p>I have this code:</p> <pre><code>SELECT idcallhistory3, callid, starttime, answertime, endtime, duration, is_answ, is_fail, is_compl, is_fromoutside, mediatype, from_no, to_no, callerid, dialednumber, lastcallerid, lastdialednumber, group_no, line_no FROM "public".callhistory3 WHERE (starttime &gt;= ?) AND (endtime &lt;= ?) AND (is_fromoutside = ?) AND (from_no = ?) AND (to_no = ?) </code></pre> <p>The problem is I need to pass one value for ? and get all the result without filter, some thing like *</p> <p>Any help?</p>
<pre><code>WHERE (@start is null OR starttime &gt;= @start) AND (@end is null OR endtime &lt;= @end) AND (@fromOutside is null OR is_fromoutside = @fromOutside) AND (@fromNo is null OR from_no = @fromNo) AND (@toNo is null OR to_no = @toNo) </code></pre> <p>Pass nulls for all parameters (dang sql nulls; thanks GC).</p>
Is there an equivalent of ASF View for MP4 files? <p>I'm working on our encoding software, and have come across a strange issue where files in a 16:9 aspect ratio are being played in 4:3 in some players, post-transcode from WMV to MP4. Using ASF view I can see that the source WMV file appears to have incorrect data in its BITMAPINFOHEADER structure (it reports that is has 4:3 dimensions but is actually 16:9), but is there an equivalent tool for MP4 files so I can check whether this problem has been carried through to the transcoded file?</p> <p>I want to read the metadata that is embedded in the stream, rather than using a tool that renders it using DirectShow/FFmpeg/other as these appear to do some mangling and report the correct aspect ratio.</p>
<p>After a bit of looking around I found MP4Box which can be used to retrieve this information using the <code>-info</code> switch, e.g.</p> <pre><code>mp4box.exe -info filename.mp4 </code></pre> <p>If anybody is interested, it turns out the problem was that the original WMV stream had the <code>AspectRatioX</code> and <code>AspectRatioY</code> metadata attributes set so that the video has non-square pixels. This non-square metadata was carried through to the MP4 file so it should play back correctly (and does in Windows Media Player) however it appears that Flash ignores this metadata attribute and plays it using square pixels.</p>
Built-in helper to parse User.Identity.Name into Domain\Username <p>Is there any built-in utility or helper to parse <code>HttpContext.Current.User.Identity.Name</code>, e.g. <code>domain\user</code> to get separately domain name if exists and user?</p> <p>Or is there any other class to do so?</p> <p>I understand that it's very easy to call <code>String.Split("\")</code> but just interesting</p>
<p>This is better (<em>easier to use, no opportunity of <code>NullReferenceExcpetion</code> and conforms MS coding guidelines about treating empty and null string equally</em>):</p> <pre><code>public static class Extensions { public static string GetDomain(this IIdentity identity) { string s = identity.Name; int stop = s.IndexOf("\\"); return (stop &gt; -1) ? s.Substring(0, stop) : string.Empty; } public static string GetLogin(this IIdentity identity) { string s = identity.Name; int stop = s.IndexOf("\\"); return (stop &gt; -1) ? s.Substring(stop + 1, s.Length - stop - 1) : string.Empty; } } </code></pre> <p>Usage:</p> <pre><code>IIdentity id = HttpContext.Current.User.Identity; id.GetLogin(); id.GetDomain(); </code></pre> <p>This requires C# 3.0 compiler (or newer) and doesn't require 3.0 .Net for working after compilation.</p>
Sniffing queries to SQL Server <p>Is there a way to sniff SQL queries sent to a SQL Server db on any level (above transport level)? Perhaps there's some kind of a tracer in ASP.NET or built-in log in SQL Server ? </p>
<p>SQL Server Profiler perhaps? This will pick up what queries are executed. You can also get statistics, query plans and many other items of interest from this.</p>
Friendly Byte Formatting in Rails <p>I need to format an integer representation of bytes into something friendly, and I'm hoping that there's a utility function in Ruby or in Rails that will do that formatting for me (to perpetuate my laziness, of course.)</p> <p>I'm looking for something that would look like:</p> <pre><code>format_bytes(1024) -&gt; "1 KB" format_bytes(1048576) -&gt; "1 MB" </code></pre> <p>Looks like there's some stuff in ActiveSupport to do it the other way around, but I haven't found a way to do it in this direction.</p> <p>If there isn't one that exists, does anyone have a particularly elegant solution?</p>
<p><a href="http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html">Number to human size</a> is what you're looking for.</p> <pre><code>require 'action_view' include ActionView::Helpers::NumberHelper number_to_human_size(123) # =&gt; 123 Bytes number_to_human_size(1234) # =&gt; 1.2 KB number_to_human_size(12345) # =&gt; 12.1 KB number_to_human_size(1234567) # =&gt; 1.2 MB number_to_human_size(1234567890) # =&gt; 1.1 GB number_to_human_size(1234567890123) # =&gt; 1.1 TB number_to_human_size(1234567, :precision =&gt; 2) # =&gt; 1.18 MB number_to_human_size(483989, :precision =&gt; 0) # =&gt; 473 KB number_to_human_size(1234567, :precision =&gt; 2, :separator =&gt; ',') # =&gt; 1,18 MB </code></pre>
How to dynamically invoke a chain of delegates in VB.NET <p>Does someone knows if it's possible to dynamically create a call chain and invoke it?</p> <p>Lets say I have two classes A &amp; B:</p> <pre><code>public class A public function Func() as B return new B() end function end class public class B public function Name() as string return "a string"; end function end class </code></pre> <p>I want to be able to get <em>MethodInfo</em> for both <em>Func()</em> &amp; <em>Name()</em> and invoke them dynamically so that I can get a call similar to <em>A.Func().Name()</em>.</p> <p>I know I can use <em>Delegate.CreateDelegate</em> to create a delegate I can invoke from the two <em>MethodInfo</em> objects but this way I can only call the two functions separately and not as part of a call chain.</p> <p>I would like two solutions one for .NET 3.5 using expression tree and if possible a solution that is .NET 2.0 compatible as well</p>
<p>Are you using .NET 3.5? If so, it should be relatively straightforward to build an expression tree to represent this. I don't have enough expression-tree-fu to easily write the relevant tree without VS open, but if you confirm that it's an option, I'll get to work in notepad (from my Eee... hence the lack of VS).</p> <p>EDIT: Okay, as an expression tree, you want something like (C# code, but I'm sure you can translate):</p> <pre><code>// I assume you've already got fMethodInfo and nameMethodInfo. Expression fCall = Expression.Call(null, fMethodInfo); Expression nameCall = Expression.Call(fCall, nameMethodInfo); Expression&lt;Func&lt;string&gt;&gt; lambda = Expression.Lambda&lt;Func&lt;string&gt;&gt;(nameCall, null); Func&lt;string&gt; compiled = lambda.Compile(); </code></pre> <p>This is untested, but I think it should work...</p>
Vim: NERD_tree Plugin. Need help understanding a bloggers .vimrc addition to streamline this plugin <p>So I'm basically a beginner when it comes to Vim, nonetheless I do know the basic things (open files, edit, move around, basic grep, .vimrc, etc)</p> <p>I would submit this link first</p> <p><a href="http://weblog.jamisbuck.org/2008/11/17/vim-follow-up" rel="nofollow">http://weblog.jamisbuck.org/2008/11/17/vim-follow-up</a></p> <p>If you scroll down to where it says "NERD___tree", it explains what it is and gives a link to the home page. I have already gotten NERD_tree installed, so far so good.</p> <p>Only thing is, this guy (JamisBuck) adds a line to the .vimrc file to streamline it's usage (I'm guessing to toggle between NERD_tree and the actual file, because as far as I can tell, there is no quick way to do it other than typing in:</p> <pre><code>:NERDTree </code></pre> <p>Every time which is less than desirable. The follwing is the code he adds to the .vimrc file:</p> <pre><code>map &lt;leader&gt;d :execute 'NERDTreeToggle ' . getcwd()&lt;CR&gt; </code></pre> <p>He doesn't explain exactly what is is and/or how to use it, so If someone could give me a short explanation and/or point me towards a resource to learn more about this, that would be appreciated.</p>
<p>I'd say <code>:help leader</code> will give you what you need, is an anti-slash by default.</p> <p>Thus, <code>map &lt;leader&gt;d</code> will be launched when you do <code>\d</code>.</p>
How do I set LC_ALL and LANG under IIS? <p>I am trying to run some Perl CGI scripts under IIS. I get the following message :</p> <pre> <code> CGI Error The specified CGI application misbehaved by not returning a complete set of HTTP headers. The headers it did return are: perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LC_ALL = (unset), LANG = (unset) are supported and installed on your system. perl: warning: Falling back to the standard locale ("C"). </code> </pre> <p>I found out that the problem occurs only when I "use" an internal library of ours but it's really a big one (using many other stuff) so I would prefer to know where to look. When I run the same script from the command line, the script runs just fine. I tried to set "LANG" to "C", then "LC_ALL" to "C" but it had no effect.</p> <p>Any pointers welcome!</p>
<p>The LANG and LC_ALL environment variables are set for your shell, but they aren't set for IIS. I'm not an IIS person, but the docs say that IIS is a service and you have to set those ahead of time then reboot.</p> <p>Alternatively, you can set these variables as soon your script starts to compile (and before you load your large library that is causing the problems:</p> <pre> BEGIN { $ENV{LC_ALL} = ...; $ENV{LANG} = ...; } </pre> <p>Get the values that you should use by looking at the ones you have in your shell.</p> <p>Good luck,</p>
Strange caching of .js file in firefox/tomcat/eclipse <p>I'm developing <code>.jsp</code> using eclipse and tomcat. </p> <p>My <code>.jsp</code> outputs html to pull in some javascript from a <code>.js</code> file. The <code>jsp</code> outputs the code which hooks up the function <code>mapTool</code> to the mousedown event. <code>imfMapFunctions5101.js</code> contains the mapTool(e) function.</p> <p><strong>The changes I make to the .js file do not take affect when I run in firefox, although they do when I run in IE.</strong> </p> <p>in the .jsp:</p> <pre><code>out.println("&lt;script language=\"JavaScript\" type=\"text/javascript\" src=\"imfMapFunctions5101.js\"&gt;&lt;/script&gt;"); .... out.println("function startup() {"); out.println(" hideLayer(\"loadMap\");"); out.println(" if (document.layers) {"); out.println(" document.captureEvents(Event.MOUSEDOWN | Event.MOUSEMOVE | Event.MOUSEUP);"); out.println(" }"); out.println(" document.onmousedown = mapTool;"); out.println(" **alert(document.onmousedown);**") //pops up the event code in the browser ; ....... </code></pre> <p>The javascript event code in <code>imfMapFunctions5101.js</code>:</p> <pre><code>function mapTool (e) { **alert('mapTool'); //my alert** if (dTools.activeTool == "Drill Down Identify") { showLayer("loadData"); ..... </code></pre> <p>when <code>alert(document.onmousedown);</code> pops up in IE I can see the event code with my added alerts:</p> <pre><code>function mapTool (e) { **alert('mapTool'); //my alert** if (dTools.activeTool == "Drill Down Identify") { showLayer("loadData"); .... </code></pre> <p>In firefox the event code that pops up does NOT contain my alert:</p> <pre><code>function mapTool (e) { if (dTools.activeTool == "Drill Down Identify") { showLayer("loadData"); </code></pre> <p>It's like the file is caching and firefox insists on getting the old cached .js file. Pretty sure that's not what happening. Have tried updating the .jsp timestamp, renaming the javascript to a bogus name, then back again. </p> <p>What's going on?</p> <p>ANy help much appreciated?</p>
<p>try refreshing the page wile clearing cache: shift+click on refresh button, or clearing the cache under tools->clear private data</p>
Conway's Game Of Life <p>I am currently writting a programe about Conway's Game of life and I am really a beginner of python, I don't know how to start at all. Anybody can help me with it?</p>
<p><a href="http://plife.sourceforge.net/" rel="nofollow">http://plife.sourceforge.net/</a></p> <p>Send the 50 quid to me :)</p> <p>(I'm kidding, of course)</p>
How do I fix my output for floating-point imprecision? <p>I am doing some float manipulation and end up with the following numbers:</p> <pre><code>-0.5 -0.4 -0.3000000000000000004 -0.2000000000000000004 -0.1000000000000000003 1.10E-16 0.1 0.2 0.30000000000000000004 0.4 0.5 </code></pre> <p>The algorithm is the following:</p> <pre><code>var inc:Number = nextMultiple(min, stepSize); trace(String(inc)); private function nextMultiple(x:Number, y:Number) { return Math.ceil(x/y)*y; } </code></pre> <p>I understand the fact the float cannot always be represented accurately in a byte. e.g 1/3. I also know my stepsize <strong>being 0.1</strong>. If I have the stepsize how could I get a proper output?</p> <p>The strange thing is that its the first time I've encountered this type of problem. Maybe I dont play with float enough.</p>
<p>A language agnostic solution would be to store your numbers as an integer number of steps, given that you know your step size, instead of as floats.</p> <p>A non-language agnostic solution would be to find out what your language's implementation of <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf.html" rel="nofollow">printf</a> is.</p> <pre><code>printf ("float: %.1f\n", number); </code></pre>
RegEx for extracting HTML Image properties <p>I need a RegEx pattern for extracting all the properties of an image tag.</p> <p>As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.</p> <p>I was looking at this solution <a href="http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php" rel="nofollow" title="How to Extract img src title and alt">http://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php</a> but it didn't quite get it all:</p> <p>I come up something like:</p> <pre><code>(alt|title|src|height|width)\s*=\s*["'][\W\w]+?["'] </code></pre> <p>Is there any possibilities I'll be missing or a more efficient simple pattern?</p> <p>EDIT: <br>Sorry, I will be more specific, I'm doing this using .NET so it's on the server side. <br>I've already a list of img tags, now I just need to parse the properties.</p>
<blockquote> <p>As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.</p> </blockquote> <p>It won't. Use a HTML parser if you have to parse "evil" (from an unknown source) HTML.</p>
ASP.NET ViewState postback with page refresh and bookmarks <p>The ASP.NET ViewState feature can sometimes be a double edged sword. I rely on it on most of my projects and it speeds up development considerably.</p> <p>My problem is that sometimes users will try to refresh a page which will cause the viewstate to be lost, other times the user might want to bookmark a page but when the get back the viewstate will be lost.</p> <p>Modern browsers will display a silly dialog when a user tries to refresh a page that is the result of a POST operation (e.g. asp postback) which is not desirable at all.</p> <p>I wonder is their a way to continue using ViewState and the postback model but without the drawback of the refresh dialog box. (and if possible bookmark the page.)</p> <p>An example of what i might want to do is having a page with records and checkboxes next to them, the user has the option to check all the records they want to delete and then click on a delete button. After the user clicks delete the records are analyzed on the server and the new page lists all the records that were selected with a confirm delete button. Now if the user clicks refresh they get this silly box to confirm if they want to post or not.</p> <p>I understant that ViewState is the result of using the Post Back model which means that most asp.net pages are the result of a POST operation, but i wonder if there are any ways around it.</p> <p>Workarounds that i thought might work: <br /> In the Page_Unload event save the viewstate in the session with a unique id and redirect the user to the same page with the unique id as a query string parameter, after the page loads with a unique id in the url the viewstate is loaded from the session and injected into the current page. Such a method will allow to user to refresh the page and always get back the same results.</p> <p>P.S. I understand that i can use <code>Response.Redirect()</code> and/or query strings but i want to use the simplicity of <code>ViewState</code></p>
<p>My 2 cents: Instead of using the simplicity of <strong>ViewState</strong> sandbag use the simplicity of <strong>Session</strong> - which really is the same simplicity and you won't have to bother worrying about page refresh and stuff. Moreover session is way more flexible since you can use it to store more than just built-in types without affecting performance (you can do it with ViewState as well but you will affect performance).</p>
Testing for whitespace in SQL Server <p>I've got some blank values in my table, and I can't seem to catch them in an IF statement. </p> <p>I've tried</p> <p><code>IF @value = ''</code> and <code>if @value = NULL</code> and neither one catches the blank values. Is there any way to test whether or not a varchar is entirely whitespace?</p> <p>AHA! Turns out I was testing for null wrong. Thanks. </p>
<pre><code>ltrim(rtrim(isNull(@value,''))) = '' </code></pre>
Child controller updating a label for a cell in parent table view <p>I have a navigation view with a cell that has something as simple as a Date of Birth. When that particular row is clicked, a new controller get pushed into view with a UIDatePicker. Once a new date is selected, I'd imagine I need to do something in viewWillDisappear: for that particular cell's UITextField value. What's the best way for me to do that? Do I need to pass in a reference to the cell's indexPath in the childController, set it there, and reload the tableView's data? </p> <p>Another tricky tidbit is let's say that my data source for the tableView is a dictionary with key/value pairs. When I call reloadData on the tableView, it'll re-read that dictionary without taking into note the date change my child controller has made. </p>
<p>First, the best place to reload data is in that particular UIViewController's viewWillAppear: method. That way you don't need to worry about references to the table in other controllers.</p> <p>Second, if I'm not misunderstanding, I think you need to brush up on objects. As long as what you change in the editing (child) controller is a reference to the same object that the table (parent) controller uses, the data will be synced. If, on the other hand, you're reloading data (say, from a file) for each controller, I'd take a look at how your app architecture works. Objects are your friend. Take advantage of that.</p>
What tools do you recommend to profile Rails apps? <p>I've been looking for profiling tools for Rails for a while. I'm currently playing and testing ruby-prof and railsbench, but I kinda frustrated with the amount of tweaking and mangling required to make then work.</p> <p>Althought I don't mind (much) the tweaking, I'd like to know if is there any other, more straight-forward and easy to use, tools to profile a Rails app? Which tools you recommend?</p>
<p>You can use the <a href="http://wiki.rubyonrails.org/rails/pages/ProfilerScript">built in profiler</a> as well:</p> <pre><code>$ ruby script/performance/profiler 'User.new' 5 % cumulative self self total time seconds seconds calls ms/call ms/call name 189.25 1.76 1.76 1 1760.00 1760.00 Profiler__.start_profile 43.01 2.16 0.40 115 3.48 3.91 ActiveRecord::ConnectionAdapters::Column#simplified_type 8.60 2.24 0.08 15 5.33 8.67 Array#each 7.53 2.31 0.07 115 0.61 5.39 ActiveRecord::ConnectionAdapters::Column#initialize 6.45 2.37 0.06 115 0.52 0.52 ActiveRecord::ConnectionAdapters::Column#type_cast 5.38 2.42 0.05 690 0.07 0.07 Regexp#=== 0.00 2.69 0.00 10 0.00 0.00 Process.times 0.00 2.69 0.00 10 0.00 0.00 Benchmark.times </code></pre> <p>Note that for Rails 3, you can use <code>rails profiler</code>.</p>
How to convert a string to a Guid <p>I did not find the TryParse method for the Guid. I’m wondering how others handle converting a guid in string format into a guid type.</p> <pre><code>Guid Id; try { Id = new Guid(Request.QueryString["id"]); } catch { Id = Guid.Empty; } </code></pre>
<pre><code>new Guid(string) </code></pre> <p>You could also look at using a <code>TypeConverter</code>.</p>
Eclipse Custom Variable for Java Code Templates <p>How do you add a new variable to be inserted into a Java code template. How do I add a variable to the list in Window->Preferences->Java->Code Style->Code Templates->Code->New Java Files->Edit->Insert Variable... ?</p> <p>Currently my new files get created with:</p> <pre><code>${filecomment} ${package_declaration} ${typecomment} ${type_declaration} </code></pre> <p>I'd like them to get created with something like:</p> <pre><code>${begin_filecomment} ${package_declaration} ${typecomment} ${type_declaration} ${end_filecomment} </code></pre> <p>where begin_filecomment and end_filecomment appear in the Insert Variable list.</p>
<p>Yes, you can indeed add a variable to this list. See the extension point called</p> <p>org.eclipse.ui.editors.templates</p> <p>and you'll find out how.</p>
How do I use a variable in a grep with groovy? <p>I need to grep for lines with bunch of names, say "clientLogin=a@yahoo.com", "clientLogin=b@gmail.com" from a file.txt file.txt has junk which is email=a@yahoo.com email=b@gmail.com. I need to filter these out</p> <p>Once I get these lines I need to grep for gmail and yahoo and get their counts</p> <pre><code>List l = new ArrayList{a@yahoo.com, b@gmail.com} def gmail = ['sh','-c','grep "clientLogin="$l.get(0) file.txt' | grep gmail | wc -l ] def yahoo = ['sh','-c','grep "clientLogin="$l.get(1) file.txt' | grep yahoo| wc -l ] </code></pre> <p>This doesn't work. How can I substitute the $l.get(1) value dynamically?</p> <hr> <p>the problem is that ${l.get(0)} has to be inside the " ", i.e. def gmail = ['sh','-c','grep "clientLogin=${l.get(0)}" file.txt' | grep gmail | wc -l ] so that it will look like def gmail = ['sh','-c','grep "clientLogin=a@yahoo.com" file.txt' | grep gmail | wc -l ] but "clientLogin=${l.get(0)}" doesn't produce the result. I am not sure where I am going wrong. </p> <p>Thanks for your suggestion but it doesn't produce the result, at least when I tried it.</p> <hr> <p>file.txt has lot of junk and a pattern something like "Into the domain clientLogin=a@yahoo.com exit on 12/01/2008 etc.."</p> <p>hence I do </p> <p>def ex = ['sh','-c','grep "domain clientLogin=$client" file.txt'| grep "something more" | wc -l]</p> <p>that way I can chain the grep as I want and eventually land at the count I need.</p> <p>I am not sure if I can chain the greps if I use </p> <p>def ex = ['grep', "$client", 'file.txt']</p> <p>thanks for your input.</p>
<p>You're already using groovy, does using a regular expression that gives you your answer work?</p> <pre><code>def file = new File("file.txt") file.delete() // clear out old version for multiple runs file &lt;&lt; """ foobar clientLogin=a@yahoo.com baz quux # should match a@yahoo.com foobar email=a@yahoo.com baz quux foobar email=b@gmail.com bal zoom foobar clientLogin=a@yahoo.com baz quux # should match a@yahoo.com foobar clientLogin=b@gmail.com bal zoom # should match b@gmail.com foobar email=b@gmail.com bal zoom """ def emailList = ["a@yahoo.com", "b@gmail.com"] def emailListGroup = emailList.join('|') def pattern = /(?m)^.*clientLogin=($emailListGroup).*$/ def resultMap = [:] (file.text =~ pattern).each { fullLine, email -&gt; resultMap[email] = resultMap[email] ? resultMap[email] + 1 : 1 } assert resultMap["a@yahoo.com"] == 2 assert resultMap["b@gmail.com"] == 1 </code></pre> <p>That feels cleaner to me than trying to shell out to a process and working with that, plus it only will pick out the exact lines with "clientLogin=(email)" that you're looking for.</p>
SQL Server Tool to script drop statements which have check existence statements before them? <p>I have tried SQL Server 2008 Management Studio and other third party tools to script all database objects (views, SPs &amp; tables) and I can't get anything to generate a one file script which has a drop statement preceded with an "If exists.." statement for every object.</p> <p>I need the "if exists" statement so I don't get any errors if an object doesn't exist. The tool doesn't have to be for sql server 2008. </p>
<p>SQL 2008 Management Studio can do this. Right click on the database name and select Tasks->Generate Scripts...check the box that says 'All Database Objects' and then on the next screen set Include If NOT EXISTS to True (this will also do the If Exists...though it's not apparent) and Script Drop to True. I think this will work for you.</p>
SQL query to calculate visit duration from log table <p>I have a MySQL table LOGIN_LOG with fields ID, PLAYER, TIMESTAMP and ACTION. ACTION can be either 'login' or 'logout'. Only around 20% of the logins have an accompanying logout row. For those that do, I want to calculate the average duration.</p> <p>I'm thinking of something like</p> <pre><code>select avg(LL2.TIMESTAMP - LL1.TIMESTAMP) from LOGIN_LOG LL1 inner join LOGIN_LOG LL2 on LL1.PLAYER = LL2.PLAYER and LL2.TIMESTAMP &gt; LL1.TIMESTAMP left join LOGIN_LOG LL3 on LL3.PLAYER = LL1.PLAYER and LL3.TIMESTAMP between LL1.TIMESTAMP + 1 and LL2.TIMESTAMP - 1 and LL3.ACTION = 'login' where LL1.ACTION = 'login' and LL2.ACTION = 'logout' and isnull(LL3.ID) </code></pre> <p>is this the best way to do it, or is there one more efficient?</p>
<p>Given the data you have, there probably isn't anything much faster you can do because you have to look at a LOGIN and a LOGOUT record, and ensure there is no other LOGIN (or LOGOUT?) record for the same user between the two.</p> <p>Alternatively, find a way to ensure that a disconnect records a logout, so that the data is complete (instead of 20% complete). However, the query probably still has to ensure that the criteria are all met, so it won't help the query all that much.</p> <p>If you can get the data into a format where the LOGIN and corresponding LOGOUT times are both in the same record, then you can simplify the query immensely. I'm not clear if the SessionManager does that for you.</p>
How bad is ignoring Oracle DUP_VAL_ON_INDEX exception? <p>I have a table where I'm recording if a user has viewed an object at least once, hence:</p> <pre><code> HasViewed ObjectID number (FK to Object table) UserId number (FK to Users table) </code></pre> <p>Both fields are NOT NULL and together form the Primary Key.</p> <p>My question is, since I don't care how many times someone has viewed an object (after the first), I have two options for handling inserts.</p> <ul> <li>Do a SELECT count(*) ... and if no records are found, insert a new record.</li> <li>Always just insert a record, and if it throws a DUP_VAL_ON_INDEX exceptions (indicating that there already was such a record), just ignore it.</li> </ul> <p>What's the downside of choosing the second option?</p> <p>UPDATE:</p> <p>I guess the best way to put it is : "Is the overhead caused by the exception worse than the overhead caused by the initial select?"</p>
<p>I would normally just insert and trap the DUP_VAL_ON_INDEX exception, as this is the simplest to code. This is more efficient than checking for existence before inserting. I don't consider doing this a "bad smell" (horrible phrase!) because the exception we handle is raised by Oracle - it's not like raising your own exceptions as a flow-control mechanism.</p> <p>Thanks to Igor's comment I have now run two different benchamrks on this: (1) where all insert attempts except the first are duplicates, (2) where all inserts are not duplicates. Reality will lie somewhere between the two cases.</p> <p>Note: tests performed on Oracle 10.2.0.3.0.</p> <p><strong>Case 1: Mostly duplicates</strong></p> <p>It seems that the most efficient approach (by a significant factor) is to check for existence WHILE inserting:</p> <pre><code>prompt 1) Check DUP_VAL_ON_INDEX begin for i in 1..1000 loop begin insert into hasviewed values(7782,20); exception when dup_val_on_index then null; end; end loop rollback; end; / prompt 2) Test if row exists before inserting declare dummy integer; begin for i in 1..1000 loop select count(*) into dummy from hasviewed where objectid=7782 and userid=20; if dummy = 0 then insert into hasviewed values(7782,20); end if; end loop; rollback; end; / prompt 3) Test if row exists while inserting begin for i in 1..1000 loop insert into hasviewed select 7782,20 from dual where not exists (select null from hasviewed where objectid=7782 and userid=20); end loop; rollback; end; / </code></pre> <p>Results (after running once to avoid parsing overheads):</p> <pre><code>1) Check DUP_VAL_ON_INDEX PL/SQL procedure successfully completed. Elapsed: 00:00:00.54 2) Test if row exists before inserting PL/SQL procedure successfully completed. Elapsed: 00:00:00.59 3) Test if row exists while inserting PL/SQL procedure successfully completed. Elapsed: 00:00:00.20 </code></pre> <p><strong>Case 2: no duplicates</strong></p> <pre><code>prompt 1) Check DUP_VAL_ON_INDEX begin for i in 1..1000 loop begin insert into hasviewed values(7782,i); exception when dup_val_on_index then null; end; end loop rollback; end; / prompt 2) Test if row exists before inserting declare dummy integer; begin for i in 1..1000 loop select count(*) into dummy from hasviewed where objectid=7782 and userid=i; if dummy = 0 then insert into hasviewed values(7782,i); end if; end loop; rollback; end; / prompt 3) Test if row exists while inserting begin for i in 1..1000 loop insert into hasviewed select 7782,i from dual where not exists (select null from hasviewed where objectid=7782 and userid=i); end loop; rollback; end; / </code></pre> <p>Results:</p> <pre><code>1) Check DUP_VAL_ON_INDEX PL/SQL procedure successfully completed. Elapsed: 00:00:00.15 2) Test if row exists before inserting PL/SQL procedure successfully completed. Elapsed: 00:00:00.76 3) Test if row exists while inserting PL/SQL procedure successfully completed. Elapsed: 00:00:00.71 </code></pre> <p>In this case DUP_VAL_ON_INDEX wins by a mile. Note the "select before insert" is the slowest in both cases.</p> <p>So it appears that you should choose option 1 or 3 according to the relative likelihood of inserts being or not being duplicates. </p>
Can I have multiple php.ini files? <p>I want to set the <code>include_path</code> variable in my <em>php.ini</em> file (<code>C:\Windows\php.ini</code>).</p> <p>But, I want different <code>include_path</code> values for different sites hosted on the same Windows server. How can I do this?</p>
<p><a href="http://php.net/manual/en/configuration.file.php" rel="nofollow">http://php.net/manual/en/configuration.file.php</a> says:</p> <blockquote> <p>php.ini is searched for in these locations (in order):</p> <p>. . .</p> </blockquote> <p>You can review this list and see if one of the techniques helps in your case. For example, you can set the environment variable <code>PHPRC</code>, or you can put a different php.ini file in each current working directory, assuming each virtual host has a distinct cwd.</p> <p>Note that when using Apache and mod_php, or other module embedding PHP in the web server (e.g. FastCGI), the php.ini file is read once, at web server startup. When you use PHP in a CGI manner, the php.ini file is read during every web request, so you have more opportunity to use a different php.ini.</p>
PHP new operator returning reference <p>I'm working with some old PHP code that has a lot of the following:</p> <pre><code>$someVar =&amp; new SomeClass(); </code></pre> <p>Did the <strong>new</strong> operator ever return a value, um, not by reference? (That feels strange to type. I feel like I'm losing my mind.)</p>
<p>It was one of those sort of optimization techniques taught in a lot of older books on OOP in PHP 4.</p> <p>Basically, the initial object created in memory is one the application can't access unless you return the instance by reference. Otherwise you get a copy of the object - the only catch is that the original exists without a symbol. Kinda dumb.</p> <p>But ya, object creating and passing and references in PHP 4 is a monumental mess.</p>
Multi column primary keys? <p>For example I have 2 tables, <code>Users</code> and <code>UserRelations</code>, and it is a one to many relationship.</p> <p>For the <code>UserRelations</code> table, I can have an identity column and make it the primary key: </p> <pre><code>[RelationID] [int] IDENTITY(1,1) NOT NULL, [UserID] [int] NOT NULL, [TargetID] [int] NOT NULL, </code></pre> <p>Or I can design the table like:</p> <pre><code>[UserID] [int] NOT NULL, [TargetID] [int] NOT NULL, </code></pre> <p>and make <code>UserID</code> + <code>TargetID</code> the primary key.</p> <p>My question is what are the implications of going with each design, which is better for performance?</p>
<p>If you use the former design, with the superfluous identity column, there's no constraint against inserting two rows with identical UserID and TargetID. You'd have to create a <code>UNIQUE</code> constraint over the other two columns, which creates a compound index anyway.</p> <p>On the other hand, some frameworks (e.g. Rails) insist that every table has a surrogate key named <code>id</code> so the "correct" design may not work. It depends on what code you're writing to use this table design.</p>
Four nodes with a width of 25% don't fit next to each other? <p>I have a header node in which four child nodes reside. None have borders, padding nor margins. All four of them have the width:25%; css rule. In Opera it works just fine, in IE the last block flips to the next line sometimes depending on the width of the window.</p> <p>I can solve it by giving one block a width of 24.8%, but Opera interprets that as 24% and thus leaves a wide open gap of 1% at the end of the blocks.</p> <p>How can I solve this? It would be ok for the last block to miss a pixel on the right.</p>
<p><a href="http://ejohn.org/blog/sub-pixel-problems-in-css/">http://ejohn.org/blog/sub-pixel-problems-in-css/</a></p> <p>This is a well-known issue in the CSS world, unfortunately. Likely the issue is that the 100% pixel-equivalent these fit into is an odd number, so there is a rounding error when calculating pixels. </p> <p>Usually I solve this by using an IE-specific selector for . Rob suggests browser-specific stylesheets, but I always found that behavior hard to maintain, and it requires an additional HTTP load from a browser. I do also hate CSS hacks, but you can try the famous #width:24.9% after declaring the proper width (e.g. width:25%; #width:24.9%; ). Hopefully if IE fixes this hack in future versions, it's also along with the rounding issue.</p> <p>Also, if you know the pixel width of the parent element, you could just make sure it's evenly divisible by 4. But if this is a fluid layout, that's not an option.</p>
Where can I find a list of SocketErrorCode and NativeErrorCode thrown by SocketException? <p>A SocketException has a SocketErrorCode and NativeErrorCode. I would like to find a list where these codes (or the common onces) are listed so I can respond in proper fasion.</p> <p>Does anybody know where to find such a list?</p>
<p>MSDN? <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socketerror.aspx" rel="nofollow">SocketError</a>; or from the native ErrorCode, the <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socketexception.errorcode.aspx" rel="nofollow">MSDN page</a> states: "For more information about socket error codes, see the Windows Sockets version 2 API error code documentation in MSDN.".</p> <p>A few searches shows this <a href="http://msdn.microsoft.com/en-us/library/ms740668.aspx" rel="nofollow">here</a>.</p>
.Net: Read properties of and disable the screensaver and other power schemes <p>I have a long-running GUI application that outputs various statuses to the user. The user wants to view every status but doesn't want to worry about the screensaver kicking in after the inactivity settings.</p> <p>Preferably in C#, how do I read the screensaver/power scheme settings (so I can reapply them when my app exits) and use settings appropriate for my app (basically disabling them)?</p> <p>EDIT: I'm going to run my own tests on these answers before I mark either as a solution. If someone has had success with either, please vote it up so I try it first.</p>
<p>The screensaver timeout values are in the registry:</p> <p><a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/oct04/hey1027.mspx" rel="nofollow">How can I change the screensaver timeout values</a> (sample code in there should be easy enough to convert to C#)</p> <p>Not sure about the power scheme settings but <a href="http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Script/Q_22951821.html" rel="nofollow">this post</a> might be useful</p>
Multiple Font/Language support in Flash <p>Greetings,</p> <p>I'm in the middle of writing a Flash application which has multilingual support. My initial choice of font for this was Tahoma, for its Unicode support. The client prefers a non-standard font such as Lucida Handwriting. Lucida Handwriting doesn't have the same, say, Cyrillic support as Tahoma, which poses a problem that there are a few ways to solve, and I'd like to ask for your advice on which is preferable:</p> <p>From what I understand, I could:</p> <ul> <li>Give the client a list of fully Unicode-compatible (Cyrillic, Hebrew, Arabic, Traditional Chinese, East Asian, etc) fonts to choose from. (I have no idea where to get such a list; my search of the web has resulted only in lists of partially unicode-compliant fonts. Try <a href="http://look.fo/list-of-unicode-compliant-fonts" rel="nofollow">http://look.fo/list-of-unicode-compliant-fonts</a> as a good starting point to see where I looked).</li> <li>Depending on the client's location (which we already have), render in Lucida Handwriting for English-speaking users and in Tahoma for international users. This may be somewhat of a headache; has anyone had any experience with this approach?</li> <li>Build a new font (IE, AlexeyMK Bold) which uses Lucida Handwriting for English and Tahoma for everything else. This ads something like 500k to the weight of the Flash file, but should (if I understand correctly) only be loaded the first time. </li> </ul> <p>What do you advise? Which of these are reasonable solutions, and which are completely out there? Is there a way that I'm not thinking of?</p> <p>Much thanks! Alexey</p> <p>EDIT: A good article on the subject: <a href="http://www.itworld.com/print/58558" rel="nofollow">http://www.itworld.com/print/58558</a></p>
<p>Well, ultimately you have only two real choices: either you embed a font in your SWF, guaranteeing what your fonts will look like, or you don't, and use device fonts. (Or a mixture of the two, using embedded or device fonts depending on region.)</p> <p>If you don't embed any fonts, then whatever font you define for your text is ultimately just a suggestion - what the user will see is device fonts, being rendered by their own machine (using the fonts on that machine). So you can "suggest" Tahoma, but what the user sees will depend on whether they have that font (and it might vary for, say, Mac versions of the font vs. PC versions). Naturally this also depends on support; if they don't have Asian fonts then then they won't see any Chinese for example. (Note: you can also choose a font like "_sans", which just tells the client to use its standard sans-serif font. My guess is that in practice this will wind up being the same font that would have been chosen if you'd defined "Tahoma", but YMMV.)</p> <p>If you embed your fonts, then the user will see exactly what you expect them to, because the font is rendered by Flash and not the OS. But if you embed fully for all regions, including the glyphs needed for Chinese, then I think you'll find it adds considerably more than 500K.. more like 2-5MB in my experience. But maybe there are some details I'm missing. Anyway, for content to be delivered over the web I would generally assume that, at minimum, asian fonts should be device fonts.</p> <p>To add a word about a mixed solution, I've done this and it's doable. That is, assuming you can add the logic to your SWF, you could (for example) make two of each text field, one using embedded "Lucida whatever" and the other using non-embedded "_sans", and then at runtime make one of them invisible and put text in the other, depending on which region you're showing. (I did this by making a single LocalizedTextfield component, and having it read the locale out of a static property when it initialized.) Then you simply have to decide, for each locale, whether the file size is worth the display for that particular set of glyphs.</p> <p>The final word is, you can't necessarily assume that the file size incurred by your fonts will only be loaded once. If you make your content the straightforward way and embed fonts in your text fields, then the font info will be part of your SWF, and thus loaded every time no matter what. To externalize it you could make the Label component a separate file, and then the decision to load it or not is up to the browser's caching settings. You can also externalize the font resource itself and use it as a shared resource, but in AS2 this is somewhat hairy to get working. I've heard it's easier in AS3 but not done it myself.</p>
What's the shortest TSQL to concatenate a person's name which may contain nulls <p>3 fields: FirstName, MiddleName, LastName</p> <p>Any field can be null, but I don't want extra spaces. Format should be "First Middle Last", "First Last", "Last", etc.</p>
<pre><code> LTRIM(RTRIM( LTRIM(RTRIM(ISNULL(FirstName, ''))) + ' ' + LTRIM(RTRIM(ISNULL(MiddleName, ''))) + ' ' + LTRIM(ISNULL(LastName, '')) )) </code></pre> <p>NOTE: This won't leave trailing or leading spaces. That's why it's a little bit uglier than other solutions.</p>
An algorithm to get the next weekday set in a bitmask <p>I've got this small question - given a bitmask of weekdays (e.g., <code>Sunday = 0x01, Monday = 0x02, Tuesday = 0x04</code>, etc...) and today's day (in a form of <code>Sunday = 1, Monday = 2, Tuesday = 3</code>, etc...) - what's the most elegant way to find out the next day from today, that's set in the bitmask? By elegant I mean, is there a way to do this without if/switch/etc..., because I know the non-elegant way?</p> <p><strong>Edit</strong> I probably should've mentioned (to make this more clear) that the variable holding the bitmask can have several of the days set, so for example (roughly):</p> <pre><code>uDay = Sunday | Monday; today = Tuesday; </code></pre> <p>I need to get "Sunday"</p>
<pre><code>int getNextDay(int days_mask, int today) { if (!days_mask) return -1; // no days set days_mask |= days_mask &lt;&lt; 7; // duplicate days into next week mask = 1 &lt;&lt; (today % 7); // keep track of the day while (!(mask &amp; days_mask)) { mask &lt;&lt;= 1; ++today; } return today % 7; } </code></pre> <p>So that's just one if at the beginning and while loop. How's that?</p> <p><strong>Edit:</strong> I just realized there was a degenerate case where if the use passes today>=14 (or greater than the highest bit set) the while loop becomes infinite. The (today % 7) on line 4 fixes this case.</p> <p>And if I may grouse (light-heartedly) about the other version getting the checkmark, my version only have 2 modulus calls, while the checked solution will have a minimum of 1 and a maximum of 6 modulus calls.</p> <p>Also, the comment about does the function return "today" if today is set is interesting. If the function should not return today unless today is the only day in the set would require that you pre-increment today on line 3 of my solution.</p>
What are the problems associated with serving pages with Content: application/xhtml+xml <p>Starting recently, some of my new web pages (XHTML 1.1) are setup to do a regex of the request header <code>Accept</code> and send the right HTTP response headers if the user agent accepts XML (Firefox and Safari do).</p> <p>IE (or any other browser that doesn't accept it) will just get the plain <code>text/html</code> content type. </p> <p>Will Google bot (or any other search bot) have any problems with this? Is there any negatives to my approach I have looked over? Would you think this header sniffer would have much effect on performance?</p>
<p>One problem with content negotiation (and with serving different content/headers to different user-agents) is proxy servers. Considering the following; I ran into this back in the Netscape 4 days and have been shy of server side sniffing ever since.</p> <p>User A downloads your page with Firefox, and gets a XHTML/XML Content-Type. The user's ISP has a proxy server between the user and your site, so this page is now cached.</p> <p>User B, same ISP, requests your page using Internet Explorer. The request hits the proxy first, the proxy says "hey, I have that page, here it is; as <strong>application/xhtml+xml</strong>". User B is prompted to download the file (as IE will download anything sent as application/xhtml+xml.</p> <p>You can get around this particular issue by using the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">Vary Header</a>, as described in this <a href="http://www.456bereastreet.com/archive/200408/content_negotiation/">456 Berea Street</a> article. I also assume that proxy servers have gotten a bit smarter about auto detecting these things.</p> <p>Here's where the <a href="http://stackoverflow.com/questions/348736/xhtml-is-writing-self-closing-tags-for-elements-not-traditionally-empty-bad-pra">CF that is HTML/XHTML</a> starts to creep in. When you use content negotiation to serve application/xhtml+xml to one set of user-agents, and text/html to another set of user agents, you're relying on all the proxies between your server and your users to be well behaved. </p> <p>Even if all the proxy servers in the world were smart enough to recognize the Vary header (they aren't) you still have to contend with the computer janitors of the world. There are a lot of smart, talented, and dedicated IT professionals in the world. There are more not so smart people who spend their days double clicking installer applications and thinking "The Internet" is that blue E in their menu. A mis-configured proxy could still improperly cache pages and headers, leaving you out of luck.</p>
Have any vb applications migrated to delphi? <p>I would like to hear of the experiences of classic vb developers who migrated their applications to delphi rather than vb.net. How has it worked out? Are you glad or sorry that you didn't move to vb.net? </p>
<p>I am not really a vb developer but rather a Delphi developer who was forced to maintain some vb apps for a while. I tried to migrate one vb app to vb.net and after that experience I never tried it again. I successfully migrated several vb apps to Delphi. It wasn't easy and it became a pain in the lower back to find native Delphi replacements for some of the OCXes that had been used (I will never again rely on a third party library for which I do not have the source code.), but it worked out OK.</p> <p>But as said above: I am an experienced Delphi developer, so I didn't have to learn Delphi at the same time as migrating a vb app. That certainly made it much easier.</p>
Why are .Net programmers so afraid of exceptions? <p>First of all, I'm not trying to be critical of anyone here or saying that all .Net programmers are this way. But I'm definitely noticing a trend: .Net programmers seem to avoid exceptions like they're the plague.</p> <p>Of course, there's always the <a href="http://blogs.msdn.com/oldnewthing/archive/2004/04/22/118161.aspx" rel="nofollow">Raymond Chen</a> blog post about how hard exceptions can be to handle. But that doesn't just apply to .Net.</p> <p>In a lot of other languages/environments, I don't notice that programmers are as likely to avoid exceptions as they are in .Net. Heck, in Python, exceptions are thrown in normal program execution (iterators throw StopIteration exceptions).</p> <p>So what am I missing here? Or am I totally off base in thinking that .net programmers avoid exceptions more than others?</p>
<p>Performance is the fear monger's buzzword when it comes to exceptions - but that really only applies to throwing them or handling them in tight loops, or for when relying on them for control flow. Personally I see exceptions as another tool in my toolbox; I'm not scared of them at all. Ideally when you use exceptions you're using them in exceptional circumstances - that is, should no longer be concerned with performance, but rather with fixing the problem (rare) or failing fast and notifying the user / logging / etc.</p> <p>Edit: JaredPar mentioned a great quote regarding this that I feel is important enough to repeat: "If you're worried about Exception performance, you're using them incorrectly." Once we find attribution I'll amend this post to include it.</p>
Quick Test Pro (Regression test scripts) - Cruisecontrol.net <p>Any one succeeded in integrating Quick Test Pro (QTP) automated test scripts in Cruisecontrol.net.</p> <p>if any one have an idea to run them unattended , in a schedule task or cruisecontrol.net </p> <p>will be more useful.#</p>
<p>I am sure this will be possible using the QTP Automation Object Model. See 'QuickTest Automation' in the 'QuickTest Advanced References' section of the on-line help. You should be able to create a simple batch file to run QTP which can then be invoked via NAnt and/or CruiseControl.</p>
Determine record in multi record html form <p>In a html form, I'm displaying multiple records from a table, ready for update.</p> <p>Right now I use: <code>name=&lt;column-name&gt;_&lt;pk-id&gt; value=&lt;value&gt;</code> for the fields. Then in my python-script I go for:</p> <pre><code>for key in form.keys(): if key.startswith('&lt;name-A&gt;_'): update &lt;table&gt; set &lt;name-A&gt; = &lt;value&gt; where pk=&lt;pk-id&gt; if key.startswith('&lt;name-B&gt;_'): update &lt;table&gt; set &lt;name-B&gt; = &lt;value&gt; where pk=&lt;pk-id&gt; </code></pre> <p>Is there a more 'organic' way to handle multi-record forms?</p>
<p>In java apps, it's common to JSONify the name.</p> <pre><code>&lt;input name="records[pk].fieldName"/&gt; </code></pre> <p><code>pk</code> being the primary key of the row and <code>fieldName</code> the field. Of course most frameworks handle this transparently. Each record ends up as a instance of a class with a property for each field, all of which are put into a list called "records". You may have to write some sort of interpreter, but that shouldn't be too hard.</p>
How abstracted should MVC models be? <p>I'm in the process of extending and improving a website that has quite a few structural problems. It looks very much like the developers before me had heard of MVC but didn't understand the ideas of abstraction or modularity. So the MVC "framework" is a) bespoke b) broken c) patched and d) there are several in use all at once. I intend to fix that.</p> <p>This is not the first time I've re-built a site's framework, BTW, but it is the first time I've had to fix an MVC framework. However, I'm coming up against some missing holes in the MVC knowledge here on SO. </p> <p>The first is how closely programmers seem to tie their SQL database with their models. This doesn't make sense to me: do programmers normally have the model looking after the data abstraction? (To me this is little better than putting SQL in raw PHP code.) Or is there a data access layer normally employed that "Does SQL"? I know from experience that the latter means the calling code doesn't have to worry about where the data is, or how to get it or how to write it: the API handles that. </p> <p>But what about the Models? Are they intended to be re-usable amongst different pages? Should they care about just where the data is stored? Shouldn't they be more concerned with handling the logic between data-fetch and data-show (e.g. turning a contact's group ID into a displayable name)? And data-save and data-write (e.g. figuring out how to turn $_POST values into savable data)?</p> <p>Maybe the MVC model really be DMVC - Data-Model-View-Controller.</p> <p>Lastly, although this is from a PHP point-of-view, how well do these concepts translate to a JSP site?</p>
<p><strong>But what about the Models? Are they intended to be re-usable amongst different pages?</strong></p> <p>Yes.</p> <p><strong>Should they care about just where the data is stored?</strong> </p> <p>No. They need not know it. All this kinda information is necessary for persistence layer or data layer.</p> <p><strong>Shouldn't they be more concerned with handling the logic between data-fetch and data-show (e.g. turning a contact's group ID into a displayable name)?</strong> </p> <p>No. They are just concerned about the business logic. Some usual application I have found the folks make the model dumb, just having attributes/properties and nothing else. The typical example in Java would be POJO, with getters/setters. We call them TOs (Transfer Objects), and use them everywhere, as a data holder. I am not really in the accord of this, IMO, there should be some methods, business related, which are appropriate and qualify to be in there. Don't make it so dumb. The new Entity Beans (EJB3) are the good example of this.</p> <p>BTW, data show is the work of a presentation layer. In java JSP is the part of view technology.</p> <p><strong>And data-save and data-write (e.g. figuring out how to turn $_POST values into savable data)?</strong></p> <p>No. This is generally done in our controllers, most of the time using some utility classes.</p>
ASP.NET: Casting XPath to bool - Possible? <p>Greetings!</p> <p>I have an XML value that I'd like to use as a boolean value to toggle the visibility of a Panel. I have something like this:</p> <pre><code>&lt;asp:FormView id="MyFormView" runat="server" DataSourceID="MyXmlDataSource"&gt; &lt;ItemTemplate&gt; &lt;!-- some stuff --&gt; &lt;asp:Panel id="MyPanel" runat="server" Visible='&lt;%# (bool)XPath("Menu/Show") %&gt;'&gt; &lt;/asp:Panel&gt; &lt;!-- some more stuff --&gt; &lt;/ItemTemplate&gt; &lt;/asp:FormView&gt; &lt;asp:XmlDataSource id="MyXmlDataSource" runat="sever" DataFile="MyFile.xml" /&gt; </code></pre> <p>However, this throws an exception. I've tried setting the value of Show in my XML to "true", "True", "0", but to no avail. Is this even possible? My XPath definitely works because I've tried moving &lt;%# (bool)XPath("Menu/Show") %> outside so that I can see its value and it is correct. I have tried this:</p> <pre><code>&lt;%#((bool)XPath("Menu/Show")).ToString() %&gt; </code></pre> <p>But this also throws an exception.</p> <p>Thanks.</p>
<p>Try <code>&lt;%#(Convert.ToBoolean(XPath("Menu/Show"))) %&gt;</code></p>
How to install Hibernate Tools in Eclipse? <p>What is the proper way to install Hibernate Tools in Eclipse as a plugin? The <a href="http://www.hibernate.org/255.html">Hibernate site</a> doesn't really give any instructions.</p> <p>Looking at the Hibernate Tools binary <code>HibernateTools-3.2.4.Beta1-R200810311334.zip</code>, it appears that I can just unzip this in my eclipse directory. Do I just unzip it in my eclipse directory? This seems like a hacky was to install it.</p>
<p>Well, most convenient and safest way is to use JBoss update site within Eclipse software updates (Help -> Software Updates... -> Add Site...):</p> <p><a href="http://download.jboss.org/jbosstools/updates/stable/">The latest stable release update site for JBoss Tools</a></p> <p>There you can find Hibernate tools together with other handy JBoss plugins.</p>
How much of the compiler should we know? <p>In order to write better code, is it worth to know deeply what the compiler does? </p> <p>Just how much would be enough? I'm not a bit scrubber, but I was thinking that knowing how the compiler operates would make me a better programmer. Am I wrong? </p> <p>If so, what resources would you recommend?</p>
<p>Probably wouldn't hurt to know how the compiler will optimize your code, but <strong>don't write for the compiler, but write for people to read</strong>.</p> <p>Writing code in a way that is more optimized for the compiler may make it more difficult for people to read it, and these days the <strong>compiler probably knows better to optimize the code for you</strong>.</p>
Sharing Views <p>Is it a good idea to share views between different controllers (using the Views/Shared folder)? I am creating my first MVC application and it requires some pieces of data that are similar to each other. They "explain" different things (and will therefore be stored in different tables) but they each have an Id, Name and Status. I can therefore use different controllers which then use the same View to display the data in a drop down list, allow the user to select one to edit or add a new one via a text box. Obviously I lose the ability to have strongly typed ViewPage data but besides that, would this be considered a good way to do this or am I better off creating a View for each controller to use?</p>
<p>Personally, if the view is generic enough to be used for multiple scenarios then I would use it as so. DRY!</p>
Python method arguments with spaces <p>I would like to create a simple file format/DSL which would allow my users to input data. My system is in python and using python's parser is appealing. Syntax like this for defining a data element seems quite convenient.</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>However, it does not support param names with spaces.</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>Python parser friendly versions can look as follows, but not very user friendly.</p> <pre><code>Allocation(("Param 1",Val1), ("Param 2",Val1) ) Allocation(**{"Param 1":Val1, "Param 2":Val1} ) </code></pre> <p>Is there a way to make this more readable in python?</p>
<p>I'd imagine that there would be some way to do it. But I feel compelled to ask, is there really a big enough difference in readability from this</p> <pre><code>Allocation(Param1 = Val1, Param2 = Val2 ) </code></pre> <p>To this:</p> <pre><code>Allocation(Param 1 = Val1, Param 2 = Val2 ) </code></pre> <p>to make that big a difference? I'm sure there's a way to do what you want to do, but my first concern is if the effort involved would be worth the result.</p> <blockquote> <p>my goal is to provide a DSL which can be used for data entry into the system. In the above scenario, params would be people names and values would be percentages.</p> </blockquote> <p>I have a better understanding of what you want to do now, but I still think that you might end up having to sacrifice some readability to get what you want. Personally, I would go with something like:</p> <pre><code>Allocation( { 'name1' : value1, 'name1' : value2, } ) </code></pre> <p>If that's not something you can go with, then you might want to reconsider whether you want to use Python for your DSL or go with something home-grown. Allowing whitespace allows too many ambiguities for most programming languages to allow it.</p> <p>If you still want to pursue this with using python, you might want to consider posting to the C-API SIG (<a href="http://www.python.org/community/sigs/" rel="nofollow">SIGS</a>) or maybe the <a href="http://mail.python.org/mailman/listinfo/python-dev" rel="nofollow">python-dev list</a> (as a last resort). The only way that I can see to do this would be to embed the python interpreter into a C/C++ program and do some kind of hacking with it (which can be difficult!).</p>
How do you do inline delegates in vb.net like c#? <p>Is it possible to create an inline delegate in vb.net like you can in c#?</p> <p>For example, I would like to be able to do something inline like this:</p> <pre><code>myObjects.RemoveAll(delegate (MyObject m) { return m.X &gt;= 10; }); </code></pre> <p>only in VB and without having to do something like this</p> <pre><code>myObjects.RemoveAll(AddressOf GreaterOrEqaulToTen) Private Function GreaterOrEqaulToTen(ByVal m as MyObject) If m.x &gt;= 10 Then Return true Else Return False End If End Function </code></pre> <p>-- edit -- I should have mentioned that I am still working in .net 2.0 so I won't be able to use lambdas.</p>
<pre><code>myObjects.RemoveAll(Function(m As MyObject) m.X &gt;= 10) </code></pre> <p>See <a href="http://msdn.microsoft.com/en-us/library/bb531253.aspx">Lambda Expressions on MSDN</a></p>
Problem with Recaptcha <p>I have a problem with the form I'm using in my webpage. </p> <p>It allows the recaptcha but It also sends the email without validating the fields in the recaptcha box. This form is using Ajax and PHP.</p> <p>I've pasted the code next:</p> <pre><code>&lt;br&gt; &lt;br&gt; &lt;div id="fields"&gt; &lt;form action="javascript:alert('success!');"&gt; &lt;label&gt;Nombre&lt;/label&gt;&lt;INPUT class="textbox" type="text" name="name" value=""&gt;&lt;br /&gt; &lt;label&gt;eMail&lt;/label&gt;&lt;INPUT class="textbox" type="text" name="email" value=""&gt;&lt;br /&gt; &lt;label&gt;Asunto&lt;/label&gt;&lt;INPUT class="textbox" type="text" name="subject" value=""&gt;&lt;br /&gt; &lt;label&gt;Mensaje&lt;/label&gt;&lt;TEXTAREA class="textbox" NAME="message" ROWS="5" COLS="25"&gt;&lt;/TEXTAREA&gt;&lt;br /&gt; &lt;?php require_once('recaptchalib.php'); // Get a key from http://recaptcha.net/api/getkey $publickey = "6LekPAQAAAAAAFoAJRfRtd9vmlzA9m-********"; $privatekey = "6LekPAQAAAAAAFqNcNsrnZba0-ZMg-********"; # the response from reCAPTCHA $resp = null; # the error code from reCAPTCHA, if any $error = null; # was there a reCAPTCHA response? if ($_POST["recaptcha_response_field"]) { $resp = recaptcha_check_answer ($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if ($resp-&gt;is_valid) { echo "Bien escrito!"; } else { # set the error code so that we can display it $error = $resp-&gt;error; } } echo recaptcha_get_html($publickey, $error); ?&gt; &lt;br/&gt; &lt;label&gt;&amp;nbsp;&lt;/label&gt;&lt;INPUT class="button" type="submit" name="submit" value="Enviar"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/fieldset&gt; </code></pre> <p>Thanks a lot.</p> <p>David.</p>
<p>The problem is that you need to check the reCAPTCHA before you display the form again. The PHP code would go above the first line of the form, perferrably before any HTML is generated so the user can be redirected to a thank you page.</p>
How do you do an IN or CONTAINS in LINQ using LAMBDA expressions? <p>I have the following Transact-Sql that I am trying to convert to LINQ ... and struggling. </p> <pre><code>SELECT * FROM Project WHERE Project.ProjectId IN (SELECT ProjectId FROM ProjectMember Where MemberId = 'a45bd16d-9be0-421b-b5bf-143d334c8155') </code></pre> <p>Any help would be greatly appreciated ... I would like to do it with Lambda expressions, if possible. </p> <p>Thanks in advance!</p>
<p>GFrizzle beat me to it. But here is a C# version</p> <pre><code>var projectsMemberWorkedOn = from p in Projects join projectMember in ProjectMembers on p.ProjectId equals projectMember.ProjectId where projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" select p; </code></pre> <p>And as a bonus a purely LINQ method chain version as well:</p> <pre><code>var projectsMemberWorkedOn = Projects.Join( ProjectMembers, p =&gt; p.ProjectId, projectMember =&gt; projectMember.ProjectId, ( p, projectMember ) =&gt; new { p, projectMember } ) .Where( @t =&gt; @t.projectMember.MemberId == "a45bd16d-9be0-421b-b5bf-143d334c8155" ) .Select(@t =&gt; @t.p ); </code></pre>
ASP.NET Web Setup <p>I have 3 web projects in a Visual studio solution.I want to create a single web setup project which should install all 3 web projects in their virtual directories.So how to create a single web setup project which supports multiple web application installation?</p>
<p>You can do this by creating a Web Setup Project. In the File System add as many Web Custom Folders as you need.</p> <p>Only the main Web Application Folder will have the installation dialog so if you want to customize the virtual directory names then you will need to add a screen and set the Property of the web custom folder to be the same as the field name on the screen you add. </p>
Skipping a column in FileHelper <p>Using the <a href="http://www.filehelpers.net/" rel="nofollow">FileHelper</a> library for .Net, can I somehow skip a number of columns from the source file?</p> <p>According to docs and samples, I have to add fields for all columns. Alas, I have an excel sheet with 216 columns to import, from which as few as 13 are necessary.</p>
<p>I have the same situation, and question. Searching the forums at filehelpers.net, I found this <a href="http://www.filehelpers.net/forums/viewtopic.php?t=394" rel="nofollow">thread</a> (from 2007?!) with a response by Marcos himself:</p> <p>Question:</p> <blockquote> <p>In a delimited length layout, is it possible to skip some fields? For example: <br>ExternalSysId|ExportDate|FirstName|LastName <br>I only want FirstName and LastName, and don't want to clutter up my code with "dummy" fields? </p> </blockquote> <p>Response:</p> <blockquote> <p>The library dont have a built in feature for this. <br><br>You can make the fields private, the library will read the values, but you dont see them from your code =) If in the future you need these fields you can meke them public </p> </blockquote> <p>So, using the Record Class Wizard to reduce the amount of required typing, and then making unnecessary fields private, looks like the best option at this point.</p>
Is it true that the smallest memory allocation in .net is a byte? <p>Is it true that the smallest amount of memory that I can allocate in managed code is a byte? </p> <p>Do I understand correctly that a Boolean variable takes up much more than a bit of memory? </p> <p>Is there a way for me to allocate memory, in .net, in chunks smaller than a byte?</p>
<p>This is correct, allocations are made on a granularity of byte (possibly rounded up to an even number of bytes or even higher). This is true of any OS I've worked with, so it's not specific to managed code. The memory manager works with bytes, not bits.</p> <p>On the other hand, it's not hard to pack booleans into a bit array if you have lots of booleans and want to achieve higher storage efficiency (see <a href="http://msdn.microsoft.com/en-us/library/system.collections.bitarray.aspx">BitArray</a>).</p>
SQL Reporting Services - Restrict Export Formats <p>Is it possible to limit export formats only PDF and Excel ?</p>
<p>Comment out or remove the formats you want to exclude in the Render section of <strong>rsreportserver.config</strong> in </p> <pre><code>..\Program Files\Microsoft SQL Server\MSSQL.&lt;n&gt;\Reporting Services\ReportServer </code></pre>
Accessing calendar entries on the iPhone/iPod touch <p>is it possible to access calendar entries on the iPhone/iPod touch, i.e. reading, creating, changing, deleting appointments?</p> <p>I searched the iPhone SDK documentation but didn't find anything. Perhaps I missed something.</p>
<p>Currently this functionality is not supported by the SDK. If you need this, please consider filing a <a href="http://bugreport.apple.com" rel="nofollow">bug report</a> with Apple.</p>
How to cancel the 'system key down' state in Windows <p>In Windows, when you press Alt, and release it again, the menu bar gets activated. However, when you press Alt, then click, then release, the menu bar does not get activated because presumably you wanted to Alt+click, not activate the menu bar.</p> <p>I want to support Alt+mouse wheel changes (which would map to horizontal scrolling). This works fine, but if you are ready and release the Alt key, the menu bar activates. Obviously this is not desirable. There must be some kind of action that Windows does internally when you Alt+click to cancel the internal 'ActivateMenuBarWhenAltIsReleased' flag. If I know what it is, I can do this myself when I receive a mouse wheel message.</p> <p>So, does anyone know how the system works that activates the menu bar when you press and release Alt, and how to cancel this? Thanks!</p>
<p>When you release the Alt key, the system generates a <code>WM_SYSCOMMAND</code>/<code>SC_KEYMENU</code> message. Futhermore, unless you press a key to open a specific popup menu, the lparam will be 0. DefWindowProc, upon receiving this, will enter the menu loop. So, all you have to do is detect this message and prevent it from getting to DefWindowProc:</p> <pre><code>LRESULT CALLBACK MainWndProc(HWND wnd, UINT msg, WPARAM wparam, LPARAM lparam) { switch (msg) { // ... case WM_SYSCOMMAND: { DWORD cmd = wparam &amp; 0xfff0; // test for Alt release without any letter key pressed if (cmd == SC_KEYMENU &amp;&amp; lparam == 0) { // don't let it reach DefWindowProc return 0; } break; } // ... } return DefWindowProc(wnd, msg, wparam, lparam); } </code></pre>
Return file from python module <p>Edit: How to return/serve a file from a python controller (back end) over a web server, with the file_name? as suggested by @JV</p>
<p>You can either pass back a reference to the file itself i.e. the full path to the file. Then you can open the file or otherwise manipulate it.</p> <p>Or, the more normal case is to pass back the file handle, and, use the standard read/write operations on the file handle.</p> <p>It is not recommended to pass the actual data as files can be arbiterally large and the program could run out of memory.</p> <p>In your case, you probably want to return a tuple containing the open file handle, the file name and any other meta data you are interested in.</p>
How to Create a Managed Path through SharePoint Object Model <p>This is a question for a WSS/SharePoint guru. </p> <p>Consider this scenario: I have an ASP.Net web service which links our corporate CRM system and WSS-based intranet together. What I am trying to do is provision a new WSS site collection whenever a new client is added to the CRM system. In order to make this work, I need to programmatically add the managed path to the new site collection. I know that this is possible via the Object Model, but when I try it in my own web service, it fails. Sample code extract below:</p> <pre><code> Dim _ClientSiteUrl As String = "http://myintranet/clients/sampleclient" Using _RootWeb As SPSite = New SPSite("http://myintranet") Dim _ManagedPaths As SPPrefixCollection = _RootWeb.WebApplication.Prefixes If Not (_ManagedPaths.Contains(_ClientSiteUrl)) Then _ManagedPaths.Add(_ClientSiteUrl, SPPrefixType.ExplicitInclusion) End If End Using </code> </pre> <p>This code fails with a NullReferenceException on SPUtility.ValidateFormDigest(). Research suggested that this may be due to insufficient privileges, I tried running the code within an elevated privileges block using SPSecurity.RunWithElevatedPrivileges(AddressOf AddManagedPath), where AddManagedPath is a Sub procedure containing the above code sample.</p> <p>This then fails with an InvalidOperationException, "Operation is not valid due to the current state of the object."</p> <p>Where am I going wrong?</p> <p>One workaround I have managed to do is to call out to STSADM.EXE via Process.Start(), supplying the requisite parameters, and this works.</p> <p><strong>Update:</strong> whilst developing the web service, I am running it using the built-in Visual Studio 2005 web server - what security context will this be running under? Can I change the security context by putting entries in web.config?</p> <p><strong>Update:</strong> I think the problem is definitely to do with not running the web service within the correct SharePoint security context. I decided to go with the workaround I suggested and shell out to STSADM, although to do this, the application pool identity that the web service runs under must be a member of the SharePoint administrators.</p>
<p><strong>Update</strong> I think you have proved that the issue is not with the code.</p> <p>SPSecurity.RunWithElevatedPrivileges: Normally the code in the SharePoint web application executes with the privileges of the user taking the action. The RunWithElevatedPrivileges runs the code in the context of the SharePoint web application pools account (i think) The description on <a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx" rel="nofollow">MSDN</a> could go into the details a tiny bit more.</p> <p>The issue with the call may be that the web service is not actually running the code within a SharePoint process, so explaining why it cannot elevate (wild guess alert). </p> <p>Have a crack at changing the user of your web services application pool and see if that gives any joy.</p> <p><hr /></p> <p>It is likely to be a permissions issue. Maybe try:</p> <pre><code>Dim clientSiteUrl As String = "http://myintranet/clients/sampleclient" Using SPSite = new SPSite(clientSiteUrl) webApp As SPWebApplication = SPWebApplication.Lookup(new Uri(clientSiteUrl)); If Not (webApp.Prefixes.Contains(clientSiteUrl)) Then webApp.Prefixes.Add(clientSiteUrl, SPPrefixType.ExplicitInclusion) End If End Using </code></pre> <p>This is not exact code.</p>
what is the difference between stringstream clear and str <p>I just wanted to know what's the difference between clear() and str("");</p> <p>For example:</p> <pre><code>stringstream ss("Stack Overflow"); ss.clear(); ss.str(""); </code></pre> <p>I wanted to know the underlying technical difference.</p>
<p><code>clear()</code> clears the error state flags in the <code>stringstream</code>. That is to say it sets the error state to <code>goodbit</code>(which is equal to zero).</p> <p><code>str("")</code> sets the associated string object to the empty string.</p> <p>They actually do completely different things. The peculiar choice of names only make it <em>sound</em> as though they perform similar tasks.</p>
pubs database documentation <p>is there a documentation of the pubs database (it comes as a demo DB for SQL 2000)? for example, what is the roysched table? what represents lowqty and hightqty and discount columns from the discount table? minlvl and maxlvl from jobs table?</p> <p>Thanks</p>
<p>You can try <a href="http://msdn.microsoft.com/en-us/library/aa238305.aspx" rel="nofollow">here</a></p>
How to create an XPS document? <p>I'd like to create an XPS document for storing and printing.</p> <p>What is the easiest way to create an XPS document (for example with a simple grid with some data inside) in my program, and to pass it around?</p>
<p>Nothing easy about it. But it can be done. I've got some (sadly, still buggy) sample code and information on my blog for creating the document in memory.</p> <p>Here's some code I whipped up for testing that encapsulates everything (it writes a collection of FixedPages to an XPS document in memory). It includes code for serializing the document to a byte array, but you can skip that part and just return the document:</p> <pre><code>public static byte[] ToXpsDocument(IEnumerable&lt;FixedPage&gt; pages) { // XPS DOCUMENTS MUST BE CREATED ON STA THREADS!!! // Note, this is test code, so I don't care about disposing my memory streams // You'll have to pay more attention to their lifespan. You might have to // serialize the xps document and remove the package from the package store // before disposing the stream in order to prevent throwing exceptions byte[] retval = null; Thread t = new Thread(new ThreadStart(() =&gt; { // A memory stream backs our document MemoryStream ms = new MemoryStream(2048); // a package contains all parts of the document Package p = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite); // the package store manages packages Uri u = new Uri("pack://TemporaryPackageUri.xps"); PackageStore.AddPackage(u, p); // the document uses our package for storage XpsDocument doc = new XpsDocument(p, CompressionOption.NotCompressed, u.AbsoluteUri); // An xps document is one or more FixedDocuments containing FixedPages FixedDocument fDoc = new FixedDocument(); PageContent pc; foreach (var fp in pages) { // this part of the framework is weak and hopefully will be fixed in 4.0 pc = new PageContent(); ((IAddChild)pc).AddChild(fp); fDoc.Pages.Add(pc); } // we use the writer to write the fixed document to the xps document XpsDocumentWriter writer; writer = XpsDocument.CreateXpsDocumentWriter(doc); // The paginator controls page breaks during the writing process // its important since xps document content does not flow writer.Write(fDoc.DocumentPaginator); // p.Flush(); // this part serializes the doc to a stream so we can get the bytes ms = new MemoryStream(); var writer = new XpsSerializerFactory().CreateSerializerWriter(ms); writer.Write(doc.GetFixedDocumentSequence()); retval = ms.ToArray(); })); // Instantiating WPF controls on a MTA thread throws exceptions t.SetApartmentState(ApartmentState.STA); // adjust as needed t.Priority = ThreadPriority.AboveNormal; t.IsBackground = false; t.Start(); //~five seconds to finish or we bail int milli = 0; while (buffer == null &amp;&amp; milli++ &lt; 5000) Thread.Sleep(1); //Ditch the thread if(t.IsAlive) t.Abort(); // If we time out, we return null. return retval; } </code></pre> <p>Note the crappy threading code. You can't do this on MTA threads; if you are on an STA thread you can get rid of that as well.</p>
How to run MSVC++ 6.0 off a USB drive as a portable app <p>Without using any third party program to do this (i.e. without VMware ThinApp, U3 or MojoPac etc.) How to move MSVC++ 6.0 from from its install on C: over to a USB drive? So that it can be used on different PCs with no admin rights and without installing anything on the host PC? Even if it's only usable as a console application would be fine, although to have the GUI including Visual Assist etc. would be even better. </p>
<p>Move the two folders that install created under <code>c:\program files\</code> to the USB drive (e.g. to <code>e:\progs\msvc\msvc6</code> and <code>e:\progs\msvc\vc98</code>), and append to the file <code>e:\progs\msvc\vc98\bin\vcvars32.bat</code> to suit e.g.</p> <pre><code>prompt $g set path=e:\progs\uedit;e:\progs\utl;%PATH% e: cd e:\work start e:\progs\uedit\uedit32.exe /i=e:\progs\uedit\uedit32.ini cmd /k </code></pre> <p>Using a shortcut to vcvars32.bat then works fine for doing any simple console programming, which is all I’m using it for so far. I don’t know how well any of the GUI type programs in the tools folder will function.</p>
Weighted random selection with and without replacement <p>Recently I needed to do weighted random selection of elements from a list, both with and without replacement. While there are well known and good algorithms for unweighted selection, and some for weighted selection without replacement (such as modifications of the resevoir algorithm), I couldn't find any good algorithms for weighted selection with replacement. I also wanted to avoid the resevoir method, as I was selecting a significant fraction of the list, which is small enough to hold in memory.</p> <p>Does anyone have any suggestions on the best approach in this situation? I have my own solutions, but I'm hoping to find something more efficient, simpler, or both.</p>
<p>One of the fastest ways to make many with replacement samples from an unchanging list is the alias method. The core intuition is that we can create a set of equal-sized bins for the weighted list that can be indexed very efficiently through bit operations, to avoid a binary search. It will turn out that, done correctly, we will need to only store two items from the original list per bin, and thus can represent the split with a single percentage.</p> <p>Let's us take the example of five equally weighted choices, <code>(a:1, b:1, c:1, d:1, e:1)</code></p> <p>To create the alias lookup:</p> <ol> <li><p>Normalize the weights such that they sum to <code>1.0</code>. <code>(a:0.2 b:0.2 c:0.2 d:0.2 e:0.2)</code> This is the probability of choosing each weight.</p></li> <li><p>Find the smallest power of 2 greater than or equal to the number of variables, and create this number of partitions, <code>|p|</code>. Each partition represents a probability mass of <code>1/|p|</code>. In this case, we create <code>8</code> partitions, each able to contain <code>0.125</code>.</p></li> <li><p>Take the variable with the least remaining weight, and place as much of it's mass as possible in an empty partition. In this example, we see that <code>a</code> fills the first partition. <code>(p1{a|null,1.0},p2,p3,p4,p5,p6,p7,p8)</code> with <code>(a:0.075, b:0.2 c:0.2 d:0.2 e:0.2)</code></p></li> <li><p>If the partition is not filled, take the variable with the most weight, and fill the partition with that variable. </p></li> </ol> <p>Repeat steps 3 and 4, until none of the weight from the original partition need be assigned to the list.</p> <p>For example, if we run another iteration of 3 and 4, we see </p> <p><code>(p1{a|null,1.0},p2{a|b,0.6},p3,p4,p5,p6,p7,p8)</code> with <code>(a:0, b:0.15 c:0.2 d:0.2 e:0.2)</code> left to be assigned</p> <p>At runtime:</p> <ol> <li><p>Get a <code>U(0,1)</code> random number, say binary <code>0.001100000</code></p></li> <li><p>bitshift it <code>lg2(p)</code>, finding the index partition. Thus, we shift it by <code>3</code>, yielding <code>001.1</code>, or position 1, and thus partition 2.</p></li> <li><p>If the partition is split, use the decimal portion of the shifted random number to decide the split. In this case, the value is <code>0.5</code>, and <code>0.5 &lt; 0.6</code>, so return <code>a</code>.</p></li> </ol> <p><a href="http://prxq.wordpress.com/2006/04/17/the-alias-method/">Here is some code and another explanation</a>, but unfortunately it doesn't use the bitshifting technique, nor have I actually verified it.</p>
Is it true that using "this." before the parameters in c# uses more memory? <p>than just to call the parameter as it is?</p>
<p>If you mean fields, then no. The compiler injects "this" (<a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldarg_0(VS.95).aspx" rel="nofollow">ldarg.0</a>) whether you use it explicitly (this.foo) or implicitly (foo).</p> <p>It does, however, take 5 more characters in your source code... so a handful of bytes on your development hard disk. It will make exactly zero difference in the compiled IL or at runtime.</p> <p>There are two scenarios where use of "this" changes things:</p> <ul> <li>when there is a variable/parameter with the same name (<code>this.foo = foo;</code>)</li> <li>when resolving extension methods (<code>this.SomeMethod()</code>;)</li> </ul>
Signal and slot connection in .ui <p>I have started to play a little with Qt 4. And then I have come across a problem with the Qt Designer. In the Signal/Slots editor I can only setup the connections that is listed there, and not all the slots is listed. If I try to add it manualy in the .ui file, the connection would not work. If I add it in the ui_*.h file it workes fine, but then the connection is deleted when I change the design. Does anyone have any good tips to how I can get around this bug? Or to ask another way: How can I make the Qt Designer list all the availible slots?</p>
<p>By default not all signals/slots are shown. You could try checking the "show signals and slots inheritied from ...." checkbox in the lower left hand corder of the "Configure Connection" dialog that comes up when you try to create a signal.</p> <p>Beyond that, you can either do what Marcin said and use <a href="http://doc.trolltech.com/4.0/designer-using-a-component.html#a-dialog-with-auto-connect" rel="nofollow">auto-connections</a>, or manually write connect statements in the constructor of the object that uses the ui.</p>
When to catch java.lang.Error? <p>In what situations should one catch <code>java.lang.Error</code> on an application?</p>
<p>Generally, never. However, sometimes you need to catch specific Errors.</p> <p>If you're writing framework-ish code (loading 3rd party classes), it might be wise to catch LinkageErrors (no class def found, unsatisfied link, incompatible class change). I've also seen some stupid 3rd-party code throwing sublcasses of Errors, so you'll have to handle these either.</p> <p>By the way, I'm not sure it isn't possible to recover from OutOfMemory.</p>
With XSLT/XPath, how can I match any element in the null namespace? <pre><code>&lt;xsl:template match="foo"&gt; </code></pre> <p>matches the foo element in the null namespace.</p> <pre><code>&lt;xsl:template match="*"&gt; </code></pre> <p>matches any element in <em>any</em> namespace.</p> <p>I tried:</p> <pre><code>xmlns:null="" ... &lt;xsl:template match="null:*"&gt; </code></pre> <p>but it's illegal to declare a prefix for the null namespace.</p> <p>So how can I match an element with any name in the null namespace?</p>
<p>You could try:</p> <pre><code>&lt;xsl:template match='*[namespace-uri() = ""]'&gt; </code></pre> <p>If the node-set is empty or has no namespace URI, an empty string is returned by the <code>namespace-uri</code> function, which should achieve what you want.</p>
How can I prevent Windows from catching my Perl exceptions? <p>I have this Perl software that is supposed to run 24/7. It keeps open a connection to an IMAP server, checks for new mail and then classifies new messages.</p> <p>Now I have a user that is hibernating his XP laptop every once in a while. When this happens, the connection to the server fails and an exception is triggered. The calling code usually catches that exception and tries to reconnect. But in this case, it seems that Windows (or Perl?) is catching the exception and delivering it to the user via a message box.</p> <p>Anyone know how I can prevent that kind of wtf? Could my code catch a "system-is-about-to-hibernate" signal?</p> <p>To clear up some points you already raised:</p> <ul> <li>I have no problem with users hibernating their machines. I just need to find a way to deal with that.</li> <li>The Perl module in question does throw an exception. It does something like "die 'foo bar'. Although the application is completely browser based and doesn't use anything like Wx or Tk, the user gets a message box titled "poll_timer". The content of that message box is exactly the contents of $@ ('foo bar' in this example).</li> <li>The application is compiled into an executable using <a href="http://docs.activestate.com/pdk/7.3/PerlApp.html" rel="nofollow">perlapp</a>. The documentation doesn't mention anything about exception handling, though.</li> </ul>
<p>I think that you're dealing with an OS-level exception, not something thrown from Perl. The relevant Perl module is making a call to something in a DLL (I presume), and the exception is getting thrown. Your best bet would be to boil this down to a simple, replicable test case that triggers the exception (you might have to do a lot of hibernating and waking the machines involved for this process). Then, send this information to the module developer and ask them if they can come up with a means of catching this exception in a way that is more useful for you.</p> <p>If the module developer can't or won't help, then you'll probably wind up needing to use the Perl debugger to debug into the module's code and see exactly what is going on, and see if there is a way you can change the module yourself to catch and deal with the exception.</p>
Clean document roles in a Doc Library <p>I have been developing an event handler to clean up the RolesAssignments of the new item of a document library in MOSS. I’ve searched for a method that could clean all the RolesAssignments efficiently, although the best way I found seams to be loop through the RolesAssignments and delete one by one? Is there another way to clean all the RolesAssignments for an item?</p> <p>The code I’m using for cleaning the RolesAssignments look like this:</p> <pre><code> for (int i = ListItem.RoleAssignments.Count - 1; i &gt;= 0; --i) { ListItem.RoleAssignments.Remove(i); } </code></pre> <p>Does anyone have any ideas on how to deal with this?</p>
<p>The example you've given within the body of your question is the most correct way to do this. ResetRoleInheritance and BreakRoleInheritance may do what you need, but this is the side-effect of the operations they perform. Their purpose is not to remove RoleAssignments, but rather operate on role inheritance. From MSDN:</p> <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.resetroleinheritance.aspx" rel="nofollow">ResetRoleInheritance</a> - "Removes the local role assignments and reverts to role assignments from the parent object."</p> <p><a href="http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.splistitem.breakroleinheritance.aspx" rel="nofollow">BreakRoleInheritance</a> - "Creates unique role assignments for the item rather than inheriting them from a parent."</p> <p>If role inheritance is already broken and you are using specific role assignments, you should remove them using a loop as you have in your question.</p>
Does a truststore need the sub-ca certificate? <p>I'm trying to setup a hierarchical PKI. Can I create a truststore containing only the root ca certificate, and will that mean my application trusts certificates signed by a sub-ca certificate which is in turn signed by the root ca?</p> <p>As an aside, it seems that you must provide an entire certificate chain, including the root ca certificate. Surely if the root ca is trusted, the certificate shouldn't need to be sent? We just want to check if the next certificate down is signed by it.</p>
<p>The trust store should only contain the root CAs, not intermediates.</p> <p>An identity store should contain private keys, each associated with its certificate chain, except for the root.</p> <p>Many, many applications in the wild are misconfigured, and when trying to identify themselves (say, a server authenticating itself with SSL), they only send their own certificate, and are missing the intermediates. There are fewer that mistakenly send the root as part of the chain, but this is less harmful. Most certificate path builders will just ignore it, and find a path to a root from their trusted key store.</p> <p>The suppositions in the original question are right on target.</p>
SQL - Temp Table: Storing all columns in temp table versus only Primary key <p>I would need to create a temp table for paging purposes. I would be selecting all records into a temp table and then do further processing with it.</p> <p>I am wondering which of the following is a better approach:</p> <p>1) Select all the columns of my Primary Table into the Temp Table and then being able to select the rows I would need</p> <p>OR</p> <p>2) Select only the primary key of the Primary Table into the Temp Table and then joining with the Primary Table later on?</p> <p>Is there any size consideration when working with approach 1 versus approach 2?</p> <p>[EDIT]</p> <p>I am asking because I would have done the first approach but looking at PROCEDURE [dbo].[aspnet_Membership_FindUsersByName], that was included with ASP.NET Membership, they are doing Approach 2</p> <p>[EDIT2]</p> <p>With people without access to the Stored procedure:</p> <pre><code> -- Insert into our temp table INSERT INTO #PageIndexForUsers (UserId) SELECT u.UserId FROM dbo.aspnet_Users u, dbo.aspnet_Membership m WHERE u.ApplicationId = @ApplicationId AND m.UserId = u.UserId AND u.LoweredUserName LIKE LOWER(@UserNameToMatch) ORDER BY u.UserName SELECT u.UserName, m.Email, m.PasswordQuestion, m.Comment, m.IsApproved, m.CreateDate, m.LastLoginDate, u.LastActivityDate, m.LastPasswordChangedDate, u.UserId, m.IsLockedOut, m.LastLockoutDate FROM dbo.aspnet_Membership m, dbo.aspnet_Users u, #PageIndexForUsers p WHERE u.UserId = p.UserId AND u.UserId = m.UserId AND p.IndexId &gt;= @PageLowerBound AND p.IndexId &lt;= @PageUpperBound ORDER BY u.UserName </code></pre>
<p>A Table Variable would be preferred over a temp table, if its within your constraints. </p> <p>Option 2 would use less resources, because there is less data duplication. </p> <p>Tony's points about this being a dirty read are really something you should be considering. </p> <p>Can you explain how you are 'paging' with temp tables? Its not a paging method I am familiar with. </p> <p>EDIT: After looking at your post edit, you should definately use a table variable in this case. Its less to cleanup and you wont blow out the tempdb so much. </p> <p>Also, its kind of unclear what benefit this temp table gives. If your aim is to stop a user from accessing an object/applicaiton, then why are you adding the part about it being "only restricted if on this particular data table page". It seems kind of hole-y from a security perspective.</p> <p>The temp table can be pretty much eliminated also, since it selects from the same tables.</p>
SQL query (order by) <p>I want to list (a sorted list) all my entries from an attribute called streetNames in my table/relation Customers. eg. I want to achieve the following order: </p> <p>Street_1A<br /> Street_1B<br /> Street_2A<br /> Street_2B<br /> Street_12A<br /> Street_12B </p> <p>A simple order by streetNames will do a lexical comparision and then Street_12A and B will come before Street_2A/B, and that is not correct. Is it possible to solve this by pure SQL?</p>
<p>Select street_name from tablex order by udf_getStreetNumber(street_name)</p> <p>in your udf_getStreetNumber - write your business rule for stripping out the number</p> <p>EDIT</p> <p>I think you can use regex functionality in SQL Server now. I'd just strip out all non-number characters from the input.</p>
jQuery fadeIn, fadeOut effects in IE <p>The below <a href="http://docs.jquery.com/Effects/fadeIn" rel="nofollow">fadeIn</a>, <a href="http://docs.jquery.com/Effects/fadeOut" rel="nofollow">fadeOut</a> effect works fine in Firefox 3.0 but it doesn't work in IE 7 ... Whay is that and what's the trick? The idea is of course to get a "blink" effect and attract the attention of the user to a specific row in a table. </p> <pre><code>function highLightErrorsAndWarnings() { $(".status-error").fadeIn(100).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300); $(".status-warning").fadeIn(100).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300).fadeOut(300).fadeIn(300); } </code></pre> <p><strong>Update:</strong> Found the stupid problem ... ".status-error" points to a tr-element. It's possible to the set the background-color and fade it on a tr in Firefox but not in IE. Changing the "CSS pointer" to ".status-error <strong><em>td</em></strong>" made it point to the td below the tr and everything worked in all browsers.</p>
<p>Weird.. couldn't tell you why you're getting that problem, but maybe try the pulsate effect plugin? <a href="http://docs.jquery.com/UI/Effects/Pulsate">http://docs.jquery.com/UI/Effects/Pulsate</a></p>
Exclude complete namespace from FxCop code analysis? <p>Is it possible to exclude a complete namespace from all FxCop analysis while still analyzing the rest of the assembly using the <code>SuppressMessageAttribute</code>?</p> <p>In my current case, I have a bunch of classes generated by LINQ to SQL which cause a lot of FxCop issues, and obviously, I will not modify all of those to match FxCop standards, as a lot of those modifications would be gone if I re-generated the classes.</p> <p>I know that FxCop has a project option to suppress analysis on generated code, but it does not seem to recognize the entity and context classes created by LINQ 2 SQL as generated code.</p>
<p>If you tag your classes with the <code>[GeneratedCode]</code> attribute, you can use the /ignoregeneratedcode flag with FxCop as described in this MSDN post:</p> <p><a href="http://blogs.msdn.com/b/codeanalysis/archive/2008/02/28/faq-how-do-i-prevent-fxcop-1-36-from-firing-warnings-against-generated-code.aspx">FAQ: How do I prevent FxCop from firing warnings against generated code</a></p> <p>You may have to add a new code file and implement new partial classes there to add the attribute to the classes:</p> <pre><code>[GeneratedCode] public partial class MainDataContext { } </code></pre> <p>Just make sure you add everything to the correct namespace when you create your new file.</p>