input
stringlengths
51
42.3k
output
stringlengths
18
55k
Reinstall development stack <p>I need to relocate my iPhone development stack to a different machine. What do I need to do in preparation and are there any gotchas?</p> <p>Thanks! </p>
<p>You need to export and transport your private keys, used for signing, from Keychain Access.</p> <p>See page 10 in the "Program Portal User Guide" available from the "Program Portal", where you manage your certificates at apple.com</p>
sql server 2008 express/enterprise <p>I am logged with windows authentication and create an entry/user in the login table.</p> <p>The new testuser has a sql-server authentication, but if a try to login local or remote, only fault 18456.</p> <p>Is there any trick... this should be so simple as explained... but should work?</p>
<p>i believe it's just that the SQL server authentication is disabled by default installation. go check your SQL server properties in management studio (right-click on the server in object explorer, then select 'properties'), select 'security' menu in the left panel. you have the 'server authentication' option on the top of the right-side options panel with 2 options. make sure that the 'SQL server and windows authentication mode' is selected, not the 'windows authentication mode' which is default.</p>
Do you know of a Java library to access the native linux api? <p>Do you know of a Java library to access the native linux api?</p> <p>I guess something like this must use JNI. So be it.</p>
<p>Have a look at <a href="https://github.com/twall/jna" rel="nofollow">JNA.</a></p> <p>Here is the summary of JNA from their home page.</p> <blockquote> <p>JNA provides Java programs easy access to native shared libraries (DLLs on Windows) without writing anything but Java code—no JNI or native code is required. This functionality is comparable to Windows' Platform/Invoke and Python's ctypes. Access is dynamic at runtime without code generation.</p> </blockquote> <p>See their <a href="https://github.com/twall/jna/blob/master/www/GettingStarted.md" rel="nofollow">getting started</a> page for some samples. Like calling native printf.</p>
wx's idle and UI update events in PyQt <p>wx (and wxPython) has two events I miss in PyQt: </p> <ul> <li><code>EVT_IDLE</code> that's being sent to a frame. It can be used to update the various widgets according to the application's state</li> <li><code>EVT_UPDATE_UI</code> that's being sent to a widget when it has to be repainted and updated, so I can compute its state in the handler</li> </ul> <p>Now, PyQt doesn't seem to have these, and the PyQt book suggests writing an <code>updateUi</code> method and calling it manually. I even ended up calling it from a timer once per 0.1 seconds, in order to avoid many manual calls from methods that may update the GUI. Am I missing something? Is there a better way to achieve this?</p> <p><hr /></p> <p>An example: I have a simple app with a Start button that initiates some processing. The start button should be enabled only when a file has been opened using the menu. In addition, there's a permanent widget on the status bar that displays information.</p> <p>My application has states:</p> <ol> <li>Before the file is opened (in this state the status bar show something special and the start button is disabled)</li> <li>File was opened and processing wasn't started: the start button is enabled, status bar shows something else</li> <li>The processing is running: the start button now says "Stop", and the status bar reports progress</li> </ol> <p>In Wx, I'd have the update UI event of the button handle its state: the text on it, and whether it's enabled, depending on the application state. The same for the status bar (or I'd use EVT_IDLE for that).</p> <p>In Qt, I have to update the button in several methods that may affect the state, or just create a update_ui method and call it periodically in a timer. What is the more "QT"-ish way?</p>
<p>The use of EVT_UPDATE_UI in wxWidgets seems to highlight one of the fundamental differences in the way wxWidgets and Qt expect developers to handle events in their code.</p> <p>With Qt, you connect signals and slots between widgets in the user interface, either handling "business logic" in each slot or delegating it to a dedicated method. You typically don't worry about making separate changes to each widget in your GUI because any repaint requests will be placed in the event queue and delivered when control returns to the event loop. Some paint events may even be merged together for the sake of efficiency.</p> <p>So, in a normal Qt application where signals and slots are used to handle state changes, there's basically no need to have an idle mechanism that monitors the state of the application and update widgets because those updates should occur automatically.</p> <p>You would have to say a bit more about what you are doing to explain why you need an equivalent to this event in Qt.</p>
ie save onunload bug <p>I have a dynamic ajaxy app, and I save the state when the user closes the explorer window. It works ok in all browsers but in IE there is problem. After I close twice the application tab, i can't connect anymore to the server.</p> <p>My theory is that the connection to the server fail to complete while the tab is being closed and somehow ie7 thinks that it has 2 outstanding connections to the server and therefore queues new connections indefinitely.</p> <p>Any one has experienced this, any workaround or solution?</p>
<p>In IE if you use long-polling AJAX request, you have to close down the XHR connection on 'unload'. Otherwise it will be kept alive by browser, even if you navigate away from your site. These kept alive connections will then cause the hang, because your browser will hit the maximum open connection limit.</p> <p>This problem does not happen in other browsers.</p>
Is it possible to speed up a recursive file scan in PHP? <p>I've been trying to replicate <a href="http://www.gnu.org/software/findutils/">Gnu Find</a> ("find .") in PHP, but it seems impossible to get even close to its speed. The PHP implementations use at least twice the time of Find. Are there faster ways of doing this with PHP?</p> <p>EDIT: I added a code example using the SPL implementation -- its performance is equal to the iterative approach</p> <p>EDIT2: When calling find from PHP it was actually slower than the native PHP implementation. I guess I should be satisfied with what I've got :)</p> <pre><code>// measured to 317% of gnu find's speed when run directly from a shell function list_recursive($dir) { if ($dh = opendir($dir)) { while (false !== ($entry = readdir($dh))) { if ($entry == '.' || $entry == '..') continue; $path = "$dir/$entry"; echo "$path\n"; if (is_dir($path)) list_recursive($path); } closedir($d); } } // measured to 315% of gnu find's speed when run directly from a shell function list_iterative($from) { $dirs = array($from); while (NULL !== ($dir = array_pop($dirs))) { if ($dh = opendir($dir)) { while (false !== ($entry = readdir($dh))) { if ($entry == '.' || $entry == '..') continue; $path = "$dir/$entry"; echo "$path\n"; if (is_dir($path)) $dirs[] = $path; } closedir($dh); } } } // measured to 315% of gnu find's speed when run directly from a shell function list_recursivedirectoryiterator($path) { $it = new RecursiveDirectoryIterator($path); foreach ($it as $file) { if ($file-&gt;isDot()) continue; echo $file-&gt;getPathname(); } } // measured to 390% of gnu find's speed when run directly from a shell function list_gnufind($dir) { $dir = escapeshellcmd($dir); $h = popen("/usr/bin/find $dir", "r"); while ('' != ($s = fread($h, 2048))) { echo $s; } pclose($h); } </code></pre>
<p>I'm not sure if the performance is better, but you could use a recursive directory iterator to make your code simpler... See <code>RecursiveDirectoryIterator</code> and <a href="http://uk.php.net/SplFileInfo" rel="nofollow">'SplFileInfo`</a>.</p> <pre><code>$it = new RecursiveDirectoryIterator($from); foreach ($it as $file) { if ($file-&gt;isDot()) continue; echo $file-&gt;getPathname(); } </code></pre>
What happened to my VS Team project bindings? <p>I'm new to using Team Explorer, I create a new project in source control using VSTS, then I see the plus signs, check marks etc.</p> <p>Then I closed the project and reopened it, all the plus signs and check marks are gone as if the project is not under source control.</p> <p>Why is this happening I wonder?</p>
<p>It's probably been disconnected. Use the Source Code Control menu item on the File menu to reconnect to your TFS server.</p>
Should I sign a non-competition clause in freelance contract? <p>I'm trying to establish myself as an iPhone freelancer, and are currently negotiating with a startup about a bigger project. They have expressed that they want me to sign a non-competition agreement, so that I wouldn't be allowed to develop a similar product for companies in competition on the same geographical market. Needless to say, I don't really like this.</p> <p>Is this a common practice? If so, how common? Would you sign it?</p>
<p>They're common. If you can get them to remove it, do so. It's never in your interest to have one. That said, they aren't terrible if they are narrowly scoped and of a reasonable time limit. You don't want one saying you cannot write any other iPhone apps. One saying you can't write the same sort of app is probably acceptable. Read the language and determine how broadly it can be viewed.</p> <p>Whether you end up having to sign one or not depends largely on the power in the relationship. If you really need the work or if your skills can't command a lot of respect, you'll have to sign. If, on the other hand, you bring unique skills and the company really wants you, you have leverage and can likely get it removed.</p>
How do I read / write gzipped files? <p>How do I read / write gzipped files in C++?</p> <p>The <code>iostream</code> wrapper classes <a href="http://www-d0.fnal.gov/d0dist/dist/packages/lm%5Faccess/devel/lm%5Faccess/gzstream.hpp">here</a> look good, and here is a simple usage example:</p> <pre><code>gz::igzstream in(filename); std::string line; while(std::getline(in, line)){ std::cout &lt;&lt; line &lt;&lt; std::endl; } </code></pre> <p>But I wasn't able to actually link it (although I have a <code>/usr/lib/libz.a</code>). A simple</p> <pre><code>g++ test-gzstream.cpp -lz </code></pre> <p>didn't do it (<code>undefined reference to gz::gzstreambase::~gzstreambase()</code>).</p>
<p>Consider using the Boost zip filters. According to them, it supports <code>bzip</code>, <code>gzip</code> and <code>zlib</code> format. </p> <ul> <li><a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/iostreams/doc/classes/zlib.html">boost zlib</a></li> <li><a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/iostreams/doc/classes/gzip.html">boost gzip</a></li> <li><a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/iostreams/doc/classes/bzip2.html">boost bzip2</a></li> </ul>
How to reuse an ostringstream? <p>I'd like to clear out and reuse an ostringstream (and the underlying buffer) so that my app doesn't have to do as many allocations. How do I reset the object to its initial state?</p>
<p>I've used a sequence of clear and str in the past:</p> <pre><code>// clear, because eof or other bits may be still set. s.clear(); s.str(""); </code></pre> <p>Which has done the thing for both input and output stringstreams. Alternatively, you can manually clear, then seek the appropriate sequence to the begin:</p> <pre><code>s.clear(); s.seekp(0); // for outputs: seek put ptr to start s.seekg(0); // for inputs: seek get ptr to start </code></pre> <p>That will prevent some reallocations done by <code>str</code> by overwriting whatever is in the output buffer currently instead. Results are like this:</p> <pre><code>std::ostringstream s; s &lt;&lt; "hello"; s.seekp(0); s &lt;&lt; "b"; assert(s.str() == "bello"); </code></pre> <p>If you want to use the string for c-functions, you can use <code>std::ends</code>, putting a terminating null like this:</p> <pre><code>std::ostringstream s; s &lt;&lt; "hello"; s.seekp(0); s &lt;&lt; "b" &lt;&lt; std::ends; assert(s.str().size() == 5 &amp;&amp; std::strlen(s.str().data()) == 1); </code></pre> <p><code>std::ends</code> is a relict of the deprecated <code>std::strstream</code>, which was able to write directly to a char array you allocated on the stack. You had to insert a terminating null manually. However, <code>std::ends</code> is not deprecated, i think because it's still useful as in the above cases. </p>
Castle Windsor Cannot find my Service Type <p>Trying to make use of the Castle Windsor IoC. I have a very simple application. My interfaces exist in Test.Services namespace. I get the following exception when compiling:</p> <p>"The type name Test.Services.IParse, Test.Services could not be located"</p> <p>This is my app.config:</p> <pre><code>&lt;configuration&gt; &lt;configSections&gt; &lt;section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" /&gt; &lt;/configSections&gt; &lt;castle&gt; &lt;components&gt; &lt;component id="HtmlTitleRetriever" type="Test.HTMLTitleRetriever, Test"&gt; &lt;/component&gt; &lt;component id="FileParser" service="Test.Services.IParse, Test.Services" type="Test.FileParser, Test"&gt; &lt;/component&gt; &lt;component id="FileDownloader" service="Test.Services.IDownload, Test.Services" type="Test.FileDownloader, Test"&gt; &lt;/component&gt; &lt;/components&gt; &lt;/castle&gt; </code></pre> <p>Can someone tell me what I'm missing?</p> <p>Thanks</p> <p>-Nick</p>
<p>Stupid question, but are you certain that the assembly containing the class you register gets actually copied to the output directory?</p>
OpenGL vertex layout <p>The problem goes like this: if I have a vertex structure defined with only the position (3 floats), with a total size of 12 bytes, things work perfectly. However, if I try to use unsigned bytes or shorts for the position components (3 or 6 bytes per vertex) it crashes with an access violation at glDrawArrays. Any idea why?</p>
<p>Looks like I had to use unsigned types.</p>
Sharepoint form layout in VB <p>OKay, I'm from a PHP background, but I've just been tasked with developing some custom Web Parts in SharePoint. I've figured out how to create and deploy a basic "Hello world" web part in VB. Okay so far.</p> <p>What I'm stuck on is a really basic, stupid point - how the hell do I lay out things in a VB web part?</p> <p>For an example, here's a label and a textbox:</p> <pre><code>protected overrides sub createchildcontrols() mybase.createchildcontrols dim mylabel as new label dim mytextbox as new textbox mylabel.text ="My label text" mytextbox.text ="My textbox" me.controls.add(mylabel) me.controls.add(mytextbox) </code></pre> <p>How would I, for example, get mylabel and my textbox to appear on different lines, rather than running one after the other as they do now? In PHP I'd just wrap them in some top break them onto differnt lines, but how do I do it here?</p>
<p>There are a number of ways to go about it. The easiest, if you really just want the controls to appear on different lines would be to add an ASP.net <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.literalcontrol.aspx" rel="nofollow">LiteralControl</a> with a BR tag between them.</p> <p>Aside from that, you can always use the ASP.net formatting controls, like <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.table.aspx" rel="nofollow">Table</a> to break your controls into sections for output.</p> <p>Additionaly, everything that derives from WebControl has an Attribues and CssClass property for setting formatting based on style-sheets you can use.</p> <p>The last method, and the most customizable, but hardest to maintain and change, would be to override the webpart's Render method and generate your HTML completely by hand in the WebPart.</p> <p>Alternately, you could scrap this altogether, and employ the <a href="http://www.codeplex.com/smartpart" rel="nofollow">SmartPart</a> to develop ASP.net user controls for use inside of SharePoint, giving you the options to use the Visual Studio designer tools to layout your controls on the form.</p>
Are there any good tutorials on linking an iPhone app to a database? <p>I have built an iPhone app that needs to pull data from a server. First I need to figure out what kind of server I will need. I'm a bit familiar with MySQL but was wondering if anyone had better suggestions on a backend. My app will have two tables that need to be populated by data residing on a server. Also, a user can submit data to this database which in turns populates the previously mentioned tables.</p> <p>If you have any tips or tutorials, code snippets, etc. it would be really appreciated!</p> <p>*Edit: I should mention this IS a remote database</p>
<p>Well if it's a remote server your thinking about then you should be looking into implementing some kind of service architecture like Web Services over SOAP or REST.</p> <p>If the data stays on the iPhone than by all means use SQLite as it's fast and lightweight.</p> <p>I would recommend starting with SQLite and local data first. Then when you have your main program logic, flow and UI complete, replacing the SQLite with Web Service calls.</p>
Tracking undisposed Disposable objects <p><strong>Is there a tool that can scan your code and determine which objects that implement IDisposable are not being disposed in a code base at compile time or runtime?</strong></p> <p>I have possible areas in the code that are not disposing objects but it's hard to look back and see which objects require this in the first place.</p>
<p>There is a lot of static analysis tooling, which can help here.</p> <p>Both CodeRush/Refactor Pro and Resharper will, at code time, in Visual Studio, show you undisposed objects.</p> <p>And FxCop, now packaged as part of Visual Studio Code Analysis can generate compile time warnings for undisposed locals and class members.</p>
How do I capture the output of a command to a file descriptor in Bourne shell? <p>The standard way to capture command output in Bourne shell is to use the <code>$()</code> syntax:</p> <pre><code>output=$(mycommand) </code></pre> <p>For commands that have a lot of output, however, this requires the shell allocate memory for the whole thing as one long string. I'd prefer to find something that does the moral equivalent of the Unix C function <code>popen</code>, to get a new file descriptor I could <code>read</code> from:</p> <pre><code>newfd=popen(mycommand) while read -u $newfd LINE; do #process output done </code></pre> <p>Is this even possible?</p>
<pre><code>#!bash ls | while read X do echo $X is a directory entry done </code></pre> <p>Replace 'ls' with the command of your choice</p>
Algorithm to return the maximum possible sum of subsequences in a sequence <pre><code>int maxSumRec(const vector&lt;int&gt; &amp;a, int left, int right){ if (left == right){ if (a[left] &gt; 0){ return a[left]; } else return 0; } int center = (left + right)/2; int maxLeftSum = maxSumRec(a, left, center); int maxRightSum = maxSumRec(a, center+1, right); int leftBorderSum = 0; int leftBorderMax = 0; for (int i = center; i &gt;= left; i--){ leftBorderSum += a[i]; if (leftBorderSum &gt; leftBorderMax){ leftBorderMax = leftBorderSum; } } int rightBorderSum = 0; int rightBorderMax = 0; for (int i = center+1; i &lt;= right; i++){ rightBorderSum += a[i]; if (rightBorderSum &gt; rightBorderMax){ rightBorderMax = rightBorderSum; } } int crossSum = rightBorderMax + leftBorderMax; return max3(maxLeftSum, maxRightSum, crossSum); } </code></pre> <p>This is a O(NlogN) algorithm, I know it is not the best one. But just have several questions on it:</p> <ol> <li><p>in the first if statement, why return 0 if a[left] &lt; 0?</p></li> <li><p>why need the 2 for loops? isn't the logic like this, find the max of the first half and the second half, and then add them to see if the addition is bigger than either. if it is this case, then we can directly jump to the last 2 lines?</p></li> </ol> <p>Thanks very much,</p> <p>Yue Harriet</p>
<blockquote> <ol> <li>in the first if statement, why return 0 if a[left] &lt; 0?</li> </ol> </blockquote> <p>Because then the empty subsequence has the maximum sum, which is 0.</p>
Online mnesia recovery from network partition <p>Is it possible to recover from a network partition in an mnesia cluster without restarting any of the nodes involved? If so, how does one go about it?</p> <p>I'm interested specifically in knowing:</p> <ul> <li>How this can be done with the standard OTP mnesia (v4.4.7)</li> <li>What custom code if any one needs to write to make this happen (e.g. subscribe to mnesia running_paritioned_network events, determine a new master, merge records from non-master to master, force load table from the new master, clear running parititioned network event -- example code would be greatly appreciated).</li> <li>Or, that mnesia categorically does not support online recovery and requires that the node(s) that are part of the non-master partition be restarted.</li> </ul> <p>While I appreciate the pointers to general distributed systems theory, in this question I am interested in erlang/OTP mnesia only.</p>
<p>After some experimentation I've discovered the following:</p> <ul> <li>Mnesia considered the network to be partitioned if between two nodes there is a node disconnect and a reconnect without an mnesia restart. </li> <li>This is true even if no Mnesia read/write operations occur during the time of the disconnection.</li> <li>Mnesia itself must be restarted in order to clear the partitioned network event - you cannot <code>force_load_table</code> after the network is partitioned.</li> <li>Only Mnesia needs to be restarted in order to clear the network partitioned event. You don't need to restart the entire node. </li> <li>Mnesia resolves the network partitioning by having the newly restarted Mnesia node overwrite its table data with data from another Mnesia node (the startup table load algorithm).</li> <li>Generally nodes will copy tables from the node that's been up the longest (this was the behaviour I saw, I haven't verified that this explicitly coded for and not a side-effect of something else). If you disconnect a node from a cluster, make writes in both partitions (the disconnected node and its old peers), shutdown all nodes and start them all back up again starting the disconnected node first, the disconnected node will be considered the master and its data will overwrite all the other nodes. There is no table comparison/checksumming/quorum behaviour.</li> </ul> <p>So to answer my question, one can perform semi online recovery by executing <code>mnesia:stop(), mnesia:start()</code> on the nodes in the partition whose data you decide to discard (which I'll call the losing partition). Executing the <code>mnesia:start()</code> call will cause the node to contact the nodes on the other side of the partition. If you have more than one node in the losing partition, you may want to set the master nodes for table loading to nodes in the winning partition - otherwise I think there is a chance it will load tables from another node in the losing partition and thus return to the partitioned network state.</p> <p>Unfortunately mnesia provides no support for merging/reconciling table contents during the startup table load phase, nor does it provide for going back into the table load phase once started. </p> <p>A merge phase would be suitable for ejabberd in particular as the node would still have user connections and thus know which user records it owns/should be the most up-to-date for (assuming one user conneciton per cluster). If a merge phase existed, the node could filter userdata tables, save all records for connected users, load tables as per usual and then write the saved records back to the mnesia cluster.</p>
Why aren't checkboxes/radiobuttons and options resetable if they were set by PHP? <p>Working with XHTML 1.1</p> <p>I have this login page managed in php. It contains several checkboxes, radiobuttons and a dropdownlist.</p> <p>There's a lot of formchecking behind it and if something doesn't check out, the page reloads and all values are filled back into their place, except for passwords.</p> <p>This means the <code>&lt;select&gt;</code>, <code>&lt;input type="radio"</code> and <code>&lt;input type="checkbox"</code> elements that have been selected are re-selected.</p> <p>Yet when I look at the source code, the <code>checked="checked"</code> and <code>selected="selected"</code> pieces are missing. But seeing as how the reloaded page has them selected, they must have been implemented.</p> <p>Yet when I click my <code>&lt;input type="reset"</code> button, nothing happens. The don't get de-selected.</p> <p>Fun thing is, when I select some other checkboxes, radiobuttons and change the select, the reset does work, but only on the newly clicked checkboxes and radiobuttons.</p> <p>Even more weird is the fact that when I click reset, the radiobuttons, checkboxes and selects don't clear themselves, they jump back to the one that was checked or selected when PHP forced the page to reload.</p> <p>What's going on here?</p> <p>Using firefox by the way, checking IE now.</p> <p>EDIT: IE same problem.</p>
<p>If you're using "View Source" and the script is setting aggressive <code>no-cache</code> headers, it's possible that you're not seeing the source code of what's being displayed. Try it in something that shows the live DOM, like Firebug or the DOM Inspector.</p>
Regex: Get Filename Without Extension in One Shot? <p>I want to get just the filename using regex, so I've been trying simple things like</p> <pre><code>([^\.]*) </code></pre> <p>which of course work only if the filename has one extension. But if it is <code>adfadsfads.blah.txt</code> I just want <code>adfadsfads.blah</code>. How can I do this with regex?</p> <p>In regards to David's question, 'why would you use regex' for this, the answer is, 'for fun.' In fact, the code I'm using is simple</p> <pre><code>length_of_ext = File.extname(filename).length filename = filename[0,(filename.length-length_of_ext)] </code></pre> <p>but I like to learn regex whenever possible because it always comes up at Geek cocktail parties.</p>
<p>Try this:</p> <pre><code>(.+?)(\.[^.]*$|$) </code></pre> <p>This will:</p> <ul> <li>Capture filenames that start with a dot (e.g. ".logs" is a file named ".logs", not a file extension), which is common in Unix.</li> <li>Gets everything but the last dot: "foo.bar.jpeg" gets you "foo.bar".</li> <li>Handles files with no dot: "secret-letter" gets you "secret-letter".</li> </ul> <p><hr/></p> <p>Note: as commenter j_random_hacker suggested, this performs as advertised, but you might want to precede things with an anchor for readability purposes.</p>
How can I compile Java code in Windows without installing the whole JDK? <p>Let’s say the runtime environment (version 1.6.0_01-b06) is already in place, but since I lack administrative privileges in this particular PC, the JDK can’t be installed. So, is there any portable JDK or standalone Java compiler for Windows that doesn’t require installation?</p>
<p>You might try taking the tools.jar file from the JDK (you would have to copy it over from another machine) and see if that worked.</p> <p>javac is essentially a small exe that starts the VM with the specific class for the compiler.</p> <p>Also, there is nothing (that I am aware of) about the JDK install that you couldn't do with a copy of it from another machine. So get on a machine you can install the JDK on, install it, and then copy the files to a place on the machine that you lack the rights to and it should work.</p>
LINQ for diffing sets <p>I have the following arrays:</p> <pre><code>var original= new int[] { 2, 1, 3 }; var target = new int[] { 1, 3, 4 }; enum Operation {Added,Removed} </code></pre> <p>I would like to execute a LINQ query that would return the following: </p> <pre><code>{{2,Removed},{4,Added}} </code></pre> <p>Limitation: I would like LINQ to perform this very efficiently and avoid and O(n^2) style algorithms. </p>
<p>Perhaps a LINQ solution is not the best option in this case.</p> <p>This will produce a dictionary with the result that you want.</p> <pre><code>Dictionary&lt;int, Operation&gt; difference = new Dictionary&lt;int,Operation&gt;(); foreach (int value in original) { difference.Add(value, Operation.Removed); } foreach (int value in target) { if (difference.ContainsKey(value)) { difference.Remove(value); } else { difference.Add(value, Operation.Added); } } </code></pre> <p>To keep the size of the dictionary down, perhaps it's possible to loop the enumerations in parallell. I'll have a look at that...</p> <p>Edit:<br /> Here it is:</p> <pre><code>Dictionary&lt;int, Operation&gt; difference = new Dictionary&lt;int,Operation&gt;(); IEnumerator&lt;int&gt; o = ((IEnumerable&lt;int&gt;)original).GetEnumerator(); IEnumerator&lt;int&gt; t = ((IEnumerable&lt;int&gt;)target).GetEnumerator(); bool oActive=true, tActive=true; while (oActive || tActive) { if (oActive &amp;&amp; (oActive = o.MoveNext())) { if (difference.ContainsKey(o.Current)) { difference.Remove(o.Current); } else { difference.Add(o.Current, Operation.Removed); } } if (tActive &amp;&amp; (tActive = t.MoveNext())) { if (difference.ContainsKey(t.Current)) { difference.Remove(t.Current); } else { difference.Add(t.Current, Operation.Added); } } } </code></pre> <p>Edit2:<br /> I did some performance testing. The first version runs 10%-20% faster, both with sorted lists and randomly ordered lists.</p> <p>I made lists with numbers from 1 to 100000, randomly skipping 10% of the numbers. On my machine the first version of the code matches the lists in about 16 ms.</p>
code to change file extension (up for review) <p>I am using the following piece of C code to change file extension.</p> <p>{</p> <pre><code> #define EVAL_MAX_LEN (300) int nLen; char szOut [EVAL_MAX_LEN] = {0}; char szPath [EVAL_MAX_LEN] = "/db/file/face.bmp"; // Get string length !!! nLen = strlen (szPath); if ((nLen &gt; 0) &amp;&amp; (nLen &lt; EVAL_MAX_LEN)) { while (nLen) { // Check for extension character !!! if (szPath [nLen] == '.') { szPath [nLen] = '\0'; break; } nLen --; }//while (nLen ... // Create output file name and with new extension sprintf (szOut, "%s.txt", szPath); }// if ((nLen &gt; 0) &amp;&amp; (nLen &lt; EVAL_MAX_LEN ... </code></pre> <p>}</p> <p>Any suggestion for a better and more elegant code is welcome. I also know that in Windows we can use _splitpath to do this in an elegant manner. But right now, I am using this code in Linux.</p>
<p>You should use <code>snprintf()</code> instead of <code>sprintf()</code> to avoid a potential buffer overflow. You can also use <a href="http://linux.die.net/man/3/strrchr" rel="nofollow"><code>strrchr(3)</code></a> to find the last period, instead of coding your own loop. However, two things to be careful of:</p> <ol> <li>What if the input file has no extension, i.e. there is no dot in the path name?</li> <li>What if the input file has no extension, but one of the folders in the path name has a dot in it? For example: <code>"/home/joeuser/dotted.folder/thefile"</code></li> </ol> <p>Make sure you handle both of those cases appropriately.</p>
converting char** to char* or char <p>I have a old program in which some library function is used and i dont have that library.</p> <p>So I am writing that program using libraries of c++. In that old code some function is there which is called like this</p> <p>*string = newstrdup("Some string goes here");</p> <p>the string variable is declared as char **string;</p> <p>What he may be doing in that function named "newstrdup" ? I tried many things but i dont know what he is doing ... Can anyone help </p>
<p>The function is used to make a copy of c-strings. That's often needed to get a writable version of a string literal. They (string literals) are itself not writable, so such a function copies them into an allocated writable buffer. You can then pass them to functions that modify their argument given, like <code>strtok</code> which writes into the string it has to tokenize. </p> <p>I think you can come up with something like this, since it is called <strong><em>new</strong>strdup</em>:</p> <pre><code>char * newstrdup(char const* str) { char *c = new char[std::strlen(str) + 1]; std::strcpy(c, str); return c; } </code></pre> <p>You would be supposed to free it once done using the string using</p> <pre><code>delete[] *string; </code></pre> <p>An alternative way of writing it is using <code>malloc</code>. If the library is old, it may have used that, which C++ inherited from C:</p> <pre><code>char * newstrdup(char const* str) { char *c = (char*) malloc(std::strlen(str) + 1); if(c != NULL) { std::strcpy(c, str); } return c; } </code></pre> <p>Now, you are supposed to free the string using <code>free</code> when done:</p> <pre><code>free(*string); </code></pre> <p>Prefer the first version if you are writing with C++. But if the existing code uses <code>free</code> to deallocate the memory again, use the second version. Beware that the second version returns <code>NULL</code> if no memory is available for dup'ing the string, while the first throws an exception in that case. Another note should be taken about behavior when you pass a <code>NULL</code> argument to your <code>newstrdup</code>. Depending on your library that may be allowed or may be not allowed. So insert appropriate checks into the above functions if necessary. There is a function called <code>strdup</code> available in POSIX systems, but that one allows neither <code>NULL</code> arguments nor does it use the <code>C++</code> operator new to allocate memory. </p> <p>Anyway, i've looked with google codesearch for <code>newstrdup</code> functions and found quite a few. Maybe your library is among the results:</p> <p><a href="http://www.google.com/codesearch?hl=en&amp;start=10&amp;sa=N&amp;q=newstrdup" rel="nofollow">Google CodeSearch, newstrdup</a> </p>
Refactoring fun: dealing with complicated state <p>Let's say we have a web app out there that is supposed to have a user fill out a form, and then it creates a ticket in the backend workflow engine. This form is going to continue to be the portal for the customer to view what's going on. Some forms go straight to ticket creation; others have to get approved by someone else before generating a ticket, and they can also be denied. This thing sends out emails, tracks answers to the questions of the form, tracks any uploaded attachments, and also logs "updates" as various actions are made to change the state of the form.</p> <p>The business logic to decide what all to do when the form is first submitted or saved is starting to get hairy and I'm looking on ways to refactor it. I've started to look at state/strategy patterns, but it seems like all the logic just needs to get lumped together in one place eventually anyway. Plus, with all the dependencies on answers/attachments/log entries, it makes it complicated to inject mocks into because it has so much that it has to track.</p> <p>Here's a pseudocode-ish layout of the form object's "save" functionality, simplified down...it's starting to get nasty and I'm trying to see if I can make it cleaner somehow.</p> <pre><code>if(this.isvalid) { if(isNewForm &amp;&amp; !this.needsApproval) //just created, so start up a ticket { CreateTicket(); } if(!isNewForm &amp;&amp; justApproved) //pulled from the DB earlier, and was just approved { CreateTicket(); } if(!isNewForm &amp;&amp; justDenied) //pulled from the DB earlier, and was just denied { this.needsApproval = false; this.closed = true; } if(isNewForm) { SendNewFormEmail(); if(this.NeedsApproval) { SendNeedsApprovalEmail(); } this.CommentEntries.Add("Request submitted."); } else if(justApproved) { SendApprovalEmail(); this.CommentEntries.Add("Request approved."); } else if(justDenied) { SendDenialEmail(); this.CommentEntries.Add("Request denied."); } this.Save(); this.Answers.Save(); this.Attachments.Save(); this.CommentEntries.Save(); } </code></pre>
<p>I've been thinking about state machines alot lately and I found the following proposal very promising. I wish I could tell you it works really great but I have not gotten that far yet. I can tell you that it looks better than any solution I've tried to date. Here's the link.. <a href="http://www.eventhelix.com/RealtimeMantra/HierarchicalStateMachine.htm" rel="nofollow">Hierarchical State Machine</a></p>
cell editing in JTable <p>Im doin a project using JTable, i want to make my table cells editable. I used, public boolean isCellEditable(int row, int column) { <br /> return true; <br /> } My problem is, the cells are ediable but once after entering data into one cell and move on to the next, the previous data gets erased... kindly any one help me...</p>
<p>Override setValueAt(Object value, int row, int col) method as well. It should store entered data, so getValueAt(int row, int col) method can return new value. Something like this:</p> <pre><code>private String[][] data; public Object getValueAt(int row, int col) { return data[row][col]; } public void setValueAt(Object value, int row, int col) { data[row][col] = value; } </code></pre>
Application Build not loaded on device <p>When I tried to upload a build on device it give the following error. Your mobile device has encountered an unexpected error <code>(0xE8000001)</code></p> <p>I am unable to solve this problem. Can anyone tell me why this is happening?</p>
<p>Anytime i get an unexpected error i hard reboot my device by holding down the home and lock buttons until the apple logo appears. No idea what causes it, but the reboot usually fixes it.</p>
Force TFS to use relative paths or update locations <p>I installed TFS 2008 Workgroup Edition a while back, and everything was running fine.</p> <p>Recently I tried opening TFS to a couple of friends so that we can collaborate on a project. The Source Control portion is working correctly, but the Documents and Reports folders are not available (they have red crosses on them). </p> <p>When I looked at the properties, I noticed that the URLs were using my internal machine name, not the external address (e.g. <code>http://INTERNALNAME/Sites/MyProject</code> instead of <code>http://www.EXTERNAL-NAME.com/Sites/MyProject</code>).</p> <p>My preference would be to somehow use relative paths, so that if I ever decide to stop exposing TFS to the outside, I don't have to do anything. </p> <p>I realize this may not be possible because TFS cannot make the assumption that Reporting Services and Share Point are on the same machine.... so is there at least an easy way to assign a new server name?</p>
<p>Yeah, relative paths cannot be used due to the way that TFS works - it sends back the full URL's to the Sharepoint and Reporting Services servers to the client machine.</p> <p>To update the URL's that are used for sharepoint and reporting services to match your fully qualified domain name you want to use TFSAdminUtil. Remote desktop to the TFS server, open a Command Prompt window, and change directories to %ProgramFiles%\Microsoft Visual Studio 2008 Team Foundation Server\Tools.</p> <p>At the command prompt, type the following command (all on one line):</p> <pre><code> TfsAdminUtil ConfigureConnections /SharepointUri:BaseSiteURL /SharepointSitesUri:SharePointSite /SharepointAdminUri:SharePointAdministration /ReportsUri:ReportsUri /ReportServerUri:ReportServer </code></pre> <p>Replacing the following strings</p> <ul> <li><strong>SharePointSite</strong> is the new URI for the SharePoint Products and Technologies site collection.</li> <li><strong>SharePointAdministration</strong> is the new URI for the SharePoint Central Administration Web site (used for new team project creation)</li> <li><strong>ReportsUri</strong> is the new URI for SQL Server Reporting Services.</li> <li><strong>ReportServer</strong> is the new URI for the ReportsService.asmx Web service.</li> </ul> <p>BTW - If you have installed SP1 for Visual Studio Team System 2008 Team Foundation Server, the <strong>ReportServer</strong> parameter will not function correctly and you have to stick /ReportService.asmx on the end. For more information about this problem and its resolution, see this KB: <a href="http://go.microsoft.com/fwlink/?LinkID=131656" rel="nofollow">Team Foundation Server 2008 SP1 TfsAdminUtil.exe 'ConfigureConnections' fails to properly set ReportServerUri</a>.</p> <p>For example, the following command would work with TFS 2008 SP1:</p> <pre><code>TfsAdminUtil ConfigureConnections /SharepointUri:http://tfs.external-name.com /SharepointSitesUri:http://tfs.external-name.com/Sites /SharepointAdminUri:http://tfs.external-name.com:17483 /ReportsUri:http://tfs.external-name.com/Reports /ReportServerUri:http://tfs.external-name.com/ReportServer/ReportService.asmx </code></pre> <p>One last thing to note is that if you are accessing your TFS server externally, then it is recommended that you do this using HTTPS to encrypt the TFS traffic. For more information on this configuration see the post on the MSDN site: <a href="http://msdn.microsoft.com/en-us/library/aa833872.aspx" rel="nofollow">Walkthrough: Setting up Team Foundation Server with Secure Sockets Layer (SSL) and an ISAPI Filter</a></p>
WebMethod response format <p>I recently saw a jQuery example where a POST was made to "Default.aspx/Test", where Test was a WebMethod in Default.aspx, and the content-type for the request was "application/json".</p> <p>The reply from the WebMethod was in JSON. I always thought WebMethods returned SOAP responses, but if I'm interpreting this code correctly, like I said, the WebMethod returns JSON.</p> <p>Is this correct? Do WebMethods return a response in the format of the request content-type? Since when has this been possible? Always? Or is this because I have ASP.NET AJAX installed? If so, what namespaces can I disassemble to see how this works?</p> <p>I've only used WebMethods for .NET to .NET communication, which has been in SOAP, and always written custom code to respond in the correct format (SOAP, JSON, or XML), based on a request query string parameter specifying the desired format. I always thought WCF was required for this kind of metaformat functionality.</p>
<p>It is a part of <code>ASP.NET AJAX</code>. See for example <a href="http://msdn.microsoft.com/en-us/library/bb515101.aspx" rel="nofollow">Using Web Services in ASP.NET AJAX</a>. Part of the AJAX client architecture goes like this:</p> <blockquote> <p>Call Web services by using the HTTP POST verb. A POST request has a body that contains the data that the browser sends to the server. It does not have a size limitation. Therefore, you can use a POST request when the size of the data exceeds the intrinsic size limitation for a GET request. The client serializes the request into <strong>JSON</strong> format and sends it as POST data to the server. The server deserializes the <strong>JSON</strong> data into .NET Framework types and makes the actual Web service call. During the response, the server serializes the return values and passes them back to the client, which deserializes them into JavaScript objects for processing.</p> </blockquote>
Does malloc() allocate a contiguous block of memory? <p>I have a piece of code written by a very old school programmer :-) . it goes something like this </p> <pre><code>typedef struct ts_request { ts_request_buffer_header_def header; char package[1]; } ts_request_def; ts_request_buffer_def* request_buffer = malloc(sizeof(ts_request_def) + (2 * 1024 * 1024)); </code></pre> <p>the programmer basically is working on a buffer overflow concept. I know the code looks dodgy. so my questions are:</p> <ol> <li><p>Does malloc always allocate contiguous block of memory ?. because in this code if the blocks are not contiguous , the code will fail big time </p></li> <li><p>Doing free(request_buffer) , will it free all the bytes allocated by malloc i.e sizeof(ts_request_def) + (2 * 1024 * 1024), or only the bytes of the size of the structure sizeof(ts_request_def) </p></li> <li><p>Do you see any evident problems with this approach , i need to discuss this with my boss and would like to point out any loopholes with this approach</p></li> </ol>
<p>To answer your numbered points.</p> <ol> <li>Yes.</li> <li>All the bytes. Malloc/free doesn't know or care about the type of the object, just the size.</li> <li>It is strictly speaking undefined behaviour, but a common trick supported by many implementations. See below for other alternatives.</li> </ol> <p>The latest C standard, ISO/IEC 9899:1999 (informally C99), allows <a href="http://www.comeaucomputing.com/techtalk/c99/#flexiblearrays">flexible array members</a>.</p> <p>An example of this would be:</p> <pre><code>int main(void) { struct { size_t x; char a[]; } *p; p = malloc(sizeof *p + 100); if (p) { /* You can now access up to p-&gt;a[99] safely */ } } </code></pre> <p>This now standardized feature allowed you to avoid using the common, but non-standard, implementation extension that you describe in your question. Strictly speaking, using a non-flexible array member and accessing beyond its bounds is undefined behaviour, but many implementations document and encourage it.</p> <p>Furthermore, <a href="http://gcc.gnu.org/">gcc</a> allows <a href="http://gcc.gnu.org/onlinedocs/gcc/Zero-Length.html">zero-length arrays</a> as an extension. Zero-length arrays are illegal in standard C, but gcc introduced this feature before C99 gave us flexible array members.</p> <p>In a response to a comment, I will explain why the snippet below is technically undefined behaviour. Section numbers I quote refer to C99 (ISO/IEC 9899:1999)</p> <pre><code>struct { char arr[1]; } *x; x = malloc(sizeof *x + 1024); x-&gt;arr[23] = 42; </code></pre> <p>Firstly, 6.5.2.1#2 shows a[i] is identical to (&#42;((a)+(i))), so x->arr[23] is equivalent to (&#42;((x->arr)+(23))). Now, 6.5.6#8 (on the addition of a pointer and an integer) says:</p> <blockquote> <p>"If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, <strong>the behavior is undefined</strong>."</p> </blockquote> <p>For this reason, because x->arr[23] is not within the array, the behaviour is undefined. You might still think that it's okay because the malloc() implies the array has now been extended, but this is not strictly the case. Informative Annex J.2 (which lists examples of undefined behaviour) provides further clarification with an example:</p> <blockquote> <p>An array subscript is out of range, even if an object is apparently accessible with the given subscript (as in the lvalue expression a&#91;1]&#91;7] given the declaration int a[4][5]) (6.5.6).</p> </blockquote>
How can I store a GridView cell value to a session variable? <p>How would I store the value of a GridView's selected rows to a session variable?</p>
<p>From the codebehind file you will want to use something like this to access the underlying data item (MyDataItem) from the selected row. </p> <pre><code>MyDataItem item = (MyDataItem)GridView1.Rows[GridView1.SelectedIndex].DataItem; Session["myItem"] = item; </code></pre> <p>Remember though, the gridview is already storing this data for you, so you may just want to access it from the GridView directly whenever you need it.</p>
Spurious unblocking in boost thread <p>I came across this interesting paragraph in the <a href="http://www.boost.org/doc/libs/1%5F38%5F0/doc/html/thread/synchronization.html#thread.synchronization.condvar%5Fref">Boost thread documentation</a> today:</p> <pre><code>void wait(boost::unique_lock&lt;boost::mutex&gt;&amp; lock) </code></pre> <p>...</p> <blockquote> <p>Effects: Atomically call lock.unlock() and blocks the current thread. The thread will unblock when notified by a call to this->notify_one() or this->notify_all(), or <strong>spuriously</strong>. When the thread is unblocked (for whatever reason), the lock is reacquired by invoking lock.lock() before the call to wait returns. The lock is also reacquired by invoking lock.lock() if the function exits with an exception.</p> </blockquote> <p>So what I am interested in is the meaning of the word "spuriously". Why would the thread be unblocked for spurious reasons? What can be done to resolve this?</p>
<p><a href="http://www.justsoftwaresolutions.co.uk/threading/condition-variable-spurious-wakes.html">This article by Anthony Williams</a> is particularly detailed.</p> <blockquote> <p>Spurious wakes cannot be predicted: they are essentially random from the user's point of view. However, they commonly occur when the thread library cannot reliably ensure that a waiting thread will not miss a notification. Since a missed notification would render the condition variable useless, the thread library wakes the thread from its wait rather than take the risk.</p> </blockquote> <p>He also points out that you shouldn't use the <code>timed_wait</code> overloads that take a duration, and you should generally use the versions that take a predicate</p> <blockquote> <p>That's the beginner's bug, and one that's easily overcome with a simple rule: always check your predicate in a loop when waiting with a condition variable. The more insidious bug comes from timed_wait().</p> </blockquote> <p><a href="http://vladimir%5Fprus.blogspot.com/2005/07/spurious-wakeups.html">This article by Vladimir Prus</a> is also interesting.</p> <blockquote> <p>But why do we need the while loop, can't we write:</p> </blockquote> <pre><code>if (!something_happened) c.wait(m); </code></pre> <blockquote> <p>We can't. And the killer reason is that 'wait' can return without any 'notify' call. That's called spurious wakeup and is explicitly allowed by POSIX. Essentially, return from 'wait' only indicates that the shared data might have changed, so that data must be evaluated again.</p> <p>Okay, so why this is not fixed yet? The first reason is that nobody wants to fix it. Wrapping call to 'wait' in a loop is very desired for several other reasons. But those reasons require explanation, while spurious wakeup is a hammer that can be applied to any first year student without fail.</p> </blockquote>
Update linked tables in MS Access Database with C# programatically <p>I have two Access 2003 databases (<code>fooDb</code> and <code>barDb</code>). There are four tables in <code>fooDb</code> that are linked to tables in <code>barDb</code>.</p> <p>Two questions:</p> <ul> <li>How do I update the table contents (linked tables in <code>fooDb</code> should be synchronized with the table contents in <code>barDb</code>)</li> <li>How do I re-link the table to a different <code>barDb</code> using <code>ADO.NET</code></li> </ul> <p>I googled but didn't get any helpful results. What I found out is how to accomplish this in VB(6) and DAO, but I need a solution for C#.</p>
<p>Here is my solution to relinking DAO tables using C#.</p> <p>My application uses a central MS Access database and 8 actual databases that are linked in. The central database is stored locally to my C# app but the application allows for the 8 data databases to be located elsewhere. On startup, my C# app relinks DAO tables in the central database based on app.config settings.</p> <p>Aside note, this database structure is the result of my app originally being a MS Access App which I ported to VB6. I am currently converting my app to C#. I could have moved off MS Access in VB6 or C# but it is a very easy to use desktop DB solution.</p> <p>In the central database, I created a table called linkedtables with three columns TableName, LinkedTableName and DatabaseName. </p> <p>On App start, I call this routine</p> <pre><code> Common.RelinkDAOTables(Properties.Settings.Default.DRC_Data , Properties.Settings.Default.DRC_LinkedTables , "SELECT * FROM LinkedTables"); </code></pre> <p>Default.DRC_Data - Current folder of central access DB Default.DRC_LinkedTables - Current folder of 8 data databases</p> <p>Here is code does the actual relinking of the DAO Tables in C#</p> <pre><code> public static void RelinkDAOTables(string MDBfile, string filepath, string sql) { DataTable linkedTables = TableFromMDB(MDBfile, sql); dao.DBEngine DBE = new dao.DBEngine(); dao.Database DB = DBE.OpenDatabase(MDBfile, false, false, ""); foreach (DataRow row in linkedTables.Rows) { dao.TableDef table = DB.TableDefs[row["Name"].ToString()]; table.Connect = string.Format(";DATABASE={0}{1} ;TABLE={2}", filepath, row["database"], row["LinkedName"]); table.RefreshLink(); } } </code></pre> <p>Additional code written to fetch data from a access database and return it as a DataTable</p> <pre><code> public static DataTable TableFromOleDB(string Connectstring, string Sql) { try { OleDbConnection conn = new OleDbConnection(Connectstring); conn.Open(); OleDbCommand cmd = new OleDbCommand(Sql, conn); OleDbDataAdapter adapter = new OleDbDataAdapter(cmd); DataTable table = new DataTable(); adapter.Fill(table); return table; } catch (OleDbException) { return null; } } public static DataTable TableFromMDB(string MDBfile, string Sql) { return TableFromOleDB(string.Format(sConnectionString, MDBfile), Sql); } </code></pre>
What is the fastest way to read a large number of small files into memory? <p>I need to read ~50 files on every server start and place each text file's representation into memory. Each text file will have its own string (which is the best type to use for the string holder?).</p> <p>What is the fastest way to read the files into memory, and what is the best data structure/type to hold the text in so that I can manipulate it in memory (search and replace mainly)?</p> <p>Thanks</p>
<p>A memory mapped file will be fastest... something like this:</p> <pre><code> final File file; final FileChannel channel; final MappedByteBuffer buffer; file = new File(fileName); fin = new FileInputStream(file); channel = fin.getChannel(); buffer = channel.map(MapMode.READ_ONLY, 0, file.length()); </code></pre> <p>and then proceed to read from the byte buffer.</p> <p>This will be significantly faster than <code>FileInputStream</code> or <code>FileReader</code>.</p> <p>EDIT: </p> <p>After a bit of investigation with this it turns out that, depending on your OS, you might be better off using a new <code>BufferedInputStream(new FileInputStream(file))</code> instead. However reading the whole thing all at once into a char[] the size of the file sounds like the worst way.</p> <p>So <code>BufferedInputStream</code> should give roughly consistent performance on all platforms, while the memory mapped file may be slow or fast depending on the underlying OS. As with everything that is performance critical you should test your code and see what works best.</p> <p>EDIT:</p> <p>Ok here are some tests (the first one is done twice to get the files into the disk cache).</p> <p>I ran it on the rt.jar class files, extracted to the hard drive, this is under Windows 7 beta x64. That is 16784 files with a total of 94,706,637 bytes.</p> <p>First the results...</p> <p>(remember the first is repeated to get the disk cache setup)</p> <ul> <li><p>ArrayTest</p> <ul> <li>time = 83016</li> <li>bytes = 118641472</li> </ul></li> <li><p>ArrayTest </p> <ul> <li>time = 46570</li> <li>bytes = 118641472</li> </ul></li> <li><p>DataInputByteAtATime</p> <ul> <li>time = 74735</li> <li>bytes = 118641472</li> </ul></li> <li><p>DataInputReadFully</p> <ul> <li>time = 8953</li> <li>bytes = 118641472</li> </ul></li> <li><p>MemoryMapped</p> <ul> <li>time = 2320</li> <li>bytes = 118641472</li> </ul></li> </ul> <p>Here is the code...</p> <pre><code>import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.util.HashSet; import java.util.Set; public class Main { public static void main(final String[] argv) { ArrayTest.main(argv); ArrayTest.main(argv); DataInputByteAtATime.main(argv); DataInputReadFully.main(argv); MemoryMapped.main(argv); } } abstract class Test { public final void run(final File root) { final Set&lt;File&gt; files; final long size; final long start; final long end; final long total; files = new HashSet&lt;File&gt;(); getFiles(root, files); start = System.currentTimeMillis(); size = readFiles(files); end = System.currentTimeMillis(); total = end - start; System.out.println(getClass().getName()); System.out.println("time = " + total); System.out.println("bytes = " + size); } private void getFiles(final File dir, final Set&lt;File&gt; files) { final File[] childeren; childeren = dir.listFiles(); for(final File child : childeren) { if(child.isFile()) { files.add(child); } else { getFiles(child, files); } } } private long readFiles(final Set&lt;File&gt; files) { long size; size = 0; for(final File file : files) { size += readFile(file); } return (size); } protected abstract long readFile(File file); } class ArrayTest extends Test { public static void main(final String[] argv) { final Test test; test = new ArrayTest(); test.run(new File(argv[0])); } protected long readFile(final File file) { InputStream stream; stream = null; try { final byte[] data; int soFar; int sum; stream = new BufferedInputStream(new FileInputStream(file)); data = new byte[(int)file.length()]; soFar = 0; do { soFar += stream.read(data, soFar, data.length - soFar); } while(soFar != data.length); sum = 0; for(final byte b : data) { sum += b; } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); } } class DataInputByteAtATime extends Test { public static void main(final String[] argv) { final Test test; test = new DataInputByteAtATime(); test.run(new File(argv[0])); } protected long readFile(final File file) { DataInputStream stream; stream = null; try { final int fileSize; int sum; stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); fileSize = (int)file.length(); sum = 0; for(int i = 0; i &lt; fileSize; i++) { sum += stream.readByte(); } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); } } class DataInputReadFully extends Test { public static void main(final String[] argv) { final Test test; test = new DataInputReadFully(); test.run(new File(argv[0])); } protected long readFile(final File file) { DataInputStream stream; stream = null; try { final byte[] data; int sum; stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); data = new byte[(int)file.length()]; stream.readFully(data); sum = 0; for(final byte b : data) { sum += b; } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); } } class DataInputReadInChunks extends Test { public static void main(final String[] argv) { final Test test; test = new DataInputReadInChunks(); test.run(new File(argv[0])); } protected long readFile(final File file) { DataInputStream stream; stream = null; try { final byte[] data; int size; final int fileSize; int sum; stream = new DataInputStream(new BufferedInputStream(new FileInputStream(file))); fileSize = (int)file.length(); data = new byte[512]; size = 0; sum = 0; do { size += stream.read(data); sum = 0; for(int i = 0; i &lt; size; i++) { sum += data[i]; } } while(size != fileSize); return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); } } class MemoryMapped extends Test { public static void main(final String[] argv) { final Test test; test = new MemoryMapped(); test.run(new File(argv[0])); } protected long readFile(final File file) { FileInputStream stream; stream = null; try { final FileChannel channel; final MappedByteBuffer buffer; final int fileSize; int sum; stream = new FileInputStream(file); channel = stream.getChannel(); buffer = channel.map(MapMode.READ_ONLY, 0, file.length()); fileSize = (int)file.length(); sum = 0; for(int i = 0; i &lt; fileSize; i++) { sum += buffer.get(); } return (sum); } catch(final IOException ex) { ex.printStackTrace(); } finally { if(stream != null) { try { stream.close(); } catch(final IOException ex) { ex.printStackTrace(); } } } return (0); } } </code></pre>
Debug with an incompatible Visual Studio, but with .pdb <p>Okay, weird situation: I need to Debug a VSTO Office Addin. This was written in Visual Studio 2008 Professional and debugging is usually done by loading the Project, Attaching to Outlook.exe and setting breakpoints - works fine.</p> <p>But I gave a situation where it does not work as expected on one machine, but I do not have VS2008 Pro on that Machine (only Express if that helps, but express will not load the project as the Project type is unsupported), and no chance to use a Remote Debugger.</p> <p>I just wonder if it's possible to still debug it without loading the project, since I'm "armed" with the .pdb File, Source Code and .dll that was used for this.</p> <p>Edit: Just for clarification, it's not an exception, it's an if/else block that goes into the else block even though it should not. I would need to set a breakpoint and inspect some .net variables, possibly even modifying them.</p>
<p>WinDbg will be able to do this, but it's not exactly user-friendly.</p>
How to generate a treeview in html from flexible xml just in client side <p>Could anyone please give me an example in this? I have found many but they didn't match my requirement. </p> <p>The treeview must have expand and collapse, the xml is flexible, which means I should test if a node is exist, and there are many may appear many times and with different contents. Also, I need it works just in client side, nothing to do with the sever or net. And I wonder if it's possible to display the treeview in the left frame, and the content on the right frame. </p> <p>In fact, I need these files, maybe have xslt, js, css etc. to be send to the users, then they can click on the xml or html to see the treeview of their owen xmls (all of them have the same DTD) </p> <p>Thank u very much</p> <p>Allen</p>
<p>You asked for examples... I can provide links to online samples :</p> <ol> <li><a href="http://www.treemenu.net/" rel="nofollow">TreeMenu</a></li> <li><a href="http://destroydrop.com/javascripts/tree/" rel="nofollow">dTree</a></li> <li><a href="http://www.blueshoes.org/en/javascript/tree/" rel="nofollow">BlueShoes JS Tree</a></li> <li><a href="http://www.treemenu.org/" rel="nofollow">Morten's JS Tree</a></li> <li><a href="http://www.codethat.com/javascript-tree.html" rel="nofollow">CodeThat Tree</a> - XML support.</li> </ol> <p>If you have loaded the tree into a page, you can use a left frame to load that particular page.</p>
What hashes are common hashes? used on the net and other programs? <p>I seen MD5 and SHA1 hashes on the net to verify files. What are common hashes used on the net and other programs? This is to verify a file not to hash a pw.</p>
<p>I've used some hash functions from the following site before - they are usually pretty quick, and full code is given on the website, and a description of each of the functions and their strengths/weaknesses:</p> <p><a href="http://www.partow.net/programming/hashfunctions/" rel="nofollow" title="http://www.partow.net/programming/hashfunctions">http://www.partow.net/programming/hashfunctions</a></p> <p>Examples of the hashes given are - Kernighan and Ritchie (from "The C Programming Language") and the Knuth hash (from "The Art Of Computer Programming Volume 3").</p>
How do I get repeatable CPU-bound benchmark runtimes on Windows? <p>We sometimes have to run some CPU-bound tests where we want to measure runtime. The tests last in the order of a minute. The problem is that from run to run the runtime varies by quite a lot (+/- 5%). We suspect that the variation is caused by activity from other applications/services on the system, eg:</p> <ul> <li>Applications doing housekeeping in their idle time (e.g. Visual Studio updating IntelliSense)</li> <li>Filesystem indexers</li> <li>etc..</li> </ul> <p><strong>What tips are there to make our benchmark timings more stable?</strong></p> <p>Currently we minimize all other applications, run the tests at "Above Normal" priority, and not touch the machine while it runs the test.</p>
<p>The usual approach is to perform lots of repetitions and then discard outliers. So, if the distractions such as the disk indexer only crops up once every hour or so, and you do 5 minutes runs repeated for 24 hours, you'll have plenty of results where nothing got in the way. It is a good idea to plot the probability density function to make sure you are understand what is going on. Also, if you are not interested in startup effects such as getting everything into the processor caches then make sure the experiment runs long enough to make them insignificant. </p>
C#: PointF() Array Initializer <p>I need to hard code an array of points in my C# program. The C-style initializer did not work.</p> <pre><code>PointF[] points = new PointF{ /* what goes here? */ }; </code></pre> <p>How is it done?</p>
<p>Like this:</p> <pre><code>PointF[] points = new PointF[]{ new PointF(0,0), new PointF(1,1) }; </code></pre> <p>In c# 3.0 you can write it even shorter:</p> <pre><code>PointF[] points = { new PointF(0,0), new PointF(1,1) }; </code></pre> <p><strong>update</strong> Guffa pointed out that I was to short with the <code>var points</code>, it's indeed not possible to "implicitly typed variable with an array initializer".</p>
how do I backup logins and jobs from SQL server 2005? <p>Is there a script or function in sqlserver2005 that i can backup the jobs and login details of a server from the master database?</p>
<p>Jobs are stored in the <a href="http://msdn.microsoft.com/en-us/library/ms187112.aspx" rel="nofollow">MSDB</a> database and logins in the <a href="http://msdn.microsoft.com/en-us/library/ms187837.aspx" rel="nofollow">Master</a> database.</p> <p>You can backup these system databases as you would any other of your user databases. Use the Management Studio GUI or via the <a href="http://msdn.microsoft.com/en-us/library/ms186865.aspx" rel="nofollow">"backup database.." TSQL syntax</a>.</p> <p>See this article on <a href="http://msdn.microsoft.com/en-us/library/ms190190.aspx" rel="nofollow">backing up your system databases</a>. With specific considerations for the <a href="http://msdn.microsoft.com/en-us/library/ms191488.aspx" rel="nofollow">backing up master</a> and <a href="http://msdn.microsoft.com/en-us/library/ms188274.aspx" rel="nofollow">backing up MSDB</a>.</p>
Best tools for Thick Client Penetration Testing <p>I am looking for Application Security Testing (Penetration Testing) of Thick Client Applications. I know of Echo Mirage and ITR as good tools to test these kinda applications. </p> <p>Does anyone know of any other tools that do this?</p>
<p>Echo Mirage is a greater starter on Thick Clients. Introduced to this by the (smart) bloke who wrote it. It works around dll injection. </p> <p>What's the context? </p> <p>It becomes extremely useful on a Thick Client which is leaking info it shouldn't (and using logic built into the client side). This was then used to own a Database /App. </p>
Django Form Preview - Adding the User to the Form before save <pre><code>class RegistrationFormPreview(FormPreview): preview_template = 'workshops/workshop_register_preview.html' form_template = 'workshops/workshop_register_form.html' def done(self, request, cleaned_data): # Do something with the cleaned_data, then redirect # to a "success" page. # data = request.POST.copy() # data['user_id'] = u'%s' % (request.user.id) # cleaned_data['user'] = u'%s' % (request.user.id) #f = self.form(cleaned_data) #f = self.form(data) #f.user = request.user f = self.form(request.POST) f.save() pdb.set_trace() return HttpResponseRedirect('/register/success') </code></pre> <p>As you can see, I've tried a few ways, and that have been commented out. The task is apparently simple: Add the user from request to the form before save, and then save.</p> <p>What is the accepted, working method here?</p>
<p>If the user can't be modified, I would say it shouldn't even be included in the form in the first place.</p> <p>Either way, <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method">using the <code>commit</code> argument</a> to prevent the resulting object being saved immediately should work (assuming <code>FormPreview</code> uses <code>ModelForm</code>):</p> <pre><code>obj = form.save(commit=False) obj.user = request.user obj.save() </code></pre>
Excel Report Setting page setup options in C# <p>I am using the following approach to create a dynamic Excel Report from HTML in my ASP.NET Application. </p> <p>While creating the excel report, I want to set the Page Setup options such that the report fits into one page. </p> <p>This is the approach I'm using to create the excel report... Please tell me how to fit this report to one page or to zoom in the report?</p> <pre><code> string sContentType = "application/vnd.excel"; string sFileName = "Detail Qutation.xls"; Hashtable oData = new Hashtable(); oData.Add("Content-Disposition", "attachment;filename=" + sFileName); oData.Add("Charset", ""); oData.Add("ContentType", sContentType); oData.Add("Content", sTable.ToString()); oData.Add("IsBinaryContent", false); this.StoreObject("Document", oData); </code></pre>
<p>You might need to render using htmltextwriter as explained in</p> <p><a href="http://forums.asp.net/p/1063850/1538066.aspx#1538066" rel="nofollow">http://forums.asp.net/p/1063850/1538066.aspx#1538066</a></p> <p>and take the concept to get a solution.</p>
jQuery Popup Bubble/Tooltip <p>I'm trying to make a "bubble" that can popup when the <code>onmouseover</code> event is fired and will stay open as long as the mouse is over the item that threw the <code>onmouseover</code> event OR if the mouse is moved into the bubble. My bubble will need to have all manners of HTML and styling including hyperlinks, images, etc.</p> <p>I've basically accomplished this by writing about 200 lines of ugly JavaScript but I would really like to find a nice jQuery plugin to clean this up a bit. I did some searching and couldn't find anything to suit my fancy.</p> <p>Does anyone know of a good jQuery plugin for doing fancy bubbles? Please let me know if you have any questions or need more information and I'd be happy add more!</p>
<p><a href="http://craigsworks.com/projects/qtip2/">Qtip is the best one I've seen.</a> It's MIT licensed, beautiful, has all the configuration you need. </p> <p>My favorite lightweight option is <a href="https://github.com/jaz303/tipsy">tipsy</a>. Also MIT licensed. It inspired <a href="http://getbootstrap.com/javascript/#tooltips">Bootstrap's tooltip plugin</a>.</p>
What is the maximum size of a MySQL database in version 5 and up? <p>What is the maximum size of a MySQL database in version 5 and up?</p> <p>I do not mean the maximum size of row or table, but the maximum size of the whole database.</p>
<p>Two billion (2'000'000'000) tables and a max total of 64TB for InnoDB. MyISAM tables are files, so it's underlying OS file limit.</p>
Are there any reasons not to use Visual Studio 6 for C++? <p>Are there any reasons why I shouldn't use Visual Studio 6 for C++ development?</p> <ul> <li>Where can I find some resources why this would or wouldn't be a good idea?</li> <li>Are there any lists of issues I would have with this?</li> </ul>
<p>I wouldn't say that Visual Studio 6 should "never" be used for C++ development. I would say that it should "no longer" be used for C++ development. Reasons:</p> <ol> <li>Microsoft's later compilers (particularly Visual Studio 2008) are much more compliant with the C++ specification.</li> <li>Microsoft's later compilers add better warnings and errors. These are useful when looking for potential security problems with your code.</li> <li>It's no longer supported. Newer releases of the Windows SDK don't work with Visual C++ 6, so you won't be able to use newer features in Windows without extra work.</li> </ol> <p>To summarise: stop using Visual C++ 6. If you have to use a Microsoft C++ compiler, use Visual Studio 2008.</p>
How can i get tasks performed on a certain date? <p>How can i display the task details performed within a particular date when i click on said date in the calendar control.</p> <p>Example:</p> <ul> <li>I click on Jan 5 in the calendar and then i get the task performed on that date.</li> </ul> <p>I am using C# and ASP.NET (2008)</p>
<p>store task with date in database. write select statement that has date parameter and return task on given parameter. Onclick event return data from executed procedure and display result.</p>
Are there any tools to aid with complex 'if' logic? <p>One of my personal programming demons has always been complex logic that needs to be controlled by if statements (or similiar). Not always necessarily that complex either, sometimes just a few states that needs to be accounted for.</p> <p>Are there any tools or steps a developer can perform during design time to help see the 'states' and take measures to refactor the code down to simplify the resulting code? I'm thinking drawing up a matrix or something along those lines...?</p>
<p>I'd recommend a basic course in <a href="http://en.wikipedia.org/wiki/Propositional_logic">propositional logic</a> for every aspiring programmer. At first, the notation and Greek letters may seem off-putting to the math-averse, but it is really one of the most powerful (and oft-neglected) tools in your skillset, and rather simple, at the core. </p> <p>The <a href="http://en.wikipedia.org/wiki/Logical_operator">basic operators</a>, <a href="http://en.wikipedia.org/wiki/De_Morgan%27s_Laws">de Morgan's</a> and <a href="http://en.wikipedia.org/wiki/Rule_of_inference">other basic laws</a>, <a href="http://en.wikipedia.org/wiki/Truth_table">truth tables</a>, and existence of e.g. <a href="http://en.wikipedia.org/wiki/Disjunctive_normal_form">disjunctive</a> and <a href="http://en.wikipedia.org/wiki/Conjunctive_normal_form">conjunctive normal forms</a> were an eye-opener to me. Before I learned about them, conditional expressions felt like dangerous beasts. Ever since, I know that I can whip them into submission whenever necessary by breaking out the heavy artillery!</p>
Threading in a DLL where the DLL must return before child thread finishes <p>I am working on writing a wrapper DLL to interface a communication DLL for a yokogawa WT1600 power meter, to a PC based automation package. I got the communication part to work but I need to thread it so that a 50ms scan time of the automation package can be maintained. (The Extended Function Block (EFB) Call will block the scan until it returns)</p> <p>These are the steps I need to do.</p> <ol> <li>Call EFB</li> <li>EFB creates a thread to perform communication setup (takes about 200ms to do)</li> <li>EFB returns EFB_BUSY while the thread is doing the work <ul> <li>3a. (automation program continues scanning until it comes back to the EFB call)</li> </ul></li> <li>Call EFB passing in that it returned busy on the last call</li> <li>EFB checks if the thread has returned</li> <li>If the thread returned Then the EFB returns success, Else return EFB_BUSY</li> <li>repeat 3a-6 until efb returns success</li> </ol> <p>So my problem is, how do I create a thread that exists past the life of the function that called it? And how do I get that thread return value when I call back into the DLL?</p> <p>EDIT #1</p> <pre><code> HeavyFunction::HeavyFunction^ hf; //HeavyFunction is a class that has a time consuming function in it ThreadStart^ efbThreadDelegate; Thread^ efbThread; if( pEfbData-&gt;nBlockingRecall != DOEFB_BUSY ) { hf = gcnew HeavyFunction::HeavyFunction; hf-&gt;iiStart = (int)(pEfbData-&gt;uParams[0].dw); hf-&gt;iiEnd = (int)(pEfbData-&gt;uParams[1].dw); efbThreadDelegate = gcnew ThreadStart( hf, &amp;HeavyFunction::HeavyFunction::iGetPrime ); efbThread = gcnew Thread( efbThreadDelegate ); efbThread-&gt;Start(); return DOEFB_BUSY; }else if ( efbThread-&gt;IsAlive ) { return DOEFB_BUSY; }else { uRetValue-&gt;dw = hf-&gt;iReturn; return 0; } </code></pre> <p>Will efbThread still have the same thread handle upon a subsequent call?</p> <p>EDIT #2</p> <p>I got it to work by creating a global HANDLE for a Mutex and a thread. Initializing the mutex in the init entry point (done upon dll loading) and creating the thread in the main function when a call is actually made to the dll.</p> <p>I used the sample code from <a href="http://msdn.microsoft.com/en-us/library/ms682516%28VS.85%29.aspx" rel="nofollow">MSDN: Creating Threads</a> as my model.</p>
<p>Any thread created (whether in a DLL or elsewhere) will not stop spontaneously. In particular, the function that created the thread may return. The new thread would still run even if the creator thread exited. That is, assuming it didn't hit the end of its entry function.</p> <p>Windows threads return a DWORD when ready. To peek, call WaitForSingleObject on the thread handle with a 0 second timeout, and it that succeeds, call GetExitCodeThread . </p> <p>I don't understand your whole "EFB" thing, neither what it is nor what it does, though. If it is doing funny things to normal Windows threads, all bets are off.</p>
How do recommendation systems work? <p>I've always been curious as to how these systems work. For example, how do netflix or Amazon determine what recommendations to make based on past purchases and/or ratings? Are there any algorithms to read up on?</p> <p>Just so there's no misperceptions here, there's no practical reason for me asking. I'm just asking out of sheer curiosity.</p> <p>(Also, if there's an existing question on this topic, point me to it. "Recommendations system" is a difficult term to search for.)</p>
<p>At it's most basic, most recommendation systems work by saying one of two things.</p> <p><strong>User-based recommendations:</strong><br /> If User A likes Items 1,2,3,4, and 5,<br /> And User B likes Items 1,2,3, and 4<br /> Then User B is quite likely to also like Item 5 </p> <p><strong>Item-based recommendations:</strong><br /> If Users who purchase item 1 are also disproportionately likely to purchase item 2<br /> And User A purchased item 1<br /> Then User A will probably be interested in item 2 </p> <p><strong>And here's a brain dump of algorithms you ought to know:</strong><br /> - Set similarity (Jaccard index &amp; Tanimoto coefficient)<br /> - n-Dimensional Euclidean distance<br /> - k-means algorithm<br /> - Support Vector Machines </p>
Sqlite3 connect class for iPhone SDK <p>Is there any common sqlite3 connection class available for working with the iPhone SDK. I realize that it is quite easy to connect and run queries everytime, but to save up more time it would be a real help if we could use a class to handle all the sql directly.</p> <p>I would imagine something which returns a NSMutableArray if you pass a query to it.</p> <p>Is there something available?</p>
<p>Also take a look at <a href="http://code.google.com/p/sqlitepersistentobjects/" rel="nofollow">SQLitePersistentObjects</a>, which I use. The big advantage is that I for now don't have to worry about schemas and such. However, SQLitePO doesn't seem to be able to store objects into alternate tables, AFAIK. Otherwise it seems to work fine.</p>
Memory leak when using time in NHibernate SQL query <p>I use NHibernate in my ASP.NET application to connect to an MS SQL Server 2005 database. In some cases I need to write my own SQL queries. However, I noticed that the SQL server thread leaks about 50 KB of memory every time I execute the following piece of code:</p> <pre><code>NHibernate.ISession session = NHibernateSessionManager.Instance.GetSession(); ISQLQuery query = session.CreateSQLQuery( "select {a.*} from t_alarm a where a.deactivationtime &gt; '" + DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss") + "'"); query.AddEntity("a", typeof(TAlarm)); System.Collections.IList aList = query.List(); </code></pre> <p>When I look in Windows task manager I see that the process <code>sqlservr.exe</code> increases its memory usage by 50 KB each time I run this code.</p> <p>Here is the really interesting part. If I, in the code above, replace <code>"yyyy-MM-dd HH:mm:ss"</code> with <code>"yyyy-MM-dd HH:mm"</code> (i.e. I remove the seconds) the memory leaks stop.</p> <p><em>Update: Apparently the memory leaks doesn't actually stop. They just show once a minute instead. Presumably when the SQL query changes.</em></p> <p>The returned results are the same in both cases.</p> <p>Does anyone have a clue what is going on here?</p>
<p>You've added a query plan to the procedure cache, perhaps?</p> <p>sqlservr.exe takes memory and does not release it unless it has to when other apps require it. Hence DB servers are standalone and not multi-purpose.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms178145%28SQL.90%29.aspx" rel="nofollow">From BOL: Dynamic Memory Management</a> </p> <p>On a 32 bit PC with 2 GB RAM, SQL Server 2000 will max out consuming 1.7GB RAM. There is a KB article describing this.</p> <p>In this case, by providing seconds you are implicitly stating "datetime" type, rather than "smalldatetime" type. This may affect your query plan. You may have an implicit conversion on "a.deactivationtime"</p>
SQL Reporting Services 2005 local time zone <p>We store our date/time information in UTC format on our SQL Server. </p> <p>When using SQL Reporting Services, we'd like to display this data in the time zone of the client workstation, but it appears that using an expression like;</p> <pre><code>System.TimeZone.CurrentTimeZone.ToLocalTime(Fields!DateStarted.Value) </code></pre> <p>... converts into the time zone of the server, not of the client workstation?</p> <p>Is there any way of performing this conversion locally, or passing the local time zone to the server for conversion?</p> <p>Thanks in advance Matt</p>
<p>If your reports are standalone I can't see other option than add timezone report parameter. </p> <p>But if you using reports inside web application, you can <a href="http://stackoverflow.com/questions/338482/can-you-determine-timezone-from-request-variables">Determine Timezone from Request Variables with JavaScript</a> and send time zone value back in hidden fields, urlparameter or postback.</p> <p>You can also add timezone to user registration info (or figure it out from Country and City fields). </p> <p>Also you may try <a href="http://www.codeproject.com/KB/asp/geoip.aspx" rel="nofollow">Target Your Visitors Using GeoIP and .NET</a>.</p>
Can my requirements be met with JMX? <p>I am completely new to <a href="http://java.sun.com/javase/technologies/core/mntr-mgmt/javamanagement/" rel="nofollow">JMX</a>. I have a specific requirement and wanted to know if it is possible to accomplish within the scope of JMX. </p> <h3>Requirements:</h3> <p>I have a set of resources which include many weblogic instances, <a href="http://www.jboss.org/" rel="nofollow">jBoss</a> instances and <a href="http://tomcat.apache.org/" rel="nofollow">Tomcat</a> instances running across many servers. Now I need a one stop solution, UI to monitor these resources, check their current status and if they are down, I need to start and stop them from that webpage.</p> <p>Is this possible using JMX?</p>
<p>You could use <a href="http://www.nagios.org" rel="nofollow">nagios</a> combined with <a href="http://www.nagiosexchange.org/cgi-bin/page.cgi?g=2338.html;d=1" rel="nofollow">check_jmx</a> to monitor (<a href="http://www.pnp4nagios.org/" rel="nofollow">create statistics</a>) and may trigger a restart of a resource. (I'm not sure if can trigger a restart direct via JMX)</p>
Possible to dynamically add an asp:CheckBox control to a TableCell? <p>In my .NET application I need to add a checkbox to each row in a dynamically created asp:Table. Is it possible to do that by dynamically creating an asp:CheckBox for each row and somehow put it inside a TableCell object? (In that case how?)</p> <p>Or do I need to replace the asp:table control with something else, like a Repeater control or GridView to make it work?</p> <p>I'm looking for the quickest solution because I don't have much time.</p> <p>Thanks in advance!</p> <p>/Ylva</p>
<p>in aspx:</p> <pre><code>&lt;asp:Table id=T1 runat=server /&gt; </code></pre> <p>in cs:</p> <pre><code>TableCell tc; foreach(TableRow tr in T1.Rows) { tr.Cells.Add(tc = new TableCell()); ((IParserAccessor)tc).AddParsedSubObject(new CheckBox()); } </code></pre>
What are your experiences with NPanday? <p>Have you used <a href="http://npanday.codeplex.com/" rel="nofollow">NPanday</a> to integrate Visual Studio with <a href="http://maven.apache.org/" rel="nofollow">Apache Maven</a>? If so, did it work well? Would you use it again?</p> <p>Edit: Less specifically, I suppose, the problem I'm trying to solve is this: I have a C# solution in Subversion that relies on other projects elsewhere in the Subversion tree. I'd like to build my project using Hudson. I can build the other project DLL locally, and reference it, but this doesn't work for the CI server. I can't reference the project because Hudson copies the project folders elsewhere, with a new name. What's the solution?</p>
<p>While some of the problems still exist, NPanday has made quite some progress since 1.1 - it has moved to <a href="http://incubator.apache.org/npanday/" rel="nofollow">Apache</a>, and <a href="http://startbigthinksmall.wordpress.com/2011/05/26/apache-npanday-1-4-0-incubating-released-net-for-maven/" rel="nofollow">1.4.0-incubating has been released</a> a while ago.</p> <p><strong>--Original answer: is quite outdated--</strong></p> <p>We tried to use NPanday even also together with Hudson. It works, but in NPanday 1.1 the lifecycle is still quite java-like and not very adjusted to the needs for .NET projects. </p> <p>The Plugin can maintain a pom.xml with all source-files. Support for resources is given, but not complete yet: localized satelite-assemblies are not supported.</p> <p>The plugin also works for English VS installations only (patch in progress)</p> <p>We ended up building our own maven-plugins which I'm now trying to get into NPanday for v1.2. (to be released before summer, hopefully)</p> <p>In Teamcity you can easily depend on artifacts produced by other buildprojects, but Hudson does <a href="http://stackoverflow.com/questions/827515/sharing-build-artifacts-between-jobs-in-hudson">not seem to support that</a>.</p>
array length <pre><code>var a = [1,4,5]; var e = a.length--; </code></pre> <p>Here <code>e</code> variable will contain 5. But if I do:</p> <pre><code>var e = a.length-=1; </code></pre> <p>Here <code>e</code> will contain 2 the number of elements array. <br>So the first is a language 'tip' to simulate a pop() array methods?</p> <p>In the language syntax doing:</p> <pre><code>a-- </code></pre> <p>or</p> <pre><code>a-=1 </code></pre> <p>is semantically the same.</p>
<pre><code>var a = [1, 4, 5]; var e = a.length--; </code></pre> <p>is the same as</p> <pre><code>var a = [1, 4, 5]; var e = a.length; a.length = a.length - 1; </code></pre> <p>whereas</p> <pre><code> var a = [1, 4, 5]; var e = a.length -= 1; </code></pre> <p>is the same as</p> <pre><code>var a = [1, 4, 5]; a.length = a.length - 1; var e = a.length; </code></pre> <p>and</p> <pre><code>var a = [1, 4, 5]; var e = --a.length; </code></pre> <p>In other words: x-- returns the value before decreasing whereas --x (and x -= 1) returns the value after decreasing. All these code snippets pop the last element off the array a.</p> <p>Note that in the first example, <code>e = a.length--</code>, e will have the value 3, not 5, therefore it is <em>not</em> the same as <code>a.pop()</code>.</p>
What is the impact of namespaces in c++ linkages compared to linkages in c? <p>What is the impact of namespaces in c++ linkages compared to linkages in c?</p> <p>Is it possible to make a name that has internal linkage to external linkage just by using namespace.Similarly the other way around.</p>
<p>In general, namespace name is prepended to any enclosed entity's name before the name is mangled and goes to the linker.</p> <p>If you have two functions with the same signatures in different namespaces they link into one file just fine. If you have two classes with the same name and at least one method with the same signature and these classes are in different namespaces – they again link together just fine.</p>
LINQ and the Count extension method <p>I have a database table which could contain many records and I'd like to count the current total in the table. I was going to do a simple:</p> <pre><code>DataContext.Table.Count(c =&gt; c.condition); </code></pre> <p>Until I realized the return type for <code>Count</code> is <code>int</code>. What if the table is to hold more values than can be represented in 32 bits? How can I count them? </p> <p>Should I be counting them in a different way when we're talking about that kind of scale?</p>
<p>Use LongCount(), same thing but with a 64 bit result.</p>
Get all images loaded into a dynamic text box in AS3 <p>I was able to smooth the loaded, rotated images in my textbox as discussed in <a href="http://stackoverflow.com/questions/624754/enable-smoothing-on-imported-rotated-image-in-dynamic-text-box-in-flash-as3">this question</a>. That solution requires that I know the id of the images that are coming in. Is there a way to generalize and get a list of all the images coming in?</p>
<p>You probably want to parse out the ids with a regular expression ?</p>
Is any source code available that has an Active X control hosted in WPF? <p>I am looking for some source code and a project to download and look at that has an Active X control hosting WPF. I can not find any source code anywhere on the net.</p> <p>I can not add a WPF resource the usual way in an Active X control. I have to add it manually to the reference section.</p>
<p>Not sure if this is even possible. I would check out WPF browser applications. That may be a better solution for you given that if you are going to be running an active x control with WPF the user will need 1) Internet Explorer and 2) .net 3.0+ installed locally. A WPF Browser application will work with IE if the user has .net 3.0+ installed and will work with IE and FireFox if the user has .net 3.5+ installed. Check out WPF Broswer Apps here: <a href="http://msdn.microsoft.com/en-us/library/aa970060.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa970060.aspx</a></p>
How can I detect if a string is empty of characters? <p>How do I determine if the string has any alpha character or not? </p> <p>In other words, if the string has only spaces in it how do I treat it as an Empty string?</p>
<p>Try:</p> <pre><code>if the_string.replace(" ", "") == "": the_string = "" </code></pre> <p>If your language supports it, using "trim", "strip" or "chomp" to remove leading/trailing whitespace could be good too...</p> <p><strong>edit</strong>: Of course, regular expressions could solve this problem too: <code>the_string.match("[^\s]")</code>... Or a custom function... Or any number of things.</p> <p><strong>edit</strong>: In Caml:</p> <pre><code>let rec empty_or_space = fun [] -&gt; true | (x::xs) -&gt; x == ` ` and empty_or_space xs;; </code></pre> <p><strong>edit</strong>: As requested, in LOLPYTHON:</p> <pre><code>BTW OHAI SO IM LIKE EMPTY WIT S OK? LOL IZ S EMPTIE? DUZ IT HAZ UNWHITESPACE CHAREZ /LOL IZ S KINDA LIKE ""? U TAKE YEAH IZ S LOOK AT EASTERBUNNY OK KINDA NOT LIKE " "? U TAKE MEH U TAKE EMPTY WIT S OWN __getslice__ WIT CHEEZBURGER AND BIGNESS S OK OK </code></pre>
Handing dates in Zend_Form - changing to and from date formats <p><br /> I'm working on a Zend Framework (v1.7) application that calls for a few forms that users need to enter dates on. </p> <p>The user is prompted to enter dates in the <strong>dd/mm/yyyy</strong> format, but the MySQL database wants the dates to be presented in <strong>yyyy-mm-dd</strong> format. Therefore, i'm having to do the following:</p> <p><em>Loading the form</em> </p> <ol> <li>Grab the data from the database</li> <li>Re-format the date fields using Zend_Date into the <strong>dd/mm/yyyy</strong> format</li> </ol> <p><em>Saving the form</em> </p> <ol> <li>Validate the date fields using Zend_Validate </li> <li>Check if the date field is present. If so, re-format it into the <strong>yyyy-mm-dd</strong> format. If not, set it to NULL</li> <li>Save to the database</li> </ol> <p>There must be an easier way to do this :-S</p> <p>Can anyone suggest one?</p> <p>Cheers,<br /> Matt</p>
<p>You can skip the reformatting if you use the according sql functions like <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function%5Fdate-format" rel="nofollow">DATE_FORMAT()</a> and <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function%5Fstr-to-date" rel="nofollow">STR_TO_DATE()</a> in MySql. The rest looks ok to me.</p>
SQL HELP - Conditional where clause based on a BIT variable - SQL Server <p>I need help writing a conditional where clause. here is my situation:</p> <p>I have a bit value that determines what rows to return in a select statement. If the value is true, I need to return rows where the import_id column is not null, if false, then I want the rows where the import_id column is null.</p> <p>My attempt at such a query (below) does not seem to work, what is the best way to accomplish this?</p> <pre> <code> DECLARE @imported BIT SELECT id, import_id, name FROM Foo WHERE (@imported = 1 AND import_id IS NOT NULL) AND (@imported = 0 AND import_is IS NULL) </code> </pre> <p>Thanks.</p>
<p>Change the <code>AND</code> to <code>OR</code></p> <pre><code>DECLARE @imported BIT SELECT id, import_id, name FROM Foo WHERE (@imported = 1 AND import_id IS NOT NULL) OR (@imported = 0 AND import_is IS NULL) </code></pre> <h3>Decomposing your original statement</h3> <p>you have essentially written</p> <pre><code> @imported = 1 AND import_id IS NOT NULL AND @imported = 0 AND import_is IS NULL </code></pre> <p>wich is equivalent to</p> <pre><code> @imported = 1 AND @imported = 0 AND import_id IS NOT NULL AND import_is IS NULL </code></pre> <p>what results in two pair of clauses that completely negate each other</p>
What is a better design? <p>I have a scenario at hand which has some design discussion going on. To break it down in simple words, think about a hierarchy as such Company -----> Customer ------> Orders (ignore the details of how the orders have products etc) if I was to expose an API to work with this, what would be a better design. </p> <p>a)</p> <pre><code>Dim comp As New Company comp.GetInfo(123) Dim cust As New Customer cust.Name= "CustomerName" comp.Add( cust) </code></pre> <p>b)</p> <pre><code>Dim custhand As Customerhandler Dim cust As New Customer cust.Name= "CustomerName" custhand.AddCustomer(cust,123) ''123 is CompanyID </code></pre>
<p>I'd go with (A) but I'd be inclined to change...</p> <pre><code>Dim comp As New Company comp.GetInfo(123) </code></pre> <p>into...</p> <pre><code>Dim comp As Company = Company.Get(123) </code></pre> <p>(so add a new shared method to the Company class to return a specific instance of Company)</p>
How do I make this class more reusable? (specific example inside) <p>I've got a method which currently takes an IList as a parameter, where UserBO is similar to the following:</p> <pre><code>public class UserBO { public string Username { get; set; } public string Password { get; set; } public string Pin { get; set; } } public class SomeClass { // An example method giving the basic idea of what I need to do public void WriteUsers(IList&lt;UserBO&gt; users) { // Do stuff with users for (var user in users) { Console.WriteLine(String.Format(User: {0}: {1}, users.Username, Hash(users.Pin)); // Now needs to optionally be users.Password } } private string Hash(string pin) { return // Hashed Pin } } </code></pre> <p>This method then uses the Username/Pin pairs to create some XML used by another program (we'll use the above method as an example).</p> <p>The thing is, now I need to be able to produce the same code except using the Password field instead of the Pin field (there's a good reason for having both fields).</p> <p>Instead of just creating another method with a similar name, I'd prefer to refactor the code so as to remove the BO specific code from this class entirely, and make it so that the decision about what class/members to use are made not in the method itself but the code calling it.</p> <p>One option would be to pass an IDictionary and use the Linq ToDictionary method to create a dictionary on the fly in the calling code. This would however lose the ordering of the items (which would be nice but not essential to keep). I could use an IList or something, but that would be more difficult to convert the IList into.</p> <p>Does anybody have any good suggestions of how to do this?</p> <p>P.S. If anybody has a better idea of how to title this post, feel free to have a go at it.</p>
<p>It's not clear <em>exactly</em> what you need to do with the strings after formatting. You could make the method take an <code>IEnumerable&lt;string&gt;</code>, and then make the calling code:</p> <pre><code>WriteUsers(users.Select(user =&gt; string.Format("{0}: {1}", users.Username, users.Pin))); </code></pre> <p>Whether that works for you or not will depend on the details.</p>
How to run a NetBeans project in command prompt? <p>My professor asked us to create a Java program that would be able to run in command prompt but could also be opened using NetBeans.</p> <p>The program is about using the different types of sorting (specifically Selection, Insertion, Exchange, Quick, and Heap sorting). our professor specifically told us to use object oriented programming in Java, and that she wants to see a main class plus the different classes that would do the sorting.</p> <p>I tried to write the program in NetBeans — thinking that later I could simply run the program in cmd using javac.</p> <p>In cmd, I typed the path where my NetBeans project was saved and I tried to compile the files using javac. but it says that "'javac' is not recognized as an internal or external command, operable program or batch file."</p> <p>So I tried to save the files in sun>sdk>jdk>bin, and from there I tried to compile the files, and it was fine. The problem sets in when I tried to run them.</p> <p>Here's how I tried to compile the files:</p> <pre><code>javac Main.java Sortchoice.java Selection.java SelectionSort.java Insertion.java InsertionSort.java Exchange.java ExchangeSort.java </code></pre> <p>(I havent finished the syntax for the next two sorting.)</p> <p>Here's how I tried to run the files in cmd:</p> <pre><code>java Main Sortchoice Selection SelectionSort Insertion InsertionSort Exchange ExchangeSort </code></pre> <p>and cmd says:</p> <pre><code>exception in thread "main" java.lang.NoClassDefFoundError: main (wring name: myjava/Main) at java.lang.ClassLoader.defineClass1(Nativ... Method)" at java.lang.ClassLoader.defineClass(ClassL... at java.security.SecureClassLoader.defineCl... at java.net.URLClassLoader.defineClass(URLC... at java.net.URLClassLoader.access$000(URLCl... at java.net.URLClassLoader$1.run(URLClassLo... at java.security.AccessController.doPrivile... Method) at java.net.URLClassLoader.findClass(URLCla... at java.lang.ClassLoader.loadClass(ClassLoa... at sun.misc.Launcher&amp;AppClassLoader.loadCla... at java.lang.ClasLoader.loadClass(ClassLoad... at java.lang.ClassLoader.loadClassInternal(... </code></pre> <p>What should I do? (Sorry for my kilometric-long explanation. I just wanted to put in as many details as possible.)</p> <p>I would also like to emphasize that I'm just a beginner in Java programming.</p>
<p>If you click build inside NetBeans, it should give you (in your compiler output) a message like, "To run this application from the command line without Ant, try: java -jar yourPathToRun"</p>
How do I host PDF content on a webpage that also is capable of running javascript? ASP.Net solutions please <p>first question so be gentle with me and thanks in advance for your help!</p> <p>I'm going to add quite a bit of context to explain why I'm asking the question I am and why I want to do what I want to do. Bear with me, it'll all be worth it.</p> <p>I should mention that this app will not be seen by the general public and we have some contraints on our users (only use IE 5.5, that sort of thing).</p> <p>I have an existing web app that I'm having to add to.</p> <p>Currently an aspx page is navigated to with some IDs passed in as a query string and in the page load a call is made to a business object, passing in the page's Response object. That business object grabs PDF byte content (from a sql server via a business object) and, having set the necessaries in the header, writes the PDF byte data into the Response object. The user gets to see the PDF and all is right with the world.</p> <p>Howewver, now we have a requirement that when the page is navigated to the app will get the PDF byte data and in addition to displaying it we'll send it to a proprietary system based local to the web client (we already do this via a java applet other points in the application's workflow and it works).</p> <p>Thing is, I need to (depending on some user settings or other) show a modal dialog when the user navigates to the 'view dynamicallly generated pdf document' page, to ask if the user wants to szend the PDF to this proprietary system. For this I need to be able to run client-side javascript to call showModalDialog (using showModalDialog is handy because I can put all the java applet calling stuff and the java applet itself on this one page that gets shown as a modal dialog).</p> <p>Problem is the way we show our PDF at the moment doesn't allow us to run javascript as all that gets sent down to the client is a page with a bunch of pdf data and marked as such.</p> <p>So far I've trieed IFrames (yeah, yeah I kow, effluent from Lucifer's fundament) with the src being dynamically set to the url of the PDF display page plus the querystring that page needs. That worked in the sense that I got my modal dialog showing which was great and the PDF displayed (which was something at least) in a cosy little two inches at the top of the page, which was not so great :(</p> <p>I've also tried using an object tag but I don't even know where to start getting that sorted to 'runat=server'. When I try to do it client side I get object required errors in my java script.</p> <p>So all I really want is some kind of 'container' that I can place on a standard aspx page, that I can use to dynamically reference another page from which will give it 'full height' in the viewport. IFrames seemed like that fella but they seem to be a bit...well...poo.</p> <p>Oh and just in case you didn't guess: I'm not as experienced a web dev as I am in WinForms.</p>
<blockquote> <p>That worked in the sense that I got my modal dialog showing which was great and the PDF displayed (which was something at least) in a cosy little two inches at the top of the page</p> </blockquote> <p>Then give the iframe a bigger height. Either through the ‘height’ attribute, if you can guess a reasonable size in pixels, or using CSS if you want to do something like basing it on page height:</p> <pre><code>&lt;iframe src="pdfscript?id=123" style="position: absolute; top: 10%; left: 10%; width: 80%; height: 80%;"&gt;&lt;/iframe&gt; </code></pre> <p>Whilst you <em>can</em> embed a PDF in a web page using the &lt;object> tag, it's strongly not recommended. At least with the iframe option, if you don't have a PDF plugin installed it will prompt you to download as a file; the object-version will just give you a broken plugin icon and maybe prompt you to install the Acrobat plugin.</p> <p>(And you definitely <em>don't</em> want the Acrobat plugin installed, because of all the security holes that are currently delivering control of our desktops to Russian hackers. Thanks Adobe.)</p>
Why all text boxes won't select? <p>I have a form with a Tab Control that has 18 pages. When I click on a tab it opens the page and select a textbox on that page (<code>txtTextbox1.Select()</code>). This works for the first 8 pages but not for the remaining 10 pages. Although on these pages I can mouse click on the textbox, enter info, save then click my Add button that clears the textboxes and has the code (<code>txtTextbox1.Select()</code>). The textbox is selected just fine. </p> <p>The code for all my pages is the same except for the tab name and the control names. The tab key will move the selection to the next textbox in order on all pages and the Enter key is coded to do the same. The first 8 pages have a total of 256 labels, buttons, list boxes, textboxes and checkboxes on them. </p> <p>I’m looking for anyone that may be able to explain why this is happening and that might have a work around or solution for it. </p>
<p>I'm curious about:</p> <blockquote> <p>The code for all my pages is the same except for the tab name and the control names.</p> </blockquote> <p>I'd guess that you created the first one from scratch and did a lot of copy/paste/edit to create each subsequent page. Am I right?</p> <p>The first thing I'd check would be to see if more than one page is calling Select() on the same TextBox. That would mean that one of them is trying to select a TextBox that's on some other page, not the page being shown. This could happen, for example, if you missed an edit after pasting code from a previous page. (You could try checking by doing a find in files for ".Select" in your whole project and looking for duplicates in the results if the only place you call Select is when a page shows.)</p> <p>If that's not it, can you move one of the non-selecting pages up to the position of one of the pages that does select? For instance, move page 18 to between page 1 and 2. Does it select its textbox correctly? If it does, then there's something about the position. If it does not, then it's something about the page.</p>
In Java what should I use for a PriorityQueue that returns the greatest element first? <p>Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/PriorityQueue.html" rel="nofollow">PriorityQueue</a> places the least element at the head of the list, however I need it to place the greatest element at the head. What what's the neatest way to get a priority queue that behaves like that.</p> <p>Since I wrote the class stored in this queue I could simply reverse the results of <code>compareTo</code>, its not used outside this queue. </p> <p>However I like to make the code an accurate representation of what I'm modeling, what I'm trying to do is get the greatest first so the code should say that rather than least first with an unusual definition of least. </p> <p>[edit]just a quick thank you everyone, Comparator sounds like what I need just as soon as I teach myself how to write one.</p>
<p>Pass a <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html">Comparator</a> that inverts the natural order when you instantiate the <a href="http://java.sun.com/javase/6/docs/api/java/util/PriorityQueue.html">PriorityQueue</a>.</p> <p>It would look something like this:</p> <pre><code>public class ReverseYourObjComparator implements Comparator&lt;YourObj&gt; { public int compare(final YourObj arg0, final YourObj arg1) { return 0 - arg0.compareTo(arg1); } } </code></pre>
Searching multiple tables with MySQL <p>I am writing a PHP/MySQL program and I would like to know how to search across multiple tables using MySQL.</p> <p>Basically, I have a search box as in the top right of most sites, and when user's search something in that box, it needs to search in users.username, users.profile_text, uploads.title, uploads.description, sets.description and comments.text. I need to get the ID (stored in a id field in each table) and if possible, a google like excerpt.</p>
<p>You can either write your procedure to query each of these tables individually, or you could create a relatively simple view that conglomerates all of the searchable columns of the important tables along with an indicator showing which table they're from. There's not really a magic way to search multiple tables other than writing the statements normally.</p> <p>The second approach would look something like this:</p> <pre><code>(SELECT 'Table 1' AS TableName, id as Id, text as Searchable FROM table1) UNION (SELECT 'Table 2' AS TableName, table2_id as Id, name as Searchable FROM table2) UNION ... </code></pre> <p>Then search on the resulting view. It's important to note that this method won't be fast. </p> <p>A similar, and faster, alternative would be to dedicate a table to this task instead of a view, and populate it on insert/update/delete of the real tables instead of recomputing it on access.</p>
Host Page - User control communication ASP.NET <p>I have a number of user controls. The user controls can be used on different pages. The behavior of the user controls are different based on what page they are used on. </p> <p>How can I set a parameter on the host page that ALL user controls have access to?</p>
<p>Your description "The behavior of the user controls are different based on what page they are used on" indicates a design flaw. The Control Model in ASP.NET is designed around <a href="http://en.wikipedia.org/wiki/Encapsulation%5F%28computer%5Fscience%29" rel="nofollow">encapsulation</a> and <a href="http://en.wikipedia.org/wiki/Object-oriented%5Fprogramming" rel="nofollow">OOP</a>, which means a control should be agnostic regarding its surrounding context. You should rethink your design with that in mind.</p> <p>That having been said, it is entirely possible (<strong>warning - bad practice</strong>) to set a public property on your page that the controls can read:</p> <pre><code>class MyPage : Page { public string MyProperty; } class MyUserControl : UserControl { void Page_Load(object sender, EventArgs e) { ((MyPage)this.Page).MyProperty //casts Page as the specific page } } </code></pre>
Will creating a new folder break subversion? <p>I have a subversion repository, but there are some things that I don't want it to mess with. For example, SVN breaks mac resource files because unix doesn't know about the resource fork. </p> <p>However, I still want some form of back-up/version control. I would like to be able to just create a folder within the top level repository folder, and stick my stuff there. However, the readme.txt file in that folder says "don't touch this unless you know what you're doing". </p> <p>So, is it safe to do that?</p> <p>thanks.</p>
<p>I'd be incredibly nervous about doing this. </p> <p>Whilst it may not actively break subversion immediately, subversion is going to assume that it has complete control of all the folders within the repository, and that it knows what they all are. If some tool, script or process performs some generic action across all the files, you could find your backups mangled and/or the repository corrupted.</p> <p>And just because it doesn't break it in the current version, doesn't mean that it won't cause problems in the next. So basically - I'd really avoid doing this, it's makes everything really messy.</p>
Zend Framework: strange url rewrite behavior <p>I am experiencing strange behavior with my Zend Framework application.</p> <p>I run this url, hoping to get index controller run the 1234567890 action.</p> <pre><code>http://hello.com/index/1234567890?test=http%3A%2F%2Fworld.com%2Findex.php </code></pre> <p>I however get exception like this:</p> <pre><code>Message: Invalid controller specified (4567890) </code></pre> <p>And strangely all URLs that are on the page now link to:</p> <pre><code>http://hello.com/index.php/index/1234567890 </code></pre> <p>Instead of:</p> <pre><code>http://hello.com/index/1234567890 </code></pre> <p>Notice that the index.php string that gets falsely injected into URLs has 9 characters, it is same number as gets cut of the <strong>index/123</strong>4567890 string to get the wrong controller name.</p> <p>Another thing is that injected index.php correlates with index.php in url encoded get parameter from the example.</p> <p>What is wrong? Is it a bug in Zend? Or am I doing something wrong?</p> <p>This is my .htaccess:</p> <pre><code>RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ /index.php [NC,L] </code></pre>
<p>You didn't put much in the way you've tried to debug this so I wandered over to my own localhost and gave your url a shot. Low and behold mine does the same thing, I tried two different modrewrite methods:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule .* index.php </code></pre> <p>And</p> <pre><code>RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ /index.php [NC,L] </code></pre> <p>They both were doing the same thing. After spending quite some time playing with the url and looking at what the request parameters looked like on my error page all I could come up with is either there is a major glitch in the default routing patterns in Zend Framework or there's something wonky about using the filename your modrewrite is sending requests to in the url.</p> <p>So I changed my main index.php file to main.php and respectively in my modrewrite and it works fine, double checked that having main.php in the url would not mess it up and it doesn't.</p> <p>So while not promising anything, if you rename your index.php (that gets written to and includes your bootstrap) to main.php or whatever you please and reflect that in your modrewrite you should be all set!</p> <p>Good luck!</p>
Localizable User Controls <p>If I have a form that is localized and has User Controls that are localized, how I can I view the form and the controls in the language specified in the VS Properties?</p> <p>Right now when I change the language, all my controls that are not part a user control adjust appropriately, but my user controls do not. </p>
<p>You have to localize each user control individually when designing it in the designer. Then you can set the property Localizable on the user control to true and choose your language. Unfortunately the surrounding Form does not escalate these two properties to its user controls when the Form is designed. That is a problem, but only at design time. At runtime however it will work and your user controls should show the correctly localized values.</p>
drawImage in Java applet flickers in Safari <p>I'm having a flicker problem in a Java applet in Safari (Mac). However, it's not the usual double buffering problem.</p> <p>I have isolated it down to one single <code>drawImage</code> call (no redundant repaint, no <code>clear</code> is called), which gives a white flicker before painting the image but not on every repaint. In fact, I measured the duration of the <code>drawImage</code> call, which is normally about 1ms, but up to 30ms about every 5th time paint is called, which is when it flickers. Repaints are triggered when I drag a component or when the window is scrolled.</p> <p>Is this a bug in the java implementation on OSX, and is there a fix for it?</p>
<p>You give very small information. That is difficult to answer.</p> <p>Do you recreate the Image before you paint it? Then you can buffer it or use an media tracker.</p> <p>If you use an old Java version then update it. The old versions for OSX are very buggy.</p>
sIFR 3.0 and sWmode <p>Previous versions of sIFR allowed users to enter "sWmode: 'transparent'" to avoid the common problem of Flash objects being overlayed on regular HTML objects on screen, no matter the z-index of either elements.</p> <p>How do I replicate this behavior in sIFR 3.0?</p>
<p>I think you just need to add: </p> <pre><code>wmode: 'transparent' </code></pre> <p>in the object you send into sIFR.replace()</p>
WPF or WinForms for internal tools? <p>At my company we develop a number of tools for internal that range from simple utilities to full-blown editors. The priorities for these tools are stability, usability, and turn-around time (meaning how quickly new features can be added).</p> <p>We've been using WinForms up until now but there's a couple of new tools on the drawing board and I'm weighing up whether we should continue with WinForms or move to WPF. As we control the environment we don't have to worry about .NET versions etc (though we do have to run on XP for the time being).</p> <p>I'm familiar with the graphical benefits offered by WPF (vector-based, hardware accelerated, skin-ability) but I'm wondering if there are any other aspects of WPF that make a compelling argument for its use over WinForms.</p> <p>Thanks,</p>
<p>Don't underestimate the learning curve. WPF can be really great to work with, and it can be a nightmare. I've seen WinForms only developers more helpless with WPF then with ASP.NET (even with very little knowledge of web development). While most developers were able to just start working with WinForms and ASP.NET without reading any books, and were productive to some level, this seems to be impossible with WPF.</p> <p>And don't forget about third-party components. Yes, there are even new players in the market, and <em>years</em> after .NET 3.0 e. g. SoftwareFX finally managed to release their charting solution for WPF (just as an example), but the component market for WPF is still significantly smaller (commercial as well as open source), and often WPF components are still less powerfull than their WinForms counterparts.</p> <p>I agree that the architecture, e. g. the data binding concept, is great, if you follow a pattern like MVVM, however there is very little documentation in MSDN on best practice e. g. about MVVM, so you will have to point your team to articles on the web and books etc. yourself.</p> <p>And data binding is already very powerful and actually very similar in WinForms 2.0. It just looks like few people know about and use it to its full potential. (Maybe they only tried it in 1.1 and thought that it was too complicated...)</p>
Flash 8 FileReference and file integrity check <p>Flash 8 FileReference API gives you the possibility to check periodically for the number of bytes being transmitted:</p> <pre><code>listener.onProgress = function(file:FileReference, bytesLoaded:Number, bytesTotal:Number):Void { trace("onProgress with bytesLoaded: " + bytesLoaded + " bytesTotal: " + bytesTotal); } </code></pre> <p>(more infos <a href="http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&amp;file=00002204.html" rel="nofollow">here</a> and <a href="http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&amp;file=00002204.html" rel="nofollow">here</a>)</p> <p>In case of upload, <strong>would you suggest to use this method to check for the integrity of the uploaded file</strong>?</p>
<p>Just listen to the onComplete event to check whenever the file is properly uploaded. If no error events have been thrown so far the file <em>should</em> be on the server.</p> <p>If you don't want to trust FlashPlayer regarding the <em>integrety</em> of the posted file (e.g. your server failed moving it from the /tmp folder, etc. ), something likely would be necessary to make sure the procedure was finished properly :</p> <ul> <li>Check the file size (best would be checksum, don't think you can get that though) client side.</li> <li>Post this information within the file upload request. </li> <li>Once the post data received, gather the same information (size, checksum) server-side from the received file and compare it with the information generated client-side.</li> <li>Send back status (fail/success)</li> </ul> <p>... Unless your application is very sensible I would skip this though, just for the simple reason that it might generate more problems than if you hadn't got any integrity-check at all : )</p> <p>Better: depending on the file you send you may be able to find out a server script to check if the file looks fine and just send back a status depending on that.</p>
Asp.net Cookie Domain / Scope <p>I have a "cookie" handler / utility class that works quite well for me. It abstracts away a lot of the issues that I drive me crazy when dealing with cookies such as how to handle a response (write) operation followed by a request (read) operation on the same postback, how to handle encryption, etc.</p> <p>The one thing that eludes me is how to segregate my cookies across different “virtual” domains. My applications are running in an intranet environment all with the same host / server name:</p> <p><a href="http://server/app1/" rel="nofollow">http://server/app1/</a></p> <p><a href="http://server/app2/" rel="nofollow">http://server/app2/</a></p> <p>I don’t want these different applications sharing cookie values in the event that they use the same names. Approaches on the Request / Response object?</p>
<p>Set the <code>Path</code> property of the <code>Cookie</code> to either <code>/app1</code> or <code>/app2</code></p>
How can I get the path of a compiled resource? <p>I have included an executable in my project ( i.e. when you unfold the project in the Solution Explorer in VS2008, you see it along with all the other classes). This executable will need to be launched by my program. How can I retrieve its path programmatically?</p>
<p>I've never done this before with executables... However, if it's an embedded resource, you can enumerate through the list of embedded resources in your application (or refer directly to it by name), when you find the one appropriate, write it to disk, and then execute it.</p> <p>To extract:</p> <pre><code>Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream("resource name") { using FileStream fs= new FileStream("executable name") { byte[] buffer = new byte[32*1024]; int bytesRead; while ((bytesRead= stream.Read(buffer, 0, buffer.Length)) &gt; 0) { fs.Write(buffer, 0, bytesRead); } } } </code></pre> <p>To execute:</p> <pre><code>using System.Diagnostics; Process someProc; someProc= Process.Start("executable name"); </code></pre> <p>As Daniel L points out, don't forget to mark the resources as an "embedded resource".</p>
Linq Fetch all controls (ordered) <p>Is there a way to fetch all the control using linq.</p> <p>What I'll like to do is something like that (order the control by tab index) :</p> <pre><code>foreach (Control control in this.Controls.OrderBy(c =&gt; c.TabIndex) { ... } </code></pre> <p>I use that kind of query when I got a List&lt;...></p> <p>I use c# and .Net 3.5</p>
<p><code>ControlCollection</code> only implements <code>IEnumerable</code>, not <code>IEnumerable&lt;T&gt;</code>. That's easy to fix though - add a call to <code>Cast()</code>:</p> <pre><code>foreach (Control control in Controls.Cast&lt;Control&gt;() .OrderBy(c =&gt; c.TabIndex)) { } </code></pre> <p>Or you could use a query expression, which will call <code>Cast()</code> where necessary:</p> <pre><code>var controls = from Control c in Controls orderby c.TabIndex select c; foreach (Control control in controls) { } </code></pre>
What's more expensive, comparison or assignment? <p>I've started reading <a href="http://www.cs.berkeley.edu/~vazirani/algorithms.html">Algorithms</a> and I keep wondering, when dealing with primitives of the same type, which is the more expensive operation, assignment or comparison? Does this vary a great deal between languages? </p>
<p>What do you think?</p> <p>At the lowest level one does two reads, the other does a read and a write.</p> <p>But why should you really care? You shouldn't care about performance at this level. Optimize for <a href="http://en.wikipedia.org/wiki/Big%5FO%5Fnotation">Big-O</a></p>
Website Partitioning and URL space <p>My website is growing. I need to partition feature sets to different group of servers instead of having all features run on a single server copy. I have 8 identical servers in a Windows Network Load Balancing setup.</p> <p>The problem is: I need to keep the URL space the same. What would be a workable solution? I don't want to start new domains for the feature sets. I am thinking some kind of reverse proxy with some URL based rewriting/routing capabilities(?!?). Any recommendations in terms of software or hardware? This is going to replace the WNLB setup as it does not have the capabilities I need.</p>
<p>There are indeed several solutions to implement load balancing:</p> <ol> <li>DNS Round-Robin</li> <li>DNS Load Balancing (with lbnamed)</li> <li>Proxy Round-Robin</li> <li>Hardware/TCP Round-Robin</li> </ol> <p>I understood 1) and 2) are not an option here so... if you have money and <strong>really high performance needs</strong>, go for 4). Else, go for 3).</p> <p>For Proxy Round-Robin, again, several solutions are possible: <a href="http://httpd.apache.org/docs/2.0/mod/mod%5Frewrite.html" rel="nofollow">Apache mod_rewrite</a>, <a href="http://httpd.apache.org/docs/2.0/mod/mod%5Fproxy.html" rel="nofollow">Apache mod_proxy</a>, <a href="http://wiki.squid-cache.org/SquidFaq/ReverseProxy" rel="nofollow">Squid</a> (and surely many others I don't know).</p> <ul> <li><p>For "dumb" load balacing, there is an example in Apache mod_rewrite's <a href="http://httpd.apache.org/docs/2.0/misc/rewriteguide.html#content" rel="nofollow">URL Rewriting Guide</a> (see <em>Proxy Throughput Round-Robin</em> section).</p></li> <li><p>Apache mod_proxy can act as proxy to connect clients to the internet but <strong>is usually used as reverse proxy to redirect an url to another server</strong>. It has no cache functionality (but can be used with mod_cache, and mod_rewrite...).</p></li> <li><p>Squid is a proxy cache and is usually used to connect clients to the internet. But it can also be used as reverse proxy and be configured to cache the requests and to accelerate content delivery.</p></li> </ul> <p>As you can see, choosing one of them depends on what and how you want to proxy. In your case, I would consider running Apache mod_proxy or Squid if you want caching on Linux (if it is an option). </p> <p>Regarding the hardware, I'm not a specialist but I think a "small" to "medium" dedicated server should be enough. Just don't forget all the requests will go through this machine so its sizing highly depends on your traffic which seems decent. This might require some digging with real life data. </p>
Avoiding duplication in WPF (following DRY) <p>Consider the follow 2 XAML snippets (which are side-by-side in the file):</p> <pre><code>&lt;Button x:Name="BuyButton" Margin="0,0,1,1" IsEnabled="{Binding CanBuy}" &gt; &lt;StackPanel DataContext="{Binding Product}"&gt; &lt;TextBlock Foreground="Red" Text="BUY" /&gt; &lt;TextBlock Foreground="Red" Text="{Binding BuyPrice}" /&gt; &lt;/StackPanel&gt; &lt;/Button&gt; &lt;Button x:Name="SellButton" Margin="0,0,1,1" IsEnabled="{Binding CanSell}" &gt; &lt;StackPanel DataContext="{Binding Product}"&gt; &lt;TextBlock Foreground="Red" Text="SELL" /&gt; &lt;TextBlock Foreground="Red" Text="{Binding SellPrice}" /&gt; &lt;/StackPanel&gt; &lt;/Button&gt; </code></pre> <p>How does one remove duplication in WPF? I have approx 4 uses (2 shown here) of this type of button, and they're 80% the same, if not more. I could extract this into a user control and put a few DPs on it and then I'd have one control, but I fear that I will start littering my code base with tons of user controls (I have a lot of "one-off" situations like this). I don't like the DataTemplate solution here because I'd still need two templates, which would have repeated code. Without creating a bunch of templates/controls, is there a way of making this code follow DRY? </p>
<p>A ControlTemplate might work:</p> <pre><code>&lt;ControlTemplate x:Key="ButtonControlTemplate1" TargetType="{x:Type Button}"&gt; &lt;StackPanel Height="Auto" Width="Auto"&gt; &lt;TextBlock Text="{TemplateBinding Content}" Foreground="Red"/&gt; &lt;TextBlock Text="{TemplateBinding Tag}" Foreground="Red"/&gt; &lt;/StackPanel&gt;&lt;/ControlTemplate&gt; </code></pre> <p>I used TemplateBinding to get the two changeable pieces of data. Now when you create the button, apply the Template, and set the Bindings to your elements:</p> <pre><code>&lt;Button x:Name="BuyButton" Margin="0,0,1,1" IsEnabled="{Binding CanBuy}" Template="{DynamicResource ButtonControlTemplate1}" Content="Button" Tag="{Binding BuyPrice}"/&gt; </code></pre> <p></p> <p>The only thing missing is the DataContext: just set it at a container above the two buttons.</p> <p>I haven't tried it specifically, but it seems it should work. I chose "Tag" above because I needed a second element for Binding. I'd love to see different suggestions about this.</p> <p>You probably also want to break the ForegroundColor="Red" type stuff into a style.</p>
Does any Unix-like system ascribe meaning to the SUID bit on a directory? <p>As the title says, does any Unix-like system ascribe a meaning to the SUID bit on a <strong>directory</strong>, and if so, what does it mean?</p> <p>The SVTX (saved text, or sticky) bit has a meaning - thou shalt not delete a file from this directory unless you can write to the file. It is used on /tmp, for example.</p> <p>The SGID (set GID) bit has a meaning - files created in this directory shall belong to the group that owns the directory (though that assignment can later be changed by an explicit call to chown(2)).</p> <p>What about the SUID bit?</p>
<p>As a followup on Node's answer, I will post the following from the FreeBSD man page for mount(8):</p> <pre><code> suiddir A directory on the mounted file system will respond to the SUID bit being set, by setting the owner of any new files to be the same as the owner of the directory. New directories will inherit the bit from their parents. Execute bits are removed from the file, and it will not be given to root. This feature is designed for use on fileservers serving PC users via ftp, SAMBA, or netatalk. It provides secu- rity holes for shell users and as such should not be used on shell machines, especially on home directories. This option requires the SUIDDIR option in the kernel to work. Only UFS file systems support this option. See chmod(2) for more information. </code></pre> <p>And the chmod(2) man page section that refers to the suid bit:</p> <pre><code> 4000 (the setuid bit). Executable files with this bit set will run with effective uid set to the uid of the file owner. Directories with this bit set will force all files and sub- directories created in them to be owned by the directory owner and not by the uid of the creating process, if the underlying file system supports this feature: see chmod(2) and the suiddir option to mount(8). </code></pre> <p>Please be aware that this is a security risk and know what you are doing when you enable it, in FreeBSD but I believe Linux as well it requires special mount flag to be enabled and will change the way files in that directory behave.</p>
rails : what's wrong with this multiple join with conditions on the associations? <p>Here are my models:</p> <pre><code>class Deck &lt; ActiveRecord::Base belongs_to :game has_many :deck_cards end class DeckCard &lt; ActiveRecord::Base belongs_to :card belongs_to :deck end class Card &lt; ActiveRecord::Base end </code></pre> <p>Here's my attempted find:</p> <pre><code>DeckCard.all :joins =&gt; [:card, :deck], :conditions =&gt; {{:decks =&gt; {:game_id =&gt; @game.id}}, {:cards =&gt; {:present =&gt; true}}} </code></pre> <p>I keep getting the error : undefined method for <code>all</code> for #Class:0x4b2a98>. I'm assuming this is a misleading error from parsing my conditions. I'm following the guide for Active Record Query. I wasn't sure about whether to use the singular or plural form of the associations. Look like with a belongs_to, you're supposed to use singular form in the :joins hash, but I wasn't sure in the :conditions hash, so I tried both and neither worked.</p> <p>In case it isn't clear, what I'm trying to do in SQL is:</p> <pre><code>SELECT * from DeckCards INNER JOIN decks on decks.id = deck_cards.deck_id INNER JOIN cards on card.id = deck_cards.card_id WHERE decks.game_id = 4 AND cards.present = true </code></pre> <p>I'm able to get around it for now by using <code>DeckCard.find_by_sql</code>, but it would be nice to figure out why the joins and conditions on associations isn't working.</p> <p>I'm using InstantRails-2.0 on windows, which is using Rails 2.0.2</p> <p>Edited : some progress using <code>DeckCard.find(:all ...)</code> instead. I also edited the brackets based on another answer. My latest code is</p> <pre><code>DeckCard.find :all, :joins =&gt; [:card, :deck], :conditions =&gt; {:deck =&gt; {:game_id =&gt; @game.id}, :cards =&gt; {:present =&gt; true}} </code></pre> <p>which is producing the following error: </p> <pre><code>Unknown column 'deck_cards.decks' in 'where clause': SELECT `deck_cards`.* FROM `deck_cards` INNER JOIN `cards` ON `cards`.id = `deck_cards`.card_id INNER JOIN `decks` ON `decks`.id = `deck_cards`.deck_id WHERE (`deck_cards`.`decks` = '--- \n- :game_id\n- 5\n' AND `deck_cards`.`cards` = '--- \n- :present\n- true\n') </code></pre> <p>The joins appear correct but not the WHERE conditions. I've tried a few different things like <code>:deck</code> or <code>:decks</code> in the conditions clause but no luck. Could this be another difference between the current ActiveRecord Query Interface docs and how conditions are done in 2.0.2?</p> <p>Thanks!</p>
<p>You need to complete your association with the Card model:</p> <pre><code>class Card &lt; ActiveRecord::Base has_many :deck_cards end </code></pre> <p><strong>EDIT 2</strong>: Try this:</p> <pre><code> DeckCard.find :all, :joins =&gt; [:card, :deck], :conditions =&gt; ["decks.game_id = ? and cards.present = ?", @game.id, true] </code></pre>
Object property "Previous Value" in Javascript <p>I'm just starting to get my mind around this whole Object Oriented thing, so bear with me.</p> <p>So, I saw an example of an object function (for Javascript) where you assign a new value and that value gets assigned as that property's actual value. Example:</p> <pre><code>function Meat (name, color, price) { function newPrice (new_price) { this.price = new_price; } this.name = name; this.color = color; this.price = price; this.newprice = newPrice; } </code></pre> <p>Fine and dandy. Now I have the ability to assign a price by using Bacon.price or Bacon.newprice. Personally, this seems like the highest order of semantics, since functionally it does the same thing. But as an advocate for semantic coding, I'll let it slide. Here's what I want:</p> <p>When I change the value of Bacon.price, the object should include a function to store the old value in a property called oldprice automatically. I played around with this, but got nowhere. Here's what I've tried so far:</p> <pre><code>function Meat (name, color, price) { function oldPrice () { this.oldprice = this.price; } this.name = name; this.color = color; this.oldprice = oldPrice; this.price = price; } /////////////////////// function Meat (name, color, price) { this.name = name; this.color = color; this.oldprice = this.price; this.price = price; } </code></pre> <p>More or less variations of that. I thought that referring to the already assigned value (which would be nothing the first time) before the new value got assigned would be enough. I know that the value (or lack thereof) is stored somewhere before it gets assigned, I just don't know how to refer to it to assign it to the oldvalue property before it gets wiped out.</p> <hr> <p>Okay, maybe the problem is with my eyes or fingers then. Because I thought I had tried the suggestions before asking (I know, I didn't mention them!) Unless I'm really confused, this should work:</p> <pre><code>function Meat(price) { function setPrice(price) { this.oldprice = this.price; this.price = price; } this.price=setPrice; } bacon = new Meat() bacon.price = "Expensive"; document.write(bacon.price+"&lt;br /&gt;"); document.write(bacon.oldprice+"&lt;br /&gt;"); bacon.price = "Cheap"; document.write(bacon.price+"&lt;br /&gt;"); document.write(bacon.oldprice+"&lt;br /&gt;"); </code></pre> <p>But the output I get is: Expensive undefined Cheap undefined</p> <p>All okay until that last one. Again, I am willing to accept bad eyesight and poor spelling as the root. But I can't figure it out.</p>
<p>This will store it when you call <code>obj.newPrice(xxx);</code> - I don't think you can do it automatically when using <code>obj.price = xxx;</code></p> <pre><code>function Meat (name, color, price) { function newPrice (new_price) { this.oldprice = this.price this.price = new_price; } this.name = name; this.color = color; this.price = price; this.newprice = newPrice; } </code></pre> <p>Edit:</p> <p>As noted by @Mauris, Javascript 1.5 does support <a href="https://developer.mozilla.org/En/Core%5FJavaScript%5F1.5%5FGuide:Creating%5FNew%5FObjects:Defining%5FGetters%5Fand%5FSetters" rel="nofollow">getters and setters</a> (see also <a href="http://ejohn.org/blog/javascript-getters-and-setters/" rel="nofollow">here</a> - you can think of them as methods disguised as properties.</p> <p>Using these, your code would look like this:</p> <pre><code>function Meat (name, color, price) { function newPrice (new_price) { this.oldprice = this.price this.price = new_price; } this.name = name; this.color = color; this.__defineSetter__("price", function(newprice) { this.oldprice = this.price this.price = price; }); } </code></pre> <p>Unfortunately this syntax isn't supported by Internet Explorer yet.</p>
How do you get the default TFS Server from Team Explorer? <p>A call like this requires the server name or url:</p> <pre><code>TeamFoundationServerFactory.GetServer("mytfsserver"); </code></pre> <p>Likewise, I can use the following to get a list of available servers or server names:</p> <pre><code>TeamFoundationServer[] servers = RegisteredServers.GetServers(); string[] serverNames = RegisteredServers.GetServerNames(); </code></pre> <p>But how do I get the default server that Team Explorer uses to connect?</p> <p>Alternatively, if I could get the current workspace I think I could use that to get the correct TeamFoundationServer to connect with. However, I want to be able to do this before a solution is loaded which means I do not have a file to use for querying what workspace it belongs in.</p>
<p>Not sure about default (which is simply the server Team Explorer was connected to the last time VS saved its configuration), but you can get the server with a mapping to the current folder.</p> <pre><code>var wsp = Microsoft.TeamFoundation.VersionControl.Client.Workstation.GetLocalWorkspaceInfo(path) var server = wsp.ServerUri </code></pre>
How to run an operation on a collection in Python and collect the results? <p>How to run an operation on a collection in Python and collect the results?</p> <p>So if I have a list of 100 numbers, and I want to run a function like this for each of them:</p> <pre><code>Operation ( originalElement, anotherVar ) # returns new number. </code></pre> <p>and collect the result like so:</p> <p>result = another list...</p> <p>How do I do it? Maybe using lambdas?</p>
<p><a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow">List comprehensions.</a> In Python they look something like:</p> <pre><code>a = [f(x) for x in bar] </code></pre> <p>Where f(x) is some function and bar is a sequence.</p> <p>You can define f(x) as a partially applied function with a construct like:</p> <pre><code>def foo(x): return lambda f: f*x </code></pre> <p>Which will return a function that multiplies the parameter by x. A trivial example of this type of construct used in a list comprehension looks like:</p> <pre><code>&gt;&gt;&gt; def foo (x): ... return lambda f: f*x ... &gt;&gt;&gt; a=[1,2,3] &gt;&gt;&gt; fn_foo = foo(5) &gt;&gt;&gt; [fn_foo (y) for y in a] [5, 10, 15] </code></pre> <p>Although I don't imagine using this sort of construct in any but fairly esoteric cases. Python is not a true functional language, so it has less scope to do clever tricks with higher order functions than (say) Haskell. You may find applications for this type of construct, but it's not really <em>that</em> pythonic. You could achieve a simple transformation with something like:</p> <pre><code>&gt;&gt;&gt; y=5 &gt;&gt;&gt; a=[1,2,3] &gt;&gt;&gt; [x*y for x in a] [5, 10, 15] </code></pre>
What should I consider when selecting a language? <h3>Duplicate:</h3> <blockquote> <p><a href="http://stackoverflow.com/questions/550332/best-language-for-rapid-prototyping">Best Language for Rapid Prototyping?</a></p> <p><a href="http://stackoverflow.com/questions/146840/which-language-should-students-start-with">Which language should students start with?</a></p> <p><a href="http://stackoverflow.com/questions/145104/what-coding-languages-should-a-web-developer-know">What coding languages should a web developer know?</a></p> </blockquote> <p>What are some criteria to keep in mind when selecting a language to use for a project? For example, why should I use Python over Ruby, PHP over ASP, C# over Java, etc. Is it scalability, documentation, maintainability, or how easy the language is to learn?</p> <p>Thanks</p> <h3>Edit:</h3> <p>I know this is a subjective question, but I'm looking for good business cases to convince a manager to switch from one language to another. I'm NOT doing this to incite a language war or prove how one language is better than another. I simply need some criteria to look at when comparing languages. I'm sorry if my question came off offensive or naive to some.</p>
<p>There are lots of questions on Stack Overflow along these lines:</p> <ul> <li><p><a href="http://stackoverflow.com/questions/145104/what-coding-languages-should-a-web-developer-know">What coding languages should a web developer know?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/146840/which-language-should-students-start-with">Which language should students start with?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/550332/best-language-for-rapid-prototyping">Best Language for Rapid Prototyping?</a></p></li> </ul> <p>The list goes on. Responses usually include the reasoning behind a particular choice, which would answer your question.</p>
Are there any studies on whether functional/declarative or imperative programming is easier to learn as a first language? <p>Not best to learn, but easiest to learn. Not easiest for programmers, but for non-programmers (as a first language). Not opinions or anecdotes, but are there any studies?</p> <p>I think that functional/declarative programming (Haskell, Scheme, Lisp etc) is more powerful and more abstract than imperative programming, and therefore is intrinsically harder to learn. I wonder if there is any actual evidence, one way or the other.</p>
<p><a href="http://htdp.org/" rel="nofollow">Matthias Felleisen and his colleagues</a> have assembled some very convincing evidence that the easiest language to learn is a language that is <strong>designed for beginning programmers</strong> and has <strong>tool support aimed at beginning programmers</strong>. They have actually designed and implemented <em>four</em> such languages, each a subset of the next, and all subsets of Scheme. They have some very convincing papers, pedagogy, and <a href="http://plt-scheme.org/" rel="nofollow">software</a>. Also, their results have been replicated in Germany as shown by impressive published results in the latest FDPE workshop, as well as many good but unpublished work in high schools.</p> <p>The take-away message is not that Scheme is good for learning, but rather that beginning programmers need tools and languages (they call them "language levels") designed just for them. I believe this language-level concept could be applied to other languages, including C (which I teach at the introductory level), but unfortunately Felleisen et al have not published a set of principles or guidelines that would allow someone to replicate their work using a different language.</p> <p>So if it's <em>evidence</em> you're looking for, the only available data conflate the use of the functional language with the use of language levels and a custom-designed programming environment. You'll have to judge for yourself which factors are most important. I know that if language levels and a "student's programming environment" were available for C, I would choose that in a heartbeat over, say, full Scheme and the Bigloo Scheme compiler.</p>
Java Swing Problem <p>I have a board with cards in which I have to find matches. I have two variables <code>buttonA</code> and <code>buttonB</code> to keep track of the squares clicked.</p> <p>When they are equal I can remove them from the board by simply adding this code:</p> <pre><code>cards[buttonA].setVisible(false); cards[buttonB].setVisible(false); </code></pre> <p>How can I place the same image on all the buttons after finding matches? I tried the following but it instead of changing the image simply leaves the same image on the buttons</p> <pre><code>cards[buttonA].setIcon(new ImageIcon("myPic.png"); </code></pre>
<p>You probably need to use:</p> <pre><code>new ImageIcon(getClass().getResource("/path/to/myPic.png")); </code></pre> <p>Where this resource is on the <code>classpath</code>. (Remember if using an IDE you need to make sure that your PNG resources get copied over to the output directory. In IDEA for example, this is achieved in the compiler settings menu)</p> <p><strong>edit:</strong> I can never remember whether the path starts with a <code>/</code> or not.</p>
How can I hide elements which only contain hidden DIVs in jQuery? <p>I want to hide all blocks which only contain hidden DIVs (aside from a caption). All elements have to be selected via class names.</p> <p>In detail, I want each "eventBlock" not to show up when all "groupBlocks" underneath are already hidden. The same with "Menu" which should not show up when all child eventBlocks are hidden.</p> <p>Each "Menu" contains multiple eventBlocks, </p> <p>each "eventBlock" contains 1 or more groupBlocks.</p> <p>I am using classes and cannot use IDs because there are lots of groupBlocks, eventBlocks etc.</p> <p>DIVs are hidden using JQuery's "hide()" function, if it's relevant.</p> <p>My HTML basically looks like this:</p> <pre><code>&lt;div class="Menu"&gt; &lt;strong&gt;&lt;a name="one"&gt;Menu CAPTION&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt; &lt;div class="eventBlock event1"&gt; &lt;p class="underlined"&gt;eventBlock CAPTION&lt;/p&gt; &lt;div class="groupBlock group2"&gt; &lt;strong&gt;name&lt;/strong&gt;&lt;br /&gt; 4pm - 6pm&lt;br /&gt; &lt;/div&gt; &lt;div class="groupBlock group1"&gt; &lt;strong&gt;name&lt;/strong&gt;&lt;br /&gt; 5pm - 7pm&lt;br /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
<p>This should work:</p> <pre><code>var blocks = jQuery(".groupBlock"); if( blocks.size() == blocks.not(":visible").size() ) { blocks.parents(".eventBlock").hide(); } </code></pre> <p>You can do something similar to hide the menu if all groupBlocks are hidden.</p>
error: X may be used uninitialized in this function in C <p>I am getting this error</p> <pre><code>error: Access.Core may be used uninitialized in this function </code></pre> <p>And this is my code:</p> <pre><code> static int FirstTime = 1; MyStruct Access; if (FirstTime) { FirstTime = 0; Access = Implementation(); DoSomething(Access); } if(Other_Variable) { Access = Implementation2(); DoSomething(Access); } //The Other_Variable will be set to 1 and to 0 by other part of the code </code></pre> <p>My code is like that because I want to call to the function Implementation only the first time. In every call the Access variable is going to be updated so it does not make many sense make it static.</p> <p>If I make Access static works, but I do not like make it static because in every other call Access is going to be updated. Any way to avoid the problem without making it static?.</p> <p>Also any better options to execute only once a function instead of using a static variable are welcome.</p> <p>Thanks a lot in advance.</p>
<p>Make <code>Access</code> like this (and remove <code>FirstTime</code> and the <code>if</code>):</p> <pre><code>static MyStruct Access = Implementation(this_b); </code></pre> <p>The reason you get this warning is because static variables survive one function call. Their value is retained across all function calls (<em>without</em> regard to which thread calls that function). So, <code>FirstTime</code> will control whether you initialize <code>Access</code>. The first time you call the function that code is in will correctly initialize the <code>Access</code> variable. But with every further function call, <code>FirstTime</code> is zero, and you will <em>not</em> initialize <code>Access</code> anymore, and thus will use an uninitialized variable down the code. </p> <p><strong>Edit:</strong> Now, with your updated information, you say that you have two <code>Implementation</code> functions. The first time you want to use one, and all the other times you want to use another function. How about this then:</p> <pre><code> // static will be false/zero by default static bool AlreadyCalled; MyStruct Access; if (!AlreadyCalled) { Access = Implementation(); AlreadyCalled = true; } else { Access = Implementation2(); } </code></pre> <p>Depending on your actual use case, there may be better ways to handle this, though. For example, why not update the state of <code>Access</code>, like this:</p> <pre><code>// let the default constructor initialize it // to a plausible state static MyStruct Access; // use RAII to update the state of Access when this // function returns. MyUpdater updater(Access); // now, do whatever the function does. </code></pre> <p>Something like this for <code>MyUpdater</code>:</p> <pre><code>struct MyUpdater { MyStruct &amp;s; MyUpdater(MyStruct &amp;s):s(s) { } ~MyUpdater() { s.ChangeState(); } }; </code></pre> <p>That pattern is called <code>RAII</code>: You associate some useful action with the constructor and destructor of a locally allocated object. </p>
Version control approaches in Scrum <p>Recently with my coworkers we were discussing how to organize the version control in a Scrum project. More specifically, the criteria for branches creation (per developer, per task, per Story, per Sprint?) and the methods of integration. </p> <p>My opinion was that a useful way to organize it is to create a branch for each User Story, so you can integrate each Story in the releasable trunk once it is completed and it also allows that you always have a "deliverable version" of the application at any moment. </p> <p>So if a story cannot be completed, it can be just left out and does not compromise the sprint release. (That considering a centralized tool, may be if using a distributed one the considerations would be different)</p> <p>I'd like to know your own approaches, which kind of tools you prefer and the pros and cons that you have seen with the experience and the lessons learned.</p>
<p>Keep branching protocol light-weight. In Scrum, if someone wants to branch the code to work on a specific feature, let them. Nobody should be afraid to branch. This is one of the benefits of DVCS - people branch when they want and aren't biased by team rules or standards.</p> <p>For my money, it's a case-by-case basis, and if you start seeing patterns in your development processes then formalize them so everyone is on the same page.</p> <p>Just make sure that every developer understands that it is their responsibility to integrate and merge their changes. That should set the bar to around about the right place to ensure people make the right call as to when to branch the code.</p>
htaccess won't load images and css <p>I recently changed the directory to one of my websites and wrote a rule within the htaccess file to handle the redirect. However, the css and images fail to load now.</p> <pre><code>Options -Indexes Options +FollowSymLinks RewriteEngine On RewriteBase / RewriteRule ^(\.*)$ http://www.myDomain.com/temp_site/$1 [R=301,L] </code></pre> <h3>EDIT:</h3> <p>Some of the files that don't work are</p> <blockquote> <p><a href="http://www.myDomain.com/css/style.css" rel="nofollow">http://www.myDomain.com/css/style.css</a><br /> <a href="http://www.myDomain.com/images/me.jpg" rel="nofollow">http://www.myDomain.com/images/me.jpg</a><br /> <a href="http://www.myDomain.com/about.php" rel="nofollow">http://www.myDomain.com/about.php</a> </p> </blockquote>
<p>Try this rule:</p> <pre><code>RewriteRule !^temp_site/ /temp_site%{REQUEST_URI} [R=301,L] </code></pre>
Can I stop 100% Width Text Boxes from extending beyond their containers? <p>Lets say I have a text box that I want to fill a whole line. I would give it a style like this:</p> <pre><code>input.wide {display:block; width: 100%} </code></pre> <p>This causes problems because the width is based on the content of the text box. Text boxes have margin, borders, &amp; padding by default, which makes a 100% width text box larger than its container.</p> <p>For example, here on the right:</p> <p><img src="http://i.stack.imgur.com/IvcQx.png" alt="enter image description here"></p> <p>Is there any way to make a text box fill the width of its container without expanding beyond it?</p> <p>Here is some example HTML to show what I mean:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head&gt; &lt;title&gt;Untitled Page&lt;/title&gt; &lt;style type="text/css"&gt; #outer{border: 1px solid #000; width: 320px; margin: 0px;padding:0px} #inner{margin: 20px; padding: 20px; background: #999;border: 1px solid #000;} input.wide {display:block; margin: 0px} input.normal {display:block; float: right} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="outer"&gt; &lt;div id="inner"&gt; &lt;input type="text" class="wide" /&gt; &lt;input type="text" class="normal" /&gt; &lt;div style="clear:both;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If this is run, you can see by looking at the "normal" text box that the "wide" text box is sticking out beyond the container. The "normal" text box floats to the actual edge of the container. I'm trying to make the "wide" text box fill its container, without expanding beyond edge like the "normal" text box is.</p>
<blockquote> <p>Is there any way to make a text box fill the width of its container without expanding beyond it?</p> </blockquote> <p>Yes: by using the CSS3 property ‘box-sizing: border-box’, you can redefine what ‘width’ means to include the external padding and border.</p> <p>Unfortunately because it's CSS3, support isn't very mature, and as the spec process isn't finished yet, it has different temporary names in browsers in the meantime. So:</p> <pre><code>input.wide { width: 100%; box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; } </code></pre> <p>The old-school alternative is simply to put a quantity of ‘padding-right’ on the enclosing &lt;div> or &lt;td> element equal to about how much extra left-and-right padding/border in ‘px’ you think browsers will give the input. (Typically 6px for IE&lt;8.)</p>
JSF Tuning <p>Running into an issue where JSF is filling up our sessions. We had a system crash the other day. Sent the Heap to IBM for review and found that we had some sessions as large as 50M. They found JSF components in the session and some very large. </p> <p>So, is there any tuning that can be done? Configuration items to look at? Or other direction.</p> <p>Our system is build using JSF and Spring for the presentation layer, the back end is EJB, Spring and Hibernate all running on WebSphere 6.1.</p>
<p>JSF is a useful technology, but you can certainly hang yourself with it.</p> <p>It sounds like, either you're inflating the size of the view state (by setting large values on components) or you're leaking references to components into other session state (which would be bad). Another potential culprit would be an excessively large view (I've seen the ease with which people can build UI trees lead to very big control graphs with data tables everywhere). I know that IBM provides rich text and spreadsheet controls - I can't comment on what effect the use of these will have on state size.</p> <p>The low hanging fruit is to check the managed beans configured for session scope in <em>faces-config.xml</em>.</p> <p>JSF saves two things between requests:</p> <ul> <li>the view (all the controls on the page)</li> <li>the view state (the state of the controls)</li> </ul> <p>These are separated because some controls, such as children of a data table, can have multiple states (one for each row). State can be saved to either a hidden field on the form (which, if unencrypted, can be a big security hazard) or in the session. In order to accommodate multiple browser windows sharing the same session (and, in some implementations, back button support), multiple views are stored.</p> <ul> <li>There should be a configuration option to set the number of view states the app will keep in the session for a given user at any given time.</li> <li>You can measure the size of view state by providing a <a href="http://java.sun.com/javaee/5/docs/api/javax/faces/application/StateManagerWrapper.html">StateManager</a> that measures the size of the saved view/state (configure a StateManager in faces-config.xml with a public constructor that takes a StateManager - see the <a href="http://java.sun.com/javaee/javaserverfaces/reference/api/index.html">JSF spec</a> PDFs for more details; the state is serializable and you can check its size by dumping it to a stream).</li> </ul> <p>Most IDE-built JSF apps have backing beans. It would be possible, via session bean scope to hold onto state longer than you want, placing a strain on the session. Since there tends to be one backing bean per page, the more pages you have, the bigger the problem will be. Check your <em>faces-config.xml</em> to see if this is a potential source of problems.</p> <p>Something else you could do would be to configure a <a href="http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpSessionAttributeListener.html">HttpSessionAttributeListener</a> in your <em>web.xml</em>. You can get a <a href="http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace%28%29">stack trace</a> to help identify problem areas in your app.</p>
tsql : how do I join this table? <p>I have the following sql statement: </p> <pre><code>SELECT TOP (100) PERCENT inv.CompanyID, cust.CustID AS ClientID, cust.CustName AS CustomerName, inv.InvcKey, inv.PrimarySperKey AS SperKey, inv.TranID AS InvoiceNumber, inv.TranDate AS PostDate, sper.SperName AS SalesPersonName, inv.SalesAmt AS InvoiceSubAmount, inv.TranAmt AS InvoiceTotal, detl.ItemKey, detl.InvoiceLineKey AS dtInvoiceLineKey, detl.Description, detl.UnitCost AS calcUnitCost, detl.UnitPrice, detl.ExtAmt, (detl.UnitPrice - detl.UnitCost) * dist.QtyShipped - detl.TradeDiscAmt AS detLineGrossProfit, dbo.tPA00175.chrJobNumber AS ARJobNumber, dist.QtyShipped, dbo.timItem.ItemID AS ARItemID, dbo.timItemClass.ItemClassID AS ARItemClass, dist.TradeDiscAmt, dbo._v_GP_SalesTerr.SalesTerritoryID FROM dbo.tarInvoiceDetl AS detl RIGHT OUTER JOIN dbo.timItem INNER JOIN dbo.timItemClass ON dbo.timItem.ItemClassKey = dbo.timItemClass.ItemClassKey ON detl.ItemKey = dbo.timItem.ItemKey RIGHT OUTER JOIN dbo._v_GP_SalesTerr RIGHT OUTER JOIN dbo.tarInvoice AS inv INNER JOIN dbo.tarCustomer AS cust ON inv.CustKey = cust.CustKey ON dbo._v_GP_SalesTerr.CustKey = cust.CustKey ON detl.InvcKey = inv.InvcKey LEFT OUTER JOIN dbo.tPA00175 INNER JOIN dbo.paarInvcHdr ON dbo.tPA00175.intJobKey = dbo.paarInvcHdr.intJobKey ON inv.InvcKey = dbo.paarInvcHdr.InvcKey LEFT OUTER JOIN dbo.tarInvoiceLineDist AS dist ON detl.InvoiceLineKey = dist.InvoiceLineKey LEFT OUTER JOIN dbo.tarSalesperson AS sper ON inv.PrimarySperKey = sper.SperKey </code></pre> <p>If I wanted to add a field called Inventory.LastUnitCost where Inventory had a surrogate key called itemkey for the table "timitem", how would i add this in there where it would just look up the LastUnitCost field by itemkey? If there wasn't a LastUnitCost corresponding to the timitem table, it would just be null..</p> <p>Everytime I attempt to add it as in Inner Join to timItem on Inventory.itemkey = timItem.itemkey, it affects the timItemClass.ItemClassID field where some of the catorgies do not show up anymore. </p> <p>thanks in advance.</p>
<p>Add <code>Inventory.LastUnitCost</code> to the <code>SELECT</code> list</p> <p>and add this line to the end of the query:</p> <pre><code>dbo.Inventory LEFT OUTER JOIN dbo.timItem ON dbo.timItem.itemkey = dbo.Inventory.itemkey </code></pre>