instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm looking to write an automated monitor script to programmatically retrieve information from another user's Exchange 2003 inbox. I have working C++ code to log into MAPI and connect to my own inbox. I can also use the Control Panel->Mail applet to configure another user's mailbox into my profile, and my code can access that way. However, this was done on my desktop with Outlook installed, which provides a richer mail profile editor.</p> <p>Since this will run on a server, I'd prefer not to install Outlook at all. Instead, I can install the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=E17E7F31-079A-43A9-BFF2-0A110307611E&amp;displaylang=en" rel="nofollow noreferrer">MAPI client</a>. I then create a simple MAPI app that pops up the mail profile wizard using <code>MAPILogonEx()</code> with the <code>MAPI_LOGON_UI</code> flag. However, the basic MAPI client doesn't have the features to configure another user's mailbox. As a requirement, I can only run this script as the service account of the monitoring application, so I cannot tell it to run as the account whose mailbox I want.</p> <p>Is it still possible to connect to another user's mailbox (assuming permissions are already granted) using the basic MAPI client? Or is it absolutely necessary to install Outlook for this functionality?</p>
<p>I see... I'm not sure how to do that explicitly; that's usually a side effect of calling <code>CreateStoreEntryID</code> with the wrong flags. What's you're looking to do is probably:</p> <ol> <li>Get an <code>IID_IExchangeManageStore</code> from your default message store</li> <li>Call <code>CreateStoreEntryID</code></li> <li><p>Then open that store by the entry ID</p> <pre><code>LPEXCHANGEMANAGESTORE mapiObject = NULL; store-&gt;QueryInterface( IID_IExchangeManageStore, (LPVOID *) &amp;mapiObject); mapiObject-&gt;CreateStoreEntryID( server, mailbox, OPENSTORE_TAKE_OWNERSHIP | OPENSTORE_USE_ADMIN_PRIVILEGE, &amp;len, &amp;buffer); //Call OpenEntry on the entry id </code></pre></li> </ol> <p>If you want a more detailed example, search the source of the MFC MAPI project for <code>CreateStoreEntryID</code>. If you have other questions, the best place to get them answered is the <code>microsoft.public.win32.programmer.messaging</code> newsgroup.</p>
<p>Have you looked into ConfigureMsgService? I believe that works with Exchange MAPI, or are you saying you tried that and it didn't work? </p>
45,565
<p>Just starting out in asp.net. Have just created a login.aspx page in my site and stuck on a asp login control - that's all I did. Now my Welcome.aspx page won't show as the start page of my site when I debug - even though it is set as this. Plus I have even edited my web.config - (see below) - and it still does the same thing. How do I make it work so I have my Welcome.aspx page start up as default?</p> <pre><code>&lt;authentication mode="Forms"&gt; &lt;forms defaultUrl="~/Welcome.aspx" loginUrl="~/login.aspx" timeout="1440" &gt;&lt;/forms&gt; &lt;/authentication&gt; </code></pre>
<p>If you want users to access welcome.aspx without being authenticated, put welcome.aspx in a separate folder, and set up a new web.config in that sub folder. fill out the authorization section in that web.config so that the files in that folder and subfolders will be accessible by anonymous users, like this:</p> <pre><code>&lt;authorization&gt;&lt;allow users="?" /&gt;&lt;/authorization&gt; </code></pre>
<p>Well, if the user isn't authenticated they will automatically be redirected to the "loginUrl" -- once you log in you should be redirected to Welcome.aspx, and it will be the default page as long as the credentials are valid.</p>
22,864
<p>I've got an interface which i've used <code>StructureMap</code> to <em>Dependency Inject</em>.</p> <pre><code>public interface IFileStorageService { void SaveFile(string fileName, byte[] data); } </code></pre> <p>The interface doesn't care WHERE the data is saved. Be it to the memory, a file, a network resource, a satellite in space....</p> <p>So, i've got two classes that implement this interface; a <code>test class</code> and a <code>network file storage class</code> :-</p> <pre><code>public class TestFileStorageService : IFileStorageService { ... etc ...} public class NetworkFileStorageService : IFileStorageService { public string NetworkUnc { get; set; } public void SaveFile(...); } </code></pre> <p>Notice how my <code>NetworkFileStorageService</code> has a property? That class requires that value in it's implementation of the SaveFile method. </p> <p>Well, i'm not sure how to define that property. </p> <p>I thought i could hard code it where i define my dependency (eg. in my bootstrapper method -> <code>ForRequestedType&lt;IFileStorageService&gt;</code>... etc) but the kicker is .. the business logic <em>DEFINES</em> the location. It's not static.</p> <p>Finally, because i use interfaces in my logic, this property is not available.</p> <p>Can anyone help?</p> <p>If you can, image you want to save two files</p> <ul> <li>Name: Test1.bin; location: \server1\folder1</li> <li>Name: Test2.bin; location: \server1\folder2</li> </ul> <p>cheers!</p>
<p>This will hardly be a Smarty problem. Just save both HTML pages and locally and compare. What's the difference? Maybe you could even use a diff tool for this. Have you tried to validate the <a href="http://validator.w3.org/" rel="nofollow noreferrer">HTML</a> and the <a href="http://jigsaw.w3.org/css-validator/" rel="nofollow noreferrer">CSS</a>? It might also give you some hints.</p> <p>This is a CSS problem - not a Smarty one. You should consider adding more information to the question and tag it with HTML/CSS.</p>
<p>you can see what's wrong using FireBug with Firefox.</p>
48,406
<p>How can I correctly clean the lacquer from bed printer?</p> <p>I have used some ethylic alcohol (ethanol) to help cleaning</p> <p>But what is the best way to do it?</p> <p><img src="https://i.stack.imgur.com/56zTH.jpg" alt="enter image description here"></p>
<p>The Ender 3 does not come with a lacquered surface at all.The bed should have a rough build surface that is a clone of the BuildTak build surface. It is <em>intended</em> to be rough and satin-gloss in its native state. I do not remember if there was a thin protective plastic foil on my Ender-3 bed on delivery, but if there was, it should have been removed during assembly.</p> <p>A BuildTak surface can be easily cleaned with isopropyl or ethyl alcohol of grease and fingerprints. The odd discoloration at the edges seems to be a layer of grease and dust, which can be easily cleaned away by soaking it in Isopropyl alcohol and then wiped with a microfiber cloth.</p> <p>If the bed surface is destroyed by chipping holes into it, sanding it or otherwise ruining it (like melting plastic rap into it), you will need to replace it. Replacement surfaces come about 5 bucks on Amazon. Doing this, you might find <a href="https://3dprinting.stackexchange.com/questions/7960/how-to-clean-up-my-buildpate-for-a-new-build-surface">How to clean up my buildpate for a new build surface?</a> helpful.</p>
<p>The "lacquer" you are referring to is assumed to be the discoloured parts of the heat bed, not the original surface layer of the heat bed. The discoloured parts of the heatbed are most probably caused by residue build-up.</p> <p>If this residue build-up is caused by depositing a print adhesive containing PolyVinylPyrrolidone (glue stick ingredient) or PolyVinylAcetate (hairspray or 3D print spray ingredient), you can simply wash is of with water using a wet hand-warm towel or a sponge. Both constituents are dissolvable in water.</p> <p>I do this frequently on non-removable aluminium heat beds (using moist kitchen towel) or removable glass bed (rinse off in the sink).</p>
1,516
<p>If I pass PHP variables with <code>.</code> in their names via $_GET PHP auto-replaces them with <code>_</code> characters. For example:</p> <pre><code>&lt;?php echo "url is ".$_SERVER['REQUEST_URI']."&lt;p&gt;"; echo "x.y is ".$_GET['x.y'].".&lt;p&gt;"; echo "x_y is ".$_GET['x_y'].".&lt;p&gt;"; </code></pre> <p>... outputs the following:</p> <pre><code>url is /SpShipTool/php/testGetUrl.php?x.y=a.b x.y is . x_y is a.b. </code></pre> <p>... my question is this: is there <strong>any</strong> way I can get this to stop? Cannot for the life of me figure out what I've done to deserve this</p> <p>PHP version I'm running with is 5.2.4-2ubuntu5.3.</p>
<p>Here's PHP.net's explanation of why it does it:</p> <blockquote> <h3>Dots in incoming variable names</h3> <p>Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it:</p> <pre><code>&lt;?php $varname.ext; /* invalid variable name */ ?&gt; </code></pre> <p>Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result.</p> <p>For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores.</p> </blockquote> <p>That's from <a href="http://ca.php.net/variables.external" rel="noreferrer">http://ca.php.net/variables.external</a>.</p> <p>Also, according to <a href="http://ca.php.net/manual/en/language.variables.external.php#81080" rel="noreferrer">this comment</a> these other characters are converted to underscores:</p> <blockquote> <p>The full list of field-name characters that PHP converts to _ (underscore) is the following (not just dot):</p> <ul> <li>chr(32) ( ) (space)</li> <li>chr(46) (.) (dot)</li> <li>chr(91) ([) (open square bracket)</li> <li>chr(128) - chr(159) (various)</li> </ul> </blockquote> <p>So it looks like you're stuck with it, so you'll have to convert the underscores back to dots in your script using <a href="https://stackoverflow.com/questions/68651/can-i-get-php-to-stop-replacing-characters-in-get-or-post-arrays#68667">dawnerd's suggestion</a> (I'd just use <a href="http://php.net/str_replace" rel="noreferrer">str_replace</a> though.)</p>
<p>Well, the function I include below, "getRealPostArray()", isn't a pretty solution, but it handles arrays and supports both names: "alpha_beta" and "alpha.beta":</p> <pre><code> &lt;input type='text' value='First-.' name='alpha.beta[a.b][]' /&gt;&lt;br&gt; &lt;input type='text' value='Second-.' name='alpha.beta[a.b][]' /&gt;&lt;br&gt; &lt;input type='text' value='First-_' name='alpha_beta[a.b][]' /&gt;&lt;br&gt; &lt;input type='text' value='Second-_' name='alpha_beta[a.b][]' /&gt;&lt;br&gt; </code></pre> <p>whereas var_dump($_POST) produces:</p> <pre><code> 'alpha_beta' =&gt; array (size=1) 'a.b' =&gt; array (size=4) 0 =&gt; string 'First-.' (length=7) 1 =&gt; string 'Second-.' (length=8) 2 =&gt; string 'First-_' (length=7) 3 =&gt; string 'Second-_' (length=8) </code></pre> <p>var_dump( getRealPostArray()) produces:</p> <pre><code> 'alpha.beta' =&gt; array (size=1) 'a.b' =&gt; array (size=2) 0 =&gt; string 'First-.' (length=7) 1 =&gt; string 'Second-.' (length=8) 'alpha_beta' =&gt; array (size=1) 'a.b' =&gt; array (size=2) 0 =&gt; string 'First-_' (length=7) 1 =&gt; string 'Second-_' (length=8) </code></pre> <p>The function, for what it's worth:</p> <pre><code>function getRealPostArray() { if ($_SERVER['REQUEST_METHOD'] !== 'POST') {#Nothing to do return null; } $neverANamePart = '~#~'; #Any arbitrary string never expected in a 'name' $postdata = file_get_contents("php://input"); $post = []; $rebuiltpairs = []; $postraws = explode('&amp;', $postdata); foreach ($postraws as $postraw) { #Each is a string like: 'xxxx=yyyy' $keyvalpair = explode('=',$postraw); if (empty($keyvalpair[1])) { $keyvalpair[1] = ''; } $pos = strpos($keyvalpair[0],'%5B'); if ($pos !== false) { $str1 = substr($keyvalpair[0], 0, $pos); $str2 = substr($keyvalpair[0], $pos); $str1 = str_replace('.',$neverANamePart,$str1); $keyvalpair[0] = $str1.$str2; } else { $keyvalpair[0] = str_replace('.',$neverANamePart,$keyvalpair[0]); } $rebuiltpair = implode('=',$keyvalpair); $rebuiltpairs[]=$rebuiltpair; } $rebuiltpostdata = implode('&amp;',$rebuiltpairs); parse_str($rebuiltpostdata, $post); $fixedpost = []; foreach ($post as $key =&gt; $val) { $fixedpost[str_replace($neverANamePart,'.',$key)] = $val; } return $fixedpost; } </code></pre>
9,421
<p>I'm setting up a new project using CruiseControl.net 1.4.</p> <p>I see from <a href="http://confluence.public.thoughtworks.org/display/CCNETCOMM/Contributions" rel="nofollow noreferrer">ccnet contributions</a> that there are two options for a subversion repository number labeller - a feature that I would really like to make use of.</p> <p>1) SVNLabeller available from <a href="http://www.jcxsoftware.com/jcx/ccnet-dev" rel="nofollow noreferrer">jcxsoftware</a></p> <p>and</p> <p>2) Svnrevisionlabeller available from <a href="http://code.google.com/p/svnrevisionlabeller/" rel="nofollow noreferrer">google code</a></p> <p>My problem is that (1) claims support for ccnet 1.4 but I can't find any documentation on how to configure it.</p> <p>(2) comes with documentation but does not claim to support ccnet 1.4</p> <p>Can anyone help me with either how to configure SVNLabeller or tell me if Svnrevisionlabeller works with 1.4? </p>
<p>this is David Keaveny, author/maintainer of SvnRevisionLabeller. I use it against v1.4.2 on a daily basis at work, so I think it's safe to say that it works OK. I should probably update the Google Code site to reflect this.</p> <p><strong>Update</strong>: I've updated the project wiki to reflect this. Oh, and I'm also picking up on a bunch of feature requests, so keep an eye open for a new release in the near future.</p>
<p>Have you looked at <a href="http://ilmatte.wordpress.com/2008/03/05/cruisecontrolnet-and-subversion-svnrevisionlabeller/" rel="nofollow noreferrer">David Keaveny’s Blog Post</a> regarding the SVNRevisionLabeller? The link will take you to a detailed post on it's usage.</p> <p>We are currently testing this utility against the current release (1.4) of CCNet without any problems, i.e. it's producing the correct revision and build labels appended to the major/minor digits we specify.</p> <p>Hope this helps</p>
18,423
<p>How do you use <code>gen_udp</code> in Erlang to do <a href="https://en.wikipedia.org/wiki/Multicast" rel="nofollow noreferrer">multicasting</a>? I know its in the code, there is just no documentation behind it. Sending out data is obvious and simple. I was wondering on how to add memberships. Not only adding memberships at start-up, but adding memberships while running would be useful too.</p>
<p>Here is example code on how to listen in on Bonjour / Zeroconf traffic.</p> <pre><code>-module(zcclient). -export([open/2,start/0]). -export([stop/1,receiver/0]). open(Addr,Port) -&gt; {ok,S} = gen_udp:open(Port,[{reuseaddr,true}, {ip,Addr}, {multicast_ttl,4}, {multicast_loop,false}, binary]), inet:setopts(S,[{add_membership,{Addr,{0,0,0,0}}}]), S. close(S) -&gt; gen_udp:close(S). start() -&gt; S=open({224,0,0,251},5353), Pid=spawn(?MODULE,receiver,[]), gen_udp:controlling_process(S,Pid), {S,Pid}. stop({S,Pid}) -&gt; close(S), Pid ! stop. receiver() -&gt; receive {udp, _Socket, IP, InPortNo, Packet} -&gt; io:format("~n~nFrom: ~p~nPort: ~p~nData: ~p~n",[IP,InPortNo,inet_dns:decode(Packet)]), receiver(); stop -&gt; true; AnythingElse -&gt; io:format("RECEIVED: ~p~n",[AnythingElse]), receiver() end. </code></pre>
<p><strong>Multicast is specified by IP Address</strong></p> <p>It's the same in erlang as for all languages. The IP addresses 224.0.0.0 through 239.255.255.255 are multicast addresses.</p> <p>Pick an address in that range, check that you're not overlapping an already assigned address, and you are good to go.</p> <p><a href="http://www.iana.org/assignments/multicast-addresses" rel="nofollow noreferrer">http://www.iana.org/assignments/multicast-addresses</a></p>
10,424
<blockquote> <p><strong>Duplicate of: <a href="https://stackoverflow.com/q/59297/1288">When/Why to use Cascading in SQL Server?</a></strong></p> </blockquote> <p>I've always been too scared to use DELETE CASCADE, but as I get more confident (lazy :D), I'm thinking how bad can it be, is it best practise to use it or should I avoid it and clean up my foreign keys etc the old fashioned way (with stored procedures)?</p>
<p>ON DELETE CASCADE is fine, but only when the dependent rows are really a logical extension of the row being deleted. For example, it's OK for DELETE ORDERS to delete the associated ORDER_LINES because clearly you want to delete this order, which consists of a header and some lines. On the other hand, DELETE CUSTOMER should not delete the associated ORDERS because ORDERS are important in their own right, they are not just attributes of a customer.</p> <p>One way to think about this is: if I issue DELETE X and it also deletes Y, will I be happy or unhappy? And if I issue DELETE X and am told "cannot delete X because Y exists" will I be glad of the protection, or irritated at the inconvenience?</p>
<p>I prefer having control over exactly what is deleted (by explicitly declaring it), so I generally opt to delete via stored procedures, and not to use cascading deletes.</p>
35,157
<p>What is a typical estimate for coding unit tests given an estimate for coding new functionality? Is this different for estimates to maintain code?</p>
<p>My time is about equal between time for unit testing and time for functional code.</p> <p>Some people would look at this and say that is a waste of time, but if your only other option is to run the app and step through all the possible paths the app can take, then the time spent on unit testing is actually less than the time you would spend on developer testing. Of course if you don't do much developer testing, then you will spend the time in fixing bugs that come back from QA.</p> <p>Either way the time spent writing unit test actually saves time from the amount I would spend on the project.</p> <p>When it comes time to maintain the code (slight changes, small additions in functionality), there might be a difference. If the code being changed is already fully covered and your changes do not require changes to the tests, then your time is 0. Otherwise obviously it is not, probably closer to equal again.</p> <p>But, your time savings in testing time is MUCH larger; you've already created the tests to cover the rest of the code, so you would uncover any incidental changes flowing from your change without any new code or walking the app.</p>
<p>I find that it varies a lot depending on the code you are working with - when writing something from scratch, test driven, it probably takes about the same amount of time to implement the feature as without tests, but you save longer term on the quantity of bugs that will be found, and how easily you can maintain and extend that code base. One might argue it is faster in this case to write with tests, as you avoid those head-scratching moments where the code just doesn't behave as expected and you have to use a debugger to find out what's going on, over a much wider change set than TDD would typically allow.</p> <p>When you are trying to implement features on top of an existing, "legacy" code base (as Michael Feathers would define legacy), it often takes significantly longer to implement the feature with tests than without, due to the amount of careful refactoring that must be done before writing tests is typically possible. In this case, writing units tests will still be of long term benefit, but you must put extra thought into whether that long term benefit is justified for the immediate cost.</p> <p>Generally, I would always push for some form of automated testing, whether unit or functional, despite the additional costs for legacy code bases. Without it, you are likely to find yourself stuck with a code base that is very difficult to maintain and requires constant, repetitive manual testing to ensure it continues to function, with frequent regressions.</p>
21,084
<p>I have a very weird problem which I cannot seem to figure out. Unfortunately, I'm not even sure how to describe it without describing my entire application. What I am trying to do is:</p> <pre> 1) read a byte from the serial port 2) store each char into tagBuffer as they are read 3) run a query using tagBuffer to see what type of tag it is (book or shelf tag) 4) depending on the type of tag, output a series of bytes corresponding to the type of tag </pre> <p>Most of my code is implemented and I can get the right tag code sent back out the serial port. But there are two lines that I've added as debug statements which when I tried to remove them, they cause my program to stop working.</p> <p>The lines are the two lines at the very bottom: <code></p> <pre><code> sprintf(buf,"%s!\n", tagBuffer); WriteFile(hSerial,buf,strlen(buf), &amp;dwBytesWritten,&amp;ovWrite); </code></pre> <p></code></p> <p>If I try to remove them, "tagBuffer" will only store the last character as oppose being a buffer. Same thing with the next line, WriteFile().</p> <p>I thought sprintf and WriteFile are I/O functions and would have no effect on variables. I'm stuck and I need help to fix this.</p> <p><code></p> <pre><code>//keep polling as long as stop character '-' is not read while(szRxChar != '-') { // Check if a read is outstanding if (HasOverlappedIoCompleted(&amp;ovRead)) { // Issue a serial port read if (!ReadFile(hSerial,&amp;szRxChar,1, &amp;dwBytesRead,&amp;ovRead)) { DWORD dwErr = GetLastError(); if (dwErr!=ERROR_IO_PENDING) return dwErr; } } // resets tagBuffer in case tagBuffer is out of sync time_t t_time = time(0); char buf[50]; if (HasOverlappedIoCompleted(&amp;ovWrite)) { i=0; } // Wait 5 seconds for serial input if (!(HasOverlappedIoCompleted(&amp;ovRead))) { WaitForSingleObject(hReadEvent,RESET_TIME); } // Check if serial input has arrived if (GetOverlappedResult(hSerial,&amp;ovRead, &amp;dwBytesRead,FALSE)) { // Wait for the write GetOverlappedResult(hSerial,&amp;ovWrite, &amp;dwBytesWritten,TRUE); if( strlen(tagBuffer) &gt;= PACKET_LENGTH ) { i = 0; } //load tagBuffer with byte stream tagBuffer[i] = szRxChar; i++; tagBuffer[i] = 0; //char arrays are \0 terminated //run query with tagBuffer sprintf(query,"select type from rfid where rfidnum=\""); strcat(query, tagBuffer); strcat(query, "\""); mysql_real_query(&amp;mysql,query,(unsigned int)strlen(query)); //process result and send back to handheld res = mysql_use_result(&amp;mysql); while(row = mysql_fetch_row(res)) { printf("result of query is %s\n",row[0]); string str = ""; str = string(row[0]); if( str == "book" ) { WriteFile(hSerial,BOOK_INDICATOR,strlen(BOOK_INDICATOR), &amp;dwBytesWritten,&amp;ovWrite); } else if ( str == "shelf" ) { WriteFile(hSerial,SHELF_INDICATOR,strlen(SHELF_INDICATOR), &amp;dwBytesWritten,&amp;ovWrite); } else //this else doesn't work { WriteFile(hSerial,NOK,strlen(NOK), &amp;dwBytesWritten,&amp;ovWrite); } } mysql_free_result(res); // Display a response to input //printf("query is %s!\n", query); //printf("strlen(tagBuffer) is %d!\n", strlen(tagBuffer)); //without these, tagBuffer only holds the last character sprintf(buf,"%s!\n", tagBuffer); WriteFile(hSerial,buf,strlen(buf), &amp;dwBytesWritten,&amp;ovWrite); } } </code></pre> <p></code></p> <p>With those two lines, my output looks like this: s sh she shel shelf shelf0 shelf00 BOOKCODE shelf0001</p> <p>Without them, I figured out that tagBuffer and buf only stores the most recent character at any one time.</p> <p>Any help at all will be greatly appreciated. Thanks.</p>
<p>Where are you allocating tagbuffer, how large is it?<br> It's possible that you are overwriting 'buf' because you are writing past the end of tagbuffer.</p>
<p>In my opinion, the real problem here is that you're trying to read and write the serial port from a single thread, and this is making the code more complex than it needs to be. I suggest that you read the following articles and reconsider your design:</p> <ul> <li><a href="http://www.flounder.com/serial.htm" rel="nofollow noreferrer">Serial Port I/O</a> from Joseph Newcomer's website.</li> <li><a href="http://msdn.microsoft.com/en-us/library/ms810467.aspx" rel="nofollow noreferrer">Serial Communications in Win32</a> from MSDN.</li> </ul> <p>In a multithreaded implementation, whenever the reader thread reads a message from the serial port you would then post it to your application's main thread. The main thread would then parse the message and query the database, and then queue an appropriate response to the writer thread.</p> <p>This may sound more complex than your current design, but really it isn't, as Newcomer explains.</p> <p>I hope this helps!</p>
34,755
<p>What I want to do is have a Windows application launch another Direct3D application and have the Direct3D application render into a control provided by the parent process. </p> <p>Is this even possible? If it is, how would it be done?</p>
<p>It can be done easly, all you need to do is pass the HWND window id as a parameter when creating D3DDevice. It even works during interop - you can pass the hWnd from .NET to C++ and render C# window using native directX.</p>
<p>This is possible. I remember doing it in VB6 when writing screen savers. The screen saver control panel sends a commandline to the screen saver with the HWND of the preview window. Using that HWND, you can then get the HDC and from there everything else you need.</p>
13,890
<p>I have a .net project in subversion which is contineously integrated with Cruisecontrol.net.</p> <p>i use Svn source control CCNET task.</p> <p>The .net project library directory with set of reusable components configured as subversion externals.</p> <p>ProjectA\libraries {reusable components directory} ProjectA\libraries\component1 ProjectA\libraries\component2 ProjectA\libraries\component3</p> <p>projectA\Src { source code directory}</p> <p>when the subversion externals are changed the build is not triggered, as it is not detecting the changes happened in extern folders.</p> <p>How to make subversion ccnet task to build immediately when there is change in configured components as externals.</p>
<p>In CruiseControl.NET 1.4 there is a few new flags for the subversion source control block, one of them is CheckExternals set this to true in your config and any modifications in your externals should trigger a build.</p> <pre><code>&lt;checkExternals&gt;True&lt;/checkExternals&gt; &lt;checkExternalsRecursive&gt;True&lt;/checkExternalsRecursive&gt; </code></pre>
<p>I just setup a polling interval to check for mods - using the triggers node in ccnet.config it is an intervalTrigger. I also tell it to build only if modifications exists (the svn source changed) using the IfModificationExists attribute (which is the default)</p> <p>You can set that interval pretty low if you want but I am not sure of a way to push a notification out of SVN that ccnet picks up.</p>
49,034
<p>I'm working on a table of links within a site using iframes. I'm wondering if there's any way to code a link to go to two simultaneous destinations within two different target frames? I've been reading all afternoon and can't find anything close to what I want to do. Basically I want one link to present a photo in one iframe and some data in another iframe. Any ideas?</p>
<p>Short answer: No.</p> <p>Longer answer: With what you describe, using strictly X/HTML, this isn't possible. You could add in javascript to change the iframe src, however. Something like:</p> <pre><code>function click_link(id) { document.getElementById('iframe1').src = "page.ext?id=" + id; document.getElementById('iframe2').src = "other_page.ext?id=" + id; } </code></pre> <p>But of course, you probably shouldn't be using iframes anyways...</p>
<p>Don't use frames. They're bad for usability, bad for SEO, and cause problems like this.</p> <p>This may seem unhelpful advice, but really in the long run you'll avoid a lot of headaches. </p> <p>If you merge files on the server side, they'll work without problems in every browser, search engine, etc. Reloading of a simple page doesn't have to be slower than loading of 2 iframes.</p> <p>Or, in case of showing photos with descriptions, a simple DHTML could do the job:</p> <pre><code>img.onclick = function(){ $('bigphoto').src = this.src.replace(/_small/,'_big'); $('description').innerHTML = this.title; } </code></pre>
26,331
<p>If a user requests a large file from an Apache web server, but cancels the download before it completes, is this logged by Apache?</p> <p>Can I tell from the log file which responses were not sent fully, and how many bytes were sent?</p>
<p>Yes, it logs those requests, but you need to use <a href="http://httpd.apache.org/docs/2.2/mod/mod_logio.html" rel="noreferrer">mod_logio</a> to know the actual bytes sent, else it will show the total amount of bytes of the file. And to know which have failed you'd have to either:</p> <ul> <li>use the <a href="http://httpd.apache.org/docs/2.2/mod/mod_log_config.html" rel="noreferrer">%X format modifier</a> and use a custom log format </li> <li>compare the actual bytes sent against the files' sizes (why would you if you have the first option :-) )</li> </ul>
<p>Yes. If I remember correctly, it will show the amount of bytes transferred before the download was interrupted. You could then work out how many bytes should have been sent for that request and compare.</p> <p>If you're using PHP (as the question was tagged a minute ago), you could probably do some sort of response buffer, where you chunk out the file in smaller bits. Start off by working out how many chunks you need to send, write a log (to db, or the syslog) to say you've started and once you hit the final chunk, another to say you've finished (or delete the first).</p>
41,868
<p>How do you perform delete and put operations restfully in rails? I have read the documentation and thought I was doing everything properly, but I can't seem to get it to work.</p> <p>For example, if I wanted to delete an employee I would create a controller called "EmployeesController" and create a destroy method to perform the delete.</p> <p>Then I went into the routes.rb file and entered <code>map.resources :employees</code>, which gives you access to the URL helper functions.</p> <p>In whatever I want to call the Ajax operation from, I should just have a line like:</p> <pre><code>&lt;%= link_to_remote "Delete", employee_path(@employee), :method =&gt; :delete %&gt; </code></pre> <p>When I click on the link, it is still is sending a POST operation, so it does nothing.</p> <p>What am I missing or doing wrong?</p>
<p>Try </p> <pre><code>:url =&gt; employee_url(@employee) </code></pre> <p>IIRC, *_path is a named route generated by the :resource directive which includes the method, thus overwriting your :method => :delete</p>
<p>If your problem is not having AJAX request you have to add proper javascript tags</p>
19,654
<p>The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?</p> <p>If object <code> foo </code> calls into object <code> bar</code>, is it correct to say (in pseudo-code):</p> <pre><code>bar = new barClass() foo = new fooClass(bar) </code></pre> <p>What happens if you need to pass messages back and forth? Do you need a method for registering the target object?</p> <pre><code>foo = new fooClass() bar = new barClass() foo.register(bar) bar.register(foo) </code></pre> <p>Is there a pattern that addresses this?</p>
<p>Generally dependency injection is the way to go. If you're just talking about two objects communicating then pass an instance of one in as a paramter to the other, as in your first example. Passing in the constructor ensure the reference is always valid. Otherwise you'd have to test to ensure register had been called. Also you'd need to make sure calling register more than once wouldn't have adverse effects.</p> <p>What if you want a controlling object, to which other objects register for events. It would then be suitable to use a Register method ( which may add to a delegate).</p> <p>See <a href="http://www.dofactory.com/Patterns/PatternObserver.aspx" rel="nofollow noreferrer">Observer Pattern</a></p>
<p>Well, depending on the level of messaging, you could implement a messaging service. Objects listen for messages, or register as a MessageListener on some MessageProvider.</p> <p>You end up with cyclical dependencies if two objects have references to each other, which I would consider bad in most cases.</p>
12,489
<p>We are a small company and would like to know the best possible (and affordable) hardware and software configuration we ought to be using for our development environment. At this moment we are a team of four people who work remotely from different locations and each one of us uses a laptop and ADSL connection to work on our projects.</p> <p>This question should help us identify a path towards optimizing our hardware and software so as to make the most of these development environments. Do we need to run everything locally on the laptops or some sort of distributed solution is possible? Which software versions do you recommend given that both Windows 2008 and SQL Server 2008 are available options? Do we use a central server or run these locally on our laptops? </p> <p>We're a young team so any help would be welcome and much appreciated! Thanks!</p> <p>Ym</p>
<p>For a team, I would suggest that you set up the local environments (laptops) as development environments, with a local DB copy and running CF developer version. Version control (VSS, Subversion, Git, etc.) is pretty much mandatory.</p> <p>Have a testing/staging/QA server with the same configuration as the live version (as much as this is possible). It should have its own CF license to follow the licensing agreement. You should put checked-in code here for everyone to test and to check integration. Several version control systems offer ways to automate this, or you could do this manually.</p> <p>Production, obviously, should be its own thing. I would suggest that you separate the database and app/web server on two separate boxes. </p> <p>I know this might be a little more/less than you were asking, so feel free to ask for clarification.</p>
<p>MS SQL Server 2008 Express, it's free. <a href="http://www.microsoft.com/downloads/details.aspx?familyid=B5D1B8C3-FDA5-4508-B0D0-1311D670E336&amp;displaylang=en" rel="nofollow noreferrer">http://www.microsoft.com/downloads/details.aspx?familyid=B5D1B8C3-FDA5-4508-B0D0-1311D670E336&amp;displaylang=en</a><br> Windows XP (prof. edition) is stable and use less resources than Vista. For asp.net I suggest using Dev Studio 2008 Pro.</p> <p>For the computer itself, you want lots of memory (2-4 GB). A fast dual-core CPU. And you will see a difference using a faster HD (on a laptop, 5400 RPM HD are fast and 4500 RPM are the standard)</p> <p>I recommend working locally and update all on a central location (with source control as Ben wrote).</p>
28,328
<p>There are several similar Oracle technologies - Oracle Streams, Oracle Change Data Capture and Database Change Notification. </p> <p>What are the differences between these? </p> <p>Are they related to Oracle Advanced Queueing?</p>
<p>Oracle CDC is all about capturing changes in DB tables and the changes are stored in special Oracle tables. There are two modes of CDC operation: asynchronous (based on Java) or synchronous (based on DB triggers, more performance overhead).</p> <p>Oracle Streams sits on top of Oracle CDC and it's a full transport mechanism (over e.g. HTTP) for data synchronization between 2 servers. It's based on Oracle Advanced Queues technology and it's designed for high performance and reliability.</p> <p>Both Oracle CDC and Streams are generally used for data synchronization between Oracle DB servers... With Oracle CDC, you don't have to use Oracle Streams for, e.g. you could write your own data export routines which create flat files for the purpose of synchronization between 2 DB servers, whereas with Streams you must have a network link between the 2 servers.</p> <p>Database Change Notification is something else again, it's not used for server-to-server synch but instead more for server notification of resultset changes to clients, mostly in the context of data caches on the client side.</p>
<p>I would add that for synchronizing between systems, you can achieve asynchronous mode by combining Streams and the CDC publishing mechanism. If you choose not to use Streams for this purpose, you would end up using a synchronous mode (I think it's via triggers) putting a little extra overhead on each transaction.</p>
34,348
<p>I noticed that I can start a program with it's associated handler by writing <strong>start filename</strong>. However, for some files, all I get is a console, and I don't know why. I'm trying to populate a list control in MFC, and I want to have the program and it's associated handler to run when I double click the selection. Is there a better way, or an explanation to why this doesn't work?<br> This is the code that could be the problem:</p> <p><pre><code> int selection = listControl.GetCurSel(); CString text; listControl.GetText(selection,text); string std_str = StringUtils::CStringToString(text); string st = string("start \"")+std_str+string("\""); const char* command = st.c_str(); system(command); </pre></code></p>
<p>If the first parameter on the <code>start</code> command line is enclosed in double-quotes, it uses that as the window title instead of the command. It's lame, but that's what it does...</p> <p>Try</p> <pre><code>string st = string("start \"\" \"")+std_str+string("\""); </code></pre> <p>instead.</p> <p>But if you're trying to get the shell handler for a file to execute from within your process, a better, cleaner way to do this instead of invoking the <code>start</code> command is to use the <a href="http://msdn.microsoft.com/en-us/library/bb762153.aspx" rel="nofollow noreferrer"><code>ShellExecute()</code></a> or <a href="http://msdn.microsoft.com/en-us/library/bb762154.aspx" rel="nofollow noreferrer"><code>ShellExecuteEx()</code></a> Win32 API.</p>
<p>I believe start uses the file handler associated with the file's extension.</p> <p>Basically it will use the files extension to lookup what application to run.<br> It sounds like the extension to the files you are using are resulting in a default handler of the console being started.</p> <p>You could start by reading the MS documentation:<br> <a href="http://msdn.microsoft.com/en-us/library/53ezey2s.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/53ezey2s.aspx</a></p>
45,625
<p>I'm not brand new to the concept of unit testing but at the same time I've not yet mastered them either.</p> <p>The one question that has been going through my head recently as I've been writing unit tests while writing my code using the TDD methodology is: to what level should I be testing?</p> <p>Sometimes I wonder if I'm being excessive in the use of unit testing.</p> <p>At what point should a developer stop writing unit tests and get actual work done?</p> <p>I might need to clarify that question before people assume I'm against using TDD...</p> <p>What I'm struggling with is the granularity of my test....</p> <ul> <li>When my app has a config file do I test that values can be retrieved from the file? I lean towards yes....but....</li> <li>Do I then write a unit test for each possible config value that will be present? ie check that they exist...and can be parsed to the correct type...</li> <li>When my app writes errors to a log do I need to test that it is able to write to the log? Do I then need to write tests to verify that entries are actually made to the log?</li> </ul> <p>I want to be able to use my unit tests to verify the behavior of my app...but I'm not quite sure where to stop. Is it possible to write tests that are too trivial?</p>
<p><strong>[Update:]</strong> Found the concise answer to this question in TDD ByExample - Pg194.</p> <blockquote> <p>The simple answer, supplied by Phlip is, "Write tests until fear is transformed into boredom."</p> </blockquote> <p>[/<strong>Update</strong>]</p> <p>I think the problem prevalent in the current times is the lack of unit testing... not excessive testing. I think I see what you're getting at.. I wouldn't term it as excessive unit-testing but rather.. not being smart about where you focus your efforts.</p> <p>So to answer your question.. some guidelines.</p> <ul> <li>If you <strong>follow TDD</strong>, you'll never have code that is not covered by a unit test.. since you only write (minimal) code to pass a failing unit test and no more. Corollary: Every issue should fail a unit test which pinpoints the location of the defect. The same defect shouldn't cause tens of UTs to break simultaneously</li> <li><strong>Don't test code that you didn't write.</strong> A corollary is: you don't test framework code (like reading values from an app.config file) You just assume it works. And how many times have you had framework code breaking? Next to zero.</li> <li>If in doubt, <strong>consider the probability of failure and weigh that against the cost of writing an automated test case</strong>. Writing test cases for accessors/repetitive data-set testing included.</li> <li><strong>Address the pain</strong>. if you find that you're having issues in a certain area periodically, get it under a test harness.. instead of spending time writing redundant tests for areas that you know are pretty solid. e.g. A third party/team library keeps breaking at the interface.. doesn't work like it is supposed to. Mocks won't catch it. Have a regression type suite using the real collaborator and running some sanity tests to verify the link if you know its been a problem child. </li> </ul>
<p>If two test cases will run exactly the same code, then there's no need to test them separately. e.g., For your example of reading the config file, you only need to test that it is able to correctly read each type of value (and that it fails in the correct manner when asked to read a nonexistent or invalid value).</p> <p>If you test that it correctly reads in every single value in the config file, then you are testing the config file, not the code.</p>
45,199
<p>I want to do the following imports in a class.</p> <pre><code>import org.eclipse.jdt.core.dom.*; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.core.compiler.IProblem; import org.eclipse.jdt.internal.compiler.ClassFile; import org.eclipse.jdt.internal.compiler.CompilationResult; import org.eclipse.jdt.internal.compiler.Compiler; import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies; import org.eclipse.jdt.internal.compiler.ICompilerRequestor; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader; import org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException; import org.eclipse.jdt.internal.compiler.env.ICompilationUnit; import org.eclipse.jdt.internal.compiler.env.INameEnvironment; import org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory; import org.eclipse.jface.text.Document; import org.eclipse.jface.text.BadLocationException; import org.eclipse.text.edits.TextEdit; </code></pre> <p>How can I import the JDT within Eclipse? Cheers.</p>
<p>I think I found an easier way to do this:</p> <ul> <li>right-click on your project in the Package Explorer;</li> <li>choose "Build Path...";</li> <li>choose "Configure Build Path";</li> <li>choose the Libraries tab;</li> <li>click the "Add Variable..." button;</li> <li>in the list box, choose the "ECLIPSE_HOME" entry, and then click the "Extend" button;</li> <li>in the list box, open up the "plugins" folder entry, scroll way down, and shift-click all the org.eclipse.jdt.* JAR files that are in the file listing <em>beneath</em> the folders;</li> <li>click OK until you're all the way back out.</li> </ul> <p>That should do it.</p>
<p>If you need these classes, you are probably in a plug-in project already. You should be able to import these classes by applying the quick fix "Fix project setup..." (Ctrl+1) on the line where Eclipse is complaining about the imports. That will add the required plug-ins to your MANIFEST.MF file in the META-INF directory (org.eclipse.jdt.core and org.eclipse.jface.text in your case). You can also add them manually in your MANIFEST.MF file. If your project is no plug-in project (and you have no MANIFEST.MF file) you can convert it by right-click on the project -> PDE Tools -> Convert Projects to Plug-in Project first. If you add dependencies to plug-in projects in the normal way ("configure build path") the classloading won't work properly at runtime (though it will compile).</p>
11,934
<pre><code>class someclass {}; class base { int a; int *pint; someclass objsomeclass; someclass* psomeclass; public: base() { objsomeclass = someclass(); psomeclass = new someclass(); pint = new int(); throw "constructor failed"; a = 43; } } int main() { base temp(); } </code></pre> <p>In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?</p> <pre><code>int main() { base *temp = new base(); } </code></pre> <p>How about in the above code? How can the memory leaks be avoided after the constructor throws?</p>
<p>Yes it will leak memory. When the constructor throws, no destructor will be called (in this case you don't show a destructor that frees the dynamically allocated objects, but lets assume you had one). </p> <p>This is a major reason to use smart pointers - since the smart poitners are full fledged objects, they will get destructors called during the exception's stack unwind and have the opportunity to free the memory.</p> <p>If you use something like Boost's scoped_ptr&lt;> template, your class could look more like:</p> <pre><code>class base{ int a; scoped_ptr&lt;int&gt; pint; someclass objsomeclass; scoped_ptr&lt;someclass&gt; psomeclass; base() : pint( new int), objsomeclass( someclass()), psomeclass( new someclass()) { throw "constructor failed"; a = 43; } } </code></pre> <p>And you would have no memory leaks (and the default dtor would also clean up the dynamic memory allocations).</p> <hr> <p>To sum up (and hopefully this also answers the question about the </p> <pre><code>base* temp = new base(); </code></pre> <p>statement):</p> <p>When an exception is thrown inside a constructor there are several things that you should take note of in terms of properly handling resource allocations that may have occured in the aborted construction of the object:</p> <ol> <li>the destructor for the object being constructed will <strong>not</strong> be called.</li> <li>destructors for member objects contained in that object's class will be called</li> <li>the memory for the object that was being constructed will be freed.</li> </ol> <p>This means that if your object owns resources, you have 2 methods available to clean up those resources that might have already been acquired when the constructor throws:</p> <ol> <li>catch the exception, release the resources, then rethrow. This can be difficult to get correct and can become a maintenance problem.</li> <li>use objects to manage the resource lifetimes (RAII) and use those objects as the members. When the constructor for your object throws an exception, the member objects will have desctructors called and will have an opportunity to free the resource whose lifetimes they are responsible for.</li> </ol>
<p>Everything you "new" needs to be deleted, or you'll cause a memory leak. So these two lines:</p> <pre><code>psomeclass = new someclass(); pint = new int(); </code></pre> <p>Will cause memory leaks, because you need to do:</p> <pre><code>delete pint; delete psomeclass; </code></pre> <p>In a finally block to avoid them being leaked.</p> <p>Also, this line:</p> <pre><code>base temp = base(); </code></pre> <p>Is unnecessary. You just need to do:</p> <pre><code>base temp; </code></pre> <p>Adding the "= base()" is unnecessary.</p>
17,770
<p>We are writing a complex rich desktop application and need to offer flexibility in reporting formats so we thought we would just expose our object model to a scripting langauge. Time was when that meant VBA (which is still an option), but the managed code derivative VSTA (I think) seems to have withered on the vine.</p> <p>What is now the best choice for an embedded scripting language on Windows .NET?</p>
<p>Personally, I'd use C# as the scripting language. The .NET framework (and Mono, thanks Matthew Scharley) actually includes the compilers for each of the .NET languages in the framework itself.</p> <p>Basically, there's 2 parts to the implementation of this system.</p> <ol> <li><p>Allow the user to compile the code This is relatively easy, and can be done in only a few lines of code (though you might want to add an error dialog, which would probably be a couple dozen more lines of code, depending on how usable you want it to be).</p></li> <li><p>Create and use classes contained within the compiled assembly This is a little more difficult than the previous step (requires a tiny bit of reflection). Basically, you should just treat the compiled assembly as a "plug-in" for the program. There are quite a few tutorials on various ways you can create a plug-in system in C# (Google is your friend).</p></li> </ol> <p>I've implemented a "quick" application to demonstrate how you can implement this system (includes 2 working scripts!). This is the complete code for the application, just create a new one and paste the code in the "program.cs" file. At this point I must apologize for the large chunk of code I'm about to paste (I didn't intend for it to be so large, but got a little carried away with my commenting)</p> <pre> <code> using System; using System.Windows.Forms; using System.Reflection; using System.CodeDom.Compiler; namespace ScriptingInterface { public interface IScriptType1 { string RunScript(int value); } } namespace ScriptingExample { static class Program { /// /// The main entry point for the application. /// [STAThread] static void Main() { // Lets compile some code (I'm lazy, so I'll just hardcode it all, i'm sure you can work out how to read from a file/text box instead Assembly compiledScript = CompileCode( "namespace SimpleScripts" + "{" + " public class MyScriptMul5 : ScriptingInterface.IScriptType1" + " {" + " public string RunScript(int value)" + " {" + " return this.ToString() + \" just ran! Result: \" + (value*5).ToString();" + " }" + " }" + " public class MyScriptNegate : ScriptingInterface.IScriptType1" + " {" + " public string RunScript(int value)" + " {" + " return this.ToString() + \" just ran! Result: \" + (-value).ToString();" + " }" + " }" + "}"); if (compiledScript != null) { RunScript(compiledScript); } } static Assembly CompileCode(string code) { // Create a code provider // This class implements the 'CodeDomProvider' class as its base. All of the current .Net languages (at least Microsoft ones) // come with thier own implemtation, thus you can allow the user to use the language of thier choice (though i recommend that // you don't allow the use of c++, which is too volatile for scripting use - memory leaks anyone?) Microsoft.CSharp.CSharpCodeProvider csProvider = new Microsoft.CSharp.CSharpCodeProvider(); // Setup our options CompilerParameters options = new CompilerParameters(); options.GenerateExecutable = false; // we want a Dll (or "Class Library" as its called in .Net) options.GenerateInMemory = true; // Saves us from deleting the Dll when we are done with it, though you could set this to false and save start-up time by next time by not having to re-compile // And set any others you want, there a quite a few, take some time to look through them all and decide which fit your application best! // Add any references you want the users to be able to access, be warned that giving them access to some classes can allow // harmful code to be written and executed. I recommend that you write your own Class library that is the only reference it allows // thus they can only do the things you want them to. // (though things like "System.Xml.dll" can be useful, just need to provide a way users can read a file to pass in to it) // Just to avoid bloatin this example to much, we will just add THIS program to its references, that way we don't need another // project to store the interfaces that both this class and the other uses. Just remember, this will expose ALL public classes to // the "script" options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location); // Compile our code CompilerResults result; result = csProvider.CompileAssemblyFromSource(options, code); if (result.Errors.HasErrors) { // TODO: report back to the user that the script has errored return null; } if (result.Errors.HasWarnings) { // TODO: tell the user about the warnings, might want to prompt them if they want to continue // runnning the "script" } return result.CompiledAssembly; } static void RunScript(Assembly script) { // Now that we have a compiled script, lets run them foreach (Type type in script.GetExportedTypes()) { foreach (Type iface in type.GetInterfaces()) { if (iface == typeof(ScriptingInterface.IScriptType1)) { // yay, we found a script interface, lets create it and run it! // Get the constructor for the current type // you can also specify what creation parameter types you want to pass to it, // so you could possibly pass in data it might need, or a class that it can use to query the host application ConstructorInfo constructor = type.GetConstructor(System.Type.EmptyTypes); if (constructor != null && constructor.IsPublic) { // lets be friendly and only do things legitimitely by only using valid constructors // we specified that we wanted a constructor that doesn't take parameters, so don't pass parameters ScriptingInterface.IScriptType1 scriptObject = constructor.Invoke(null) as ScriptingInterface.IScriptType1; if (scriptObject != null) { //Lets run our script and display its results MessageBox.Show(scriptObject.RunScript(50)); } else { // hmmm, for some reason it didn't create the object // this shouldn't happen, as we have been doing checks all along, but we should // inform the user something bad has happened, and possibly request them to send // you the script so you can debug this problem } } else { // and even more friendly and explain that there was no valid constructor // found and thats why this script object wasn't run } } } } } } } </code> </pre>
<p>I havnt tried this yet but it looks pretty cool:</p> <p><a href="http://www.codeplex.com/scriptdotnet" rel="nofollow noreferrer">http://www.codeplex.com/scriptdotnet</a></p>
16,682
<p>Does anybody know a way with JavaScript or CSS to basically grey out a certain part of a form/div in HTML?</p> <p>I have a '<em>User Profile</em>' form where I want to disable part of it for a '<em>Non-Premium</em>' member, but want the user to see what is behind the form and place a '<em>Call to Action</em>' on top of it.</p> <p>Does anybody know an easy way to do this either via CSS or JavaScript?</p> <p>Edit: I will make sure that the form doesn't work on server side so CSS or JavaScript will suffice.</p>
<p>Add this to your HTML:</p> <pre><code>&lt;div id="darkLayer" class="darkClass" style="display:none"&gt;&lt;/div&gt; </code></pre> <p>And this to your CSS:</p> <pre><code>.darkClass { background-color: white; filter:alpha(opacity=50); /* IE */ opacity: 0.5; /* Safari, Opera */ -moz-opacity:0.50; /* FireFox */ z-index: 20; height: 100%; width: 100%; background-repeat:no-repeat; background-position:center; position:absolute; top: 0px; left: 0px; } </code></pre> <p>And finally this to turn it off and on with JavaScript:</p> <pre><code>function dimOff() { document.getElementById("darkLayer").style.display = "none"; } function dimOn() { document.getElementById("darkLayer").style.display = ""; } </code></pre> <p>Change the dimensions of the darkClass to suite your purposes.</p>
<p>If you rely on CSS or JavaScript to prevent a user from editing part of a form then this can easily by circumvented by disabling CSS or JavaScript.</p> <p>A better solution might be to present the non-editable information outside of the form for non-premium members, but include the relevant form fields for premium members.</p>
19,340
<p>I looked around and found some ideas about how to do this, but no definitive best way. One of the ideas was to use sp&#95;start&#95;job to kick off an SQL Server Agent job that runs the DTS package. If this is the best way to do it, then the next question would be, "How do I schedule a DTS package from a job and make it non-recurring?"</p> <p>Thanks, Tim</p>
<p><a href="http://msdn.microsoft.com/en-us/library/ms175046.aspx" rel="nofollow noreferrer">xp_cmdshell</a> would allow you to execute dtsrun.</p>
<p>Instead of using xp&#95;cmdshell, I did this:</p> <p>When a certain value in a table changes, the trigger uses msdb.sp&#95;start&#95;job to start a job. This job should not run on a schedule, only when initiated by a user. I set the job schedule to run one time, which is now in the past, and I unchecked the enabled box. </p> <p>This job has one step, which is DTSRun /~Z0xHEXENCRYPTEDVALUE. The DTS package copies some rows from this server to another server on a different platform and on success resets values in the table with the trigger for next time. The trigger checks a table value before calling sp&#95;start&#95;job, so that the job starts only under certain conditions, not every time.</p> <p>Since sp&#95;start&#95;job runs asyhchronously the trigger completes quickly. The only drawback to this is that I need to poll the value that was reset on success and either let the user know it worked, or after some time out period, it did not work.</p> <p>The alternative would be to use xp_cmdshell if I needed synchronous operation, which might not be a good idea from inside of a trigger.</p>
31,404
<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>
<p>See also my answer <a href="https://stackoverflow.com/questions/475990/php-by-reference#476023">here</a> which includes a simple code sample to illustrate the issue.</p>
45,682
<p>After tinkering around to solve [this][1] problem, I think the core of the problem is the following:</p> <p>When you use the Html.RadioButton() html helper with an Enum as value field, you can only choose your option once. AFter reposting the page, the helpers will ignore the value set in the call and set all radio buttons to the same value, being the value you selected the previous post back. Am I doing something wrong?</p> <p><em>Example (watch the <strong>value</strong> of the buttons)</em></p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;Test&lt;/legend&gt; &lt;div&gt; &lt;label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel"&gt; Any &lt;/label&gt; &lt;%=Html.RadioButton("SearchBag.EffectIndicator", "Any" , ViewData.Model.SearchBag.EffectIndicatorIsAny, new { @id = "SearchBag.EffectIndicatorAny" })%&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel"&gt; Solid &lt;/label&gt; &lt;%=Html.RadioButton("SearchBag.EffectIndicator", "Solid", ViewData.Model.SearchBag.EffectIndicatorIsSolid, new { @id = "SearchBag.EffectIndicatorSolid" })%&gt; &lt;/div&gt; &lt;div&gt; &lt;label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel"&gt; Effect &lt;/label&gt; &lt;%=Html.RadioButton("SearchBag.EffectIndicator", "Effect", ViewData.Model.SearchBag.EffectIndicatorIsEffect, new { @id = "SearchBag.EffectIndicatorEffect" })%&gt; &lt;/div&gt; &lt;/fieldset&gt; </code></pre> <p>Will generate </p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;Effect&lt;/legend&gt; &lt;div class="horizontalRadio"&gt; &lt;label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel"&gt; Any &lt;/label&gt; &lt;input checked="checked" id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Any" /&gt; &lt;/div&gt; &lt;div class="horizontalRadio"&gt; &lt;label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel"&gt; Solid &lt;/label&gt; &lt;input id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" /&gt; &lt;/div&gt; &lt;div class="horizontalRadio"&gt; &lt;label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel"&gt; Effect &lt;/label&gt; &lt;input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Effect" /&gt; &lt;/div&gt; &lt;/fieldset&gt; </code></pre> <p>And will generate the second time:</p> <pre><code>&lt;fieldset&gt; &lt;legend&gt;Effect&lt;/legend&gt; &lt;div class="horizontalRadio"&gt; &lt;label for="SearchBag.EffectIndicatorAny" id="EffectIndicatorAnyLabel"&gt; Any &lt;/label&gt; &lt;input id="SearchBag.EffectIndicatorAny" name="SearchBag.EffectIndicator" type="radio" value="Solid" /&gt; &lt;/div&gt; &lt;div class="horizontalRadio"&gt; &lt;label for="SearchBag.EffectIndicatorSolid" id="EffectIndicatorSolidLabel"&gt; Solid &lt;/label&gt; &lt;input checked="checked" id="SearchBag.EffectIndicatorSolid" name="SearchBag.EffectIndicator" type="radio" value="Solid" /&gt; &lt;/div&gt; &lt;div class="horizontalRadio"&gt; &lt;label for="SearchBag.EffectIndicatorEffect" id="EffectIndicatorEffectLabel"&gt; Effect &lt;/label&gt; &lt;input id="SearchBag.EffectIndicatorEffect" name="SearchBag.EffectIndicator" type="radio" value="Solid" /&gt; &lt;/div&gt; &lt;/fieldset&gt; </code></pre>
<p>This is due to a bug in the ASP.NET MVC Beta code. I wrote a full explanation of the issue at asp.net MVC forum. Refer to this <a href="http://forums.asp.net/t/1338576.aspx" rel="nofollow noreferrer">link</a></p>
<p>One thing to check. Are you using the updated model to render your view? I.e. is the same model data that was updated from the post passed to the view the second time it's displayed?</p>
35,035
<p>As many do I have a config.php file in the root of a web app that I want to include in almost every other php file. So most of them have a line like:</p> <pre><code>require_once("config.php"); </code></pre> <p>or sometimes</p> <pre><code>require_once("../config.php"); </code></pre> <p>or even</p> <pre><code>require_once("../../config.php"); </code></pre> <p>But I never get it right the first time. I can't figure out what php is going to consider to be the current working directory when reading one of these files. It is apparently not the directory where the file containing the require_once() call is made because I can have two files in the same directory that have different paths for the config.php.</p> <p>How I have a situation where one path is correct for refreshing the page but an ajax can that updates part of the page requires a different path to the config.php in the require_once() statement;</p> <p>What's the secret? From where is that path evaluated?</p> <p>Shoot, I was afraid this wouldn't be a common problem - This is occurring under apache 2.2.8 and PHP 5.2.6 running on windows.</p>
<p>The current working directory for PHP is the directory in which the called script file is located. If your files looked like this:</p> <pre><code>/A foo.php tar.php B/ bar.php </code></pre> <p>If you call foo.php (ex: <a href="http://example.com/foo.php" rel="noreferrer">http://example.com/foo.php</a>), the working directory will be /A/. If you call bar.php (ex: <a href="http://example.com/B/bar.php" rel="noreferrer">http://example.com/B/bar.php</a>), the working directory will be /A/B/.</p> <p>There is where it gets tricky. Let us say that foo.php is such:</p> <pre><code>&lt;?php require_once( 'B/bar.php' ); ?&gt; </code></pre> <p>And bar.php is:</p> <pre><code>&lt;?php require_once( 'tar.php'); ?&gt; </code></pre> <p>If we call foo.php, then bar.php will successfully call tar.php because tar.php and foo.php are in the same directory which happens to be the working directory. If you instead call bar.php, it will fail.</p> <p>Generally you will see either in all files:</p> <pre><code>require_once( realpath( dirname( __FILE__ ) ).'/../../path/to/file.php' ); </code></pre> <p>or with the config file:</p> <pre><code>// config file define( "APP_ROOT", realpath( dirname( __FILE__ ) ).'/' ); </code></pre> <p>with the rest of the files using:</p> <pre><code>require_once( APP_ROOT.'../../path/to/file.php' ); </code></pre>
<p>Take a look at the function getcwd. <a href="http://us2.php.net/getcwd" rel="nofollow noreferrer" title="getcwd">http://us2.php.net/getcwd</a></p>
33,433
<p>I'm trying to determine which records to delete from a database when a user submits a form. The page has two CheckBoxList one representing the records before modification and one after.</p> <p>I can easily get the selected values that need to be deleted like this...</p> <pre><code>//get the items not selected that were selected before var oldSelectedItems = from oItem in oldChklSpecialNeeds.Items.Cast&lt;ListItem&gt;() where !(from nItem in newChklSpecialNeeds.Items.Cast&lt;ListItem&gt;() where nItem.Selected select nItem.Value).Contains(oItem.Value) &amp;&amp; oItem.Selected select oItem.Value; </code></pre> <p>now I am trying to do something like this but it isn't allowing it...</p> <pre><code>var itemsToDelete = from specialNeed in db.SpecialNeeds join oldSelectedItem in oldSelectedItems on specialNeed.SpecialNeedsTypeCd equals oldSelectedItem.Value where specialNeed.CustomerId == customerId </code></pre> <p>I can easily just use a foreach loop and a .DeleteOnSubmit() for each item but I'm thinking there is a way use functionality of LINQ and pass the whole query result of an inner join to .DeleteAllOnSubmit() </p> <pre><code>//like so db.SpecialNeeds.DeleteAllOnSubmit(itemsToDelete); </code></pre> <p>Any ideas?</p>
<p>Local collections can be used in LINQ to SQL with the Contains() method. You can try changing the <em>join</em> clause into a <em>where</em> with Contains():</p> <pre><code>var itemsToDelete = from specialNeed in db.SpecialNeeds where oldSelectedItems.Contains(specialNeed.SpecialNeedsTypeCd) &amp;&amp; specialNeed.CustomerId == customerId select ...; </code></pre>
<p>What is the error you are getting? Is it a type mismatch between SpecialNeedsTypeCd and oldSelectedItem.Value? Have you just omitted the select in the second Linq statement in this post or is that the problem?</p>
21,768
<p>After update, old Eclipse plugins remain in "plugins" folder (there are also leftovers in "features" folder).</p> <p>Is there a way to remove those automatically?</p>
<p>To get rid of the old plugins you have to clear the Installation History. Go to Help | About Eclipse | Installation Details | Installation History and select all the old stuff. Then click delete and restart. Voila. This works with Eclipse Helios (3.6)</p>
<p>For STM32CubeIDE, a popular Eclipse-based IDE for the STM32 microcontroller-family, this command did clean-up old plugin versions under Windows 10:</p> <pre><code>&quot;C:\ST\STM32CubeIDE_1.3.0\STM32CubeIDE\eclipsec&quot; -application org.eclipse.equinox.p2.garbagecollector.application -profile STM32CubeIDE </code></pre>
27,302
<p>Right now, my SVN repository is on my laptop's HDD (although I use a code hosting service for more "critical" personal projects) and I just copy the directory over on a weekly basis (which will eventually be scripted or perhaps I'll make an app for the hell of it). Am I at risk for corrupting my SVN repository? So far, I haven't had any problems with the original or the copy, but that doesn't mean that I'm not at risk in the future.</p>
<p>Consider using <a href="http://svnbook.red-bean.com/en/1.2/svn.ref.svnadmin.c.hotcopy.html" rel="nofollow noreferrer">hot copy</a>:</p> <blockquote> <p>svnadmin hotcopy — Make a hot copy of a repository...</p> <p>This subcommand makes a full “hot” backup of your repository, including all hooks, configuration files, and, of course, database files. If you pass the <code>--clean-logs</code> switch, <code>svnadmin</code> will perform a hotcopy of your repository, and then remove unused Berkeley DB logs from the original repository. You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository...</p> </blockquote>
<p>You wrote:</p> <blockquote> <p>Right now, my SVN repository is on my laptop's HDD and I just copy the directory over on a weekly basis </p> </blockquote> <p>A question for you: why?</p> <blockquote> <p>Am I at risk for corrupting my SVN repository? </p> </blockquote> <p>Not at all if your copy is just that: a copy. If your "copy" opens some file <em>locked</em> for writing you might be at risk (you said in a comment it something that looks like you are under windows, and it might happen on windows) - if there is another process trying to write something into the repos at the same time.</p> <blockquote> <p>So far, I haven't had any problems with the original or the copy, but that doesn't mean that I'm not at risk in the future.</p> </blockquote> <p>Real point is: are you copying for backup purpose? If so, a copy it might be useless (depending on the details of the restore process). See: <a href="http://svnbook.red-bean.com/en/1.5/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate" rel="nofollow noreferrer">http://svnbook.red-bean.com/en/1.5/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate</a></p> <p>So finally: <strong>use svnadmin dump</strong></p>
22,828
<p>I was thinking about the idea of using Ajax instead of TagLib. The most elegant way would be: Using Java Annotation. The idea is, designers or anybody can make the HTML without any taglib ,just using the "standard" HTML tags with id or name, and call the Javascript. That way any WYSIWYG can be used, developer don't have to care about HTML format or the way it's designed. In many (at least open-source) WYSIWYG don't show the taglibs in that final result (or have a template of it), so it's hard to "preview". Other reason is, developer should know Java and HTML/TagLibs should not be a must-have, since we got CSS and AJAX.</p> <p>It should work just like that:</p> <p><strong>MyClass.java</strong>: <code></p> <pre><code>import ... // Use the ResourceBundle resource[.{Locale}].properties @Jay2JI18n(resourceBundle="org.format.resource",name="MyClassForm") public class MyClass { private Integer age; private String name private Date dob; private salary; @Jay2JLabel(resource="label.name") @Jay2JMaxLength(value=50,required=true,) @Jay2JException(resource="exception.message") public String getName() { ... } public void setName(String name) { if ( name.trim().equal("") ) { throw new Exception("Name is required"); } } /* Getter and setter for age */ ... @Jay2JLabel(message="Salary") @Jay2JFormat(format="##,###.00",language="en") @Jay2JFormat(format="##.###,00",language="pt_BR") // or you could use that to access a property of the ResourceBundle //@Jay2I18nResource(resource="money.format") public Date getSalary() { ... } /* Setter for salary and getter/setter for the rest */ ... } </code></pre> <p></code></p> <p><strong>Page.html</strong>: <code></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;SCRIPT&gt; &lt;/SCRIPT&gt; &lt;/head&gt; &lt;body&gt; &lt;form onload="Jay2J.formalize(this)"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p></code></p> <p>of it can be a HTML with the fields filled; <strong>PageWithFields.html</strong>: <code></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;SCRIPT&gt; &lt;/SCRIPT&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="myfavoritewaytopostthis" onsubmit="return Jay2J.validate(this)" onload="Jay2J.formalizeExistField(this)"&gt; &lt;label&gt;Name&lt;/label&gt;&lt;input type="text" name="name" id="name" /&gt; &lt;label&gt;DOB&lt;/label&gt;&lt;input type="text" name="dateOfBirth" id="dob" /&gt; &lt;label&gt;Salary&lt;/label&gt;&lt;input type="text" name="salary" id="salary" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p></code></p> <p>That way the Annotation (no XML, it's like HTML in the way that it's only another file modify and XML is not Java) will define how the HTML will be treated. That way developer can stop developing in HTML and use just JAVA (or JavaScript), do you think that's a valid idea?</p>
<p>When i see your topic title i thought:</p> <p>You cant use Ajax in stead of a taglib. AJAX is javascript on the client and the taglib is java code on the server.</p> <p>After reading your post i thought, ah he whats to do what [link text][1] does </p> <p>But then not entrily the same. </p> <p>[1]: <a href="http://code.google.com/webtoolkit/" rel="nofollow noreferrer">http://code.google.com/webtoolkit/</a> GWT</p>
<p>First impression is ... yuck, someone who picks this up will have no idea what they're looking at without learning your (new, different, non-standard) way of doing things. You could do something similar by implementing a tag that takes a bean (value object) and maybe does some minor reflection/annotation inspection to emit the proper html, and you'll save yourself a lot of heartache down the line. </p> <p>Make your value objects implement a simple interface that your tag will use to extract and format the html, and you can probably get 80-90% of where you're trying to go with 1/2 the work or less.</p>
30,661
<p>Management wants us to switch to Infragistics. But my boss says that any 3rd party is destined to fail, and at that point there won't be anything we can do about it.</p> <p>Is he right, is he wrong? I don't know. </p> <p>What are your opinions, is it better to use something developed inside the company, or do you prefer something like DevExpress, Infragistics, Krypton to name a few or is there something else even better that you would recommend instead?</p>
<p>When shopping for 3rd party controls, look for the option to purchase source code (for a reasonable price). With source code you should be able to make any necessary changes to the components to keep them running well in your environment.</p> <p>The Krypton Suite of controls from Component Factory does just this. Phil offers the source code for the entire suite for an amazing price (currently less than $400). I have used the Krypton Suite in my development for a year now and I have been extremely pleased with it. Krypton gives me the power to create shrink wrapped software with Office 2007 UI look and feel with consistency far beyond any other toolkit I tried. Phil is also very active in the support forums and provides you a direct link to the development path of the software.</p>
<p>As long as you have access to the source code of the library and are able to modify it and distribute the modified library without paying any royalties, your boss's fears are unfounded.</p> <p>I'd go for DevExpress myself, but they are quite pricey when compared to the other frameworks.</p>
14,839
<p>I want to have CListCtrl.EditLabel() for any column of the list. How can I implement such a feature?</p>
<p>When using ADO LIKE searches must use % instead of *. I know * works in Access but for some stupid reason ADO won't work unless you use % instead. </p> <p>I had the same problem and ran accoss this forum while trying to fix it. Replacing *'s with %'s worked for me.</p>
<p>I put brackets around the word "Description" in the SELECT statement, but it's behavior remains. It works fine as long as I don't put anything in the WHERE clause. I've found if I put anything in the where clause, the description is blank (despite showing up in the Query analyzer). If I use a LIKE statement in the WHERE clause, the entire recordset is empty but it still works properly in the Query Analyzer.</p>
31,657
<p>I'm working on a web application that will return a variable set of modules depending on user input. Each module is a Python class with a constructor that accepts a single parameter and has an '.html' property that contains the output.</p> <p>Pulling the class dynamically from the global namespace works:</p> <pre><code>result = globals()[classname](param).html </code></pre> <p>And it's certainly more succinct than:</p> <pre><code>if classname == 'Foo': result = Foo(param).html elif classname == 'Bar': ... </code></pre> <p>What is considered the best way to write this, stylistically? Are there risks or reasons not to use the global namespace?</p>
<p>A flaw with this approach is that it may give the user the ability to to more than you want them to. They can call <em>any</em> single-parameter function in that namespace just by providing the name. You can help guard against this with a few checks (eg. isinstance(SomeBaseClass, theClass), but its probably better to avoid this approach. Another disadvantage is that it constrains your class placement. If you end up with dozens of such classes and decide to group them into modules, your lookup code will stop working.</p> <p>You have several alternative options:</p> <ol> <li><p>Create an explicit mapping:</p> <pre><code> class_lookup = {'Class1' : Class1, ... } ... result = class_lookup[className](param).html </code></pre> <p>though this has the disadvantage that you have to re-list all the classes.</p></li> <li><p>Nest the classes in an enclosing scope. Eg. define them within their own module, or within an outer class:</p> <pre><code>class Namespace(object): class Class1(object): ... class Class2(object): ... ... result = getattr(Namespace, className)(param).html </code></pre> <p>You do inadvertantly expose a couple of additional class variables here though (__bases__, __getattribute__ etc) - probably not exploitable, but not perfect.</p></li> <li><p>Construct a lookup dict from the subclass tree. Make all your classes inherit from a single baseclass. When all classes have been created, examine all baseclasses and populate a dict from them. This has the advantage that you can define your classes anywhere (eg. in seperate modules), and so long as you create the registry after all are created, you will find them.</p> <pre><code>def register_subclasses(base): d={} for cls in base.__subclasses__(): d[cls.__name__] = cls d.update(register_subclasses(cls)) return d class_lookup = register_subclasses(MyBaseClass) </code></pre> <p>A more advanced variation on the above is to use self-registering classes - create a metaclass than automatically registers any created classes in a dict. This is probably overkill for this case - its useful in some "user-plugins" scenarios though.</p></li> </ol>
<p>Another way to build the map between class names and classes:</p> <p>When defining classes, add an attribute to any class that you want to put in the lookup table, e.g.:</p> <pre><code>class Foo: lookup = True def __init__(self, params): # and so on </code></pre> <p>Once this is done, building the lookup map is:</p> <pre><code>class_lookup = zip([(c, globals()[c]) for c in dir() if hasattr(globals()[c], "lookup")]) </code></pre>
27,400
<p>My webapp (ASP.NET 2.0) consumes a webservice (asmx on 1.1 framework) on the same machine. After getting XML in return, I pass it to <code>XslCompiledTransform</code> for transform XML to HTML and it works fine.</p> <p>Yesterday I got a <code>System.IO.FileNotFoundException</code> frequently and don't know what causes this kind of problem.</p> <p>First look I thought it's about read/write permission on c:\windows\temp and then I made sure give it full permission for Network Service (also Everybody at last -_-!) but it doesn't help.</p> <p>Any ideas or solutions would be appreciate.</p> <pre><code>-------------------- stack trace -------------------------- Exception: **System.IO.FileNotFoundException** **Could not find file 'C:\WINDOWS\TEMP\sivvt5f6.dll'.** at System.IO.__Error**.WinIOError**(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) at Microsoft.CSharp.CSharpCodeGenerator.FromFileBatch(CompilerParameters options, String[] fileNames) at Microsoft.CSharp.CSharpCodeGenerator.FromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) at Microsoft.CSharp.CSharpCodeGenerator.System.CodeDom.Compiler.ICodeCompiler.CompileAssemblyFromDomBatch(CompilerParameters options, CodeCompileUnit[] ea) at System.CodeDom.Compiler.CodeDomProvider.CompileAssemblyFromDom(CompilerParameters options, CodeCompileUnit[] compilationUnits) at System.Xml.Xsl.Xslt.Scripts.CompileAssembly(List`1 scriptsForLang) at System.Xml.Xsl.Xslt.Scripts.CompileScripts() at System.Xml.Xsl.Xslt.QilGenerator.Compile(Compiler compiler) at System.Xml.Xsl.Xslt.**Compiler. Compile**(Object stylesheet, XmlResolver xmlResolver, QilExpression&amp; qil) at System.Xml.Xsl.XslCompiledTransform.LoadInternal(Object stylesheet, XsltSettings settings, XmlResolver stylesheetResolver) at System.Xml.Xsl.**XslCompiledTransform.Load**(String stylesheetUri, XsltSettings settings, XmlResolver stylesheetResolver) </code></pre>
<p>After checking for details and googling for the related topics,</p> <ol> <li>This problem found with .Transform() and also occures with XmlSerialization as Marc said. Christoph Schittko has a good article for <a href="http://msdn.microsoft.com/en-us/library/aa302290.aspx" rel="nofollow noreferrer">troubleshooting</a>. </li> <li><p>Someone said the problem may because some update patch of windows that can change the behavior of serializer.</p> <p>I called my administrator to clarify if there's any changes on our server and he said nothing changes and he suggest me for restarting.</p> <p>and Yes... my problem has been solved by.....restarting server (windows 2003 ;)</p></li> </ol>
<p>OK, that's an interesting one. I've seen similar issues with serializers, but not with <code>XslCompiledTransform</code> specifically.</p> <p>From the title, I was expecting it to be an issue loading included/imported transforms, which would probably have been fixable by supplying an <code>XmlResolver</code>. Not finding the self-generated dlls is very odd!</p> <p>As a stop-gap (while you investigate the issue), you might want to see if it still happens with <code>XslTransform</code>. I realise this isn't ideal (given the optimisations etc in <code>XslCompiledTransform</code>), but it might at least let your app work while you investigate...</p> <p>The first investigative thing I would do is look at the event log. Anything interesting? Also worth checking if your anti-virus software hasn't gone mad with false positives (unlikely).</p> <p>The next thing I would do is isolate the app - i.e. snip off the 1.1 stuff - since you're calling it via an asmx page (to a separate application) it shouldn't be a factor, so you <em>should</em> (theoretically) be able to reproduce it just from a flat xml file. Ideally, it would be good to have a page (maybe an ashx for simplicity) in you project that <em>just</em> tries to do a transform from a local file.</p> <p>Is it reproducable with simple xslt/xml? The simpler you can make the code that has an issue, the closer you are to either finding/fixing it, or having something that you can fire at MS via "connect".</p>
34,113
<p>I am writing some code and trying to speed it up using SIMD intrinsics SSE2/3. My code is of such nature that I need to load some data into an XMM register and act on it many times. When I'm looking at the assembler code generated, it seems that GCC keeps flushing the data back to the memory, in order to reload something else in XMM0 and XMM1. I am compiling for x86-64 so I have 15 registers. Why is GCC using only two and what can I do to ask it to use more? Is there any way that I can "pin" some value in a register? I added the "register" keyword to my variable definition, but the generated assembly code is identical.</p>
<p>Yes, you can. <a href="http://gcc.gnu.org/onlinedocs/gcc/Explicit-Reg-Vars.html" rel="nofollow noreferrer">Explicit Reg Vars</a> talks about the syntax you need to pin a variable to a specific register.</p>
<p>It sounds like you compiled with optimization disabled, so no variables are kept in registers between C statements, not even <code>int</code>.</p> <p>Compile with <code>gcc -O3 -march=native</code> to let the compiler make non-terrible asm, optimized for your machine. The default is <code>-O0</code> with a &quot;generic&quot; target ISA and tuning.</p> <p>See also <a href="https://stackoverflow.com/questions/53366394/why-does-clang-produce-inefficient-asm-with-o0-for-this-simple-floating-point">Why does clang produce inefficient asm with -O0 (for this simple floating point sum)?</a> for more about why &quot;debug&quot; builds in general are like that, and the fact that <code>register int foo;</code> or <code>register __m128 bar;</code> can stay in a register even in a debug build. But it's much better to actually have the compiler optimize, as well as using registers, if you want your code to run fast overall!</p>
15,142
<p>I'm writing an import utility that is using phone numbers as a unique key within the import.</p> <p>I need to check that the phone number does not already exist in my DB. The problem is that phone numbers in the DB could have things like dashes and parenthesis and possibly other things. I wrote a function to remove these things, the problem is that it is <strong>slow</strong> and with thousands of records in my DB and thousands of records to import at once, this process can be unacceptably slow. I've already made the phone number column an index.</p> <p>I tried using the script from this post:<br> <a href="https://stackoverflow.com/questions/52315/t-sql-trim-nbsp-and-other-non-alphanumeric-characters">T-SQL trim &amp;nbsp (and other non-alphanumeric characters)</a></p> <p>But that didn't speed it up any.</p> <p>Is there a faster way to remove non-numeric characters? Something that can perform well when 10,000 to 100,000 records have to be compared.</p> <p>Whatever is done needs to perform <strong>fast</strong>.</p> <p><strong>Update</strong><br> Given what people responded with, I think I'm going to have to clean the fields before I run the import utility. </p> <p>To answer the question of what I'm writing the import utility in, it is a C# app. I'm comparing BIGINT to BIGINT now, with no need to alter DB data and I'm still taking a performance hit with a very small set of data (about 2000 records). </p> <p>Could comparing BIGINT to BIGINT be slowing things down?</p> <p>I've optimized the code side of my app as much as I can (removed regexes, removed unneccessary DB calls). Although I can't isolate SQL as the source of the problem anymore, I still feel like it is.</p>
<p>I saw this solution with T-SQL code and PATINDEX. I like it :-)</p> <pre><code>CREATE Function [fnRemoveNonNumericCharacters](@strText VARCHAR(1000)) RETURNS VARCHAR(1000) AS BEGIN WHILE PATINDEX('%[^0-9]%', @strText) &gt; 0 BEGIN SET @strText = STUFF(@strText, PATINDEX('%[^0-9]%', @strText), 1, '') END RETURN @strText END </code></pre>
<p>I would recommend enforcing a strict format for phone numbers in the database. I use the following format. (Assuming US phone numbers)</p> <p>Database: 5555555555x555</p> <p>Display: (555) 555-5555 ext 555</p> <p>Input: 10 digits or more digits embedded in any string. (Regex replacing removes all non-numeric characters)</p>
13,168
<p>I work for a very small company (~5 employees, 2.5 coders). We have gotten away with no code or document management for several years, but it's starting to catch up with us as we grow a bit.</p> <p>Any suggestions for a management system. Free is better, but cheap is acceptable. We just don't want to spend more time on installation/configuration than it is going to save us.</p> <p>We use mostly VC++ 6, but we're branching into VC# 2008. Also, we need to keep track of mechanical drawings and circuit diagrams for several pieces of hardware, as well as user manuals for both hardware and software (but I don't really expect to find one tool that will do all of this, just hoping).</p>
<p><a href="http://trac.edgewall.org/" rel="nofollow noreferrer">http://trac.edgewall.org/</a> - might be a bit hard to install but otherwise is very good if coupled with svn repository</p>
<p>If you get a MSDN developer license, you can run TFS workgroup edition. That has source control and document management rolled all up in one package that's pretty easy to use and manage. That, in addition to an internal wiki, is what my company does.</p>
10,987
<p>I'm interested in actual examples of using fixed point combinators (such as the <a href="https://stackoverflow.com/questions/93526/what-is-a-y-combinator">y-combinator</a> in C++. Have you ever used a fixed point combinator with <a href="http://p-stade.sourceforge.net/boost/libs/egg/doc/html/boost_egg/function_adaptors.html#boost_egg.function_adaptors.fix" rel="noreferrer">egg</a> or <a href="http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html" rel="noreferrer">bind</a> in real live code?</p> <p>I found this example in egg a little dense:</p> <pre><code>void egg_example() { using bll::_1; using bll::_2; int r = fix2( bll::ret&lt;int&gt;( // \(f,a) -&gt; a == 0 ? 1 : a * f(a-1) bll::if_then_else_return( _2 == 0, 1, _2 * lazy(_1)(_2 - 1) ) ) ) (5); BOOST_CHECK(r == 5*4*3*2*1); } </code></pre> <p>Can you explain how this all works?</p> <p>Is there a nice simple example perhaps using bind with perhaps fewer dependancies than this one?</p>
<p>Here is the same code converted into <code>boost::bind</code> notice the y-combinator and its application site in the main function. I hope this helps.</p> <pre><code>#include &lt;boost/function.hpp&gt; #include &lt;boost/bind.hpp&gt; #include &lt;iostream&gt; // Y-combinator compatible factorial int fact(boost::function&lt;int(int)&gt; f,int v) { if(v == 0) return 1; else return v * f(v -1); } // Y-combinator for the int type boost::function&lt;int(int)&gt; y(boost::function&lt;int(boost::function&lt;int(int)&gt;,int)&gt; f) { return boost::bind(f,boost::bind(&amp;y,f),_1); } int main(int argc,char** argv) { boost::function&lt;int(int)&gt; factorial = y(fact); std::cout &lt;&lt; factorial(5) &lt;&lt; std::endl; return 0; } </code></pre>
<blockquote> <p>Can you explain how this all works?</p> </blockquote> <p>fix2 is a y-combinator (specifically, it is a combinator for functions with two arguments; the first argument is the function (for the purpose of recursion), the second argument is a "proper" function argument). It creates recursive functions.</p> <p>bll::ret(...) appears to create some form of a function object, the body of which is</p> <pre><code>if(second arg == 0) { return 1; } else { return second arg * first arg(second arg - 1); } </code></pre> <p>The "lazy" is presumably there to stop an infinite expansion of the first (function) argument (read up on the difference between lazy and strict y combinators to see why).</p> <p>The code is quite horrible. Anonymous functions are nice to have, but the hackery to work around C++'s lack of syntactic support make them not worth the effort.</p>
18,341
<p>There's PLA filament clogged in my Bowden tube, is there a best practice for cleaning it out or do I need to replace the whole tube?</p> <p>Also, the couplings are totally stuck, so I guess those would need replacement too or are there ways to get stuck couplings off?</p> <p>Click <a href="https://streamable.com/bi73e" rel="nofollow noreferrer">here</a> for a video.</p>
<p>As a short-term fix, grab a twist drill bit that is on the order of 1.5 mm diameter (assuming a 1.75 mm tube). Using a hand drill, slowly and gently drill out the clogged filament. Obviously you want to try to avoid scarring the teflon lining, so better to use the thinnest drill that will work. </p> <p>With a little training and a little luck, you'll get the clog cleared. I would recommend removing the nozzle first so that the chips don't fall into the nozzle.</p>
<p>Most standard filaments soften at 200 °C, meaning a pot of near-boiling water should soften whatever is stuck, allowing you to either fuse another strand of filament to it or use it to push it out of the tube.</p>
1,040
<p>If you create a panel on a form and set it to Dock=Top and drop another panel and set its Dock=Fill, it may fill the entire form, ignoring the first panel. Changing the tab order does nothing.</p>
<p>Docking layout depends on the <strong>order</strong> of sibling controls. Controls are docked "button up", so <strong>the last control in the collection is docked first</strong>. A docked control only take the layout of <em>previously</em> docked siblings into account. Hence the control with Dock=Fill should be first (top) in the sibling order, if you want it to take the other docked controls into account. If it is not the first control, earlier controls will overlap it.</p> <p>This can be confusing because the sibling-order is not necessarily the same as the visual order, and the sibling order is not always apparent from the design view. </p> <p>The <strong>Document outline</strong> window (View -> Other Windows -> Document outline) gives a useful tree-view over the control hierarchy and order, and allows you to change the sibling order of controls.</p> <p>You can also change sibling order directly in the designer by context menu -> Bring to front / Send to back, which moves the control to be first or last of the siblings. These menu labels may be somewhat confusing since the actual effect depends on the layout model.</p> <p>With fixed positioned controls, the 2D position is independent of the sibling order, but when controls are overlapping, the control earliest in the order will be "on top", hiding part of siblings later in the order. In this context Bring to front / Send to back makes sense.</p> <p>Inside flow- or table-layout panels, the creation order determines the visual order of the controls. There is no overlapping controls. So bring to front/send to back really means make first or last in the order of controls.</p> <p>With docked layout, the bring to front / send to back may be even more confusing since it determines in which order the docking is calculated, so "bring to front" on a fill-docked control will place the control in the <em>middle</em> of the parent, taking all edge-docked controls into account.</p>
<p>Here is a trick that worked for me..</p> <p>Place the Top item and dock it top.</p> <p>Place a Splitter, and also dock it top, then set it disabled (unless you want to resize the top).</p> <p>Then Place the Fill object and set Docking to Fill. The object will stay below the splitter.</p>
18,681
<p>I need to validate a certain property to one of my classes. When I set the property, the class should validate the input and if incorrect, set the object to an invalid state.</p> <p>Question : The property value must be in a certain mask/format eg. &amp;&amp;&amp;&amp;-&amp;&amp;&amp;&amp;-&amp;&amp;&amp;&amp;. I cannot use regular expressions. Is it possible to validate text against a mask value?</p>
<p>Regular expressions are often over-used, but this is a pretty good example of when a regex is ideal... so: why can't you use them here?</p>
<blockquote> <p>Is it possible to validate text against a mask value ?</p> </blockquote> <p>Of course it's possible, in that you could write a function to take a string and a mask and check one against another. </p> <p>So I'm unclear on what you're asking - are you asking if there are functions in the standard .Net libraries to do this? Or asking for an implementation of a mask-validation function? Or something else?</p> <p>If you're looking for something in the library to help, <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.maskedtextprovider.aspx" rel="nofollow noreferrer">MaskedTextProvider</a> would probably do it, although it's overkill.</p>
42,126
<p>I need a pseudorandom number generator algorithm for a assembler program assigned in a course, and I would prefer a simple algorithm. However, I cannot use an external library. </p> <p>What is a good, simple pseudorandom number generator algorithm for assembly?</p>
<p>Easy one is to just choose two big relative primes a and b, then keep multiplying your random number by a and adding b. Use the modulo operator to keep the low bits as your random number and keep the full value for the next iteration.</p> <p>This algorithm is known as the <a href="http://en.wikipedia.org/wiki/Linear_congruential_generator" rel="noreferrer">linear congruential generator</a>. </p>
<p>also you probably can emulate shifting register with XOR sum elements between separate bits, which will give you pseudo-random sequence of numbers. </p>
11,560
<p>During .NET v1 days, I have tried without much success to convince colleagues to develop test-driven and automated-build work habits using the additional tools of NUnit and NAnt. When .NET Framework 2.0 and Visual Studio 2005 Team Suite came into picture, I was able to "force" my team into writing tests and provide themselves with visual testing right inside Visual Studio. I was further able to tweak project files with extra MSBuild tasks to carry out more build automation.</p> <p>Of course this does not mean Microsoft has delivered perfect systems, but I believe they have taken these in the correct steps forward. With all these features baked right into the framework and products and becoming "native" it got abit easier to motion developers into better development practices.</p> <p>Having long forgotten the open-source options (which I do miss), I am wondering what value proposition do the current incarnations of NUnit and NAnt hold? What case can one argue at this stage to convince a team <em>not</em> to use MSBuild or MSTest?</p> <p><strong>Clarification</strong>: My company is a pure Microsoft SI. Visual Studio Team Suite editions, Database Professional edition, TFS, and the like are available for our use. We do not use Visual Studio Professional edition or lesser.</p>
<p>MSBuild is a pretty good build tool. I've used it in combination with NAnt and Cruisecontrol.Net a couple of times. NAnt together with the NAnt contrib extensions seems a bit more flexible in handling OSS tools like NUnit, NCover etc while the fact that MSBuild can build VS solutions is a big plus for it. I found the easiest way to create build scripts is to use both, NAnt to call the different parts of the build (build, fxcop, test, coverage etc) and MSBuild to do the actual building.</p> <p>I haven't got much good to say about MSTest. It's slow and cumbersome to install on for example a build server. It's not very flexible and has all kinds of 'extras' that seem more geared to integration testing than unit testing. I found light weight XUnit.Net, MBUnit or NUnit to be far better suited for unit testing. Speed is important here, you want to run the tests often for quick feedback on the effects of your changes in code. Portability is important too. You want to have the tests run everywhere without a lot of setup and hacking like you need for MSTest on a machine that doesn't have team system installed. Although Unit testing isn't new there's still a lot of development going on there. Best practices change a lot and so do the tools. I don't want to be tied to a tool that only gets upgraded every few years with visual studio. Every one of the three OSS .net unit testing tools is set up to be extensible. MSTest isn't (as far as i've seen).</p>
<p>In my view NUnit is the de facto standard for unit tests in .NET. It's free and you can easily write tests in any edition of Visual Studio. If MS had made MS Test available in VS 2005 Pro (as they have in VS 2008 Pro), it might have taken over by now - but I think it's too late.</p> <p>I view ReSharper as basically essential for Visual Studio, and that includes a great test runner which works very well with NUnit. If I'm developing an open source project, why would I want to require VS 2008 Pro or VS 2005 Team Suite?</p> <p>MSBuild vs NAnt is slightly different, as MSBuild is bundled with either the framework or the SDK (I can't remember which now) - but I think NAnt is a more pleasant environment to work in. MSBuild is clearly better for doing the raw "build the solution" bit - but you can invoke it from NAnt.</p>
27,232
<p>What is the difference between <a href="http://msdn.microsoft.com/en-us/library/9a6a2sxy.aspx" rel="noreferrer"><code>Math.Floor()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.math.truncate.aspx" rel="noreferrer"><code>Math.Truncate()</code></a> in .NET?</p>
<p><code>Math.Floor</code> rounds down, <code>Math.Ceiling</code> rounds up, and <code>Math.Truncate</code> rounds towards zero. Thus, <code>Math.Truncate</code> is like <code>Math.Floor</code> for positive numbers, and like <code>Math.Ceiling</code> for negative numbers. Here's the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.math.truncate" rel="noreferrer">reference</a>.</p> <p>For completeness, <code>Math.Round</code> rounds to the nearest integer. If the number is exactly midway between two integers, then it rounds towards the even one. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.math.round" rel="noreferrer">Reference.</a></p> <p>See also: <a href="https://stackoverflow.com/questions/14/whats-the-difference-between-math-floor-and-math-truncate-in-c/580252#580252">Pax Diablo's answer</a>. Highly recommended!</p>
<p>Truncate drops the decimal point.</p>
2,235
<p>How can I programmatically change my browser's default home page with C#?</p>
<p>Set it in this registry setting:</p> <pre><code>HKCU\Software\Microsoft\Internet Explorer\Main\Start Page </code></pre>
<p>I'd hit the registry:</p> <p><strong>For User Based Changes</strong></p> <p>HKCU\Software\Clients\StartMenuInternet</p> <p>Check the keys below this key for the list of browsers on the system. Set the reg_sz value to the name of the key of the browser that you want to set as default.</p> <p><strong>For Machine-Wide Changes</strong></p> <p>Check HKLM\Software\Clients\StartMenuInternet for the system</p> <p><strong>Help with C# Registry Modifications</strong></p> <p>see here: <a href="http://www.csharphelp.com/archives2/archive392.html" rel="nofollow noreferrer">http://www.csharphelp.com/archives2/archive392.html</a></p>
43,073
<p>We have a client/server application with a rich client front end (in .Net) and also an administration portal (Asp.Net). Currently users have to sign on in both the rich client and on the website. We'd like to enable them to sign into the rich client, but not have to sign on to the website if they launch it from within the client. How can we do that?</p> <p>Going the other way is less important, but would be nice if possible: signing on to the website, then not having to sign into the rich client.</p>
<p>A possible solution is:</p> <ul> <li>sign-in to the rich client</li> <li>a random token is generated by the server and stored againsed the signed-in user</li> <li>rich client gets that token from the server</li> <li>that token is used in the url pointing to the website</li> <li>going to that url (using a link or a button from the rich client) will auto-login the user and reset the token</li> </ul>
<p>You could add a token, to identify them, to the URL which opens the site.</p> <p>You'll have to add some security to the token: TTL, a hash, a salt</p>
10,708
<p>So I've done the trivial "warmup" apps with GAE. Now I'd like to build something with a more complex directory structure. Something along the lines of:</p> <pre><code>siteroot/ models/ controllers/ controller1/ controller2/ ... templates/ template1/ template2/ ... </code></pre> <p>..etc. The controllers will be Python modules handling requests. They would then need to locate (Django-style) templates in associated folders. Most of the demo apps I've seen resolve template paths like this:</p> <pre><code>path = os.path.join(os.path.dirname(__file__), 'myPage.html') </code></pre> <p>...the __ file __ property resolves to the currently executing script. So, in my above example, if a Python script were running in controllers/controller1/, then the 'myPage.html' would resolve to that same directory -- controllers/controller1/myPage.html -- and I would rather cleanly separate my Python code and templates.</p> <p>The solution I've hacked together feels... hacky:</p> <pre><code>base_paths = os.path.split(os.path.dirname(__file__)) template_dir = os.path.join(base_paths[0], "templates") </code></pre> <p>So, I'm just snipping off the last element of the path for the currently running script and appending the template directory to the new path. The other (non-GAE specific) solutions I've seen for resolving Python paths seem pretty heavyweight (such as splitting paths into lists and manipulating accordingly). Django seems to have an answer for this, but I'd rather stick to the GAE API, vs. creating a full Django app and modifying it for GAE.</p> <p>I'm assuming anything hard-coded would be non-starter, since the apps live on Google's infinite server farm. So what's a better way?</p>
<p>You can't use relative paths, as Toni suggests, because you have no guarantee that the path from your working directory to your app's directory will remain the same.</p> <p>The correct solution is to either use os.path.split, as you are, or to use something like:</p> <pre><code>path = os.path.join(os.path.dirname(__file__), '..', 'templates', 'myPage.html') </code></pre> <p>My usual approach is to generate a path to the template directory using the above method, and store it as a member of my controller object, and provide a "getTemplatePath" method that takes the provided filename and joins it with the basename.</p>
<p>The <code>dirname</code> function returns an absolute path, use relative paths. See what is the current directory when your controllers are executed with <code>os.path.abspath(os.path.curdir)</code> and build a path to the templates relative to that location (without the <code>os.path.abspath</code> part of course).</p> <p>This will only work if the current directory is somewhere inside <em>siteroot</em>, else you could do something like this:</p> <pre><code>template_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "templates") </code></pre>
8,722
<p>As a way to find inspiration and improve my PHP skills, I am looking for some beautiful PHP source code to read, preferably an open source "standard" web site rather than a more tool-like project such as phpMyAdmin.</p> <p>So, where can I find some beautiful PHP code?</p>
<p>CodeIgniter code is beautiful. There are many projects written in CodeIgniter which are publically available and you can check out the source code.</p> <p>Have a look at the <a href="http://codeigniter.com/user_guide/overview/getting_started.html" rel="nofollow noreferrer">Getting started</a> page of CodeIgniter's tutorial and read through. I can gaurantee you'll be inspired and want to fire up your IDE and get coding straight away :).</p> <p>You can also download and have a look at the source code of <a href="http://bambooinvoice.org/" rel="nofollow noreferrer">Bamboo invoice</a>. When I need inspiration I also search for 'php code' on youtube :)</p>
<p>PHP.net is an open source website, but isn't exactly beautiful - some of it feels archaic but it works and is very secure.</p> <p><a href="http://www.symfony-project.org/" rel="nofollow noreferrer">Symfony</a> is worth looking at, and there are some projects in the <a href="http://cvs.php.net/" rel="nofollow noreferrer">PHP.net CVS</a> that are a bit more modern than the website.</p>
17,351
<p>We are evaluating options for a Gantt chart control (on Windows Forms) as opposed developing one on our own. What are the various Gantt Chart controls you have had experience with? Pros and cons?</p> <p>Is it a viable idea to develop such a control from scratch (given that the control is not the primary product in this case)?</p> <p><strong>Update:</strong> Just bringing this up again since I've got only one answer. I'd be very grateful for more inputs. (Hope this is legal.)</p>
<p>I have not worked with the Gantt charts from Telerik, but many people are very happy with Telerik. I would never consider creating my own Gantt chart except if i was in the business of selling user controls</p>
<p>FlexGantt at <a href="http://www.dlsc.com" rel="nofollow noreferrer">http://www.dlsc.com</a> is a Java control but as far as I know you could port it to .NET with J++ or so. Then again, I am not an expert in that area.</p> <p>Dirk</p>
47,975
<p>Okay I know I asked about this before, and the answer was basically cache data that doesn't change often.</p> <p>Well what does one do when at least 99.9% of the data changes?</p> <p>In my project the only tables that doesn't get updated or won't get updated frequently would be the member profile info (name/address, and settings)</p> <p>So how does one still enable some kind of caching but keep and make sure the data being viewed is updated when changes are applied?</p>
<p>I guess, it's not really 99.9% of all data that changes, but it's in 99.9% of all data locations that changes happen.</p> <p>For example, if you are running a bulletin board, that means that there will be a steady stream of new posts, but old posts will remain the same, and even old threads will stay unchanged for a long, long time.</p> <p>In that case, you'll need a way to invalidate old cached data, so that you can build a cache as soon as a thread (in the example) is viewed. If there is a change to ONE of these threads (i.e. when someone adds a new post), this one cached item is deleted/marked outdated, so the next time it is viewed, it will be rebuilt. Other items that still haven't changed will use the cache, though.</p>
<p>When in a single-instance web-application scenario you could manually update the cache whenever an object changes, as well as in the database.</p> <p>Once in a while you could flush the cache to make sure nothing is out-of-sync (eg. if the database was updated by some other application).</p> <p>Note that this wouldn't work well for enterprise-scale scenarios.</p>
28,330
<p>On these questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/17653/which-vista-edition-is-the-best-for-developer-machine">Which Vista edition is best for a developer machine?</a></li> <li><a href="https://stackoverflow.com/questions/4433/vista-or-xp-for-dev-machine">Vista or XP for Dev Machine</a></li> </ul> <p>People are recommending 64 bit, can you explain why? Is it just so you can have more then 3GB of addressable RAM that 32 bit gives you?</p> <p>And how does Visual Studio benefit from all this extra RAM?</p> <p>I went from 64 bit XP back to 32 bit due to 90% of the software I was using only being 32 bit anyway and I had issues with drivers and some software with 64 bit.</p>
<p>A number of reasons.</p> <ol> <li>Yes, you're right it is so you can have more than 3 gig of ram</li> <li>More and more systems are going to be 64 bit soon so it makes sense to develop on what you're going to be running on</li> <li>Some bugs can only be observed when running in 64 bit mode</li> </ol>
<p>XP 64bit wasn't ready for prime time, there were no drivers for it. In Windows Vista 64-bit this isn't the case. So if you are looking to install Windows Vista go 64-bit if you are keeping XP stay at 32-bit.</p>
3,866
<p>Do you always use a second-level cache in Hibernate or do you first try it without and only use it when the performance goes down?</p>
<p>Make it work first, then make it fast. If you don't need caching, don't implement it.</p>
<p>To quote the famous Donald Knuth: "Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%."</p> <p>If you are seeing performance issues, only then you can begin to optimize. And you should only optimize the largest bottleneck and work your way down if needed.</p> <p>However, implementing this optimization in NHibernate has negligible impact on debugging and maintenance in most situations, and can often be implemented with very minimal additions to the code.</p> <p>If you rely extensively on lazy loading, have read only tables, do not have to worry about concurrency with applications not using NHibernate, performance is an issue, and you are knowledgeable about how to optimize using 2nd level cache (meaning you already know the answer to this question), then you should use a second level cache.</p>
28,374
<p>Is it possible to search for an object by one of its properties in a Generic List?</p> <pre><code>Public Class Customer Private _id As Integer Private _name As String Public Property ID() As Integer Get Return _id End Get Set _id = value End Set End Property Public Property Name() As String Get Return _name End Get Set _name = value End Set End Property Public Sub New(id As Integer, name As String) _id = id _name = name End Sub End Class </code></pre> <p>Then loading and searching</p> <pre><code>Dim list as new list(Of Customer) list.Add(New Customer(1,"A") list.Add(New Customer(2,"B") </code></pre> <p>How can I return customer object with id =1? Does this have to do with the "Predicate" in Generics?</p> <p>Note: I am doing this in VB.NET.</p>
<p>Yes, this has everything to do with predicates :)</p> <p>You want the <a href="http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx" rel="noreferrer">Find(Of T)</a> method. You need to pass in a predicate (which is a type of delegate in this case). How you construct that delegate depends on which version of VB you're using. If you're using VB9, you could use a lambda expression. (If you're using VB9 you might want to use LINQ instead of Find(Of T) in the first place, mind you.) The lambda expression form would be something like:</p> <pre><code>list.Find(function(c) c.ID = 1) </code></pre> <p>I'm not sure if VB8 supports anonymous methods in the same way that C# 2 does though. If you need to call this from VB8, I'll see what I can come up with. (I'm more of a C# person really :)</p>
<p>If you are using .NET 3.5 this can be done with <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_Objects" rel="nofollow noreferrer">LINQ&nbsp;to&nbsp;Objects</a>:</p> <p><em><a href="http://msdn.microsoft.com/en-us/library/bb397937.aspx" rel="nofollow noreferrer">How to: Query an ArrayList with LINQ</a></em></p> <p>If not, in .NET 2.0 you can use the <a href="http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx" rel="nofollow noreferrer"><code>Find</code> method of the list</a>.</p> <p>The idea is that you will need to provide an method that return true if a property of your object satisfies a certain condition.</p>
24,407
<p>Where does the DirectoryEntry class fetches data from?</p>
<p>Arun I think you are very new to this area. Use google and msdn. You can also use articles or books related with active directory and c#</p>
<p>A very unclear question; the short answer is AD - have you looked at <a href="http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry.aspx" rel="nofollow noreferrer">MSDN</a>?</p>
45,821
<p>An answer and subsequent <a href="https://stackoverflow.com/questions/360899/c-math-problem#360931">debate in the comments</a> in another thread prompted me to ask:</p> <p>In C# || and &amp;&amp; are the short-circuited versions of the logical operators | and &amp; respectively.<br /></p> <p>Example usage:</p> <pre><code>if (String.IsNullOrEmpty(text1) | String.IsNullOrEmpty(text2) | String.IsNullOrEmpty(text3)) { //... } </code></pre> <p>versus:</p> <pre><code>if (String.IsNullOrEmpty(text1) || String.IsNullOrEmpty(text2) || String.IsNullOrEmpty(text3)) { //... } </code></pre> <p>In terms of coding practice which is the better to use and why?</p> <p>Note: I do realize this question is similar to <a href="https://stackoverflow.com/questions/89154/benefits-of-using-short-circuit-evaluation">this question</a> but I believe it warrants a language specific discussion.</p>
<blockquote> <p>In terms of coding practice which is the better to use and why?</p> </blockquote> <p>Simple answer: always use the short-circuited versions. There’s simply no reason not to. Additionally, you make your code clearer because you express your <em>intent</em>: logical evaluation. Using the bitwise (logical) operations implies that you want just that: bit operations, not logical evaluation (even though the MSDN calls them “logical operators” as well, when applied to boolean values).</p> <p>Additionally, since short-circuiting only evaluates what needs evaluating, it’s often faster, and it allows to write such code as</p> <pre><code>bool nullorempty = str == null || str.Length == 0; </code></pre> <p>(Notice that to solve this particular problem a better function already exists, namely <code>string.IsNullOrEmpty</code> which you also used in your question.) This code wouldn’t be possible with the bitwise logical operations because even if <code>str</code> were <code>null</code>, the second expression would get evaluated, resulting in a <code>NullReferenceException</code>.</p> <p><strong>EDIT</strong>: If you <em>want</em> side-effects to occur in a logical context please <em>still</em> don’t use bitwise operations. This is a typical example of being too clever. The next maintainer of the code (or even yourself, after a few weeks) wo sees this code will think “hmm, this code can be cleared up to use conditional operators,” thus inadvertedly breaking the code. I pity whoever is in charge of fixing this bug.</p> <p>Instead, if you have to rely on side, effects, make them explicit:</p> <pre><code>bool hasBuzzed = checkMakeBuzz(); bool isFrobbed = checkMakeFrob(); bool result = hasBuzzed || isFrobbed; </code></pre> <p>Granted, three lines instead of one. But a much clearer code as a result.</p>
<p>Use <code>&amp;&amp;</code> and <code>||</code> when you only care about the result and want to know that result as soon as possible and none of your expressions have side effects that must occur even if the boolean condition is not met. That is to say, pretty much always.</p> <p>Use <code>&amp;</code> and <code>|</code> when every expression must be evaluated (for example, if you have side effects from your expressions). But since you should never have side effects that your program depends on that must occur even if the boolean condition is not met, you should probably not be using <code>&amp;</code> and <code>|</code>.</p> <p>For example, this would probably be exceptionally silly:</p> <pre><code>if (false &amp; somethingThatUpdatesTheDatabase()) { /* ... */ } </code></pre>
47,120
<pre><code> (define a 42) (set! 'a 10) (define a 42) (define (symbol) 'a) (set! (symbol) 10) (define a (cons 1 2)) (set! (car a) 10) </code></pre> <p>I tried running them in DrScheme and they don't work. Why?</p>
<p>Think of set! is a special form like define which does not evaluate its first operand. You are telling the scheme interpreter to set that variable exactly how you write it. In your example, it will not evaluate the expression 'a to the word a. Instead, it will look for a variable binding named "'a" (or depending on your interpreter might just break before then since I think 'a is not a valid binding).</p> <p>For the last set of expressions, if you want to set the car of a pair, use the function (set-car! pair val) which works just like any scheme function in that it evaluates all of its operands. It takes in two values, a pair and some scheme value, and mutates the pair so that the car is now pointing to the scheme value.</p> <p>So for example.</p> <pre><code>&gt;(define pair (cons 1 2)) &gt;pair (1 . 2) &gt;(set-car! pair 3) (3 . 2) </code></pre>
<p>The issue is with <em>(set! 'a 10)</em>, as you shouldn't be quoting the symbol <em>a</em>.</p> <p>It sounds like you're trying to learn Scheme, and you don't know Lisp, yes? If so, I strongly recommend trying Clojure as an easier to learn Lisp. I failed to grasp the interaction between the reader, evaluation, symbols, special forms, macros, and so forth in both Common Lisp and Scheme because those things all seemed to interact in tangled ways, but I finally really understand them in Clojure. Even though it's new, I found Clojure documentation is actually clearer than anything I found for Scheme or CL. Start with the videos at <a href="http://clojure.blip.tv/" rel="nofollow noreferrer">http://clojure.blip.tv/</a> and then read the docs at clojure.org.</p>
38,529
<p>I'm very impressed with my initial tests with db4o. However, i'm wondering just how many enterprise class websites are out there powered by db4o, i couldn't see any on the main website? </p> <p>I can't see any reason why db4o should not be used. There appears to be decent enough support for transactions and ways to handle concurrency for example. </p> <p>Anyone got a list of websites i could look at?</p>
<p>A particular search engine used to be powered by db4o (I say "used to" because I haven't talked to the author about this since a long time).</p> <p><a href="http://www.rel8r.com/" rel="nofollow noreferrer">http://www.rel8r.com/</a></p> <p>The author is Travis Reeder.</p>
<p>Although I cannot see websites specifically, here is a list of Open Source Projects from the db4o website:</p> <p><a href="http://developer.db4o.com/ProjectSpaces/view.aspx/Open_Source_Products" rel="nofollow noreferrer">http://developer.db4o.com/ProjectSpaces/view.aspx/Open_Source_Products</a></p>
20,725
<p>I have a simple php script on a server that's using fsockopen to connect to a server.</p> <pre><code>&lt;?php $fp = fsockopen("smtp.gmail.com", 25, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno)&lt;br /&gt;\n"; } else { echo fgets($fp, 1024); fclose($fp); } ?&gt; </code></pre> <p>The problem is the the script times out and fails to connect. If i change the port from 25 to 80 for example it works without problems on any host. So the problem seems to be only the port 25 no matter what host i use, i tried a lot of them and all work for port 80 and others but for 25 fails.<br> Connections are not blocked form firewall as if i telnet from shell it successfully connects to any port on any host.<br> Any idea what could be the problem as it's really weird? </p> <p>LE: If i run the same php script from the shell, php scriptname.php it works so only when i run it by http it fails. I have apache with SuPHP so the problem is around here somewhere</p>
<p>Interesting... Some firewalls can block specific program's connections to specific ports. Please check it again, try to stop firewall completely. Also try to stop any anti-spyware.</p>
<p>I've run into some strange issues with PHP's socket handling, too. It ended up being a problem with the system it was running on. Have you tried running your code on a different machine?</p>
47,733
<p>Is there anything I should know before converting a large C++ program from VS2005 to VS2008?</p>
<p>I'm working on this very problem right now. </p> <p><em>Running WinMerge to see what I've changed...</em></p> <p>OK, here is what I had to fix in an huge Win32/MFC client application:</p> <p>Some MFC functions have become virtual (which were not in the past - CWnd::GetMenu for one, if I recall correctly). Also something related to our legacy mouse wheel support (before Windows had built-in mouse wheel support) somehow broke (I just removed the feature, so I never really figured out why that broke).</p> <p>Some ATL methods (or method params) have changed to const that were not originally (screwed up my overrides).</p> <p>The Platform SDK is newer - be careful if you're setting the windows SDK version #defines correctly (we were not in all places - which was dumb). You may now be building with newer versions (Vista/2008) of Win32 structures. This didn't work so great on my XP box.</p> <p>STDMETHOD now includes __declspec(nothrow) which is 100% right - except this found some problems in our code. Some interface that was written like it would be exposed through COM, but never was, threw exceptions.</p> <p>The IDE has a <a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=366060&amp;wa=wsignin1.0" rel="nofollow noreferrer">bug</a> where disabled breakpoints don't show the hollow circle in the margin if you don't have the break points set to highlight the whole line (which I <em>think</em> is the default for VC++, maybe?).</p> <p>Most of these issues were due to subtle mistakes in our code or aggressive overloading of MFC/ATL libraries. Since everyone else's code is perfect, you should be fine ;)</p>
<p>Is there a difference in the syntax that you can't just simply recompile? VS will convert the .sln and vcproj files for you automatically. The rest is just code, and unless you are doing something really strange, it should just recompile as-is.</p>
30,153
<p>Is there a c# library which provides similar functionality to the <a href="http://wiki.wxpython.org/PubSub" rel="nofollow noreferrer">Python PubSub</a> library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.</p>
<p>These may be a bit heavy for you depending on your needs but: <a href="http://www.nservicebus.com/" rel="nofollow noreferrer">http://www.nservicebus.com/</a> <a href="http://blog.phatboyg.com/masstransit/" rel="nofollow noreferrer">http://blog.phatboyg.com/masstransit/</a></p>
<p>Again, my be overkill, but the <a href="http://ose.sf.net" rel="nofollow noreferrer">OSE</a> library allows thins kind of thing.</p>
10,582
<p>What is the best way to get a value from a ICollection? We know the Collection is empty apart from that. </p>
<p>You can use LINQ for this:.</p> <pre><code>var foo = myICollection.OfType&lt;YourType&gt;().FirstOrDefault(); // or use a query var bar = (from x in myICollection.OfType&lt;YourType&gt;() where x.SomeProperty == someValue select x) .FirstOrDefault(); </code></pre>
<p>If you know your collection has only one item, should only ever have one item, you can use the Linq extension method <a href="https://msdn.microsoft.com/en-us/library/bb155325.aspx" rel="nofollow noreferrer"><code>Single()</code></a>.</p> <p>This converts a <code>ICollection&lt;T&gt;</code> into a <code>T</code> object containing the single item of that collection. If the length of the collection is 0, or more than one, this will throw an <code>InvalidOperationException</code>.</p>
47,442
<p>I'm trying to figure out how to fix the selection box size under JCrop. The documentation mentions how to set an initial selection area but not how to make it fixed size. Does anybody knows how could I make it fixed. Thanks in advance.</p> <p><a href="http://deepliquid.com/content/Jcrop_Manual.html" rel="noreferrer">http://deepliquid.com/content/Jcrop_Manual.html</a></p>
<p>You are basically looking for the API section. Having extensively used this plugin myself, I know exactly what you're looking for:</p> <pre><code>var api; var cropWidth = 100; var cropHeight = 100; $(window).load(function() { // set default options var opt = {}; // if height and width must be exact, dont allow resizing opt.allowResize = false; opt.allowSelect = false; // initialize jcrop api = $.Jcrop('#objectId', opt); // set the selection area [left, top, width, height] api.animateTo([0,0,cropWidth,cropHeight]); // you can also set selection area without the fancy animation api.setSelect([0,0,cropWidth,cropHeight]); }); </code></pre>
<p>Hi this might be helpful -</p> <pre><code>&lt;script&gt; $(window).load(function() { var jcrop_api; var i, ac; initJcrop(); function initJcrop() { jcrop_api = $.Jcrop('#imgCrop', { onSelect: storeCoords, onChange: storeCoords }); jcrop_api.setOptions({ aspectRatio: 1/ 1 }); jcrop_api.setOptions({ minSize: [180, 180], maxSize: [180, 250] }); jcrop_api.setSelect([140, 180, 160, 180]); }; function storeCoords(c) { jQuery('#X').val(c.x); jQuery('#Y').val(c.y); jQuery('#W').val(c.w); jQuery('#H').val(c.h); }; }); &lt;/script&gt; </code></pre>
45,027
<p>A friend accidentally deleted his forum database. Which wouldn't normally be a huge issue, except for the fact that he neglected to perform backups. 2 years of content is just plain gone. Obviously, he's learned his lesson.</p> <p>The good news, however, is that Google keeps backups, even if individual site owners are idiots. The bad news is, that traditional crawling robots would choke on the Google Cache version of the website. </p> <p>Is there anything existing that would help trawl the Google Cache, or how would I go about rolling my own?</p>
<p>You may want to consider looking at crawling the archive.org cache as well. If you're in there, it's generally better structured.</p>
<p>If the website is small enough that you can crawl it manually, <a href="http://userscripts.org/scripts/show/30878" rel="nofollow">this userscript</a> to seamlessly navigate Google's cache is very useful.</p>
48,672
<p>How do I do backups in MySQL? </p> <p>I'm hoping there'll be something better than just running mysqldump every "x" hours.</p> <p>Is there anything like SQL Server has, where you can take a full backup each day, and then incrementals every hour, so if your DB dies you can restore up to the latest backup?</p> <p>Something like the DB log, where as long as the log doesn't die, you can restore up to the exact point where the DB died?</p> <p>Also, how do these things affect locking? I'd expect the online transactions to be locked for a while if I do a mysqldump.</p>
<p>You might want to look at <a href="http://dev.mysql.com/doc/refman/5.5/en/point-in-time-recovery.html" rel="noreferrer">incremental backups</a>.</p>
<p>@Daniel,</p> <p>in case you are still interested, there is a newish (new to me) solution shared by <a href="http://capttofu.livejournal.com/" rel="nofollow noreferrer">Paul Galbraith</a>, a tool that allows for online backup of innodb tables called <a href="http://www.innodb.com/hot-backup/" rel="nofollow noreferrer">ibbackup</a> from oracle which to quote Paul,</p> <blockquote> <p>when used in conjunction with <a href="http://www.innodb.com/support/documentation/innodb-hot-backup-manual/#innobackup" rel="nofollow noreferrer">innobackup</a>, has worked great in creating a nightly backup, with no downtime during the backup</p> </blockquote> <p>more detail can be found on <a href="http://capttofu.livejournal.com/12455.html" rel="nofollow noreferrer">Paul's blog</a></p>
6,870
<p>Is there a tsql command on sqlserver 2008 which can be run in order to enable Database Diagramming instead of this dialog appearing:</p> <p>This database does not have one or more of the support objects required to use database diagramming. Do you wish to create them? </p>
<p>The script is a little too long to add here, but here's what you can do. 1) Create a new database. 2) Start sql server profiler 3) Click the "Database Diagrams" folder in management studio. 4) Clear the profiler. 5) Confirm the message box with a prompt to enable diagramming. 6) Profiler now contains the script that enabled diagramming. 7) Select the script in profiler and copy the output from the bottom pane.</p> <p>Kim</p>
<p>Yeah, but first you have to select the option 'YES' to create the support objects to use database diagramming.Later run the below select query under the DB where Database Diagramming needs to be configured.</p> <p>select * from dtproperties</p> <p>Alter the table dtproperties by inserting a column 'uvalue' to the table with the below query.As the column will be used in sproc</p> <p>ALTER TABLE dtproperties ADD [uvalue] nvarchar</p> <pre><code>CREATE PROCEDURE dbo.sp_upgraddiagrams AS BEGIN IF OBJECT_ID(N'dbo.sysdiagrams') IS NOT NULL return 0; CREATE TABLE dbo.sysdiagrams ( name sysname NOT NULL, principal_id int NOT NULL, -- we may change it to varbinary(85) diagram_id int PRIMARY KEY IDENTITY, version int, definition varbinary(max) CONSTRAINT UK_principal_name UNIQUE ( principal_id, name ) ); -- Add this if we need to have some form of extended properties for diagrams */ IF OBJECT_ID(N'dbo.sysdiagram_properties') IS NULL BEGIN CREATE TABLE dbo.sysdiagram_properties ( diagram_id int, name sysname, value varbinary(max) NOT NULL ) END IF OBJECT_ID(N'dbo.dtproperties') IS NOT NULL begin insert into dbo.sysdiagrams ( [name], [principal_id], [version], [definition] ) select convert(sysname, dgnm.[uvalue]), DATABASE_PRINCIPAL_ID(N'dbo'), -- will change to the sid of sa 0, -- zero for old format, dgdef.[version], dgdef.[lvalue] from dbo.[dtproperties] dgnm inner join dbo.[dtproperties] dggd on dggd.[property] = 'DtgSchemaGUID' and dggd.[objectid] = dgnm.[objectid] inner join dbo.[dtproperties] dgdef on dgdef.[property] = 'DtgSchemaDATA' and dgdef.[objectid] = dgnm.[objectid] where dgnm.[property] = 'DtgSchemaNAME' and dggd.[uvalue] like N'_EA3E6268-D998-11CE-9454-00AA00A3F36E_' return 2; end return 1; END </code></pre> <p>So finally right click on the DB to create Database diagramms[Invalid Column name<a href="https://i.stack.imgur.com/S8ZDc.png" rel="nofollow noreferrer">1</a> </p>
35,646
<p>I need to do a multilingual website, with urls like</p> <pre><code>www.domain.com/en/home.aspx for english www.domain.com/es/home.aspx for spanish </code></pre> <p>In the past, I would set up two virtual directories in IIS, and then detect the URL in global.aspx and change the language according to the URL</p> <pre><code>Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) Dim lang As String If HttpContext.Current.Request.Path.Contains("/en/") Then lang = "en" Else lang = "es" End If Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang) Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang) End Sub </code></pre> <p>The solution is more like a hack. I'm thinking about using Routing for a new website. </p> <p><strong>Do you know a better or more elegant way to do it?</strong></p> <p>edit: The question is about the URL handling, not about resources, etc.</p>
<p>I decided to go with the new ASP.net Routing.<br> Why not urlRewriting? Because I don't want to change the clean URL that routing gives to you.</p> <p>Here is the code:</p> <pre><code>Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) ' Code that runs on application startup RegisterRoutes(RouteTable.Routes) End Sub Public Sub RegisterRoutes(ByVal routes As RouteCollection) Dim reportRoute As Route Dim DefaultLang As String = "es" reportRoute = New Route("{lang}/{page}", New LangRouteHandler) '* if you want, you can contrain the values 'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = "[a-z]{2}"}) reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = "home"}) routes.Add(reportRoute) End Sub </code></pre> <p>Then LangRouteHandler.vb class:</p> <pre><code>Public Class LangRouteHandler Implements IRouteHandler Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _ Implements System.Web.Routing.IRouteHandler.GetHttpHandler 'Fill the context with the route data, just in case some page needs it For Each value In requestContext.RouteData.Values HttpContext.Current.Items(value.Key) = value.Value Next Dim VirtualPath As String VirtualPath = "~/" + requestContext.RouteData.Values("page") + ".aspx" Dim redirectPage As IHttpHandler redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page)) Return redirectPage End Function End Class </code></pre> <p>Finally I use the default.aspx in the root to redirect to the default lang used in the browser list.<br> Maybe this can be done with the route.Defaults, but don't work inside Visual Studio (maybe it works in the server)</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim DefaultLang As String = "es" Dim SupportedLangs As String() = {"en", "es"} Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang Response.Redirect(DefaultLang + "/") End Sub </code></pre> <p>Some sources:<br> * <a href="http://blogs.msdn.com/mikeormond/archive/2008/05/14/using-asp-net-routing-independent-of-mvc.aspx" rel="noreferrer">Mike Ormond's blog</a><br> * <a href="http://chriscavanagh.wordpress.com/2008/04/25/systemwebrouting-with-webforms-sample/" rel="noreferrer">Chris Cavanagh’s Blog</a><br> * <a href="http://msdn.microsoft.com/en-us/library/cc668201.aspx" rel="noreferrer">MSDN</a> </p>
<p>I personnaly use <a href="http://msdn.microsoft.com/en-us/library/c6zyy3s9.aspx" rel="nofollow noreferrer">the resources files</a>.</p> <p>Very efficient, very simple.</p>
10,809
<p>How can I check if a given string is a valid URL address?</p> <p>My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web.</p>
<p>I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 (<a href="http://www.faqs.org/rfcs/rfc3987.html" rel="noreferrer">http://www.faqs.org/rfcs/rfc3987.html</a>). These are in PCRE syntax.</p> <p>For absolute IRIs (internationalized):</p> <pre><code>/^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&amp;'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])|[\/\?])*)?$/i </code></pre> <p>To also allow relative IRIs:</p> <pre><code>/^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&amp;'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&amp;'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&amp;'\(\)\*\+,;=:@])|[\/\?])*)?)$/i </code></pre> <p>How they were compiled (in PHP):</p> <pre><code>&lt;?php /* Regex convenience functions (character class, non-capturing group) */ function cc($str, $suffix = '', $negate = false) { return '[' . ($negate ? '^' : '') . $str . ']' . $suffix; } function ncg($str, $suffix = '') { return '(?:' . $str . ')' . $suffix; } /* Preserved from RFC3986 */ $ALPHA = 'a-z'; $DIGIT = '0-9'; $HEXDIG = $DIGIT . 'a-f'; $sub_delims = '!\\$&amp;\'\\(\\)\\*\\+,;='; $gen_delims = ':\\/\\?\\#\\[\\]@'; $reserved = $gen_delims . $sub_delims; $unreserved = '-' . $ALPHA . $DIGIT . '\\._~'; $pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG); $dec_octet = ncg(implode('|', array( cc($DIGIT), cc('1-9') . cc($DIGIT), '1' . cc($DIGIT) . cc($DIGIT), '2' . cc('0-4') . cc($DIGIT), '25' . cc('0-5') ))); $IPv4address = $dec_octet . ncg('\\.' . $dec_octet, '{3}'); $h16 = cc($HEXDIG, '{1,4}'); $ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address); $IPv6address = ncg(implode('|', array( ncg($h16 . ':', '{6}') . $ls32, '::' . ncg($h16 . ':', '{5}') . $ls32, ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32, ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32, ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32, ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32, ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32, ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16, ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::', ))); $IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+'); $IP_literal = '\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\]'; $port = cc($DIGIT, '*'); $scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\+\\.'), '*'); /* New or changed in RFC3987 */ $iprivate = '\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}'; $ucschar = '\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}' . '\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}' . '\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}' . '\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}' . '\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}' . '\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}'; $iunreserved = '-' . $ALPHA . $DIGIT . '\\._~' . $ucschar; $ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@')); $ifragment = ncg($ipchar . '|' . cc('\\/\\?'), '*'); $iquery = ncg($ipchar . '|' . cc($iprivate . '\\/\\?'), '*'); $isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+'); $isegment_nz = ncg($ipchar, '+'); $isegment = ncg($ipchar, '*'); $ipath_empty = '(?!' . $ipchar . ')'; $ipath_rootless = ncg($isegment_nz) . ncg('\\/' . $isegment, '*'); $ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\/' . $isegment, '*'); $ipath_absolute = '\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( "/" isegment ) $ipath_abempty = ncg('\\/' . $isegment, '*'); $ipath = ncg(implode('|', array( $ipath_abempty, $ipath_absolute, $ipath_noscheme, $ipath_rootless, $ipath_empty ))) . ')'; $ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*'); $ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name))); $iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*'); $iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?'); $irelative_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_noscheme . '', '' . $ipath_empty . '' ))); $irelative_ref = $irelative_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?'); $ihier_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_rootless . '', '' . $ipath_empty . '' ))); $absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?'); $IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?'); $IRI_reference = ncg($IRI . '|' . $irelative_ref); </code></pre> <p>Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way:</p> <pre><code>$escape_backslash = '/(?&lt;!\\)\\(?![\[\]\\\^\$\.\|\*\+\(\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\{[0-9a-f]{1,4}\}|\c[A-Z]|)/'; $absolute_IRI = preg_replace($escape_backslash, '\\\\', $absolute_IRI); $IRI = preg_replace($escape_backslash, '\\\\', $IRI); $IRI_reference = preg_replace($escape_backslash, '\\\\', $IRI_reference); </code></pre>
<pre class="lang-none prettyprint-override"><code>/^(http|HTTP)+(s|S)?:\/\/[\w.-]+(?:\.[\w\.-]+)+[\w\-\._\$\(\)/]+$/g </code></pre> <p>check demo with tests:</p> <p><a href="https://regexr.com/5cedu" rel="nofollow noreferrer">https://regexr.com/5cedu</a></p>
19,555
<p>I've been beating my head against this wall for quite some time now, so I thought I'd ask some experts.</p> <p>I need to send an xml string from one computer to the next. I would like to format the xml something like this:</p> <pre><code>&lt;xml&gt; &lt;author&gt;Joe the Magnificent&lt;/author&gt; &lt;title&gt;Joe Goes Home&lt;/title&gt; &lt;/xml&gt; </code></pre> <p>Can anyone provide some assistance?</p> <p>Edit: More detail</p> <p>I control both the send and receive, and have successfully transfered a hard coded string one-way.</p> <p>Here is the receive side:</p> <pre><code> Dim author As String Dim title As String Dim xDoc As New XmlDocument Dim xAuthor As XmlElement Dim xTitle As XmlElement xDoc.LoadXml(xml) xAuthor = xDoc.FirstChild.Item("author") xTitle = xDoc.FirstChild.Item("title") author = xAuthor.FirstChild.Value title = xTitle.FirstChild.Value ShowMessage(author, title) </code></pre> <p>Mostly this is an exercise in learning how to do XML for me, so there's no real purpose to it other than my own knowledge. I was kind of looking for some opinions on the best way to do such things.</p>
<p>Here's what I ended up doing:</p> <pre><code>Public Function FormatMessage(ByVal author As String, ByVal title As String, ByVal genre As String) As String Dim xDoc As New XmlDocument ' Create outer XML Dim xNode As XmlNode = xDoc.AppendChild(xDoc.CreateElement("xml")) ' Create Author Node Dim xAuthor As XmlNode = xNode.AppendChild(xDoc.CreateElement("author")) xAuthor.InnerText = author ' Create Message Node Dim xTitle As XmlNode = xNode.AppendChild(xDoc.CreateElement("message")) xtitle.InnerText = title ' Create Genre Node Dim xGenre As XmlNode = xNode.AppendChild(xDoc.CreateElement("genre")) xGenre.InnerText = genre ' Create StringWriter to convert XMLDoc to string Dim xWriter As New IO.StringWriter() Dim xml_writer As New XmlTextWriter(xWriter) xDoc.WriteContentTo(xml_writer) Return xWriter.ToString End Function </code></pre> <p>This function builds the xml string based on the input values, then to break the xml string back down into the original values, I used this:</p> <pre><code>Dim author As String Dim title As String Dim genre As String Dim xDoc As New XmlDocument Dim xAuthor As XmlElement Dim xTitle As XmlElement Dim xGenre as XmlElement xDoc.LoadXml(xml) If xDoc.DocumentElement.Name = "xml" Then xAuthor = xDoc.FirstChild.Item("author") xTitle = xDoc.FirstChild.Item("title") author = xAuthor.FirstChild.Value title = xTitle.FirstChild.Value genre = xGenre.FirstChild.Value End If ShowMessage(author, title, genre) </code></pre> <p>Thanks for the help! KJ</p>
<p>Create a class like this:</p> <pre><code>Imports System.Data Public Class STKReservedStock_insertrow Inherits Request Public Sub New(User As String, Company As String) MyBase.New("stkreservestockall", User, Company) End Sub #Region "Properties" Public Property _pdt As String Get Return DirectCast(Field("pdt"), String) End Get Set(ByVal value As String) Field("pdt") = value End Set End Property Public Property _whse As String Get Return DirectCast(Field("whse"), String) End Get Set(ByVal value As String) Field("whse") = value End Set End Property Public Property _traceNumber As Integer Get Return DirectCast(Field("traceNumber"), Integer) End Get Set(ByVal value As Integer) Field("traceNumber") = value End Set End Property Public Property _bin As String Get Return DirectCast(Field("bin"), String) End Get Set(ByVal value As String) Field("bin") = value End Set End Property Public Property _lotref As String Get Return DirectCast(Field("lotref"), String) End Get Set(ByVal value As String) Field("lotref") = value End Set End Property Public Property _packUOM As String Get Return DirectCast(Field("packUOM"), String) End Get Set(ByVal value As String) Field("packUOM") = value End Set End Property Public Property _grade As String Get Return DirectCast(Field("grade"), String) End Get Set(ByVal value As String) Field("grade") = value End Set End Property Public Property _shpLabel As Integer Get Return DirectCast(Field("shpLabel"), Integer) End Get Set(ByVal value As Integer) Field("shpLabel") = value End Set End Property Public Property _countLoc As String Get Return DirectCast(Field("countLoc"), String) End Get Set(ByVal value As String) Field("countLoc") = value End Set End Property Public Property _palletType As String Get Return DirectCast(Field("palletType"), String) End Get Set(ByVal value As String) Field("palletType") = value End Set End Property Public Property _subPdt As String Get Return DirectCast(Field("subPdt"), String) End Get Set(ByVal value As String) Field("subPdt") = value End Set End Property Public Property _subTn As Integer Get Return DirectCast(Field("subTn"), Integer) End Get Set(ByVal value As Integer) Field("subTn") = value End Set End Property Public Property _origReserved As Decimal Get Return DirectCast(Field("origReserved"), Integer) End Get Set(ByVal value As Decimal) Field("origReserved") = value End Set End Property Public Property _reserved As Decimal Get Return DirectCast(Field("reserved"), Integer) End Get Set(ByVal value As Decimal) Field("reserved") = value End Set End Property Public Property _dateReserved As Date Get Return DirectCast(Field("dateReserved"), Date) End Get Set(ByVal value As Date) Field("dateReserved") = value End Set End Property Public Property _reservedBy As String Get Return DirectCast(Field("reservedBy"), String) End Get Set(ByVal value As String) Field("reservedBy") = value End Set End Property Public Property _reason As String Get Return DirectCast(Field("reason"), String) End Get Set(ByVal value As String) Field("reason") = value End Set End Property Public Property _party As String Get Return DirectCast(Field("party"), String) End Get Set(ByVal value As String) Field("party") = value End Set End Property Public Property _Cancelled As String Get Return DirectCast(Field("Cancelled"), String) End Get Set(ByVal value As String) Field("Cancelled") = value End Set End Property Public Property _CancelledByUsr As String Get Return DirectCast(Field("CancelledByUsr"), String) End Get Set(ByVal value As String) Field("CancelledByUsr") = value End Set End Property Public Property _RsvQty As Decimal Get Return DirectCast(Field("RsvQty"), Integer) End Get Set(ByVal value As Decimal) Field("RsvQty") = value End Set End Property #End Region End Class </code></pre> <p>Then just send it like this:</p> <pre><code> Dim XMLRqst As New STKReservedStock_insertrow(User, Company) Rqst._pdt = If(IsDBNull(drStock.Item("pdt")), "", drStock.Item("pdt").ToString) Rqst._whse = If(IsDBNull(drStock.Item("whse")), "", drStock.Item("whse").ToString) Rqst._traceNumber = If(IsDBNull(drStock.Item("traceNumber")), 0, CInt(drStock.Item("traceNumber"))) Rqst._bin = If(IsDBNull(drStock.Item("bin")), "", drStock.Item("bin").ToString) Rqst._lotref = If(IsDBNull(drStock.Item("lotref")), "", drStock.Item("lotref").ToString) Rqst._packUOM = If(IsDBNull(drStock.Item("packUOM")), "", drStock.Item("packUOM").ToString) Rqst._grade = If(IsDBNull(drStock.Item("grade")), "", drStock.Item("grade").ToString) Rqst._shpLabel = If(IsDBNull(drStock.Item("shpLabel")), 0, CInt(drStock.Item("shpLabel"))) Rqst._countLoc = If(IsDBNull(drStock.Item("countLoc")), "", drStock.Item("countLoc").ToString) Rqst._palletType = If(IsDBNull(drStock.Item("palletType")), "", drStock.Item("palletType").ToString) Rqst._subPdt = If(IsDBNull(drStock.Item("subPdt")), "", drStock.Item("subPdt").ToString) Rqst._subTn = If(IsDBNull(drStock.Item("subTn")), 0, CInt(drStock.Item("subTn"))) Rqst._origReserved = reservedqty Rqst._reserved = reservedqty Rqst._dateReserved = Now Rqst._reservedBy = User Rqst._reason = reason Rqst._party = party Rqst._Cancelled = "f" Rqst._CancelledByUsr = "" Rqst._RsvQty = reservedqty Send(XMLRqst.toxml) </code></pre> <p>Send would obviously be your send sub routine (wherever it is sending it)</p>
33,092
<p>Currently, if I want to apply a method to a group of ActiveRecord objects, I have to structure the call like so:</p> <pre><code>messages = Message.find(:all) csv = Message.to_csv(messages) </code></pre> <p>How can I define the method so it's structured like so?</p> <pre><code>messages = Message.find(:all) csv = messages.to_csv </code></pre> <p>This is the current model code:</p> <pre><code>require 'fastercsv' class Message &lt; ActiveRecord::Base def Message.to_csv(messages) FasterCSV.generate do |csv| csv &lt;&lt; ["from","to", "received"] for m in messages csv &lt;&lt; [m.from,m.to,m.created_at] end end end end </code></pre>
<p>The following will call to_csv on all instances included in the messages array.</p> <pre><code>messages = Message.find(:all) csv = messages.map { |message| message.to_csv } </code></pre> <p>In Rails, in Ruby 1.9 or with Symbol#to_proc available through other means, you can also shorten it to:</p> <pre><code>csv = messages.map(&amp;:to_csv) </code></pre> <p>The longer form is useful when you want to make a more complex operation:</p> <pre><code>csv = messages.map { |message| if message.length &lt; 1000 message.to_csv else "Too long" end } </code></pre>
<p>You could create a method on your Message class to do something along the lines of...</p> <p>In your controller....</p> <pre><code>@csv_file = Message.send_all_to_csv </code></pre> <p>In your model...</p> <pre><code>require 'fastercsv' class Message &lt; ActiveRecord::Base def send_all_to_csv @messages = Find.all FasterCSV.generate do |csv| csv &lt;&lt; ["from","to", "received"] for message in @messages csv &lt;&lt; [message.from,message.to,message.created_at] end end # do something with your csv object (return it to the controller # or pass it on to another class method end end </code></pre>
27,686
<p>In <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a>, I can do something like this:</p> <pre><code>ALTER SEQUENCE serial RESTART WITH 0; </code></pre> <p>Is there an Oracle equivalent?</p>
<p>Here is a good procedure for resetting any sequence to 0 from Oracle guru <a href="http://asktom.oracle.com" rel="noreferrer">Tom Kyte</a>. Great discussion on the pros and cons in the links below too.</p> <pre><code>tkyte@TKYTE901.US.ORACLE.COM&gt; create or replace procedure reset_seq( p_seq_name in varchar2 ) is l_val number; begin execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by -' || l_val || ' minvalue 0'; execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0'; end; / </code></pre> <p>From this page: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:951269671592" rel="noreferrer">Dynamic SQL to reset sequence value</a><br> Another good discussion is also here: <a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1119633817597" rel="noreferrer">How to reset sequences?</a></p>
<p>Stored procedure that worked for me</p> <pre><code>create or replace procedure reset_sequence( p_seq_name in varchar2, tablename in varchar2 ) is l_val number; maxvalueid number; begin execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'select max(id) from ' || tablename INTO maxvalueid; execute immediate 'alter sequence ' || p_seq_name || ' increment by -' || l_val || ' minvalue 0'; execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by '|| maxvalueid ||' minvalue 0'; execute immediate 'select ' || p_seq_name || '.nextval from dual' INTO l_val; execute immediate 'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0'; end; </code></pre> <p>How to use the stored procedure:</p> <pre><code>execute reset_sequence('company_sequence','company'); </code></pre>
7,453
<p>When designing FPGA systems how can I estimate roughly the number of logic blocks a given task would require?</p> <p>Anyone have a rough order of magnitude on what I should expect for these comon devices?:</p> <ul> <li>UART</li> <li>packet deframer with CRC32</li> <li>8 micro core</li> </ul> <p>I've seen www.opencores.org, however, they are not giving a number of gates magnitude for each project.</p>
<p>UART: 3200 gates. 8-bit uC: 10k gates. Check <a href="http://www.design-reuse.com/%22design-reuse%22" rel="nofollow noreferrer">http://www.design-reuse.com/</a> for others.</p>
<p>An entire Amiga can fit in 400k gates, excluding CPU. See the Minimig project, it's opensource and should include some useful reference files. There's also an FPGA 68k core somewhere online that you can check, written by tobiflex. Also check out the commodore one machine and C64/CPC cores (Z80, 6845, SID, 6502, etc) to see how they compare.</p>
42,297
<p>What is the best method for utilizing a single code base for multiple websites? </p> <p>We have validation and session management libraries that we use on multiple websites. Is there a best practice for keeping a single copy rather than having to maintain updates of local copies for each website?</p>
<p>If you are using subversion, you can branch your common code and use svn:external to keep an up to date version (or a specific tag) of the common code in your repository. (<a href="http://svnbook.red-bean.com/en/1.0/ch07s03.html" rel="nofollow noreferrer">http://svnbook.red-bean.com/en/1.0/ch07s03.html</a>)</p> <p>Other SCM systems may have similar features.</p>
<p>We have a single codebase that we share with all websites we build. We're an ASP.NET shop, so in practice that means a VB.NET class library. This includes extensions of the basic ASP.NET controls (a custom SqlDatasource, a custom FormView, a custom CheckboxList, etc.) as well as other custom web controls and a library of utility classes and functions.</p> <p>Typically a website consists of a 2-project VisualStudio solution, one project for the website itself, and another project for the shared codebase. When we build the solution, any changes to the common codebase are built at the same time. Changes to the codebase are checked in to source control and propagated to other websites whenever they're opened back up and the latest code is pulled down. </p>
28,609
<p>Can I use a metal filament such as Copper, Zinc Alloy, Silver filaments on M3D Micro? <em>The Pro hasn't come out yet but I assume it would if the Micro can since the Pro is suppose to be the improvement edition.</em></p> <p>An example of a metal filament that I found is this <a href="http://rads.stackoverflow.com/amzn/click/B00T76GLWE" rel="noreferrer">Silver PLA 1.75mm Filament</a>. Here's one for <a href="http://www.sainsmart.com/sainsmart-plated-copper-pla-1-75mm-filament-1kg-2-2lb-for-3d-printers.html?gclid=CjwKEAjwtLO7BRDax4-I4_6G71USJAA6FjN1VDu_t4Co-u949PfHWjVL0x6BD-I-4ZLRUEij0bhWLhoCSSbw_wcB" rel="noreferrer">Cooper PLA 1.75mm Filament</a>.</p> <p>I would like to make small sculptures or bracelet beads/charms, and whatever else I could think of making using metal. And, I'm asking because I'm new to 3d printing, I want to learn how to work with a 3d printer and M3D is very affordable for me. <em>So I'm making sure before I buy</em>. Note that I've emailed M3D twice and I didn't get any reply. </p> <p>If not M3D, can any other 3D Printer comparable to M3D do this? The MBot Mini, maybe?</p>
<p>Most 3D printers that use non-proprietary filament <em>can</em> print exotic filaments, such as the ones you mention. One thing to be aware of, though, is that some of these filaments <a href="http://makezine.com/2015/09/11/carbon-fiber-filament-ruins-nozzles/" rel="noreferrer">wear down the nozzle</a> far more quickly than ordinary PLA, and therefore should be used with <a href="http://e3d-online.com/V6-nozzle-hardened-steel-3mmx0.4mm" rel="noreferrer">reinforced nozzles</a> (unless you have extra nozzles to spare). Carbon fibre and metallic filaments are generally known to increase nozzle wear, while softer alloys such as wood and bamboo generally are less abrasive.</p> <p>A quick google search reveals that many people have used non-proprietary filament on the M3D Micro successfully, but be aware that using such filaments is not covered by your <a href="https://printm3d.com/terms-of-use" rel="noreferrer">warranty</a>. If you are going to use abrasive filaments with your Micro, I would check that M3D allows you to replace the nozzle first.</p>
<p>It is my understanding that the metals are so fine and mixed in with other ingredients that you cannot tell that there is metal at all. But looks like its 100% metals.</p>
329
<p>Previously, I asked the <a href="https://stackoverflow.com/questions/79136/how-do-i-create-a-container-file">question</a>.</p> <p>The problem is the demands of our file structure are very high.</p> <p>For instance, we're trying to create a container with up to 4500 files and 500mb data.</p> <p>The file structure of this container consists of </p> <ul> <li>SQLite DB (under 1mb)</li> <li>Text based xml-like file <li><p>Images inside a dynamic folder structure that make up the rest of the 4,500ish files</p></li> <li><p>After the initial creation the images files are read only with the exception of deletion.</p></li> <li>The small db is used regularly when the container is accessed.</li> </ul> <p>Tar, Zip and the likes are all too slow (even with 0 compression). Slow is subjective I know, but to untar a container of this size is over 20 seconds.</p> <p>Any thoughts?</p>
<p>Three things.</p> <p>1) What Timothy Walters said is right on, I'll go in to more detail.</p> <p>2) 4500 files and 500Mb of data is simply a lot of data and disk writes. If you're operating on the entire dataset, it's going to be slow. Just I/O truth.</p> <p>3) As others have mentioned, there's no detail on the use case.</p> <p>If we assume a read only, random access scenario, then what Timothy says is pretty much dead on, and implementation is straightforward.</p> <p>In a nutshell, here is what you do.</p> <p>You concatenate all of the files in to a single blob. While you are concatenating them, you track their filename, the file length, and the offset that the file starts within the blob. You write that information out in to a block of data, sorted by name. We'll call this the Table of Contents, or TOC block.</p> <p>Next, then, you concatenate the two files together. In the simple case, you have the TOC block first, then the data block.</p> <p>When you wish to get data from this format, search the TOC for the file name, grab the offset from the begining of the data block, add in the TOC block size, and read FILE_LENGTH bytes of data. Simple.</p> <p>If you want to be clever, you can put the TOC at the END of the blob file. Then, append at the very end, the offset to the start of the TOC. Then you lseek to the end of the file, back up 4 or 8 bytes (depending on your number size), take THAT value and lseek even farther back to the start of your TOC. Then you're back to square one. You do this so you don't have to rebuild the archive twice at the beginning.</p> <p>If you lay out your TOC in blocks (say 1K byte in size), then you can easily perform a binary search on the TOC. Simply fill each block with the File information entries, and when you run out of room, write a marker, pad with zeroes and advance to the next block. To do the binary search, you already know the size of the TOC, start in the middle, read the first file name, and go from there. Soon, you'll find the block, and then you read in the block and scan it for the file. This makes it efficient for reading without having the entire TOC in RAM. The other benefit is that the blocking requires less disk activity than a chained scheme like TAR (where you have to crawl the archive to find something).</p> <p>I suggest you pad the files to block sizes as well, disks like work with regular sized blocks of data, this isn't difficult either.</p> <p>Updating this without rebuilding the entire thing is difficult. If you want an updatable container system, then you may as well look in to some of the simpler file system designs, because that's what you're really looking for in that case.</p> <p>As for portability, I suggest you store your binary numbers in network order, as most standard libraries have routines to handle those details for you.</p>
<p>Working on the assumption that you're only going to need read-only access to the files why not just merge them all together and have a second "index" file (or an index in the header) that tells you the file name, start position and length. All you need to do is seek to the start point and read the correct number of bytes. The method will vary depending on your language but it's pretty straight forward in most of them.</p> <p>The hardest part then becomes creating your data file + index, and even that is pretty basic!</p>
32,178
<p>Im creating a report using crystal report in vb.net.</p> <p>The report contained a crosstab which I have 3 data: 1. Dealer - row field 2. Month - column 3. Quantity Sales - summarize field</p> <p>How can I arrange this by ascending order based on the Quantity Sales - summarize field?</p> <p>thanks</p>
<p>Depending on how you're working with it, you can adjust the input to order the data ascending.</p> <blockquote> <pre><code>SELECT customer, sum(amountdue) AS total FROM invoices GROUP BY customer ORDER BY total ASC </code></pre> </blockquote> <p>If you're doing in a way that you can't change that information, could you provide a little more insight?</p>
<p>Note that other Business Objects products order on the total of a summary field when sorting a cross tab by it's values. I forget how CR does it exactly.</p>
28,307
<p>Is it possible to call into COM objects via x86 assembly language? If so, how?</p> <p>Why would I want to do this? Let's say I've got two programs that I don't have source for - all I've got are the binaries. One of them implements a COM interface, the other doesn't. I want to inject code into the first program to call into the second using this COM interface, and this requires me to use x86 assembly.</p>
<p>Of course it's possible - in effect that's what the C/C++ compiler does.</p> <p>But why in God's name would you want to do this? If it were for educational value, then surely doing the COM stuff by hand in straight C would do the trick.</p> <hr> <p>Given the updated question, I'd suggest that you write the COM stuff in a DLL and inject that DLL into the program you want to patch, then patch in simple x86 code into the program to call your DLL that does the heavy lifting. I don't recall the techniques for injecting a DLL into the address space of a process, but there are at least a couple. The AppInit registry setting (or something like that) is one.</p> <p>However, I think that most of the avenues for injecting code into a process are considered security flaws (and have often been used by malware), so I suspect that Microsoft may have removed many if not most (or all) from more recent service packs or OS versions.</p>
<p>Yes -- COM is designed primarily as a <strong>binary API</strong> albeit one that has a very easy implementation from C/C++. However, the specification is not in terms of C or C++.</p> <p>You can refer to the original COM spec, there is a copy <a href="http://www.daimi.au.dk/~datpete/COT/COM_SPEC/html/com_spec.html" rel="nofollow noreferrer">here</a> and it must be buried somewhere on the Microsoft site as well.</p> <p><strong>Update</strong>: your use case doesn't seem to require the use of assembly directly, any code injection technique can be used. How you compile the code to be injected is a different matter to how you inject it.</p>
23,010
<p>I attended a job fair yesterday and a developer asked me how I would rank my proficiency in C. I then realized that this is incredibly arbitrary and almost impossible to nail down, so my question is what knowledge makes you an expert in programming C?</p> <p>Edit: or what would the breakdown be? what makes you good, decent, proficient, etc.</p> <p>Edit again: I was looking more for like a list of skills or some other constructive measure by which to judge one's own proficiency in C, as that's hard to do.</p> <p>List so far:<ul> <li>Experience in large projects <li>Mastery of Pointers (and memory management, I'd assume) <li>Mastery of a debugger (gdb, ...) <li>Mastery of a profiler (gprof,...) <li>Mastery of a memory profiler (valgrind, ...) <li>Knowledge of the fundamental standards </ul></p>
<p>Experience is key, knowing the "rules" and syntax of the of the language is of course a must, but it is only a base. Learning the common pitfalls and idioms for doing things right is key.</p> <p>Knowing what if any resources exist to get help from while your programing, and of course, knowing you're tool chain. I've known many C++ "experts" who had never used a debugger, or a memory tracker. If you ask me, being an expert in something is different from being proficient in something in you knowing all aspects of it.</p>
<p>Mastery of pointers.</p>
12,932
<p>Which is the best mocking library for C# 3.0/ ASP.NET MVC? Why?</p>
<p><a href="https://github.com/Moq/moq4" rel="nofollow noreferrer">Moq</a></p> <p>It's amazing, fully supports the new language features of C# 3.0 and it's very easy to get going with. I would highly recommend it.</p>
<p>I'm going through that process now, weighing them up for use by my team, and I have to say Moq as well, it seems to have the least of a learning curve, and some nice features, I love the use of Moq generics to specify a Mock class</p>
10,549
<p>I have been mulling over writing a peak-fitting library for a while. I know Python fairly well and plan on implementing everything in Python to begin with but envisage that I may have to re-implement some core routines in a compiled language eventually.</p> <p>IIRC, one of Python's original remits was as a prototyping language, however Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran.</p> <p>What should I know about designing functions/classes which I envisage will have to interface into the compiled language? And how much of these potential problems are dealt with by libraries such as cTypes, bgen, <a href="http://www.swig.org/" rel="nofollow noreferrer">SWIG</a>, <a href="http://www.boost.org/doc/libs/1_35_0/libs/python/doc/index.html" rel="nofollow noreferrer">Boost.Python</a>, <a href="http://cython.org/" rel="nofollow noreferrer">Cython</a> or <a href="http://www.riverbankcomputing.co.uk/software/sip/intro" rel="nofollow noreferrer">Python SIP</a>?</p> <p>For this particular use case (a fitting library), I imagine allowing users to define mathematical functions (Guassian, Lorentzian etc.) as Python functions which can then to be passed an interpreted by the compiled code fitting library. Passing and returning arrays is also essential.</p>
<p>Finally a question that I can really put a value answer to :). </p> <p>I have investigated f2py, boost.python, swig, cython and pyrex for my work (PhD in optical measurement techniques). I used swig extensively, boost.python some and pyrex and cython a lot. I also used ctypes. This is my breakdown:</p> <p><strong>Disclaimer</strong>: This is my personal experience. I am not involved with any of these projects. </p> <p><strong>swig:</strong> does not play well with c++. It should, but name mangling problems in the linking step was a major headache for me on linux &amp; Mac OS X. If you have C code and want it interfaced to python, it is a good solution. I wrapped the GTS for my needs and needed to write basically a C shared library which I could connect to. I would not recommend it.</p> <p><strong>Ctypes:</strong> I wrote a libdc1394 (IEEE Camera library) wrapper using ctypes and it was a very straigtforward experience. You can find the code on <a href="https://launchpad.net/pydc1394" rel="noreferrer">https://launchpad.net/pydc1394</a>. It is a lot of work to convert headers to python code, but then everything works reliably. This is a good way if you want to interface an external library. Ctypes is also in the stdlib of python, so everyone can use your code right away. This is also a good way to play around with a new lib in python quickly. I can recommend it to interface to external libs. </p> <p><strong>Boost.Python</strong>: Very enjoyable. If you already have C++ code of your own that you want to use in python, go for this. It is very easy to translate c++ class structures into python class structures this way. I recommend it if you have c++ code that you need in python. </p> <p><strong>Pyrex/Cython:</strong> Use Cython, not Pyrex. Period. Cython is more advanced and more enjoyable to use. Nowadays, I do everything with cython that i used to do with SWIG or Ctypes. It is also the best way if you have python code that runs too slow. The process is absolutely fantastic: you convert your python modules into cython modules, build them and keep profiling and optimizing like it still was python (no change of tools needed). You can then apply as much (or as little) C code mixed with your python code. This is by far faster then having to rewrite whole parts of your application in C; you only rewrite the inner loop. </p> <p><strong>Timings</strong>: ctypes has the highest call overhead (~700ns), followed by boost.python (322ns), then directly by swig (290ns). Cython has the lowest call overhead (124ns) and the best feedback where it spends time on (cProfile support!). The numbers are from my box calling a trivial function that returns an integer from an interactive shell; module import overhead is therefore not timed, only function call overhead is. It is therefore easiest and most productive to get python code fast by profiling and using cython.</p> <p><strong>Summary</strong>: For your problem, use Cython ;). I hope this rundown will be useful for some people. I'll gladly answer any remaining question.</p> <hr> <p><strong>Edit</strong>: I forget to mention: for numerical purposes (that is, connection to NumPy) use Cython; they have support for it (because they basically develop cython for this purpose). So this should be another +1 for your decision. </p>
<blockquote> <p>Python is pretty liberal in allowing functions, functors, objects to be passed to functions and methods, whereas I suspect the same is not true of say C or Fortran.</p> </blockquote> <p>In C you cannot pass a function as an argument to a function but you can pass a function pointer which is just as good a function.</p> <p>I don't know how much that would help when you are trying to integrate C and Python code but I just wanted to clear up one misconception.</p>
3,678
<p>In C# which is more memory efficient: Option #1 or Option #2?</p> <pre><code>public void TestStringBuilder() { //potentially a collection with several hundred items: string[] outputStrings = new string[] { "test1", "test2", "test3" }; //Option #1 StringBuilder formattedOutput = new StringBuilder(); foreach (string outputString in outputStrings) { formattedOutput.Append("prefix "); formattedOutput.Append(outputString); formattedOutput.Append(" postfix"); string output = formattedOutput.ToString(); ExistingOutputMethodThatOnlyTakesAString(output); //Clear existing string to make ready for next iteration: formattedOutput.Remove(0, output.Length); } //Option #2 foreach (string outputString in outputStrings) { StringBuilder formattedOutputInsideALoop = new StringBuilder(); formattedOutputInsideALoop.Append("prefix "); formattedOutputInsideALoop.Append(outputString); formattedOutputInsideALoop.Append(" postfix"); ExistingOutputMethodThatOnlyTakesAString( formattedOutputInsideALoop.ToString()); } } private void ExistingOutputMethodThatOnlyTakesAString(string output) { //This method actually writes out to a file. System.Console.WriteLine(output); } </code></pre>
<p>Several of the answers gently suggested that I get off my duff and figure out it myself so below are my results. I think that sentiment generally goes against the grain of this site but if you want something done right, you might as well do.... :)</p> <p>I modified option #1 to take advantage of @Ty suggestion to use StringBuilder.Length = 0 instead of the Remove method. This made the code of the two options more similar. The two differences are now whether the constructor for the StringBuilder is in or out of the loop and option #1 now uses the the Length method to clear the StringBuilder. Both options were set to run over an outputStrings array with 100,000 elements to make the garbage collector do some work.</p> <p>A couple answers offered hints to look at the various PerfMon counters &amp; such and use the results to pick an option. I did some research and ended up using the built-in Performance Explorer of the Visual Studio Team Systems Developer edition that I have at work. I found the second blog entry of a multipart series that explained how to set it up <a href="http://blogs.msdn.com/ianhu/archive/2005/02/11/371418.aspx" rel="noreferrer">here</a>. Basically, you wire up a unit test to point at the code you want to profile; go through a wizard &amp; some configurations; and launch the unit test profiling. I enabled the .NET object allocation &amp; lifetime metrics. The results of the profiling where difficult to format for this answer so I placed them at the end. If you copy and paste the text into Excel and massage them a bit, they'll be readable.</p> <p>Option #1 is the most memory efficiency because it makes the garbage collector do a little less work and it allocates half the memory and instances to the StringBuilder object than Option #2. For everyday coding, picking option #2 is perfectly fine.</p> <p>If you're still reading, I asked this question because Option #2 will make the memory leak detectors of an experience C/C++ developer go ballistic. A huge memory leak will occur if the StringBuilder instance is not released before being reassigned. Of course, we C# developers don't worry about such things (until they jump up and bite us). Thanks to all!!</p> <hr> <pre><code>ClassName Instances TotalBytesAllocated Gen0_InstancesCollected Gen0BytesCollected Gen1InstancesCollected Gen1BytesCollected =======Option #1 System.Text.StringBuilder 100,001 2,000,020 100,016 2,000,320 2 40 System.String 301,020 32,587,168 201,147 11,165,268 3 246 System.Char[] 200,000 8,977,780 200,022 8,979,678 2 90 System.String[] 1 400,016 26 1,512 0 0 System.Int32 100,000 1,200,000 100,061 1,200,732 2 24 System.Object[] 100,000 2,000,000 100,070 2,004,092 2 40 ======Option #2 System.Text.StringBuilder 200,000 4,000,000 200,011 4,000,220 4 80 System.String 401,018 37,587,036 301,127 16,164,318 3 214 System.Char[] 200,000 9,377,780 200,024 9,379,768 0 0 System.String[] 1 400,016 20 1,208 0 0 System.Int32 100,000 1,200,000 100,051 1,200,612 1 12 System.Object[] 100,000 2,000,000 100,058 2,003,004 1 20 </code></pre>
<p>I'd say option #2 if definitely more straightforward. In terms of performance, sounds like something you'd just need to test and see. I'd guess that it doesn't make enough difference to choose the less straightforward option.</p>
33,469
<p>I'm currently planning the infrastructure for my future web project. I want to go the way Joel went with having one DB per client and now thinking which DB engine will be good for me. The best would be of course SQL Server, but I can't afford a full-blown version at this moment and I don't think SQL Server Express will be a good choice for the loaded service. Now I'm thinking of using PostgreSQL instead. Given that my development environment will be ASP.NET 3.5 with say NHibernate or LINQ to SQL, how much trouble will I have if I use PostgreSQL instead of SQL Server?</p> <p>Thanks!</p>
<p>NHibernate works OK with PostgreSQL (whether the db is on Windows or UNIX-like OSes) and .NET works well with it using the Npgsql db provider.</p> <p>The only "trouble" you'll get is of course PostgreSQL doesn't do T-SQL. In fact its PL/pgSQL stored proc language is closer to Oracle's PL/SQL than it is to MS SQL Server's T-SQL. So you'll have to recode your stored procs, and there will be some gotchas to watch out for if you do ADO.NET. If you use NHibernate, you probably won't have to worry much about that. No LINQ to SQL though, so tough luck for you.</p> <p>PostgreSQL is scalable and works OK now with Windows (earlier versions didn't support Windows formally), and pgAdmin is a good management tool for it, you'll be able to do most of the stuff you can do with SQL Server's GUI tools with it in a short time.</p>
<p>If you go with PostgreSQL you won't be able to use LINQ to SQL. Currently LINQ only works with SQL Server (possibly Oracle). I'm not sure about NHibernate. Also, if you use PostgreSQL, last time I checked, they had dropped windows support. So you'll be looking into having a second box running Linux for the DB.</p> <p>[EDIT]</p> <p>It turns out PostgreSQL is supported on windows. I can't recall where I saw support being cancelled. Anyway, I've heard it runs better on Linux anyway, so you might want to look into doing that regardless.</p>
15,904
<p>My colleague has an app that hosts a simple WCF service with a net.tcp endpoint. I can add the service reference to any app I create using the address net.tcp://192.168.0.22:9999/GSS-POS/QueryDispatcher/mex</p> <p>However, when he tries to add the service reference to an app running on his machine he immediately gets a socket error 10045. We've tried using both net.tcp://localhost:9999/GSS-POS/QueryDispatcher/mex</p> <p>and</p> <p>net.tcp://192.168.0.22:9999/GSS-POS/QueryDispatcher/mex</p> <p>He's tried re-installing Visual Studio 2008, Service Pack 1 and XP Service Pack 3 all to no avail. Can anybody provide any pointers?</p> <p>UPDATE: This appears as though it is related to Visual Studio. By using the WCF Client test app, it is possible to see the service. It seems as though VS is having the problem adding the service reference.</p> <p>UPDATE 2: Adding a reference with VS 2008 works with named pipe and http transport. The problem only manifests itself when trying to add a service reference which utilises a net.tcp endpoint.</p> <p>Best regards,</p> <p>Simon</p>
<p>I don't have an answer for you, but the code 10045 represents WSAEOPNOTSUPP (operation not supported) which, according to <a href="http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx" rel="nofollow noreferrer">MSDN</a>, means:</p> <blockquote> <p>The attempted operation is not supported for the type of object referenced. Usually this occurs when a socket descriptor to a socket that cannot support this operation is trying to accept a connection on a datagram socket.</p> </blockquote>
<p>The <a href="https://rads.stackoverflow.com/amzn/click/com/0596526997" rel="nofollow noreferrer" rel="nofollow noreferrer">book by Juval Lowy</a> says that tcp communications are "optimised" for WCF->WCF comms only. Maybe that has something to do with your problem.</p>
47,282
<p>At the office we are currently writing an application that will generate XML files against a schema that we were given. We have the schema in an .XSD file.</p> <p>Are there tool or libraries that we can use for automated testing to check that the generated XML matches the schema?</p> <p>We would prefer free tools that are appropriate for commercial use although we won't be bundling the schema checker so it only needs to be usable by devs during development.</p> <p>Our development language is C++ if that makes any difference, although I don't think it should as we could generate the xml file and then do validation by calling a separate program in the test.</p>
<p>After some research, I think the best answer is <a href="http://xerces.apache.org/" rel="noreferrer">Xerces</a>, as it implements all of XSD, is cross-platform and widely used. I've created a <a href="https://github.com/amouat/xsd-validator" rel="noreferrer">small Java project on github</a> to validate from the command line using the default JRE parser, which is normally Xerces. This can be used on Windows/Mac/Linux. </p> <p>There is also a <a href="https://xerces.apache.org/xerces-c/" rel="noreferrer">C++ version of Xerces</a> available if you'd rather use that. The <a href="http://xerces.apache.org/xerces-c/stdinparse-3.html" rel="noreferrer">StdInParse utility</a> can be used to call it from the command line. Also, a commenter below points to this <a href="http://jmvanel.free.fr/xsd/" rel="noreferrer">more complete wrapper utility</a>.</p> <p>You could also use xmllint, which is part of <a href="http://xmlsoft.org/" rel="noreferrer">libxml</a>. You may well already have it installed. Example usage:</p> <pre><code>xmllint --noout --schema XSD_FILE XML_FILE </code></pre> <p>One problem is that libxml doesn't implement all of the specification, so you may run into issues :(</p> <p>Alternatively, if you are on Windows, you can use <a href="http://msdn.microsoft.com/en-us/library/ms763742.aspx" rel="noreferrer">msxml</a>, but you will need some sort of wrapper to call it, such as the GUI one described in this <a href="http://www.ddj.com/architect/184416391" rel="noreferrer">DDJ article</a>. However, it seems most people on Windows use an XML Editor, such as Notepad++ (as described in <a href="https://stackoverflow.com/a/1088659/4332">Nate's answer</a>) or <a href="http://www.microsoft.com/en-us/download/details.aspx?id=7973" rel="noreferrer">XML Notepad 2007</a> as <a href="https://stackoverflow.com/a/3915105/4332">suggested by SteveC</a> (there are also several commercial editors which I won't mention here).</p> <p>Finally, you'll find different programs will, unfortunately, give different results. This is largely due to the complexity of the XSD spec. You may want to test your schema with several tools.</p> <p><strong>UPDATE</strong>: I've expanded on this in a <a href="http://www.adrianmouat.com/bit-bucket/2013/11/xml-schema-validation/" rel="noreferrer">blog post</a>.</p>
<p>I tend to use xsd from Microsoft to help generate the xsd from a .NET file. I also parse out sections of the xml using xmlstarlet. The final free tool that would be of use to you is altovaxml, which is available at this URL: <a href="http://www.altova.com/download_components.html" rel="nofollow">http://www.altova.com/download_components.html</a> .</p> <p>This allows me to scan all the xml files picking up which xsd to use by parsing the xml.</p> <pre><code># Function: # verifyschemas - Will validate all xml files in a configuration directory against the schemas in the passed in directory # Parameters: # The directory where the schema *.xsd files are located. Must be using dos pathing like: VerifySchemas "c:\\XMLSchemas\\" # Requirements: # Must be in the directory where the configuration files are located # verifyschemas() { for FILENAME in $(find . -name '*.xml' -print0 | xargs -0) do local SchemaFile=$1$(getconfignamefromxml $FILENAME).xsd altovaxml /validate $FILENAME /schema $SchemaFile &gt; ~/temp.txt 2&gt; /dev/null if [ $? -ne 0 ]; then printf "Failed to verify: " cat ~/temp.txt | tail -1 | tr -d '\r' printf " - $FILENAME with $SchemaFile\n" fi done } </code></pre> <p>To generate the xml I use: xsd DOTNET.dll /type:CFGCLASS &amp; rename schema0.xsd CFGCLASS.xsd</p> <p>To get the xsd name I use: xmlstarlet sel -t -m /XXX/* -v local-name() $1 | sed 's/ $//'</p> <p>This allows me to pickup the correct XSD using an element tag within the xml file.</p> <p>The net result is that I can call a bash function to scan all the XML files and verify them. Even if they are in multiple subdirectories.</p>
15,181
<p>I remember seeing in a sample a while ago that it is possible to break up a windsor configuration file into multiple ones and reference them from the app.config in a way that they get parsed automatically.</p> <p>Of course I didn't bookmark it and now I can't find it and my Windsor.Config.xml file is creeping up on 600 lines. Can anyone tell me how to do this?</p> <p>Currently I just instantiate my container directly off the file: IWindsorContainer container = new WindsorContainer("Windsor.Config.xml");</p> <p>But I'd like to break it up, reference the xml in the app.config and have it included automatically. </p>
<p>I think you mean using includes:</p> <p><a href="http://www.castleproject.org/container/documentation/v1rc3/usersguide/includes.html" rel="nofollow noreferrer">http://www.castleproject.org/container/documentation/v1rc3/usersguide/includes.html</a></p> <p>All you need to do is specify an include node with the Uri that will be used to create the proper Resource. For example, the following will use the FileResource: </p> <p>The file is relative to the configuration file that has the include:</p> <pre><code>&lt;include uri="file://Configurations/facilities.xml"&gt; &lt;include uri="file://Configurations/services.xml"&gt; </code></pre>
<p>You can break the castle configuration into several files <a href="http://castleproject.org/container/documentation/trunk/usersguide/includes.html" rel="nofollow noreferrer">using includes</a></p>
47,034
<p>Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods? </p>
<p>Assume your class has a <code>responseData</code> instance variable, then:</p> <pre><code>responseData = [[NSMutableData data] retain]; NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]]; [[NSURLConnection alloc] initWithRequest:request delegate:self]; </code></pre> <p>And then add the following methods to your class:</p> <pre><code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { // Show error } - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // Once this method is invoked, "responseData" contains the complete result } </code></pre> <p>This will send a GET. By the time the final method is called, <code>responseData</code> will contain the entire HTTP response (convert to string with [[NSString alloc] initWithData:encoding:].</p> <p>Alternately, for POST, replace the first block of code with:</p> <pre><code>NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]]; [request setHTTPMethod:@"POST"]; NSString *postString = @"Some post string"; [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; </code></pre>
<p>If you're using Objective C, you'll need to use the NSURL, NSURLRequest, and NURLConnection classes. <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLRequest_Class/NSURLRequest_Class.pdf" rel="nofollow noreferrer">Apple's NSURLRequest doc</a>. HttpRequest is for JavaScript.</p>
41,305
<p>When building a application that accesses a MySQL database on linux using C/C++ i have to dynamically link into the mysql client library. Is there a way in which i can statically link the application so that the mysql client libraries are no longer required?</p> <p>What is the best practice, with regards to C\C++ development, to include rather long queries in the application but outside the code? Using stored procedures an not possible as the database runs on a MySQL 4 server.</p>
<p>Should be easy to create the static mysql client libs. If you downloaded the source, you just need to make sure you configure it appropriately: ./configure --enable-static This should build libmysql/libmysqlclient.a (or possibly libmysql/.libs/libmysqlclient.a) which should be easy to link statically into your executable.</p> <p>You'll need your executable to be licensed under the GPL or you'll need to buy an appropriate license from the MySQL folks.</p>
<p>The following compile command-line worked for me to statically link the mysql client libs:</p> <pre><code>gcc -I/usr/include/mysql -c mysql.c gcc -o mysql mysql.o -static -lmysqlclient -static-libgcc -lm -lz -lpthread </code></pre> <p>However, I received the following warnings, which may or may not be a problem for you. It seems to be saying that there is a dependency on the target machine having the same glibc version as your build machine. </p> <pre><code>/usr/lib/gcc/i486-linux-gnu/4.2.4/../../../../lib/libmysqlclient.a(mf_pack.o): In function `unpack_dirname': (.text+0x6cc): warning: Using 'getpwnam' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/gcc/i486-linux-gnu/4.2.4/../../../../lib/libmysqlclient.a(libmysql.o): In function `read_user_name': (.text+0x5ed7): warning: Using 'getpwuid' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/gcc/i486-linux-gnu/4.2.4/../../../../lib/libmysqlclient.a(mf_pack.o): In function `unpack_dirname': (.text+0x6e1): warning: Using 'endpwent' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/gcc/i486-linux-gnu/4.2.4/../../../../lib/libmysqlclient.a(my_gethostbyname.o): In function `my_gethostbyname_r': (.text+0x3c): warning: Using 'gethostbyname_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking /usr/lib/gcc/i486-linux-gnu/4.2.4/../../../../lib/libmysqlclient.a(libmysql.o): In function `mysql_server_init': (.text+0x695d): warning: Using 'getservbyname' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking </code></pre>
35,560
<p>What is the best way to determine duplicate records in a SQL Server table?</p> <p>For instance, I want to find the last duplicate email received in a table (table has primary key, receiveddate and email fields).</p> <p>Sample data:</p> <pre><code>1 01/01/2008 stuff@stuff.com 2 02/01/2008 stuff@stuff.com 3 01/12/2008 noone@stuff.com </code></pre>
<p>something like this</p> <pre><code>select email ,max(receiveddate) as MaxDate from YourTable group by email having count(email) &gt; 1 </code></pre>
<p>Couldn't you join the list on the e-mail field and then see what nulls you get in your result?</p> <p>Or better yet, count the instances of each e-mail address? And only return the ones with count > 1</p> <p>Or even take the email and id fields. And return the entries where the e-mail is the same, and the IDs are different. (To avoid duplicates don't use != but rather either &lt; or >.)</p>
6,900
<pre><code> $a = '{ "tag": "&lt;b&gt;&lt;/b&gt;" }'; echo json_encode( json_decode($a) ); </code></pre> <p>This outputs:</p> <pre><code>{"tag":"&lt;b&gt;&lt;\/b&gt;"} </code></pre> <p>when you would think it would output exactly the input. For some reason json_encode adds an extra slash.</p>
<p>Because it's part of the JSON standard</p> <p><a href="http://json.org/" rel="noreferrer">http://json.org/</a></p> <blockquote> <p>char</p> <pre><code>any-Unicode-character- except-&quot;-or-\-or- control-character \&quot; \\ \/ &lt;---- see here? \b \f \n \r \t \u four-hex-digits </code></pre> </blockquote>
<p>That's probably a security-feature. The escaped version (Eg. the output) would be parsed as similar to the unescaped-version, by Javascript (Eg. <code>\/</code> becomes <code>/</code>). Having escaped the slash like that, there is a lesser chance of the browser misinterpreting the Javascript-string as HTML. Of course, if you treat the data correct, this shouldn't be needed, so it's more a safeguard against a clueless programmer messing things up for himself.</p>
15,549
<p>I'm considering switching to a Dvorak-based keyboard layout, but one optimized for programming (mostly) Java and python (e.g. <a href="http://www.siteuri.ro/dvorak/DDvorak.aspx" rel="noreferrer">DDvorak</a>, <a href="http://www.kaufmann.no/roland/dvorak/" rel="noreferrer">Programmer Dvorak</a>, etc.). What particular keyboard would be best for such an undertaking? I'd consider either natural or straight keyboards.</p> <p>Thanks.</p>
<p>I <em>strongly</em> discourage you from learning a layout that has been heavily optomized for any one programming language (or even a class of them..) it's much, much easier to change languages than keylayouts, and you'll have a lot of trouble finding the tweaked layouts on any random computers you need to use.</p> <p>That said, I've used dvorak for years (something like 7-8 years now) on a <a href="http://www.kinesis-ergo.com/contoured.htm" rel="noreferrer">Kinesis Contoured keyboard</a> and it works wonderfully. The kinesis is programmable, switches between qwerty/dvorak, and you can remap the keys all you want (so you could try out ddvorak or programmer dvorak pretty easily, without making software changes, if you wanted).</p> <p>The contoured keyboard also forces you to touch-type more "correctly", since you can't easily reach across the keyboard with the wrong hand.</p>
<p>Do you use a natural keyboard, or a straight one? Keyboard preference can be intensely personal, but many higher-end keyboards have keys fitted specifically for the location of the key (slant and curvature), meaning for Dvorak you'll need to ignore the labels, move the keys and eliminate that advantage, or go with something like the <a href="http://www.daskeyboard.com/" rel="nofollow noreferrer">blank das keyboard</a></p>
9,304
<p>Does anyone have any good references for equations which can be implemented relatively easily for how to compute the transfer of angular momentum between two rigid bodies?</p> <p>I've been searching for this sort of thing for a while, and I haven't found any particularly comprehensible explanations of the problem.</p> <p>To be precise, the question comes about as this; two rigid bodies are moving on a frictionless (well, nearly) surface; think of it as air hockey. The two rigid bodies come into contact, and then move away. Now, without considering angular momentum, the equations are relatively simple; the problem becomes, what happens with the transfer of angular momentum between the bodies?</p> <p>As an example, assume the two bodies have no angular momentum whatsoever; they're not rotating. When they interact at an oblique angle (vector of travel does not align with the line of their centers of mass), obviously a certain amount of their momentum gets transferred into angular momentum (i.e. they each get a certain amount of spin), but how much and what are the equations for such?</p> <p>This can probably be solved by using a many-body rigid system to calculate, but I want to get a much more optimized calculation going, so I can calculate this stuff in real-time. Does anyone have any ideas on the equations, or pointers to open-source implementations of these calculations for inclusion in a project? To be precise, I need this to be a rather well-optimized calculation, because of the number of interactions that need to be simulated within a single "tick" of the simulation.</p> <p>Edit: Okay, it looks like there's not a lot of precise information about this topic out there. And I find the "Physics for Programmers" type of books to be a bit too... dumbed down to really get; I don't want code implementation of an algorithm; I want to figure out (or at least have sketched out for me) the algorithm. Only in that way can I properly optimize it for my needs. Does anyone have any mathematic references on this sort of topic?</p>
<p>If you're interested in rotating non-spherical bodies then <a href="http://www.myphysicslab.com/collision.html" rel="nofollow noreferrer">http://www.myphysicslab.com/collision.html</a> shows how to do it. The asymmetry of the bodies means that the normal contact force during the collision can create a torque about their respective CGs, and thus cause the bodies to start spinning.</p> <p>In the case of a billiard ball or air hockey puck, things are a bit more subtle. Since the body is spherical/circular, the normal force is always right through the CG, so there's no torque. However, the normal force is not the only force. There's also a friction force that is tangential to the contact normal which will create a torque about the CG. The magnitude of the friction force is proportional to the normal force and the coefficient of friction, and opposite the direction of relative motion. Its direction is opposing the relative motion of the objects at their contact point.</p>
<p>Please have a look at this references! If you want to go really into Mecanics, this is the way to go, and its the correct and mathematically proper way!</p> <p>Glocker Ch., Set-Valued Force Laws: Dynamics of Non-Smooth Systems. Lecture Notes in Applied Mechanics 1, Springer Verlag, Berlin, Heidelberg 2001, 222 pages. PDF (Contents, 149 kB)</p> <p>Pfeiffer F., Glocker Ch., Multibody Dynamics with Unilateral Contacts. JohnWiley &amp; Sons, New York 1996, 317 pages. PDF (Contents, 398 kB)</p> <p>Glocker Ch., Dynamik von Starrkörpersystemen mit Reibung und Stößen. VDI-Fortschrittberichte Mechanik/Bruchmechanik, Reihe 18, Nr. 182, VDI-Verlag, Düsseldorf, 1995, 220 pages. PDF (4094 kB)</p>
39,904
<p>I come from the Java world, where you can hide variables and functions and then run unit tests against them using reflection. I have used nested functions to hide implementation details of my classes so that only the public API is visible. I am trying to write unit tests against these nested functions to make sure that I don't break them as I develop. I have tried calling one of the nested functions like:</p> <pre><code>def outer(): def inner(): pass outer.inner() </code></pre> <p>which results in the error message:</p> <blockquote> <p>AttributeError: 'function' object has no attribute 'inner'</p> </blockquote> <p>Is there a way for me to write unit tests against these nested functions? If not, is there a way to trigger the name munging for function names like you can for class variables by prefixing them with __?</p>
<p>inner doesn't exist until outer makes it. You should either move inner up to a toplevel function for testability, or have the outer test test all the possible execution paths of itself and inner.</p> <p>Do note that the inner function isn't a simple function, it's a closure. Consider this case:</p> <pre><code>def outer(a): b = compute_something_from(a) def inner(): do_something_with(a, b) </code></pre> <p>That's the standard testability trade-off. If your <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity" rel="noreferrer">cyclomatic complexity</a> is too high, your tests will be too numerous.</p>
<p>I ran into an interesting case where I was able to run a unit test on a nested function using MagicMock. The key was that the nested function was being sent as an argument to another function that I had access to. To keep with the OP's example:</p> <pre><code># my_app.py def util(func): # run some logic using func def outer(): def inner(): pass util(inner) </code></pre> <p>Being able to mock the <code>util</code> function allowed access to the call arguments, which in this case happens to be the <code>inner</code> function:</p> <pre><code>def test_inner # Arrange mock_util = MagicMock() with patch.object(my_app, 'util', mock_util): outer() # run the outer function to capture the util call with MagicMock inner_function = mock_util.call_args[0][0] # Act inner_function() # run the inner function for testing # Assert # make whatever assertions you would like </code></pre> <p>I got lucky this time, in that I did not need to alter the code that I was asked to test. <a href="https://stackoverflow.com/a/37897092/5365001">@Victor-Barroso's answer</a> features an intentional way to do something similar, for those who are looking for options. Although, if you are going to alter the code, you may as well follow <a href="https://stackoverflow.com/a/326912/5365001">@Dustin's advice</a> or any of the other good answers on this question.</p>
42,355
<p>Yesterday evening i have been trying to print a few upgrades but after coming home after an hour, it is printing in the air because there is to much filament dust inside the extruder. Is this because the filament that is being extruded is getting to soft so the gear grinds parts off? I never had this problem before. </p> <p>Printer:</p> <p>Anet A8. </p>
<p>If you are using Repetier the code to test the endstops is m119 I think. If your z stop is triggered, you may have to invert it in the config.h file. I had this same issue for days before i figured out the control board was reading the switch as normal close instead of normal open. Hope that helps!</p>
<p>Try sending a motion command manually, such as G1 X20 Z10, to eliminate any bugginess from the software interface as a reason for the Z not moving properly when commanded to. Next you could check the park location in Pronterface, perhaps the extruder head is sitting there waiting for the next command.</p>
683
<p>We want to switch a web server from Windows 2003 to Windows 2003 Enterprise (64 bits) to use 8GB of RAM. Will IIS 6.0 and an ASPNET 1.1 application be able to benefit from the change?</p>
<p>Since ASP.Net 1.1 has no x64 support, you are limited to running IIS 6 using 32 bit worker processes. The /3GB switch doesn't do anything on x64, but x64 natively gives 32bit processes 4 GB instead of 2GB, so you will have more memory available for your worker proces.</p> <p>You will need to set the AppPools to 32 bit:</p> <pre><code>cscript %SystemDrive%\inetpub\AdminScripts\adsutil.vbs set w3svc/AppPools/Enable32bitAppOnWin64 1 </code></pre> <p>You could consider tweaking the ASP.net memory from 60% of the application to 80%, which we've had some success.</p> <pre><code>&lt;system.web&gt; &lt;processModel memoryLimit="80" /&gt; &lt;/system.web&gt; </code></pre> <p>This can stress the app pool when you get up into the 1.2GB to 1.6 GB range.</p> <p>Other things to consider is that most ASP.Net 1.1 applications have no issues when run in a 2.0 application pool, allowing you to easily convert your 1.1 32 bit application to a 2.0 64 bit application. This doesn't require any recompilation, just change the app pool to 2.0, then switch to x64 using the above ADSUTIL.VBS script (set to 0 rather than 1).</p>
<p>My understanding is that there was a virtual address space limitation of 3 GB in ASP.NET 1.1, and that it was never made 64 bit compatible, though 2.0 was.</p> <p>You can get IIS 6.0 to run 32 bit (i.e. ASP.NET 1.1) on the 64 OS, but it will be in a 32 bit mode (along with anything else hosted, including ASP.NET 2.0 sites).</p> <p><a href="http://support.microsoft.com/?id=894435" rel="nofollow noreferrer">Microsoft article on switching between 32 bit and 64 bit</a></p>
15,096
<p>When using 3rd party libraries/components in production projects, are you rigorous about using only released versions of said libraries?</p> <p>When do you consider using a pre-release or beta version of a library (in dev? in production, under certain circumstances)? </p> <p>If you come across a bug or shortcoming of the library and you're already committed to using it, do you apply a patch to the library or create a workaround in your code?</p>
<p>I am a big fan of not coding something when someone else has a version that I could not code in a reasonable amount of time or would require me to become an expert on something that wouldn't matter in the long run. </p> <p>There are several open source components and libraries I have used in our production environment such as Quartz.NET, Log4Net, nLog, SharpFTPLibrary (heavily modified) and more. Quartz.NET was in beta when I first released an application using it into production. It was a very stable beta and I had the source code so I could debug an issue and there were a few. When I encountered a bug or an error I would fix it and post the issue to the bug tracker or author. I feel very comfortable using a beta product if the source is available for me to debug any issues or there is a strong following of developers hammering out any issues.</p>
<ul> <li>Yes. Unless there's a feature we really need in a beta version.</li> <li>There's no point using a beta version in dev if you aren't certain you'll use it in production. That just seems like a wasted exercise</li> <li>I'll use the patch. Why write code for something you've paid for?</li> </ul>
4,271
<p>I'm astonished that the <a href="http://commons.apache.org/collections/" rel="nofollow noreferrer">Apache Commons Collections</a> project still hasn't got around to making their library generics-aware. I really like the features provided by this library, but the lack of support for generics is a big turn-off. There is a <a href="http://larvalabs.com/collections/index.html" rel="nofollow noreferrer">Lavalabs fork of Commons Collections which does support generics</a>, which seems to claim backward compatibility, but when I tried updating to this version, my web application failed to start (in JBoss).</p> <p>My questions are:</p> <ul> <li>Whether anyone has successfully updated from Commons Collections to the fork mentioned above</li> <li>If Commons Collections has any plans to add support for generics</li> </ul> <p>BTW, I'm aware of Google collections, but am reluctant to use it until the API stabilises.</p> <p>Cheers, Don</p>
<p>There are contributions. Checkout the <a href="https://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&amp;mode=hide&amp;sorter/order=DESC&amp;sorter/field=priority&amp;resolution=-1&amp;pid=12310465&amp;fixfor=12312131" rel="nofollow noreferrer">jira</a>'s</p> <p>There is also a <a href="http://svn.apache.org/repos/asf/commons/proper/collections/branches/collections_jdk5_branch/" rel="nofollow noreferrer">JDK5 branch</a>.</p> <p>We do would like to add generics and update Commons Collections to 1.5 (and 1.6). The biggest problem is how to address backwards compatibility. And people have very different opinions there. For some of the Commons components the newer JDK almost asks for a rewrite for the new JDKs IMHO.</p> <p>During ApacheCon I felt the urge across several people to get this moving though. It's just a big task.</p> <p>Feel free to show up on dev@commons.apache.org</p> <p>cheers, Torsten</p>
<p>I can't imagine what reason you can have to don't use google collections. It's quite simple to use that library.</p> <p>For my work i use both, apache collections and google collections. </p> <p>can you explain more about why you can't use google collections?</p> <p>regards</p>
37,869
<p>What is the best way to unit test a method that doesn't return anything? Specifically in c#.</p> <p>What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.</p>
<p>If a method doesn't return anything, it's either one of the following</p> <ul> <li><strong>imperative</strong> - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)</li> <li><strong>informational</strong> - just notifying someone that something happened (without expecting action or response) respectively. </li> </ul> <p>Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.</p> <pre><code>void DeductFromBalance( dAmount ) </code></pre> <p>can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount</p> <p>Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.</p> <pre><code>void OnAccountDebit( dAmount ) // emails account holder with info </code></pre> <p>can be tested by verifying if the email is being sent</p> <p><em>Post more details about your actual method and people will be able to answer better.</em><br> <strong>Update</strong>: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested. </p> <pre><code>string[] ExamineLogFileForX( string sFileName ); void InsertStringsIntoDatabase( string[] ); </code></pre> <p>String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check <a href="https://stackoverflow.com/questions/31837/best-books-about-tdd">this thread</a> for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.<br> In the code it would be used like </p> <pre><code>InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) ); </code></pre>
<p>What ever instance you are using to call the void method , You can just use ,<code>Verfiy</code> </p> <p>For Example: </p> <p>In My case its <code>_Log</code> is the instance and <code>LogMessage</code> is the method to be tested:</p> <pre><code>try { this._log.Verify(x =&gt; x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure"); } Catch { Assert.IsFalse(ex is Moq.MockException); } </code></pre> <p>Is the <code>Verify</code> throws an exception due to failure of the method the test would Fail ?</p>
30,527
<p>I am using VSTO 3.0 and the ribbon designer gives me a ribbon that is apparently shared across documents.</p> <p>So if I have Document specific state( number of XML marked up tags say) that needs to show up in the ribbon( or a toggle button ) then all documents seem to share the ribbon instance</p> <p>How can I fix this TIA</p>
<p>Hook into an appropriate event (such as when the active document is changed) within the document model, and in that event invalidate the appropriate ribbon button (you'll need the id of the element from the original Ribbon xml you load).</p> <p>Then, when the refresh state callback for that button occurs, you can update the caption/image/enabled as required.</p>
<p>Hook into an appropriate event (such as when the active document is changed) within the document model, and in that event invalidate the appropriate ribbon button (you'll need the id of the element from the original Ribbon xml you load).</p> <p>Then, when the refresh state callback for that button occurs, you can update the caption/image/enabled as required.</p>
37,644
<p>I'm planning software that's an OLAP application at its heart (it helps analyse metering data) and is going to have some kind of star schema for its database, because the stored values will be looked at from different angles (time, source, type etc.) and the requests will be asking for aggregated data along these dimensions. The queries tend to deliver a lot of rows (up to some 100 000).</p> <p>My research on this topic (see also <a href="https://stackoverflow.com/questions/261743/good-fast-storage-strategy-for-facts-with-dynamically-evolving-dimensions">my question here</a>) seems to indicate that bitmap indices are a good way to search for data the way I'm planning to. However, I want to support multiple db engines, some of which do not offer bitmap indices on their tables (in particular, MySQL).</p> <p>Now, I can certainly build and maintain my own bitmap index and use it to look for row ids pointing to the fact table. However, I suspect that this is going to defeat the whole purpose of the index, because the database is still going to search for row ids in a B-Tree. Could somebody with more profound theoretical background or more experience tell me if I still gain anything, like not having to do slow JOINs on the dimension tables?</p> <p>I would also appreciate hints on what I have to evaluate if the answer is not straightforward.</p>
<p>Some DB engines that do not directly support bitmap indexes still have star optimisations that can do this type of query without hitting the fact table. SQL Server, for instance has a feature called Index Intersection that does something similar by constructing bitmaps on the fly to do the resolution. Microsoft <em>claims</em> that the performance of this is comparable to bitmap indexes. See <a href="https://stackoverflow.com/questions/126188/ms-sql-server-and-oracle-which-one-is-better-in-terms-of-scalability#126267">This posting</a> for a bit of fan-out on this topic.</p> <p>I'm not sure off the top of my head if MySQL does this, but Postgresql certainly does. IIRC some of the variants (Greenplum, I think) also directly support bitmap indexes and there was some talk of incorporating it in the main DB engine. I don't recall if this has been done yet.</p> <p>I think you will find that most modern DBMS platforms offer star query optimisations of one sort or another, so you probably don't need to re-invent the wheel. You may find one or two that cannot do this, but you always have the option of just not supporting them.</p>
<p>Some DB engines that do not directly support bitmap indexes still have star optimisations that can do this type of query without hitting the fact table. SQL Server, for instance has a feature called Index Intersection that does something similar by constructing bitmaps on the fly to do the resolution. Microsoft <em>claims</em> that the performance of this is comparable to bitmap indexes. See <a href="https://stackoverflow.com/questions/126188/ms-sql-server-and-oracle-which-one-is-better-in-terms-of-scalability#126267">This posting</a> for a bit of fan-out on this topic.</p> <p>I'm not sure off the top of my head if MySQL does this, but Postgresql certainly does. IIRC some of the variants (Greenplum, I think) also directly support bitmap indexes and there was some talk of incorporating it in the main DB engine. I don't recall if this has been done yet.</p> <p>I think you will find that most modern DBMS platforms offer star query optimisations of one sort or another, so you probably don't need to re-invent the wheel. You may find one or two that cannot do this, but you always have the option of just not supporting them.</p>
34,259