instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>What is a good way to remove the code from display pages when developing with PHP. Often the pages I work on need to be editted by an outside person. This person is often confused by lots of blocks of PHP, and also likes to break my code.</p> <p>I've tried moving blocks of code out into functions, so now there are functions spread out all throughout the HTML now. As some pages become more complex it becomes a program again, and processing POSTs are questionable.</p> <p>What can I be doing better in my PHP development?</p>
<p>You don't need a "system" to do templating. You can do it on your own by keeping presentation &amp; logic separate. This way the designer can screw up the display, but not the logic behind it.</p> <p>Here's a simple example:</p> <pre><code>&lt;?php $people = array('derek','joel','jeff'); $people[0] = 'martin'; // all your logic goes here include 'templates/people.php'; ?&gt; </code></pre> <p>Now here's the people.php file (which you give your designer):</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;?php foreach($people as $name):?&gt; &lt;b&gt;Person:&lt;/b&gt; &lt;?=$name?&gt; &lt;br /&gt; &lt;?php endforeach;?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
<p>There's a lot that can be said on this topic but a very basic starting point would be to move as much code as possible out into separate files and then use include statements.</p>
5,703
<p>Looking for a software solution to to store large files (>50MB - 1.5GB), distributed across multiple servers. We have looked at MogileFS, however, given existing software demands, need to have an NFS interface. Would prefer open source, however, open to all options.</p>
<p>If you have only a small number of servers, you could try <a href="http://samba.anu.edu.au/rsync/" rel="nofollow noreferrer">rsync</a>. Couple it with SSH for some security.</p>
<p>did you look at Hadoop DFS? it's much more then distributed file system but should be good for very big files.</p>
18,867
<p>I need to save a user's login information in encrypted form for this application I'm building, but I'm not sure of the best place to save the file. I don't want to save it into the program application folder as I want it per user.</p> <p>So what is the best folder (or way) to save it into?</p> <p>Edit: Using C++.</p>
<p>Seems like C:\Documents and Settings\%username%\Local Settings\Application Data may be the appropriate place according to <a href="http://en.wikipedia.org/wiki/Special_Folders" rel="nofollow noreferrer">Wikipedia</a>. The article says this location is used for "User-specific and computer-specific application settings".</p> <p>Edit: Cruizer pointed out in the comments (I'd reply there but I can't comment yet) that in Vista it is C:\Users\%username% and that it shouldn't be hard-coded. Thanks.</p>
<p>are you using .NET? how about <a href="http://msdn.microsoft.com/en-us/library/3ak841sy(VS.80).aspx" rel="nofollow noreferrer">IsolatedStorage</a>? That way you wouldn't have to worry about the directory location, it'll just be there...</p>
17,764
<p>In a drop down list, I need to add spaces in front of the options in the list. I am trying</p> <pre><code>&lt;select&gt; &lt;option&gt;&amp;#32;&amp;#32;Sample&lt;/option&gt; &lt;/select&gt; </code></pre> <p>for adding two spaces but it displays no spaces. How can I add spaces before option texts?</p>
<p>Isn't <code>&amp;#160</code> the entity for space?</p> <pre><code>&lt;select&gt; &lt;option&gt;&amp;#160;option 1&lt;/option&gt; &lt;option&gt; option 2&lt;/option&gt; &lt;/select&gt; </code></pre> <p>Works for me...</p> <h3>EDIT:</h3> <p>Just checked this out, there <em>may</em> be compatibility issues with this in older browsers, but all seems to work fine for me here. Just thought I should let you know as you may want to replace with <code>&amp;nbsp;</code></p>
<p>I tried several of these examples, but the only thing that worked was using javascript, much like dabobert's, but not jQuery, just plain old vanilla javascript and spaces:</p> <pre><code>for(var x = 0; x &lt; dd.options.length; x++) { item = dd.options[x]; //if a line that needs indenting item.text = ' ' + item.text; //indent } </code></pre> <p>This is IE only. IE11 in fact. Ugh.</p>
4,534
<p>I want to select nodes for which a specific attribute does not exist. I've tried the Not() function, but it doesn't work. Is there a way for this?</p> <p>Example: The following Xpath query:</p> <pre><code>group/msg[not(@owner)] </code></pre> <p>Should retrieve the first node but not the 2nd one. However, both SketchPath (tool to test Xpath queries) and my C# code consider that the 2 nodes are ok.</p> <pre><code>&lt;group&gt; &lt;msg id="EVENTDATA_CCFLOADED_XMLCONTEXT" numericId="14026" translate="False" topicId="302" status="translated" &gt; &lt;text&gt;Context&lt;/text&gt; &lt;comment&gt;&lt;/comment&gt; &lt;/msg&gt; &lt;msg id="EVENTDATA_CCFLOADED_XMLCONTEXT_HELP" numericId="14027" translate="False" topicId="302" status="translated" owner="EVENTDATA_CCFLOADED_XMLCONTEXT" &gt; &lt;text&gt;Provides the new data displayed in the Object.&lt;/text&gt; &lt;comment&gt;&lt;/comment&gt; &lt;/msg&gt; &lt;/group&gt; </code></pre> <hr> <p>In fact the Not() function works correctly, it's just that I had other conditions and parentheses weren't set correctly. <em>errare humanum est</em>.</p>
<p>In some old and not very standard XPath engine I had to use <code>string-length(@attr)=0</code> for the same reason.</p>
<p>Works for me when testing with <a href="http://sourceforge.net/projects/xpe" rel="nofollow noreferrer" title="XPath Explorer">XPath Explorer</a> (based on <a href="http://jaxen.org/" rel="nofollow noreferrer" title="Jaxen">Jaxen</a> library).<br> So I guess it is indeed depending on the XPath implementation.</p>
47,373
<p>I'm using Delphi 6, and I want a database bound list box with multiselect. I found three types of List boxes: <code>TListBox</code>, <code>TDBListBox</code> and <code>TDBLookupListBox</code>. </p> <p>As far as I can understand, <code>TListbox</code> is not bound to database. <code>TDBListBox</code> and <code>TDBLookupListBox</code> can't be multiselected.</p> <p>Is there a way to get a multiselect listbox binded to database?</p>
<p>The problem with databinding components is that they rely on a datasource and a datasource has only a single cursor. That is probably the reason why.</p> <p>By the way, do you need to change the data? Else you could fill a normal listbox from a dataset. Or even use an invisible data listbox and copy the contents to a normal listbox.</p>
<p>In a TDbLookupListBox you have the option to bind two different things to data; first you can bind the list to a dataset (ListSource/ListField/KeyField), second you can bind the selected item to a field in another dataset (DataSource, DataField). There is nothing conceptually wrong with wanting to bind the list of items to a dataset, and then manually manage multiple selections, however I don't think it is possible with the current implementation without subclassing and enabling the required control styles.</p>
30,328
<p>I'm setting up an online ordering system but I'm in Australia and for international customers I'd like to show prices in US dollars or Euros so they don't have to make the mental effort to convert from Australian dollars.</p> <p>Does anyone know if I can pull up to date exchange rates off the net somewhere in an easy-to-parse format I can access from my PHP script ?</p> <hr> <p><strong>UPDATE:</strong> I have now written a PHP class which implements this. <a href="http://www.doctort.org/adam/general/currency-calculation-in-php.html" rel="noreferrer">You can get the code from my website</a>.</p>
<p>You can get currency conversions in a simple format from yahoo:</p> <p>For example, to convert from GBP to EUR: <code>http://download.finance.yahoo.com/d/quotes.csv?s=GBPEUR=X&amp;f=sl1d1t1ba&amp;e=.csv</code></p>
<p>coinnill.com has a sort-of web-service.</p> <blockquote> <p><a href="http://coinmill.com/rss/AUD_USD.xml" rel="nofollow noreferrer">http://coinmill.com/rss/AUD_USD.xml</a></p> </blockquote> <p>will give you the AUD --> USD rate for example. You'll just need to parse the XML that comes back.</p>
21,989
<p>Resharper, RefactorPro, etc?</p>
<p>I have tried using Resharper for some while and also CodeRush with Refactor later on. </p> <p>I have stayed with CodeRush/Refactor. There is one major difference - the discoverability of the commands. Their learning videos are quite nice and show you a lot.</p> <p>Most importantly Coderush has one key/shortcut for all refactorings which makes you much more likely to actually use them. There is side window that shows you what keys to press in order to use the templates as well. I have liked Resharper's searching for usage of a method, but CodeRush has a similar feature ignited by Shift + F12 and you can also simply press Tab on a variable, function etc. to jump to its next usage.</p> <p>I also liked the interface of CodeRush/Refactor more.</p> <p>One of the pro's for Resharper is the integrated testing tool so yuo can run test directly from Visual Studio.</p>
<p>I think ReSharper is great. I've been using it for 3 years now and I just love it more and more.</p>
6,970
<p>Is it possible to access JSTL's forEach variable via code from within the loop?</p> <pre><code>&lt;c:forEach items="${elements}" var="element"&gt; &lt;% element.someMethod(); %&gt; &lt;/c:forEach&gt; </code></pre>
<p>Well, I believe "element" is stored in the page context.</p> <pre><code>&lt;c:forEach items="${elements}" var="element"&gt; &lt;% ((Element) pageContext.getAttribute("elements")).someMethod(); %&gt; &lt;/c:forEach&gt; </code></pre>
<p>Edit following the correction of the example:</p> <p>Yes, it is possible to access the <code>var</code> inside the <code>c:forEach</code> </p> <p>Here's an example:</p> <pre><code>&lt;c:forEach items="${elements}" var="element"&gt; ${((Element)element).someMethod()} &lt;/c:forEach&gt; </code></pre> <p>See <a href="http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/c/forEach.html" rel="nofollow noreferrer">c:forEach</a> in the JSTL Documentation.</p>
43,458
<p>I have a file with n lines. (n above 100 millions)</p> <p>I want to output a file with only 1 of 10 lines, I can't split the file in ten part and keep only one part, as it must be a little more random. later I have to do a statistical analysis I can't afford to create a strong bias in the data).</p> <p>I was thinking of reading the file and for each record if the record number mod 10 then output it.</p> <p>The constraints are:</p> <ul> <li><p>it's a windows (likely hardened) computer possibly XP Vista or Windows server 2003.</p></li> <li><p>no development tools available</p></li> <li><p>no network,usb,cd-rom. read no external communication.</p></li> </ul> <p>Therefore I was thinking of windows batch file (I can't assume powershell, and vbscript is likely to have been removed). And at the moment looking at the FOR /F command. Still I am not an expert and I don't know how to achieve this.</p> <p><em>Thank you Paul for your answer. I reformat (with Hosam help) the answer to put it in a batch file:</em></p> <pre><code>@echo off setlocal findstr/N . inputFile| findstr ^[0-9]*0: &gt;temporaryFile FOR /F "tokens=1,* delims=: " %%i in (temporaryfile) do echo %%j &gt; outputFile </code></pre> <p><em>Thanks quux and Pax for the similar alternative solution. However after a quick test on a larger file Paul's answer is roughly 8 times faster. I guess the evaluation (in SET) is kind of slow, even if the logic seems brilliant.</em></p>
<p>Ok, I think I've cracked it:</p> <pre><code>findstr/N . path-to-log-file | findstr ^[0-9]*0: </code></pre> <p>(use findstr to add the line number to the beginning of the line, then again to print only lines with a line number ending in zero)</p> <p>So you'll get one line in 10, but with the linenumber and colon prepended to each line</p> <p><strike>If I can think of a way using command-line tools only of stripping that out, I'll edit this answer :)</strike></p> <p>Remove the line number and colon with</p> <pre><code>FOR /F "tokens=1,2* delims=: " %i in (file-with-linenumbers) do echo %j </code></pre> <p>Paul.</p>
<p>Paul has a really good answer. By adding the redirection operator you can have the data written to a file.</p> <pre><code>findstr /n . yourLogFile.txt | findstr ^[0-9]*0: &gt; numberedFile.txt for /f "tokens=1,2* delims=:" %i in (numberedFile.txt) do echo %j &gt; smallFile.txt del numberedFile.txt </code></pre> <p>This will work if run from the command line. If you want to put it in a batch file, replace every '%' character with '%%' (so that %i will become %%i, and %j will be %%j, because in batch files '%' has a special meaning).</p>
42,440
<p>Has anyone experienced memcached limitations in terms of:</p> <ul> <li><h1>of objects in cache store - is there a point where it loses performance?</h1></li> <li>Amount of allocated memory - what are the basic numbers to work with?</li> </ul>
<p>I can give you some metrics for our environment. We run memcached for Win32 on 12 boxes (as cache for a very database heavy ASP.NET web site). These boxes each have their own other responsibilities; we just spread the memcached nodes across all machines with memory to spare. Each node had max 512MB allocated by memcached.</p> <p>Our nodes have on average 500 - 1000 connections open. A typical node has 60.000 items in cache and handles 1000 requests per second (!). All of this runs fairly stable and requires little maintenance.</p> <p>We have run into 2 kinds of limitations: 1. CPU use on the client machines. We use .NET serialization to store and retrieve objects in memcached. Works seamless, but CPU use can get very high with our loads. We found that some object can better be first converted to strings (or HTML fragments) and then cached. 2. We have had some problems with memcached boxes running out of TCP/IP connections. Spreading across more boxes helped.</p> <p>We run memcached 1.2.6 and use the .NET client from <a href="http://www.codeplex.com/EnyimMemcached/" rel="nofollow noreferrer">http://www.codeplex.com/EnyimMemcached/</a></p>
<p>I can't vouch for the accuracy of this claim, but at a linux/developer meetup a few months ago an engineer talked about how his company scaled memcache back to using 2GB chunks, 3-4 per memcache box. They found that throughput was fine, but with very large memcache daemons that they were getting 4% more misses. He said they couldn't figure out why there was a difference but decided to just go with what works.</p>
46,634
<p>I am running both maven inside the m2eclipse plugin, windows command line and my cygwin command line.</p> <p>cygwin's bash shell dumps artifacts into the cygwin /home/me/.m2 directory</p> <p>but m2eclipse &amp; windows shell (on vista) uses /Users/me/Documents/.m2</p> <p>Is it possible to tell the mvn command to use one central .m2 directory ?</p> <p>Thanks</p>
<p>Sure, several ways. The most typical is to specify this in your settings.xml file:</p> <ul> <li><a href="http://maven.apache.org/settings.html" rel="noreferrer">http://maven.apache.org/settings.html</a></li> </ul> <blockquote> <pre><code>&lt;settings xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"&gt; &lt;localRepository&gt;/my/secret/repository&lt;/localRepository&gt; &lt;/settings&gt; </code></pre> </blockquote>
<p>Sure, several ways. The most typical is to specify this in your settings.xml file:</p> <ul> <li><a href="http://maven.apache.org/settings.html" rel="noreferrer">http://maven.apache.org/settings.html</a></li> </ul> <blockquote> <pre><code>&lt;settings xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd"&gt; &lt;localRepository&gt;/my/secret/repository&lt;/localRepository&gt; &lt;/settings&gt; </code></pre> </blockquote>
25,424
<p>I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.</p> <p>If I have <em>x</em> items which I want to display in chunks of <em>y</em> per page, how many pages will be needed?</p>
<p>Found an elegant solution:</p> <pre><code>int pageCount = (records + recordsPerPage - 1) / recordsPerPage; </code></pre> <p>Source: <a href="http://www.cs.nott.ac.uk/~rcb/G51MPC/slides/NumberLogic.pdf" rel="noreferrer">Number Conversion, Roland Backhouse, 2001</a></p>
<p>You'll want to do floating point division, and then use the ceiling function, to round up the value to the next integer.</p>
3,854
<p>At my work we are running a group of tests that consist of about 3,000 separate test cases. Previously we were running this entire test suite on one machine, which took about 24-72 hours to complete the entire test run. We now have created our own system for grouping and distributing the tests among about three separate machines and the tests are prioritized so that the core tests get run first for more immediate results and the extra tests run when there is an available machine.</p> <p>I am curious if anyone has found a good way to distribute their tests among several machines to reduce total test time for a complete run and what tools were used to achieve that. I've done some research and it looks like TestNG is <a href="http://beust.com/weblog/archives/000362.html" rel="noreferrer">moving in this direction</a>, but it looks like it is still under quite a bit of development. </p> <p>We don't plan on rewriting any of our tests, but as we add new tests and test new products or add-ons I'd like to be able to deal with the fact that we are working with very large numbers of tests. On the other hand, if we can find a tool that would help distribute our Junit <code>3.x</code> tests even in a very basic fashion, that <em>would</em> be helpful since we wouldn't have to maintain our own tooling to do that.</p>
<p>I've seen some people having a play with <a href="http://216.93.179.140:8080/wiki/display/GG15UG/Distributed+JUnit+Overview" rel="nofollow noreferrer">distributed JUnit</a>. I can't particularly vouch for how effective it is, but the other teams I've seen seemed to think it was straight forward enough. Hope that helps.</p>
<p>Our build people use Mozilla Tinderbox. It seems to have some hooks for distributed testing. I'm sorry not to know the details but I thought I would at least pass on the pointer to you.</p> <p>It's also nice coz you can find out immediately when a build breaks, and what checkin might have been the culprit.</p> <p><a href="http://www.mozilla.org/tinderbox.html" rel="nofollow noreferrer">http://www.mozilla.org/tinderbox.html</a></p>
2,968
<p>I'm about to put my head thru this sliding glass door. I can't figure out how to execute the following code in VB.NET to save my life. </p> <pre><code>private static void InitStructureMap() { ObjectFactory.Initialize(x =&gt; { x.AddRegistry(new DataAccessRegistry()); x.AddRegistry(new CoreRegistry()); x.AddRegistry(new WebUIRegistry()); x.Scan(scanner =&gt; { scanner.Assembly("RPMWare.Core"); scanner.Assembly("RPMWare.Core.DataAccess"); scanner.WithDefaultConventions(); }); }); } </code></pre>
<p>At the moment, it's simply not possible. The current version of VB does not support multiline (or statement) lambdas. Each lambda can only comprise one single expression. The next version of VB will fix that (there simply wasn't enough time in the last release).</p> <p>In the meantime, you'll have to make do with a delegate:</p> <pre><code>Private Shared Sub Foobar(x As IInitializationExpression) x.AddRegistry(New DataAccessRegistry) x.AddRegistry(New CoreRegistry) x.AddRegistry(New WebUIRegistry) x.Scan(AddressOf Barfoo) End Sub Private Shared Sub Barfoo(ByVal scanner As IAssemblyScanner) scanner.Assembly("RPMWare.Core") scanner.Assembly("RPMWare.Core.DataAccess") scanner.WithDefaultConventions End Sub ' … ' ObjectFactory.Initialize(AddressOf Foobar) </code></pre>
<p>That's awesome, for whatever reason though, it doesn't compile. Ugh.</p> <p>Here's what it came up with though:</p> <pre><code>Private Shared Sub InitStructureMap() ObjectFactory.Initialize(Function (ByVal x As IInitializationExpression) x.AddRegistry(New DataAccessRegistry) x.AddRegistry(New CoreRegistry) x.AddRegistry(New WebUIRegistry) x.Scan(Function (ByVal scanner As IAssemblyScanner) scanner.Assembly("RPMWare.Core") scanner.Assembly("RPMWare.Core.DataAccess") scanner.WithDefaultConventions End Function) End Function) End Sub </code></pre> <p>And I tried adding the _ to make it one line (that didn't work either)</p> <pre><code> Private Shared Sub InitStructureMap() ObjectFactory.Initialize(Function (ByVal x As IInitializationExpression) _ x.AddRegistry(New DataAccessRegistry) _ x.AddRegistry(New CoreRegistry) _ x.AddRegistry(New WebUIRegistry) _ x.Scan(Function (ByVal scanner As IAssemblyScanner) _ scanner.Assembly("RPMWare.Core") _ scanner.Assembly("RPMWare.Core.DataAccess") _ scanner.WithDefaultConventions() _ End Function) _ End Function) End Sub </code></pre> <p>Anyone else hate their legacy apps? :P</p>
47,880
<p>I have trouble comparing 2 double in Excel VBA</p> <p>suppose that I have the following code</p> <pre><code>Dim a as double Dim b as double a = 0.15 b = 0.01 </code></pre> <p>After a few manipulations on b, b is now equal to 0.6</p> <p>however the imprecision related to the double data type gives me headache because</p> <pre><code>if a = b then //this will never trigger end if </code></pre> <p>Do you know how I can remove the trailing imprecision on the double type?</p>
<p>You can't compare floating point values for equality. See this article on "<a href="http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/" rel="noreferrer">Comparing floating point numbers</a>" for a discussion of how to handle the intrinsic error.</p> <p>It isn't as simple as comparing to a constant error margin unless you know for sure what the absolute range of the floats is beforehand.</p>
<p>Try to use Single values if possible. Conversion to Double values generates random errors.</p> <pre><code>Public Sub Test() Dim D01 As Double Dim D02 As Double Dim S01 As Single Dim S02 As Single S01 = 45.678 / 12 S02 = 45.678 D01 = S01 D02 = S02 Debug.Print S01 * 12 Debug.Print S02 Debug.Print D01 * 12 Debug.Print D02 End Sub 45,678 45,678 45,67799949646 45,6780014038086 </code></pre>
29,142
<p>I'm experimenting with the Tiny MCE editor. We also use jQuery, and I noticed that the standard Tiny MCE install includes a file called <code>tiny_mce_jquery.js</code>. Can anyone enlighten me as to what that's for? Oddly, I can't find anything about it online. Should I reference it in addition to the standard Tiny MCE script, or instead of? Does it provide anything additional or just avoid incompatibilities? </p>
<p>You should use the 'struts-and-springs' control in IB to set your base view to be full-justified. Then it will auto-resize. Once you do this, you can just use the view.bounds property to access its visible area.</p>
<p>You should use Ben Gottlieb's solution but in terms of calculating the visible area of a view named "<code>view</code>", you could probably use:</p> <pre><code>CGRect viewBoundsInWindow = [[[UIApplication sharedApplication] keyWindow] convertRect:view.layer.visibleRect fromView:view]; </code></pre>
42,663
<p>I am receiving a message from a commercial program stating that the "LogMessage" stored procedure is not found. There does not appear to be a stored procedure called LogMessage in the associated MS SQLServer 2000 database. What can I do to track down the missing procedure, other than calling the company?</p>
<p>The reason you couldn't find it is because it's not there. Unless you have the original proc, you're going to have to call the company.</p> <p>Granted, you could take a stab at creating the proc, yourself. But why bother when somebody already has the original proc?</p> <p>Is this a fresh install of the commercial product? If so, this is completely their responsibility.</p>
<p>LogMessage seems pretty self-explanatory. You could probably take a stab at creating one yourself just to see what happens, if you can't easily get the real thing.</p> <p>Create a new table called LoggedMessages and just insert to the table when the proc is called. Then see what pops in.</p> <p>Kind of hacky, but given that it's a logging mechanism, which is tangential to the main features of the app, you could give it a try.</p>
9,972
<p>I have heard/read the term but don't quite understand what it means.</p> <p>When should I use this technique and how would I use it? Can anyone provide a good code sample?</p>
<p>The visitor pattern is a way of doing double-dispatch in an object-oriented way.</p> <p>It's useful for when you want to choose which method to use for a given argument based on its type at runtime rather than compile time.</p> <p>Double dispatch is a special case of <strong>multiple dispatch</strong>. </p> <p>When you call a virtual method on an object, that's considered single-dispatch because which actual method is called depends on the type of the single object.</p> <p>For double dispatch, both the object's type and the method sole argument's type is taken into account. This is like method overload resolution, except that the argument type is determined at runtime in double-dispatch instead of statically at compile-time.</p> <p>In multiple-dispatch, a method can have multiple arguments passed to it and which implementation is used depends on each argument's type. The order that the types are evaluated depends on the language. In LISP, it checks each type from first to last.</p> <p>Languages with multiple dispatch make use of generic functions, which are just function delcarations and aren't like generic methods, which use type parameters.</p> <p><strong>To do double-dispatch in C#</strong>, you can declare a method with a sole object argument and then specific methods with specific types:</p> <pre><code>using System.Linq; class DoubleDispatch { public T Foo&lt;T&gt;(object arg) { var method = from m in GetType().GetMethods() where m.Name == "Foo" &amp;&amp; m.GetParameters().Length==1 &amp;&amp; arg.GetType().IsAssignableFrom (m.GetParameters()[0].GetType()) &amp;&amp; m.ReturnType == typeof(T) select m; return (T) method.Single().Invoke(this,new object[]{arg}); } public int Foo(int arg) { /* ... */ } static void Test() { object x = 5; Foo&lt;int&gt;(x); //should call Foo(int) via Foo&lt;T&gt;(object). } } </code></pre>
<p>Full listing of working code</p> <pre class="lang-cs prettyprint-override"><code>using System; using System.Linq; namespace TestConsoleApp { internal class Program { public static void Main(string[] args) { const int x = 5; var dispatch = new DoubleDispatch(); Console.WriteLine(dispatch.Foo&lt;int&gt;(x)); Console.WriteLine(dispatch.Foo&lt;string&gt;(x.ToString())); Console.ReadLine(); } } public class DoubleDispatch { public T Foo&lt;T&gt;(T arg) { var method = GetType() .GetMethods() .Single(m =&gt; m.Name == "Foo" &amp;&amp; m.GetParameters().Length == 1 &amp;&amp; arg.GetType().IsAssignableFrom(m.GetParameters()[0].ParameterType) &amp;&amp; m.ReturnType == typeof(T)); return (T) method.Invoke(this, new object[] {arg}); } public int Foo(int arg) { return arg; } public string Foo(string arg) { return arg; } } } </code></pre>
6,415
<p>I am in the process of researching/comparing CXF and Spring-WS for web services? I need to function both as a provider and a consumer of WS. In a nutshell, I have been told that Spring-WS is more configurable, but CXF is easier to get up and running. This question is subjective, but will help direct me in my research.</p> <ul> <li>What experience do you have with either of these frameworks?</li> <li>Have you run into any pitfalls with either framework?</li> <li>Have you found any useful features provided by either that is possibly not provided by the other?</li> </ul>
<p>About Apache CXF:</p> <ul> <li>CXF supports several standards including SOAP, the WSI Basic Profile, WSDL, WS-Addressing, WS-Policy, WS-ReliableMessaging, WS-Security, WS-SecurityPolicy, and WS-SecureConversation. </li> <li>Apache CXF offers both contract-last (starting with Java) and Contract-first (starting with the WSDL) approaches. </li> <li>Apache CXF implements JAX-WS and JAX-RS.</li> </ul> <p>About Spring WS:</p> <ul> <li>Spring WS offers "only" contract-first, starting from an XSD Schema. </li> <li>Spring WS supports SOAP, WS-Security, WS-Addressing.</li> </ul> <p>So, at the end, I see Spring WS as a <strong>minimal</strong> web services framework but consider that it doesn't (in my opinion) have any advantages over Apache CXF (which integrates extremely well with Spring). Between both, I'd pick up Apache CXF.</p>
<p>Please take a look at a related post at : <a href="http://justcompiled.blogspot.com/2010/09/building-web-service-with-spring-ws.html" rel="nofollow">Building a web service with Spring-WS</a></p>
37,991
<p>I'm developing a web app with java servlet, I hope to get the user ip info by calling <code>request.getRemoteAddr()</code> from inside <code>processRequest(HttpServletRequest request,HttpServletResponse response)</code>.</p> <p>But it returns a wrong IP. Since I'm not very knowledgeable about this area, I don't know what it is displaying, maybe a proxy, I got this:</p> <pre> RemoteAddr : 127.0.0.1 RemoteHost : 127.0.0.1 x-forwarded-for : null </pre> <p>127.0.0.1 is not my IP.</p> <p>Yet when I go to: <code>http://www.javascriptkit.com/script/script2/displayip.shtml</code> it will display the right one, since I'm using servlet, I don't have the .shtml to my dynamically generated html page, what can I do? And why the script on that site can display it correctly while <code>request.getRemoteAddr()</code> can't do it?</p> <p>Thanks for all the answers, I have a clue now, after deploying it to the server, it works as expected. Showed the correct address.</p> <p>But even when I develop it on my local machine, how to ask it to display the absolute IP as if it running on a real server? Or is it doable?</p>
<p>What IP address is it displaying? My guess is there's some proxy or something changing things. (For instance, that script page displayed my ADSL router's IP address - not the one inside my LAN - for obvious reasons.)</p> <p>EDIT: Now that you've shown that the IP address you're seeing is 127.0.0.1 the answer is fairly clear - you're seeing your loopback adapter (i.e. the shortcut to the same machine) presumably because you're testing on the same machine you're developing on. The answer is entirely correct.</p> <p>Try it from a different machine and you'll get a more useful IP address.</p>
<p>You're running your test server on your local computer and connecting to it on <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a>. Since you're connecting on the local interface, the source of the connection is also localhost, aka 127.0.0.1.</p>
32,905
<p>I have a utility (grep) that gives me a list of filenames and a line numbers. After I have determined that devenv is the correct program to open a file, I would like to ensure that it is opened at the indicated line number. In emacs, this would be:</p> <pre><code>emacs +140 filename.c </code></pre> <p>I have found nothing like this for Visual Studio (devenv). The closest I have found is:</p> <pre><code>devenv /Command "Edit.Goto 140" filename.c </code></pre> <p>However, this makes a separate instance of devenv for each such file. I would rather have something that uses an existing instance.</p> <p>These variations re-use an existing devenv, but don't go to the indicated line:</p> <pre><code>devenv /Command "Edit.Goto 140" /Edit filename.c devenv /Command /Edit filename.c "Edit.Goto 140" </code></pre> <p>I thought that using multiple "/Command" arguments might do it, but I probably don't have the right one because I either get errors or no response at all (other than opening an empty devenv).</p> <p>I could write a special macro for devenv, but I would like this utility to be used by others that don't have that macro. And I'm not clear on how to invoke that macro with the "/Command" option.</p> <p>Any ideas?</p> <hr> <p>Well, it doesn't appear that there is a way to do this as I wanted. Since it looks like I'll need to have dedicated code to start up Visual Studio, I've decided to use EnvDTE as shown below. Hopefully this will help somebody else.</p> <pre class="lang-cpp prettyprint-override"><code>#include "stdafx.h" //----------------------------------------------------------------------- // This code is blatently stolen from http://benbuck.com/archives/13 // // This is from the blog of somebody called "BenBuck" for which there // seems to be no information. //----------------------------------------------------------------------- // import EnvDTE #pragma warning(disable : 4278) #pragma warning(disable : 4146) #import "libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("8.0") lcid("0") raw_interfaces_only named_guids #pragma warning(default : 4146) #pragma warning(default : 4278) bool visual_studio_open_file(char const *filename, unsigned int line) { HRESULT result; CLSID clsid; result = ::CLSIDFromProgID(L"VisualStudio.DTE", &amp;clsid); if (FAILED(result)) return false; CComPtr&lt;IUnknown&gt; punk; result = ::GetActiveObject(clsid, NULL, &amp;punk); if (FAILED(result)) return false; CComPtr&lt;EnvDTE::_DTE&gt; DTE; DTE = punk; CComPtr&lt;EnvDTE::ItemOperations&gt; item_ops; result = DTE-&gt;get_ItemOperations(&amp;item_ops); if (FAILED(result)) return false; CComBSTR bstrFileName(filename); CComBSTR bstrKind(EnvDTE::vsViewKindTextView); CComPtr&lt;EnvDTE::Window&gt; window; result = item_ops-&gt;OpenFile(bstrFileName, bstrKind, &amp;window); if (FAILED(result)) return false; CComPtr&lt;EnvDTE::Document&gt; doc; result = DTE-&gt;get_ActiveDocument(&amp;doc); if (FAILED(result)) return false; CComPtr&lt;IDispatch&gt; selection_dispatch; result = doc-&gt;get_Selection(&amp;selection_dispatch); if (FAILED(result)) return false; CComPtr&lt;EnvDTE::TextSelection&gt; selection; result = selection_dispatch-&gt;QueryInterface(&amp;selection); if (FAILED(result)) return false; result = selection-&gt;GotoLine(line, TRUE); if (FAILED(result)) return false; return true; } </code></pre>
<p>With VS2008 <strong>SP1</strong>, you can use the following command line to open a file at a specific line in an existing instance :</p> <pre><code>devenv /edit FILE_PATH /command "edit.goto FILE_LINE" </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/xee0c8y7%28VS.80%29.aspx" rel="noreferrer">Source</a></p>
<p>I was about to ask this question because when you get the "yellow screen of death" when debugging a web application, you want to quickly go to the file and line that it gives you in the stacktrace e.g:</p> <pre><code>[ContractException: Precondition failed: session != null] System.Diagnostics.Contracts.__ContractsRuntime.TriggerFailure(ContractFailureKind kind, String msg, String userMessage, String conditionTxt, Exception inner) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\CustomErrorsPageController.cs:0 System.Diagnostics.Contracts.__ContractsRuntime.ReportFailure(ContractFailureKind kind, String msg, String conditionTxt, Exception inner) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\CustomErrorsPageController.cs:0 System.Diagnostics.Contracts.__ContractsRuntime.Requires(Boolean condition, String msg, String conditionTxt) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\CustomErrorsPageController.cs:0 IAS_UI.Web.IAS_Session..ctor(HttpSessionStateBase session) in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Web\IAS_Session.cs:15 IAS_UI.Controllers.ServiceUserController..ctor() in C:\_svn\IntegratedAdaptationsSystem\Source\IntegratedAdaptationsSystem\IAS_UI\Controllers\ServiceUserController.cs:41 </code></pre> <p>Say I want to go to ServiceUserController.cs at line 41. Usually I would open Visual Studio and do it manually but then I wrote a little Autohotkey script which does it.</p> <p>To open it, you will highlight the filename and line number e.g. <code>ServiceUserController.cs:41</code> and thereafter press your shortcut <code>Alt + v</code>. Here is the code for it:</p> <pre><code>$!v:: if (NOT ProcessExists("devenv.exe")) { MsgBox, % "Visual Studio is not loaded" } else { IfWinExist, Microsoft Visual Studio { ToolTip, Opening Visual Studio... c := GetClip() if (NOT c) { MsgBox, % "No text selected" } else { WinActivate ; now activate visual studio Sleep, 50 ; for now assume that there is only one instance of visual studio - handling of multiple instances comes in later arr := StringSplitF(c, ":") if (arr.MaxIndex() &lt;&gt; 2) { MsgBox, % "Text: '" . c . "' is invalid." } else { fileName := arr[1] lineNumber := arr[2] ; give focus to the "Find" box SendInput, ^d ; delete the contents of the "Find" box SendInput, {Home} SendInput, +{End} SendInput, {Delete} ; input *** &gt;of FILENAME *** into the "Find" box SendInput, &gt;of{Space} SendInput, % fileName ; select the first entry in the drop down list SendInput, {Down} SendInput, {Enter} ; lineNumber := 12 remove later ; open the go to line dialog SendInput, ^g Sleep, 20 ; send the file number and press enter SendInput, % lineNumber SendInput {Enter} } } ToolTip } } return </code></pre> <p>You will want to paste the following "utility functions" before it:</p> <pre><code>GetClip() { ClipSaved := ClipboardAll Clipboard= Sleep, 30 Send ^c ClipWait, 2 Sleep, 30 Gc := Clipboard Clipboard := ClipSaved ClipSaved= return Gc } ProcessExists(procName) { Process, Exist, %procName% return (ErrorLevel != 0) } StringSplitF(str, delimeters) { Arr := Object() Loop, parse, str, %delimeters%, { Arr.Insert(A_LoopField) } return Arr } </code></pre>
45,599
<p>All my prints come out about 1 mm too short in the Z dimension. So for example a 20 mm cube comes out 19 mm high. A 10 mm cube comes out 9 mm high. The X and Y dimensions are fine. There's a little bit of visible elephant's foot at the bottom, so I assume whatever is happening is in the first couple of layers. The problem is fairly consistently around 1 mm even for larger prints.</p> <p><a href="https://i.stack.imgur.com/Pjuev.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pjuev.jpg" alt="10 mm test cube" /></a> <a href="https://i.stack.imgur.com/RSPfi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RSPfi.jpg" alt="20 mm test cube" /></a></p> <p>The printer is an Ender 3 Pro with a glass bed and BLTouch for automatic leveling, but otherwise stock.</p> <p>I had a <a href="https://3dprinting.stackexchange.com/questions/13940/expansion-in-bottom-skin-after-first-layer">similar issue with another Ender 3 Pro</a> that was resolved thanks to a link to <a href="https://3dprinting.stackexchange.com/questions/8022/first-3-mm-prints-poorly-then-fine-after-that">this question about problems in the first 3 mm</a>. The solution was turning the eccentric nuts on the left and right to loosen the rollers that connect the X-axis gantry to the vertical posts. There the Z issue was not as pronounced, and I was getting really messy prints in the first few Z layers. Here that is not an issue; the first few layers look fine while they're printing. Loosening the rollers did not resolve it.</p> <p>Things I've tried:</p> <ul> <li>Tightening and loosening the gantry rollers using the eccentric nuts. They're currently just tight enough that turning them moves the gantry, but loose enough that I can turn them without moving the gantry if I hold it still.</li> <li>Tightening and loosening the two little screws that attach the extruder mount to the Z-axis lead screw. Currently I made them just tight, then backed off 1/4 turn.</li> <li>Adding a shim between the vertical post and the Z-axis lead screw. The lead screw is now pretty much parallel to the post.</li> <li>Slowly turning the lead screw by hand to raise and lower the gantry. There's no noticeable catching or increased resistance anywhere.</li> <li>Varying the brand and type of PLA filament.</li> <li>Varying the temperature from 190 °C to 210 °C.</li> <li>Obsessively leveling and re-leveling the bed. Manually leveling, auto leveling with the BLTouch, and adjusting the z-offset.</li> </ul> <p>I'm using the stock Ender 3 Pro profile in Cura, and printing at 0.2 mm layer height. I've kind of run out of things to check. What else can cause Z height loss in the first few layers like this?</p>
<p>Do you have any “slop” on the right side (non motor) of the gantry?</p> <p>I’ve noticed that my gantry will settle on the right side and lag behind the motor driven - ever so slightly - when it starts to drive up. It will, after that first lag, move fine for the rest of the time. Z axis travel seems barely affected but all my prints are consistently about 0.5 mm short.</p>
<p>I have the exact same issue on my Ender 3 V2, perfect bed level using a dial gauge, perfect first layer test prints (printing 9 squares all 1 layer high).</p> <p>I can only get rid of it two ways:</p> <ol> <li>Using a Raft as you have said (annoying).</li> <li>Adjusting the Z-height Just exactly as the 1st layer finishes. I raise the height by 0.15-0.20 mm (in my case), and the resulting elephant foot is about 80-90 % better.</li> </ol> <p>I recommend you follow Luke Hatfields guide on Ender 3 rework for The X-Gantry, as well as his other sections. Youtube channel &quot;Edge Of Tech&quot; does a decent job covering the rework in video form. Following most of these reworks I have made everything else in the print absolutely perfect, unfortunately EF remains.</p>
1,701
<p>How would you attach a propertychanged callback to a property that is inherited? Like such:</p> <pre><code>class A { DependencyProperty prop; } class B : A { //... prop.AddListener(PropertyChangeCallback); } </code></pre>
<p>(edited to remove recommendation to use DependencyPropertyDescriptor, which is not available in Silverlight)</p> <p><a href="http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/" rel="nofollow noreferrer">PropertyDescriptor AddValueChanged Alternative</a></p>
<p>Have you tried a two way data binding between the two dependency properties?</p>
3,344
<p>jQuery selectors are wonderful, but I sometimes I find myself typing them over and over, and it gets a little annoying.</p> <pre><code> $('#mybutton').click(function() { $('#message-box').doSomething(); $('#message-box').doSomethingElse(); $('#message-box').attr('something', 'something'); }); </code></pre> <p>So often I like to cache my objects in variables:</p> <pre><code>$('#mybutton').click(function() { var msg = $('#message-box'); msg.doSomething(); msg.doSomethingElse(); // you get the idea }); </code></pre> <p>Are there any pros or cons between these two patterns? Sometimes it feels like creating the variables is extra work, but sometimes it saves my fingers a lot of typing. Are there any memory concerns to be aware of? Do selectors clean up nicely after being used, whereas my bad coding habits tends to keep the vars in memory longer?</p> <p>This doesn't keep me up at night, but I am curious. Thanks.</p> <p>EDIT: Please see <a href="https://stackoverflow.com/questions/291841/does-jquery-do-any-kind-of-caching-of-selectors">this question</a>. It essentially asks the same thing, but I like the answer better.</p>
<p>You should chain them:</p> <pre><code>$('#mybutton').click(function() { $('#message-box').doSomething().doSomethingElse().attr('something', 'something'); }); </code></pre> <p>If you need to do something over and over again and the functions don't return the jQuery object saving them in a var is faster.</p>
<p>Actually the question is much more complex.</p> <ol> <li><p>Chaining is not always possible, because selector strings or cached jQuery selector instances might be stored in new function() properties, accessed by various prototype functions, not the single piece of code.</p></li> <li><p>You may chain both selector strings and cached jQuery selectors. I guess that using selector strings as 'this' properties should bring slower but less RAM-consuming code, while using cached selectors should bring faster yet more RAM-consuming code. Am I right?</p></li> </ol> <p>I am about to change quite a lot of new function() properties from selector strings to cached selectors, that's why I am asking.</p>
42,655
<p>I find my self having a repeater control which is being databound to an xml document. My client is now requesting that the Textbox's which are being repeater can be either a Textbox or a Checkbox.</p> <p>I cannot seem to find an easyway to essentially do the following:</p> <pre><code>if ((System.Xml.XmlNode)e.Item.DataItem.Attributes["type"] == "text") &lt;asp:TextBox runat="server" ID="txtField" Text='&lt;%#((System.Xml.XmlNode)Container.DataItem).InnerText %&gt;' CssClass="std"&gt;&lt;/asp:TextBox&gt; else &lt;asp:CheckBox runat="server" ID="txtField" Text='&lt;%#((System.Xml.XmlNode)Container.DataItem).InnerText %&gt;' CssClass="std"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Is there a nice way I can extend my current implementaion without have to rewrite the logic. If I could inject the control via "OnItemDataBound" that would also be fine. But I cannot seem to make it work</p>
<p>What about something similar to this in your markup in each the textbox and checkbox controls?</p> <blockquote> <pre><code>Visible=&lt;%= Eval("type").tostring() == "text") %&gt; </code></pre> </blockquote>
<p>If there is needed to add controls based on data then there can be used this approach:</p> <pre><code>&lt;asp:Repeater ID=&quot;ItemsRepeater&quot; runat=&quot;server&quot; OnItemDataBound=&quot;ItemRepeater_ItemDataBound&quot;&gt; &lt;itemtemplate&gt; &lt;div&gt; &lt;asp:PlaceHolder ID=&quot;ItemControlPlaceholder&quot; runat=&quot;server&quot;&gt;&lt;/asp:PlaceHolder&gt; &lt;/div&gt; &lt;/itemtemplate&gt; &lt;/asp:Repeater&gt; </code></pre> <pre><code>protected void ItemRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { var placeholder = e.Item.FindControl(&quot;ItemControlPlaceholder&quot;) as PlaceHolder; var col = (ItemData)e.Item.DataItem; placeholder.Controls.Add(new HiddenField { Value = col.Name }); placeholder.Controls.Add(CreateControl(col)); } </code></pre>
15,590
<p>In java, there's three levels of access:</p> <ul> <li>Public - Open to the world</li> <li>Private - Open only to the class </li> <li>Protected - Open only to the class and its subclasses (inheritance).</li> </ul> <p>So why does the java compiler allow this to happen?</p> <p>TestBlah.java:</p> <pre><code>public class TestBlah { public static void main(String[] args) { Blah a = new Blah("Blah"); Bloo b = new Bloo("Bloo"); System.out.println(a.getMessage()); System.out.println(b.getMessage()); //Works System.out.println(a.testing); System.out.println(b.testing); //Works } } </code></pre> <p>Blah.java:</p> <pre><code>public class Blah { protected String message; public Blah(String msg) { this.message = msg; } protected String getMessage(){ return(this.message); } } </code></pre> <p>Bloo.java:</p> <pre><code>public class Bloo extends Blah { public Bloo(String testing) { super(testing); } } </code></pre>
<p>Actually it should be:</p> <blockquote> <p>Open only to the <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html" rel="noreferrer"><strong>classes on the same package</strong></a> the class and its subclasses (inheritance)</p> </blockquote> <p>That's why</p>
<p>You're able to call <code>b.getMessage()</code> because <code>b</code> is of type <code>Bloo</code>, which extends <code>Blah</code>, and <code>getMessage()</code> is protected. Protected, as you mentioned, allows subclasses to access the method.</p> <p>You've got the following errors, though:</p> <ul> <li>Calling <code>super()</code> with no arguments in the <code>Bloo</code> constructor is an error. The compiler can't find the no-parameter <code>Blah</code> constructor because you defined one with a String parameter.</li> <li>Calling <code>new Blah()</code> in <code>TestBlah</code> <code>main</code> method is an error for the same reason as above.</li> <li>Referring to <code>a.testing</code> and <code>b.testing</code> is an error because you didn't define the variable <code>testing</code> for any class.</li> </ul>
43,148
<p>SQL Server 2005/2008 Express edition has the limitation of 4 GB per database. As far as I known the database engine considers data only, thus excluding log files, unused space, and index size.</p> <p>Getting the length of the MDF file should not give the correct database size in terms of SQL Server limitation. My question is how to get the database size?</p>
<p>sp_spaceused</p>
<p><strong><em>Common Query To Check Database Size in SQL Server that supports both Azure and On-Premises-</em></strong></p> <p><strong>Method 1 – Using ‘sys.database_files’ System View</strong></p> <pre><code>SELECT DB_NAME() AS [database_name], CONCAT(CAST(SUM( CAST( (size * 8.0/1024) AS DECIMAL(15,2) ) ) AS VARCHAR(20)),' MB') AS [database_size] FROM sys.database_files; </code></pre> <p><strong>Method 2 – Using ‘sp_spaceused’ System Stored Procedure</strong></p> <pre><code>EXEC sp_spaceused ; </code></pre>
21,249
<p>My solution includes these two projects:</p> <ul> <li>MyNamespace.Web.UI</li> <li>MyNamespace.Web.Core</li> </ul> <p>UI references Core, and Core references Foobar.dll, which exists nowhere except my library. When I build from Visual Studio 2008 Foobar.dll is in the UI project's Bin folder as expected. I have made certain it was not there before the build. </p> <p>But when I build from NAnt, it is not there, which results in a runtime exception. Here's what the NAnt task looks like:</p> <pre><code>&lt;target name="compile" depends="init"&gt; &lt;exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe" commandline="${solution.file} /m /t:Clean /p:Configuration=${project.config} /v:q" workingdir="." /&gt; &lt;exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe" commandline="${solution.file} /m /t:Rebuild /p:Configuration=${project.config} /v:q" workingdir="." /&gt; &lt;/target&gt; </code></pre> <p>In VS I have tried building, rebuilding, rebuilding all in release mode and debug mode, etc. It's always the same. Foobar.dll is in the Bin folder. Not so with NAnt. I have tried also to remove the /m switch from the NAnt script. Same result.</p> <p>There are several other dlls referenced in Core and not in UI, and they appear in Bin as expected after the NAnt build.</p> <p>My workaround is to reference Foobar.dll in the UI project, but that makes me a little nauseous. Any idea what can cause this?</p> <p>(Incidentally Foobar.dll is actually NHibernate.ProxyGenerators.CastleDynamicProxy.dll)</p>
<p>You likely have the option in VS to "Copy Local" on, which is implicitly, well, copying it locally before the build. You'll need to emulate that in NAnt. </p> <p>Similar to why you can just do a "Publish" for a web project from Visual Studio, but for the command line you have to both build and then copy out the output to wherever you are going.</p>
<p>In some things that I've worked on, I've resorted to using NAnt's <a href="http://nant.sourceforge.net/release/latest/help/tasks/copy.html" rel="nofollow noreferrer">copy task</a> to copy the DLL into the bin directory so that the project will build. I don't know if that's necessarily best practice, but it works.</p>
33,994
<p>I've read <a href="http://www.xs4all.nl/~hipster/lib/scheme/gauche/define-syntax-primer.txt" rel="noreferrer">JRM's Syntax-rules Primer</a> for the Merely Eccentric and it has helped me understand syntax-rules and how it's different from common-lisp's define-macro. syntax-rules is only one way of implementing a syntax transformer within define-syntax.</p> <p>I'm looking for two things, the first is more examples and explanations of syntax-rules and the second is good sources for learning the other ways of using define-syntax. What resources do you recommend?</p>
<p>To answer your second question: <code>syntax-case</code> is the other form that goes inside <code>define-syntax</code>. Kent Dybvig is the primary proponent of <code>syntax-case</code>, and <a href="http://www.cs.uml.edu/~giam/91.531/Textbooks/RKDybvig.pdf" rel="noreferrer">he has a tutorial on using it [PDF].</a></p> <p>I also <a href="http://docs.plt-scheme.org/guide/syntax-case.html" rel="noreferrer">read the PLT Scheme documentation</a> on <code>syntax-case</code> for a few more examples, and to learn about the variation in implementation.</p>
<p>The list of resources at <a href="https://web.archive.org/web/20150321052219/http://schemecookbook.org/Cookbook/GettingStartedMacros" rel="nofollow noreferrer">The Scheme Cookbook</a> is a great place to start. If you prefer papers, then don't hessitate to visit <a href="https://web.archive.org/web/20160306064729/http://readscheme.org/" rel="nofollow noreferrer">readscheme.org</a>.</p>
15,948
<p>I'll regularly get an extract from a DB/2 database with dates and timestaps formatted like this:</p> <pre><code>2002-01-15-00.00.00.000000 2008-01-05-12.36.05.190000 9999-12-31-24.00.00.000000 </code></pre> <p>Is there an easier way to convert this into the Excel date format than decomposing with substrings?</p> <pre><code>DB2date = DateValue(Left(a, 4) + "/" + Mid(a, 6, 2) + "/" + Mid(a, 9, 2)) </code></pre> <p>thanks for your help!</p>
<p>It's not clear if you talk about formula functions or VBA functions.</p> <h2>Formula functions</h2> <p>Don't use the DateValue function, which expects a string; use the Date function, which expects numeric Year, Month, Day:</p> <pre><code>=DATE(INT(LEFT(A1,4)),INT(MID(A1,6,2)),INT(MID(A1,9,2))) </code></pre> <p>assuming that the date-as-string is in A1.</p> <h2>VBA functions</h2> <p>Similar calculation as above, just use the <strong>DateSerial</strong> function instead:</p> <pre><code>dt= DateSerial(Int(Left$(dt$, 4), Int(Mid$(dt$, 6, 2)), Int(Mid$(dt$, 9, 2))) </code></pre>
<p>I'm sure you could cook something up with Regex's if you really cared to. It wouldn't be any 'better' though, probably worse. </p> <p>If you'll forgive a bit of C# (I havn't touched VB in years, so I don't know the function calls anymore) you could also do:</p> <pre><code>DB2string = "2002-01-15-00.00.00.000000"; DB2date = DateValue(DB2string.SubString(0, 10).Replace('-', '/')); </code></pre> <p>But again, you're not really gaining anything. Can you give an example of where your current code would break?</p>
20,071
<p>What is the XPath expression that I would use to get the string following 'HarryPotter:' for each book.</p> <p>ie. Given this XML:</p> <pre><code>&lt;bookstore&gt; &lt;book&gt; HarryPotter:Chamber of Secrets &lt;/book&gt; &lt;book&gt; HarryPotter:Prisoners in Azkabahn &lt;/book&gt; &lt;/bookstore&gt; </code></pre> <p>I would get back:</p> <pre><code>Chamber of Secrets Prisoners in Azkabahn </code></pre> <p>I have tried something like this:</p> <pre><code>/bookstore/book/text()[substring-after(. , 'HarryPotter:')] </code></pre> <p>I think my syntax is incorrect...</p>
<p>In XPath 2.0 this can be produced by a single XPath expression:</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><code>/*/*/substring-after(., 'HarryPotter:')</code></strong></p> <p>Here we are using the very powerful feature of XPath 2.0 that at the end of a path of location steps we can put a function and this function will be applied on all nodes in the current result set.</p> <p><strong>In XPath 1.0 there is no such feature</strong> and this cannot be accomplished in one XPath expression.</p> <p>We could perform an XSLT transformation like the following:</p> <pre> &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> &lt;xsl:output method="text"/> &lt;xsl:template match="/"> &lt;xsl:for-each select="/*/*[substring-after(., 'HarryPotter:')]"> &lt;xsl:value-of select= "substring-after(., 'HarryPotter:')"/> &lt;xsl:text>&amp;#xA;&lt;/xsl:text> &lt;/xsl:for-each> &lt;/xsl:template> &lt;/xsl:stylesheet> </pre> <p>When applied on the original XML document:</p> <pre> &lt;bookstore> &lt;book> HarryPotter:Chamber of Secrets &lt;/book> &lt;book> HarryPotter:Prisoners in Azkabahn &lt;/book> &lt;/bookstore> </pre> <p>this transformation produces the wanted result:</p> <p><strong>Chamber of Secrets <br /> Prisoners in Azkabahn</strong> </p>
<p>Xpath:</p> <pre><code>substring-after(//book, 'HarryPotter:') </code></pre> <p>I'm totally new in this area, but for me, it works ...!</p>
43,191
<p>I've used both and I've found MySql to have several frustrating bugs, limited support for: IDE integration, profiling, integration services, reporting, and even lack of a decent manager. Total cost of ownership of MSSQL Server is touted to be less than MySQL too (.net environment), but maintaining an open mind could someone point out any killer features of MySql?</p>
<p>I've used MySQL in the past and I'm using MSSQL lately but I can't remember anything that MySQL has and MSSQL can't do. </p> <p>I think the most killer feature of MySQL it's the simplicity. For some projects you just don't need all the power you can have with a huge system like MSSQL. I have an UNIX heritage and find the simple configuration file like my.ini a killer feature of MySQL.</p> <p>Also the security system of MySQL is much less robust but it makes the job right for most of applications. I believe MySQL it's killer itself from this point of view, and should stay that way, letting young users being introduced to RDBMS with a simple view first. If your project gets big enough that you are considering switch to a more robust system, then MSSQL can pop as a possibility. </p> <p>That's what happened to me.</p>
<p>MySQL probably has a lower TCO, since administration and configuration is more simple and straightforward than the Spaghetti GUI that MS SQL makes you do most of the configuration through, having to dig through hundreds of obscure properties dialogs to accomplish even basic administration tasks.</p> <p>There is one area where MS SQL clearly excels over MySQL in my experience:</p> <ul> <li>Integration with other technologies. MS SQL allows you to replicate back and forth with Oracle and MySQL databases, and provides SSIS for executing scheduled data transformations from other database servers.</li> </ul> <p>There may be others, but I don't have experience with them.</p>
28,185
<p>A few years ago client Java was unsuitable for web development because a remarkable part of web users did not have Java installed. ( I don't remember exact numbers, more than 10%). </p> <p>Now I see the Google Analytics stats for a big site and it tells that >98% of users have Java installed.</p> <p>Is these stats very biased by Javascript usage? As I understand Google Analytics measure only users that has Javascript.</p> <p>Is the picture similar on other big sites?</p> <p><b>Does client Java have really "stopper" drawbacks compared to Flash?</b></p> <p>EDIT: I mean java applets mainly, java WebStart seems to be not suitable for average user.<br> I mention Javascript only to describe the way Google Analytics works.</p>
<p>When I wrote my diploma project, I had to choose between Flash and Java Applets. Here are some pros and cons: </p> <p>Java Applets: </p> <ul> <li>[plus] you program in Java, which is mature and stable</li> <li>[plus] you can use the Java GUI frameworks that pack a lot of punch</li> <li>[minus] the first time the user hits the page with the applet, the JVM must be initialized and this can take up to a few minutes even on a fast computer</li> <li>[minus] Applets are not meant to be used as animation media; sure, you can do stuff, but it is like programming in C - you do everything from scratch</li> </ul> <p>example: i needed to show a data packet as it moved between two routers. The packet must be a control of some sort, like a button or smth. This animation can be defined in 1 line of code in Flash, where all objects derive from some base object that can be animated. I could not find a suitable solution in Java. </p> <p>Flash: </p> <ul> <li>[plus] really really focused on animations; </li> <li>[plus] ActionScript is actually an OO language</li> <li>[minus] ActionScript is sloppy, bughish and has only a few supporters. If you are stuck, be prepared to search obscure Japanese forums for solutions</li> <li>[minus] ActionSCript may be OO, but it lacks a lot of features, like Enums, fully fledged interfaces, threads (!!!!) etc.</li> <li>[minus] Flash was designed to be used by non-tech people - they just use the authoring tool; I wrote code for everything and it worked, but it was a pain. </li> </ul> <p>My conclusion: </p> <p>I eagerly await a programming paradigm for animations and rich client interfaces. </p> <p>ps: Silverlight seems to be a disappointment so far, maybe Microsoft will inject some $ into it.</p>
<p>Not an exact answer, as it would be very opinionated, just sharing my experience... </p> <p>In a recent project, where we were building a WAI compliant site, we were asked to avoid flash objects as accessiblity was a major issue. Applets on a different note don't go very well with most web developers ;). One reason might be the differences in the paradigms of Rich UI vs. web UI. </p> <p>However, we found applets to be irreplaceable (not speaking for .NET and ActiveX controls) when client side monitoring was needed. The application uses SmartCard based authentication and applets are loaded into browser to listen for client side events (card removal) and alert the server to end session.</p> <p>In this context I tend to feel that Flash is meant to be eye candy (view) where as applet though designed to be versatile, takes the role of model on client side. It is to be noted that both applets and flash consume CPU cycles on client machine, hence were traditionally suited for tasks involving lengthy computation. Calculators, Report generators, Trend illustrators, Astrological chart generators (yes) and other tasks where data can be fed by user and are results shown immediately make use of these.</p> <p>A major concern involves lack of client side software (Java, flash plugins). The user experience in such cases is more than annoying.</p>
37,304
<p>In PHP you can access characters of strings in a few different ways, one of which is substr(). You can also access the Nth character in a string with curly or square braces, like so:</p> <pre><code>$string = 'hello'; echo $string{0}; // h echo $string[0]; // h </code></pre> <p>My question is, is there a benefit of one over the other? What's the difference between {} and []?</p> <p>Thanks.</p>
<p>use <code>$string[0]</code>, the other method (braces) has been removed in PHP 8.0.</p> <p>For <a href="https://www.php.net/manual/en/language.types.string.php" rel="nofollow noreferrer">strings</a>:</p> <blockquote> <p>Accessing characters within string literals using the {} syntax has been deprecated in PHP 7.4. This has been removed in PHP 8.0.</p> </blockquote> <p>And for <a href="https://www.php.net/manual/en/language.types.array.php" rel="nofollow noreferrer">arrays</a>:</p> <blockquote> <p>Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.</p> </blockquote>
<p>Yes, there's no difference. This language quirk has some history...</p> <p>Originally, the curly brace syntax was intended to replace the square bracket syntax which was going to be deprecated:</p> <p><a href="http://web.archive.org/web/20010614144731/http://www.php.net/manual/en/language.types.string.php#language.types.string.substr" rel="nofollow">http://web.archive.org/web/20010614144731/http://www.php.net/manual/en/language.types.string.php#language.types.string.substr</a>.</p> <p>Later that policy was reversed, and the square brackets syntax was preferred instead:</p> <p><a href="http://web.archive.org/web/20060702080821/http://php.net/manual/en/language.types.string.php#language.types.string.substr" rel="nofollow">http://web.archive.org/web/20060702080821/http://php.net/manual/en/language.types.string.php#language.types.string.substr</a></p> <p>and even later, the curly braces one was going to be deprecated:</p> <p><a href="http://web.archive.org/web/20080612153808/http://www.php.net/manual/en/language.types.string.php#language.types.string.substr" rel="nofollow">http://web.archive.org/web/20080612153808/http://www.php.net/manual/en/language.types.string.php#language.types.string.substr</a></p> <p>As of this writing, it seems that the deprecation has been withdrawn as well and they are just considered two alternative syntaxes:</p> <p><a href="http://web.archive.org/web/20160607224929/http://php.net/manual/en/language.types.string.php#language.types.string.substr" rel="nofollow">http://web.archive.org/web/20160607224929/http://php.net/manual/en/language.types.string.php#language.types.string.substr</a></p>
43,470
<pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; div { border:1px solid #000; min-width: 50%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt;This is some text. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I believe the div should be 50 percent of the page, unless, for some reason, the text inside the div makes it larger. However, the border around the div stretches across the entire page width. This occurs in both IE and Firefox.</p> <p>Suggestions?</p>
<p>If you provide <code>absolute</code> positioning to the element, it will be <code>50%</code> in Firefox. However, IE doesn't like the <code>min-width</code> or <code>min-height</code> attributes, so you will have to define width as <code>50%</code> also for it to work in IE.</p>
<p>You may want to try an IE specific style-sheet and include and expression like:</p> <pre><code>print("width:expression(document.body.clientWidth &lt; 1024? "50%" : "100%");"); </code></pre> <p>This will change the width setting based on the width of the browser window at load time. I personally like to use px as the unit measurement, but you need to try it with your specific setup.</p>
24,132
<p>I don't need to validate that the IP address is reachable or anything like that. I just want to validate that the string is in dotted-quad (xxx.xxx.xxx.xxx) IPv4 format, where xxx is between 0 and 255.</p>
<p>You probably want the <a href="http://man7.org/linux/man-pages/man3/inet_pton.3.html" rel="nofollow noreferrer">inet_pton</a>, which returns -1 for invalid AF argument, 0 for invalid address, and +1 for valid IP address. It supports both the IPv4 and future IPv6 addresses. If you still need to write your own IP address handling, remember that a standard 32-bit hex number is a valid IP address. Not all IPv4 addresses are in dotted-decimal notation. </p> <p>This function both verifies the address, and also allows you to use the same address in related socket calls. </p>
<pre><code>void validate_ip_address(const std::string&amp; s) { const std::string number_0_255 = "((([0-9])|([1-9][0-9])|(1[0-9][0-9]|2[0-4][0-9]|25[0-5])){1})"; const std::string dot = "(\\.){1}"; static const boost::regex e(number_0_255 + dot + number_0_255 + dot + number_0_255 + dot + number_0_255); if (!regex_match(s, e)) { throw std::runtime_error(std::string("Uncorrect address IP: ") + s); } } </code></pre>
41,124
<p>Like many projects, we deploy to many environments, QA, UA, Developer trunks, etc..</p> <p>What is the best way to store sensitive configuration parameters in SVN? Or, should you not and just maintain a smaller unversioned file with credentials in it on the server?</p> <p>Mainly, we do not want to expose production credentials to every developer.</p>
<p>I'd rather provide configuration examples than real config files. In my project there is <code>setup.default.php</code> file in root directory that every user need to copy as <code>setup.php</code> and amend to match local environment. Additionally, to prevent checking in back customised setup files there is a rule for it in <code>.svnignore</code>.</p> <pre><code>$ echo 'setup.php' &gt; .svnignore $ svn propset svn:ignore -F .svnignore . </code></pre>
<p>I would not store configuration information in the repository at all. That way you don't have to worry about SVN trying to update the config when you update your source. </p>
18,013
<p>Today at work we came across the following code (some of you might recognize it):</p> <pre><code>#define GET_VAL( val, type ) \ { \ ASSERT( ( pIP + sizeof(type) ) &lt;= pMethodEnd ); \ val = ( *((type *&amp;)(pIP))++ ); \ } </code></pre> <p>Basically we have a byte array and a pointer. The macro returns a reference to a variable of type and advance the pointer to the end of that variable.</p> <p>It reminded me of the several times that I needed to "think like a parser" in order to understand C++ code.</p> <p>Do you know of other code examples that caused you to stop and read it several times till you managed to grasp what it was suppose to do?</p>
<p>The inverse square root implementation in Quake 3:</p> <pre><code>float InvSqrt (float x){ float xhalf = 0.5f*x; int i = *(int*)&amp;x; i = 0x5f3759df - (i&gt;&gt;1); x = *(float*)&amp;i; x = x*(1.5f - xhalf*x*x); return x; } </code></pre> <p><strong>Update:</strong> <a href="http://www.lomont.org/Math/Papers/2003/InvSqrt.pdf" rel="noreferrer">How this works</a> (thanks ryan_s)</p>
<p>Binary shift confuses me all the time. An example from the <code>java.util.concurrent.ConcurrentHashMap</code> package:</p> <pre><code>return ((h &lt;&lt; 7) - h + (h &gt;&gt;&gt; 9) + (h &gt;&gt;&gt; 17)) </code></pre>
21,485
<p>I'm trying to create a c++ library for use on windows/MSVC.</p> <p>My problem is that it seems that in order to link properly, I need to distribute a bunch of different versions, linked against different versions of MSVC's c++ runtimes - single and multi-threaded, debug and release, different compiler versions, various other security and other options.</p> <p>I'd love to just distribute maybe two, 32 bit and 64 bit.</p> <p>My idea is to maybe use a different new operator (say, mynew) and custom allocators for all my STL types. When creating the lib, /nodefaultlib. Then, when linking in from a parent project, require them to thunk mynew to new, and my stl allocator to the standard one (or one of their choosing). I guess I'd need to do delete, and a few other functions. Naturally I'd provide an example thunking implementation with the library, but this would hopefully save everyone a lot of headache.</p> <p>Is this possible? Has anyone ever tried this? Is there a best practices for library creation/distribution on windows/MSVC?</p>
<p>You want static linking, as a general answer.</p> <p>Quick note on Chris' answer (don't want to de-boost cause it's mostly good, but...):</p> <p>DO NOT link to msvcrt.dll (the unversioned one); this is the OS-specific version DLL, and if you link to it, your app probably will not work on other versions of Windows. You should always be linking to msvcrt##.dll, as far as I know. The DDK may contain a lib for it, but don't link to it unless you really know what you're doing.</p>
<p>You don't need to use a custom allocator if you are using C++, and you wrap all allocations around <code>std::tr1::shared_ptr</code> (where you can specify a deallocation function). This ensures that even when clients release the last reference to the shared pointer, it's still code in your library (or your library's CRT) that gets called when the object is to be freed.</p> <p>This is one way to solve "DLL boundary hell". Hope it helps! :-)</p> <p>Edit: I think I misread the intent of your question. Rather than not wanting any dependency on a CRT because you are worried about DLL boundary hell, I suppose you just wanted a version of your DLL that you can install anywhere. In that case, you can make your program link to <code>msvcrt.dll</code>. That's available on any Windows system.</p> <p>You didn't hear this from me, but apparently in the Driver Development Kit you can find some sort of import library that allows newer versions of Visual Studio to link to <code>msvcrt</code>.</p>
23,061
<p>Is it possible to make efficient queries that use the complete regular expression feature set.</p> <p>If not Microsoft really should consider that feature.</p>
<p>For SQL Server 2000 (and any other 32 bit edition of SQL Server), there is <a href="http://www.codeproject.com/KB/database/xp_pcre.aspx" rel="nofollow noreferrer">xp_pcre</a>, which introduces Perl compatible regular expressions as a set of extended stored procedures. I've used it, it works.</p> <p>The more recent versions give you direct access to the <a href="http://msdn.microsoft.com/en-us/magazine/cc163473.aspx" rel="nofollow noreferrer">.NET integrated regular expressions</a> (this link seems to be dead, here is another one: <a href="https://msdn.microsoft.com/en-us/library/hh272683(v=vs.103).aspx" rel="nofollow noreferrer">MSDN: How to: Work with CLR Database Objects</a>).</p>
<p>I think we can see from the new types in SQL Server 2008 (hierarchyid, geo-spatial) that if Microsoft do add this it will come in the form of a SQL CLR Assembly</p> <p>If you are able to install Assemblies into your database you could roll your own by creating a new Database\SQL Server project in Visual Studio - this will allow you to make a new Trigger / UDF / Stored Proc / Aggregate or UDT. You could import System.Text.RegularExpressions into the class and go from there.</p> <p>Hope this helps</p>
33,610
<p>Is it possible to have multiple view of the same display object? (e.g. same-computer multi-player game using split screen)</p> <p>The sample code that failed to work follows:</p> <pre><code> var content: Sprite = new Sprite(); var v1: Sprite = new Sprite(); var v2: Sprite = new Sprite(); with(content.graphics) { lineStyle(2, 0xff0000); drawCircle(100, 100, 80); lineStyle(5, 0x009999); drawRect(50, 80, 200, 30); } v1.addChild(content); v1.x = 0; v1.y = 0; v1.scrollRect = new Rectangle(0, 0, 100, 100); addChild(v1); v2.addChild(content); v2.x = 100; v2.y = 0; v2.scrollRect = new Rectangle(0, 0, 100, 100); addChild(v2); </code></pre> <p>I thought this would make two viewports (<code>v1</code> and <code>v2</code>) of the same object (<code>content</code>). But when I checked the docs, DisplayObjectContaner/addChild method, it says,</p> <p>"If you add a child object that already has a different display object container as a parent, the object is removed from the child list of the other display object container."</p> <p>Is there a solution for this?</p> <hr> <p>Obtained result</p> <p><img src="https://i.stack.imgur.com/aWKOO.png" alt="Obtained result"></p> <p>Expected result (simulated)</p> <p><a href="http://img337.imageshack.us/img337/7914/222mq4.png" rel="nofollow noreferrer">Expected result (simulated) http://img337.imageshack.us/img337/7914/222mq4.png</a></p> <hr> <p>Rendering to a bitmap as suggested by Antti is a great idea, but the rendered sprites will not be able to catch mouse events. Is there a way to redirect the mouse clicks on the bitmap to trigger clicks on the original sprites?</p>
<p>The easiest way to do this is to have a bitmap that's updated with the original display object's contents, something like:</p> <pre> var bitmap:Bitmap = new Bitmap(new BitmapData(1,1)); addChild(bitmap); addEventListener(Event.ENTER_FRAME,enterFrameHandler); function enterFrameHandler(event:Event):void { bitmap.bitmapData.dispose(); bitmap.bitmapData = new BitmapData(displayObject.width, displayObject.height, true, 0x00000000); bitmap.bitmapData.draw(displayObject); } </pre>
<p>If you put render to a bitmap inside of sprite, then you can capture mouse clicks.</p> <p>mike</p>
23,172
<p>I have following string</p> <pre><code>String str = "replace :) :) with some other string"; </code></pre> <p>And I want to replace first occurance of <code>:)</code> with some other string</p> <p>And I used <code>str.replaceFirst(":)","hi");</code></p> <p>it gives following exception</p> <blockquote> <p>"Unmatched closing ')'"</p> </blockquote> <p>I tried using <code>replace</code> function but it replaced all occurance of <code>:)</code>.</p>
<p>The <code>replaceFirst</code> method takes a regular expression as its first parameter. Since <code>)</code> is a special character in regular expressions, you must quote it. Try:</p> <pre><code>str.replaceFirst(":\\)", "hi"); </code></pre> <p>The double backslashes are needed because the double-quoted string also uses backslash as a quote character.</p>
<p><a href="http://commons.apache.org/" rel="nofollow noreferrer">Apache Jakarta Commons</a> are often the solution for this class of problems. In this case, I would have a look at <a href="http://commons.apache.org/lang/" rel="nofollow noreferrer">commons-lang</a>, espacially <a href="http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html#replaceOnce(java.lang.String,%20java.lang.String,%20java.lang.String)" rel="nofollow noreferrer">StringUtils.replaceOnce()</a>.</p>
38,167
<p>I am trying to write a unit test for an action method which calls the <code>Controller.RedirectToReferrer()</code> method, but am getting a "No referrer available" message.</p> <p>How can I isolate and mock this method?</p>
<p>Have you thought about creating a <a href="http://xunitpatterns.com/Test%20Double.html" rel="nofollow noreferrer">test double</a>?</p>
<p>In <em>my</em> version of the trunk I'm working against, r5299, I had to do this to mock out RedirectToReferrer. I think it's been changed in recent commits, I'm not sure.</p> <pre><code>[TestFixture] public class LoginControllerTests : GenericBaseControllerTest&lt;LoginController&gt; { private string referrer = "http://www.example.org"; protected override IMockRequest BuildRequest() { var request = new StubRequest(Cookies); request.UrlReferrer = referrer; return request; } protected override IMockResponse BuildResponse(UrlInfo info) { var response = new StubResponse(info, new DefaultUrlBuilder(), new StubServerUtility(), new RouteMatch(), referrer); return response; } </code></pre> <p>etc. etc.</p> <p>It's oddly the <em>Response</em> that you need to molest to get the <code>RedirectToReferrer</code> to work. I had to crawl around in the monorail sources to figure it out.</p>
8,737
<p>Is there something like <a href="http://effbot.org/zone/python-getattr.htm" rel="noreferrer">Python's getattr()</a> in C#? I would like to create a window by reading a list which contains the names of controls to put on the window.</p>
<p>There is also <a href="http://msdn.microsoft.com/en-us/library/66btctbe.aspx" rel="noreferrer">Type.InvokeMember</a>.</p> <pre><code>public static class ReflectionExt { public static object GetAttr(this object obj, string name) { Type type = obj.GetType(); BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty; return type.InvokeMember(name, flags, Type.DefaultBinder, obj, null); } } </code></pre> <p>Which could be used like:</p> <pre><code>object value = ReflectionExt.GetAttr(obj, "PropertyName"); </code></pre> <p>or (as an extension method):</p> <pre><code>object value = obj.GetAttr("PropertyName"); </code></pre>
<p>There's the System.Reflection.PropertyInfo class that can be created using object.GetType().GetProperties(). That can be used to probe an object's properties using strings. (Similar methods exist for object methods, fields, etc.)</p> <p>I don't think that will help you accomplish your goals though. You should probably just create and manipulate the objects directly. Controls have a Name property that you can set, for example.</p>
16,697
<p>My bash script doesn't work the way I want it to:</p> <pre><code>#!/bin/bash total="0" count="0" #FILE="$1" This is the easier way for FILE in $* do # Start processing all processable files while read line do if [[ "$line" =~ ^Total ]]; then tmp=$(echo $line | cut -d':' -f2) count=$(expr $count + 1) total=$(expr $total + $tmp) fi done &lt; $FILE done echo "The Total Is: $total" echo "$FILE" </code></pre> <p>Is there another way to modify this script so that it reads arguments into <code>$1</code> instead of <code>$FILE</code>? I've tried using a <code>while</code> loop:</p> <pre><code>while [ $1 != "" ] do .... done </code></pre> <p>Also when I implement that the code repeats itself. Is there a way to fix that as well?</p> <p>Another problem that I'm having is that when I have multiple files <code>hi*.txt</code> it gives me duplicates. Why? I have files like <code>hi1.txt</code> <code>hi1.txt~</code> but the tilde file is of 0 bytes, so my script shouldn't be finding anything.</p> <hr> <p>What i have is fine, but could be improved. I appreciate your awk suggestions but its currently beyond my level as a unix programmer. </p> <p>Strager: The files that my text editor generates automatically contain nothing..it is of 0 bytes..But yeah i went ahead and deleted them just to be sure. But no my script is in fact reading everything twice. I suppose its looping again when it really shouldnt. I've tried to silence that action with the exit commands..But wasnt successful.</p> <pre><code>while [ "$1" != "" ]; do # Code here # Next argument shift done </code></pre> <p>This code is pretty sweet, but I'm specifying all the possible commands at one time. Example: hi[145].txt If supplied would read all three files at once. Suppose the user enters hi*.txt; I then get all my hi files read twice and then added again.</p> <p>How can I code it so that it reads my files (just once) upon specification of hi*.txt? I really think that this is because of not having $1.</p>
<p>It looks like you are trying to add up the totals from the lines labelled 'Total:' in the files provided. It is always a good idea to state what you're trying to do - as well as how you're trying to do it (see <a href="http://www.catb.org/~esr/faqs/smart-questions.html" rel="nofollow noreferrer">How to Ask Questions the Smart Way</a>).</p> <p>If so, then you're doing in about as complicated a way as I can see. What was wrong with:</p> <pre><code>grep '^Total:' "$@" | cut -d: -f2 | awk '{sum += $1} END { print sum }' </code></pre> <p>This doesn't print out "The total is" etc; and it is not clear why you echo $FILE at the end of your version.</p> <p>You can use Perl or any other suitable program in place of <code>awk</code>; you could do the whole job in Perl or Python - indeed, the <code>cut</code> work could be done by <code>awk</code>:</p> <pre><code>grep "^Total:" "$@" | awk -F: '{sum += $2} END { print sum }' </code></pre> <p>Taken still further, the whole job could be done by <code>awk</code>:</p> <pre><code>awk -F: '$1 ~ /^Total/ { sum += $2 } END { print sum }' "$@" </code></pre> <p>The code in Perl wouldn't be much harder and the result might be quicker:</p> <pre><code>perl -na -F: -e '$sum += $F[1] if m/^Total:/; END { print $sum; }' "$@" </code></pre> <p>When iterating over the file name arguments provided in a shell script, you should use '<code>"$@"</code>' in place of '<code>$*</code>' as the latter notation does not preserve spaces in file names.</p> <p>Your comment about '<code>$1</code>' is confusing to me. You could be asking to read from the file whose name is in <code>$1</code> on each iteration; that is done using:</p> <pre><code>while [ $# -gt 0 ] do ...process $1... shift done </code></pre> <p>HTH!</p>
<p>If you define a function, it'll receive the argument as $1. Why is $1 more valuable to you than $FILE, though?</p> <pre><code>#!/bin/sh process() { echo "doing something with $1" } for i in "$@" # Note use of "$@" to not break on filenames with whitespace do process "$i" done </code></pre>
42,359
<p>I have embedded a Python interpreter in a C program. Suppose the C program reads some bytes from a file into a char array and learns (somehow) that the bytes represent text with a certain encoding (e.g., ISO 8859-1, Windows-1252, or UTF-8). How do I decode the contents of this char array into a Python string?</p> <p>The Python string should in general be of type <code>unicode</code>—for instance, a <code>0x93</code> in Windows-1252 encoded input becomes a <code>u'\u0201c'</code>.</p> <p>I have attempted to use <code>PyString_Decode</code>, but it always fails when there are non-ASCII characters in the string. Here is an example that fails:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *py_string; Py_Initialize(); py_string = PyString_Decode(c_string, 1, "windows_1252", "replace"); if (!py_string) { PyErr_Print(); return 1; } return 0; } </code></pre> <p>The error message is <code>UnicodeEncodeError: 'ascii' codec can't encode character u'\u201c' in position 0: ordinal not in range(128)</code>, which indicates that the <code>ascii</code> encoding is used even though we specify <code>windows_1252</code> in the call to <code>PyString_Decode</code>.</p> <p>The following code works around the problem by using <code>PyString_FromString</code> to create a Python string of the undecoded bytes, then calling its <code>decode</code> method:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *raw, *decoded; Py_Initialize(); raw = PyString_FromString(c_string); printf("Undecoded: "); PyObject_Print(raw, stdout, 0); printf("\n"); decoded = PyObject_CallMethod(raw, "decode", "s", "windows_1252"); Py_DECREF(raw); printf("Decoded: "); PyObject_Print(decoded, stdout, 0); printf("\n"); return 0; } </code></pre>
<p>PyString_Decode does this:</p> <pre><code>PyObject *PyString_Decode(const char *s, Py_ssize_t size, const char *encoding, const char *errors) { PyObject *v, *str; str = PyString_FromStringAndSize(s, size); if (str == NULL) return NULL; v = PyString_AsDecodedString(str, encoding, errors); Py_DECREF(str); return v; } </code></pre> <p>IOW, it does basically what you're doing in your second example - converts to a string, then decode the string. The problem here arises from PyString_AsDecodedString, rather than PyString_AsDecodedObject. PyString_AsDecodedString does PyString_AsDecodedObject, but then tries to convert the resulting unicode object into a string object with the default encoding (for you, looks like that's ASCII). That's where it fails.</p> <p>I believe you'll need to do two calls - but you can use PyString_AsDecodedObject rather than calling the python "decode" method. Something like:</p> <pre><code>#include &lt;Python.h&gt; #include &lt;stdio.h&gt; int main(int argc, char *argv[]) { char c_string[] = { (char)0x93, 0 }; PyObject *py_string, *py_unicode; Py_Initialize(); py_string = PyString_FromStringAndSize(c_string, 1); if (!py_string) { PyErr_Print(); return 1; } py_unicode = PyString_AsDecodedObject(py_string, "windows_1252", "replace"); Py_DECREF(py_string); return 0; } </code></pre> <p>I'm not entirely sure what the reasoning behind PyString_Decode working this way is. A <a href="http://mail.python.org/pipermail/python-dev/2001-May/014547.html" rel="nofollow noreferrer">very old thread on python-dev</a> seems to indicate that it has something to do with chaining the output, but since the Python methods don't do the same, I'm not sure if that's still relevant.</p>
<p>You don't want to decode the string into a Unicode representation, you just want to treat it as an array of bytes, right?</p> <p>Just use <code>PyString_FromString</code>:</p> <pre><code>char *cstring; PyObject *pystring = PyString_FromString(cstring); </code></pre> <p>That's all. Now you have a Python <code>str()</code> object. See docs here: <a href="https://docs.python.org/2/c-api/string.html" rel="nofollow noreferrer">https://docs.python.org/2/c-api/string.html</a></p> <p>I'm a little bit confused about how to specify "str" or "unicode." They are quite different if you have non-ASCII characters. If you want to decode a C string <strong>and</strong> you know exactly what character set it's in, then yes, <code>PyString_DecodeString</code> is a good place to start.</p>
26,259
<p>What are the most common memory optimizations in csharp, dotnet 2.0. Wanted to see if there common things that people may not be doing by default in winform app</p>
<ul> <li>use structs for small wrapper objects to avoid heap fragmentation</li> <li>think carefully about object lifetimes, especially for large objects so they do not end up on the LOH unless you intend them to</li> <li>think about allocations inside of a loop</li> <li>make sure dynamically sized array will be of reasonable size, otherwise partition the problem</li> </ul>
<p>Sealing as much classes as possible should also help. AFAIK this is one trick that SmartAssembly uses to reduce memory consumption.</p>
8,560
<p>I did some googling to try to answer this question but even after that I'm not quite clear about something. Is it possible to create a console app from VB6? </p> <p>I've got a VB6 app that doesn't put up a window. I always assumed that it was a console app. However, I want to be able to use the Windows API SetConsoleCtrlHandler function from within it. I believe that with C++/MFC apps you have to set a linker switch to create a console app. And one of my fellow developers told me that VB6 doesn't create a true console app and therefore this would not work. So is it possible to create a console app that Windows will recognize as a console app from VB6?</p> <p>Platform: Windows XP SP2</p> <p>Development Platform: VB6</p>
<p>Yes. It's also possible to create totally headless applications (which I've done a few times in the past). <a href="http://www.tek-tips.com/faqs.cfm?fid=5647" rel="noreferrer">This link</a> gives an example with a code snippet.</p>
<p>See this <a href="http://visualbasic.about.com/od/learnvb6/l/bldykvb6dosa.htm" rel="nofollow noreferrer">article</a>. </p> <p>Or you could rewrite the VB6 app as a VBScript program.</p>
36,490
<p>Is there a way to get notification of date change in c#?</p> <p>I have a requirement where I have to do something when the system date is changed.</p> <p>I found that SystemsEvent.TimeChanged is an event you can hook into, however it is only fired only when user has changed the time.</p>
<p>Would this be better handled by having a scheduled task/cron job that runs at midnight?</p>
<p>Your app could run a loop that sleeps for a minute, then checks the date. If it's different than last time, run your logic.</p> <p>But I agree that this scenario would be better handled with a scheduled task.</p>
48,665
<p>Visual Studio gives many navigation hotkeys: <kbd>F8</kbd> for next item in current panel (search results, errors ...), <kbd>Control</kbd>+<kbd>K</kbd>, <kbd>N</kbd> for bookmarks, <kbd>Alt</kbd>+<kbd>-</kbd> for going back and more.</p> <p>There is one hotkey that I can't find, and I can't even find the menu-command for it, so I can't create the hotkey myself.</p> <p>I don't know if such exist: Previous and Next call-stack frame.</p> <p>I try not using the mouse when programming, but when I need to go back the stack, I must use it to double click the previous frame.</p> <p>Anyone? How about a macro that does it?</p>
<p>I wrote 2 macros to gain it: <code>PreviousStackFrame</code> and <code>NextStackFrame</code> and assigned shortcuts to</p> <pre><code>Function StackFrameIndex(ByRef aFrames As EnvDTE.StackFrames, ByRef aFrame As EnvDTE.StackFrame) As Long For StackFrameIndex = 1 To aFrames.Count If aFrames.Item(StackFrameIndex) Is aFrame Then Exit Function Next StackFrameIndex = -1 End Function Sub NavigateStack(ByVal aShift As Long) If DTE.Debugger.CurrentProgram Is Nothing Then DTE.StatusBar.Text = "No program is currently being debugged." Exit Sub End If Dim ind As Long = StackFrameIndex(DTE.Debugger.CurrentThread.StackFrames, DTE.Debugger.CurrentStackFrame) If ind = -1 Then DTE.StatusBar.Text = "Stack navigation failed" Exit Sub End If ind = ind + aShift If ind &lt;= 0 Or ind &gt; DTE.Debugger.CurrentThread.StackFrames.Count Then DTE.StatusBar.Text = "Stack frame index is out of range" Exit Sub End If DTE.Debugger.CurrentStackFrame = DTE.Debugger.CurrentThread.StackFrames.Item(ind) DTE.StatusBar.Text = "Stack frame index: " &amp; ind &amp; " of " &amp; DTE.Debugger.CurrentThread.StackFrames.Count End Sub Sub PreviousStackFrame() NavigateStack(1) End Sub Sub NextStackFrame() NavigateStack(-1) End Sub </code></pre>
<p>Look in <strong>Tools->Options->Environment->Keyboard</strong>. Enter "stack" or "frame" and related menus will appear. It seems that there's no next and previous call-stack frame.</p>
28,393
<p>I have a struts-based webapp, and I would like the default "welcome" page to be an action. The only solutions I have found to this seem to be variations on making the welcome page a JSP that contains a redirect to the action. For example, in <code>web.xml</code>:</p> <pre><code>&lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; </code></pre> <p>and in <code>index.jsp</code>:</p> <pre><code>&lt;% response.sendRedirect("/myproject/MyAction.action"); %&gt; </code></pre> <p>Surely there's a better way!</p>
<p>Personally, I'd keep the same setup you have now, but change the redirect for a forward. That avoids sending a header back to the client and having them make another request.</p> <p>So, in particular, I'd replace the </p> <pre><code>&lt;% response.sendRedirect("/myproject/MyAction.action"); %&gt; </code></pre> <p>in index.jsp with</p> <pre><code>&lt;jsp:forward page="/MyAction.action" /&gt; </code></pre> <p>The other effect of this change is that the user won't see the URL in the address bar change from "<a href="http://server/myproject" rel="noreferrer">http://server/myproject</a>" to "<a href="http://server/myproject/index.jsp" rel="noreferrer">http://server/myproject/index.jsp</a>", as the forward happens internally on the server.</p>
<p>This works as well reducing the need of a new servlet or jsp</p> <pre><code>&lt;welcome-file-list&gt; &lt;welcome-file&gt;/MyAction.action&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; </code></pre>
6,045
<p>I am trying to create a custom control that a "gridview" like control but specifcally for business objects that implement certain custom interfaces. </p> <p>In doing this I have come across the following problem.</p> <p>I have a control that I have disabled viewstate on (and I don't want to re-enable it) and it has a child control that I want viewstate enabled on. I can't seem to get the viewstate on the child control to work since its parents is disabled. Does anyone have any ideas of how to get that to work?</p>
<p>You cannot enable viewstate on a control which is within another control that has viewstate disabled.</p> <p>Your only option is to enable it for the outer control, and then turn it off for all of the controls within it, except for the control you need viewstate.</p> <p>EnableViewState property on any container will override the behavior of all controls within that containter.</p> <p>Good Luck!</p> <p><strong>EDIT:</strong> You may want to look at your <strong>CreateChildContols()</strong> method and enumerate the controls disabling viewstate from there for each of the controls within the custom control using the <strong>EnableViewState</strong> property.</p>
<p>If you're happy putting data into the ViewState manually (instead of letting ASP.NET preserve the state of your control for you), You could put items directly into the ViewState of the page, rather than the ViewState of your control.</p> <p>I.e. instead of saying:</p> <pre><code>this.ViewState["someKey"] = someValue; </code></pre> <p>say:</p> <pre><code>this.Page.ViewState["someKey"] = someValue; </code></pre> <p>Be careful though - if you have more than one instance of your control on the page, you'll have to make sure they use different keys!</p>
21,132
<p>Has anybody been successful in integrating the Enterprise Library v4.0 with SharePoint WSS 3.0? I created a very simple .ASPX page. It's only purpose will to be to connect to an Oracle database and display some values in a DropDownList. But right now, all it does is displays Hello World. I've added the necessary references and everything compiles fine. When I test the page, it displays Hello World. But once I add the using Microsoft.Practices.EnterprisesLibrary.Data, the page no longer works. I just get the standard Unknown Error message. Is there a log file I can check? </p> <p>I'm looking for any steps or tips that I can use to get this up and running. I use this Enterprise Library in all my ASP.NET applications and it works great. Trying to get this to work in SharePoint seems like a natural fit. But why does it seem so difficult? And why does there seem to be a lack of information?</p> <p>Anyways, thank you so much for any information anybody can provide.</p>
<p>I'm not sure about the Enterprise Library, but to get a more meaningful error message from SharePoint than the super informative "Unknown Error" message go modify a couple things in web.config:</p> <ol> <li>In <code>&lt;SharePoint&gt;&lt;SafeMode&gt;</code> set the CallStack property = "true"</li> <li>In <code>&lt;system.web&gt;&lt;compilation&gt;</code> set the debug property = "true"</li> <li>In <code>&lt;system.web&gt;&lt;customErrors&gt;</code> set the mode property = "Off"</li> </ol>
<p>Are you able to debug and see where the failure is occurring in your code? Is it occurring on an Enterprise Library related call? If so I would capture the exception that is being thrown and evaluate the message that it provides using; try {} catch (Exception ex) {}.</p> <p>One thing I have seen with Enterprise Library that if it is not properly configured it will sometimes log messages to the Event Log on the server.</p> <p>I'm sorry I can't get much more information without more technical details about your implementation. I can assure you though that Enterprise Library works very well with SharePoint and that for the past few years I have used Enterprise Library in all of my SharePoint solution work.</p>
22,455
<p>I'm working on a gadget a bit like a jewelry box. I want the lid on a hinge. Are 3d printed hinges robust enough for daily use long term? Perhaps with a metal pin?</p> <p>I want to incorporate the hinge into the design but my thinking is that it would be a waste of time if the hinge will break as I'd need to reprint the whole gadget.</p>
<p>You can make a print-in-place hinge as a horizontal cone with a 45-degree angle. The opposing face will be a similar conical hole with a 0.25 mm gap between the faces (or whatever your printer's tolerance needs to be).</p> <p>The strength of this (as in the other answers) depends on the diameter of the hinge. The strength you need depends on how heavy the thing it holds up will be.</p> <p>There are many parts on Thingiverse that use conical hinges like this if you need examples.</p> <p><a href="https://i.stack.imgur.com/5mEi1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5mEi1.png" alt="disassembled conical hinge" /></a> The above is a disassembled conical hinge from <a href="https://www.thingiverse.com/thing:5143964" rel="nofollow noreferrer">thing:5143964 (sturdy infinity cube)</a> which I split into parts and then arranged the hinged coupling next to the block it fits in. (Technically I suppose this is a frustrum. But things that come to a zero diameter pointy tip tend to not print well.)</p> <p>There are 4 holes in the linkage, and the whole assembly is printed at once.</p>
<p>Maker's Muse has <a href="https://www.youtube.com/watch?v=7JhjhgjchfM" rel="nofollow noreferrer">a video</a> on how to design hinged objects for printing. It's quite old and might be outdated with regard to materials, slicer functionality, etc. but I think it provides a good background on the topic and a source of ideas. One of the good tips is to look at the abundance of existing hinged designs on Thingiverse and other model sharing sites - that way you can study how they work and test print some before you spend time designing your own thing that might not work.</p>
2,119
<p>I am writing a console program in C#.</p> <p>Is there a way I can use a Console.Clear() to only clear certain things on the console screen?</p> <p>Here's my issue:</p> <p>I have a logo (I put it on screen using Console.WriteLine()) and a 2d array which I want to keep constant and clear everything below it. </p>
<p>You could use a custom method to clear parts of the screen...</p> <pre><code>static void Clear(int x, int y, int width, int height) { int curTop = Console.CursorTop; int curLeft = Console.CursorLeft; for (; height &gt; 0;) { Console.SetCursorPosition(x, y + --height); Console.Write(new string(' ',width)); } Console.SetCursorPosition(curLeft, curTop); } </code></pre>
<p>Can you not clear and then re-write the logo and array? The console is not designed to be used as you describe.</p>
49,498
<p>I'm having some doubts on how to set up my SVN stuff. </p> <p>First my situation: Programmer working alone on most stuff, outside access not needed (yet).</p> <p>I want:<ul> <li>A speedy SVN, preferably free. <li>Private <li>Backup friendly <li>Somewhat hassle free <li>A lot of storage. </ul> I don't want:<ul> <li>To have problems transfering my data to another comp / svn install. </ul> I tried: Assembla free hosted solution and some other free hosted solutions, these won't work for me because of storage / project limitations. </p> <p>So now I have the options:<ul> <li>Get a shared host with a large amount of space for SVN. <li>Just install it on one of my comps (running windows) <li>Install it on a vmware image which would make it easier to copy and maybe ease the backup process. </ul></p> <p>What would you do in my situation and why?</p> <p>Edit:</p> <p>Or is GIT a better option in this situation, and if so why? (keeping in mind that I have no experience with this technology)</p>
<p>I would have a look at <a href="http://visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a>. It installs easily on Windows and addresses all your concerns.</p>
<p>Hmm, my bet would be to install it on your machine, on an external hard disk drive. You will sacrifice a bit of the speed, but you'll have the storage (it has it's own HDD) and the back-up friendliness.</p>
38,168
<p>I'm trying to convert an incoming sting of 1s and 0s from stdin into their respective binary values (where a string such as "11110111" would be converted to 0xF7). This seems pretty trivial but I don't want to reinvent the wheel so I'm wondering if there's anything in the C/C++ standard libs that can already perform such an operation?</p>
<pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int main(void) { char * ptr; long parsed = strtol("11110111", &amp; ptr, 2); printf("%lX\n", parsed); return EXIT_SUCCESS; } </code></pre> <p>For larger numbers, there as a <code>long long</code> version, <code>strtoll</code>.</p>
<pre><code>#include &lt;iostream&gt; #include &lt;stdio.h&gt; #include &lt;string&gt; using namespace std; string getBinaryString(int value, unsigned int length, bool reverse) { string output = string(length, '0'); if (!reverse) { for (unsigned int i = 0; i &lt; length; i++) { if ((value &amp; (1 &lt;&lt; i)) != 0) { output[i] = '1'; } } } else { for (unsigned int i = 0; i &lt; length; i++) { if ((value &amp; (1 &lt;&lt; (length - i - 1))) != 0) { output[i] = '1'; } } } return output; } unsigned long getInteger(const string&amp; input, size_t lsbindex, size_t msbindex) { unsigned long val = 0; unsigned int offset = 0; if (lsbindex &gt; msbindex) { size_t length = lsbindex - msbindex; for (size_t i = msbindex; i &lt;= lsbindex; i++, offset++) { if (input[i] == '1') { val |= (1 &lt;&lt; (length - offset)); } } } else { //lsbindex &lt; msbindex for (size_t i = lsbindex; i &lt;= msbindex; i++, offset++) { if (input[i] == '1') { val |= (1 &lt;&lt; offset); } } } return val; } int main() { int value = 23; cout &lt;&lt; value &lt;&lt; &quot;: &quot; &lt;&lt; getBinaryString(value, 5, false) &lt;&lt; endl; string str = &quot;01011&quot;; cout &lt;&lt; str &lt;&lt; &quot;: &quot; &lt;&lt; getInteger(str, 1, 3) &lt;&lt; endl; } </code></pre>
14,344
<p>I need to compress portions of our application's network traffic for performance. I presume this means I need to stay away from some of the newer algorithms like bzip2, which I think I have heard is slower.</p>
<p>You can use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/zip/Deflater.html" rel="nofollow noreferrer">Deflater</a>/<a href="http://docs.oracle.com/javase/7/docs/api/java/util/zip/Inflater.html" rel="nofollow noreferrer">Inflater</a> which is built into the JDK. There are also GZIPInputStream and GZIPOutputStream, but it really depends on your exact use. </p> <p>Edit:</p> <p>Reading further comments it looks like the network taffic is HTTP. Depending on the server, it probably has support for compression (especially with deflate/gzip). The problem then becomes on the client. If the client is a browser it probably already supports it. If your client is a webservices client or an <a href="http://hc.apache.org/httpclient-3.x/" rel="nofollow noreferrer">http client</a> check the documentation for that package to see if it is supported.</p> <p>It looks like jakarta-commons httpclient may require you to manually do the compression. To enable this on the client side you will need to do something like</p> <pre><code>.addRequestHeader("Accept-Encoding","gzip,deflate"); </code></pre>
<p>If the network traffic is going over HTTP, most of the various web servers/servlet containers support for negotiated zipping, e.g., mod_deflate for Apache.</p>
15,454
<p>I have a method to return a group of objects as a generic list which I then bind to a Repeater. I want to implement paging on the repeater using the PagedDataSource class but I'm not sure that this is possible as it doesn't seem to work.</p> <p>Will I have to change the return type of my method or is it possible to bind the PagedDataSource to the generic list?</p>
<p>I've just modified some of my code to use a generic list and seems to have worked fine, hope this helps:</p> <p>Note that this entire method can be called with or without a page number to automatically set the page, it also builds a paging control inside of a panel calling PagingPanel.</p> <p>The line that sets the DataSource on the PagedDataSource instance (dataSource) did take an array of NewsItems (searchResults), I've updated it to consume a List that's created using the NewItem array.</p> <pre><code>void PopulateNewsItems (int? pageNo) { var model = ModelFactory.GetNewsModel (); var searchResults = model.GetNewsItems (); var dataSource = new PagedDataSource (); // CHANGED THE ARRAY OF NEWSITEMS INTO A GENERIC LIST OF NEWSITEMS. dataSource.DataSource = new List&lt;NewsItem&gt; (searchResults); dataSource.AllowPaging = true; var pageSizeFromConfig = ConfigurationManager.AppSettings["NewsItemsPageCount"]; var pageSize = 10; int.TryParse (pageSizeFromConfig, out pageSize); dataSource.PageSize = pageSize; dataSource.CurrentPageIndex = pageNo ?? 0; PagingPanel.Controls.Clear (); for (var i = 0; i &lt; dataSource.PageCount; i++) { var linkButton = new LinkButton (); linkButton.CommandArgument = i.ToString (); linkButton.CommandName = "PageNo"; linkButton.Command += NavigationCommand; linkButton.ID = string.Format ("PageNo{0}LinkButton", i); if (pageNo == i || (pageNo == null &amp;&amp; i == 0)) { linkButton.Enabled = false; linkButton.CssClass = "SelectedPageLink"; } linkButton.Text = (i + 1).ToString (); PagingPanel.Controls.Add (linkButton); if (i &lt; (dataSource.PageCount - 1)) PagingPanel.Controls.Add (new LiteralControl ("|")); } NewsRepeater.DataSource = dataSource; NewsRepeater.DataBind (); } void NavigationCommand (object sender, CommandEventArgs e) { PopulateNewsItems (int.Parse ((string)e.CommandArgument)); } </code></pre>
<ol> <li>Set your PagedDataSource's datasource to your list</li> <li>Setup the paging variables of your PagedDataSource to whatever you require</li> <li>Set your repeater's datasource to the pageddatasource object itself</li> <li>Bind the repeater</li> <li>Job done</li> </ol>
38,668
<p>is there a quick way to sort the items of a select element? Or I have to resort to writing javascript?</p> <p>Please any ideas.</p> <pre><code>&lt;select size="4" name="lstALL" multiple="multiple" id="lstALL" tabindex="12" style="font-size:XX-Small;height:95%;width:100%;"&gt; &lt;option value="0"&gt; XXX&lt;/option&gt; &lt;option value="1203"&gt;ABC&lt;/option&gt; &lt;option value="1013"&gt;MMM&lt;/option&gt; &lt;/select&gt; </code></pre>
<p>This will do the trick. Just pass it your select element a la: <code>document.getElementById('lstALL')</code> when you need your list sorted.</p> <pre><code>function sortSelect(selElem) { var tmpAry = new Array(); for (var i=0;i&lt;selElem.options.length;i++) { tmpAry[i] = new Array(); tmpAry[i][0] = selElem.options[i].text; tmpAry[i][1] = selElem.options[i].value; } tmpAry.sort(); while (selElem.options.length &gt; 0) { selElem.options[0] = null; } for (var i=0;i&lt;tmpAry.length;i++) { var op = new Option(tmpAry[i][0], tmpAry[i][1]); selElem.options[i] = op; } return; } </code></pre>
<p>Not quite as pretty as the JQuery example by Marco but with prototype (i may be missing a more elegant solution) it would be:</p> <pre><code>function sort_select(select) { var options = $A(select.options).sortBy(function(o) { return o.innerHTML }); select.innerHTML = ""; options.each(function(o) { select.insert(o); } ); } </code></pre> <p>And then just pass it a select element:</p> <pre><code>sort_select( $('category-select') ); </code></pre>
35,109
<p>What kinds of hook scripts are people using for Subversion? Just general ideas but code would be great too!</p>
<p>I am using the <code>pre-revprop-change</code> hook that allows me to actually go back and edit comments and such information after the commit has been performed. This is very useful if there is missing/erroneous information in the commit comments.</p> <p>Here I post a <code>pre-revprop-change.bat</code> batch file for Windows NT or later. You can certainly enhance it with more modifications. You can also derive a <code>post-revprop-change.cmd</code> from it to back up the old <code>snv:log</code> somewhere or just to append it to the new log.</p> <p>The only tricky part was to be able to actually parse the stdin from the batch file. This is done here with the <code>FIND.EXE</code> command.</p> <p>The other thing is that I have had reports from other users of issues with the use of the <code>/b</code> with the <code>exit</code> command. You may just need to remove that <code>/b</code> in your specific application if error cases do not behave well.</p> <pre><code>@ECHO OFF set repos=%1 set rev=%2 set user=%3 set propname=%4 set action=%5 :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Only allow changes to svn:log. The author, date and other revision :: properties cannot be changed :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if /I not '%propname%'=='svn:log' goto ERROR_PROPNAME :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Only allow modifications to svn:log (no addition/overwrite or deletion) :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if /I not '%action%'=='M' goto ERROR_ACTION :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Make sure that the new svn:log message contains some text. :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: set bIsEmpty=true for /f "tokens=*" %%g in ('find /V ""') do ( set bIsEmpty=false ) if '%bIsEmpty%'=='true' goto ERROR_EMPTY goto :eof :ERROR_EMPTY echo Empty svn:log properties are not allowed. &gt;&amp;2 goto ERROR_EXIT :ERROR_PROPNAME echo Only changes to svn:log revision properties are allowed. &gt;&amp;2 goto ERROR_EXIT :ERROR_ACTION echo Only modifications to svn:log revision properties are allowed. &gt;&amp;2 goto ERROR_EXIT :ERROR_EXIT exit /b 1 </code></pre>
<p>The most common one I think is to allow people to change revision comments after comitting. </p> <p>You need to enable the 'pre-revprop-change' hook script to allow that. The example provided, if enabled allows editing only the comment property and only be the original comitter. Great for correcting typos.</p>
2,797
<p>I am developing a CMS where the clients will need to upload files larger than 2mb - up to 10mb at least. I have changed the details in the php.ini file and I cannot see anywhere else that the problem might be. Any help?</p> <p>Cheers</p>
<p>Here's what I recommend changing (assuming Apache &amp; PHP):</p> <p>I've found this works well for up to about 30mb attachments</p> <h2>PHP Settings</h2> <ul> <li>max<code>_execution</code>_time = 120</li> <li>max<code>_input</code>_time = 120</li> <li>memory_limit = 30M</li> <li>post<code>_max</code>_size = 30M</li> <li>upload<code>_max</code>_filesize 30M</li> <li>file_uploads = On <em>(although it sounds like you already have this turned)</em></li> </ul> <h2>Apache Settings</h2> <ul> <li>LimitRequestBody 31457280</li> </ul>
<p>As long as you have restarted your web service (ie apache) then the changes should take effect, however if you are developing for anyone other then yourself then instead of changing the php.ini I would add this to the upload script:</p> <pre><code>ini_set('upload_max_filesize', '10M'); </code></pre> <p>as some people may not be able to modify php.ini this will change it just for the page it is on.</p>
24,023
<p>I would like to have the authentication and registration parts of my website encrypted (for obvious reason). This site is currently and older site which some friends and I started in middle school and still use today. I may or may not register it to be a Non-Profit Organization in the near future, but either way, a CA costs money and the organization doesn't have any and we are currently college kids.</p> <p>Verisign is unreasonable and GoDaddy is $30/year. GoDaddy isn't too unreasonable, and I think their certs are accepted by most web browsers. The thing with GoDaddy is that I don't know why they have different SSL products (i.e.: why is it cheap to not verify me? does this have any implications on the cert and how the browser treats it if it just contains a domain name?)</p> <p>Also, is there an issue with using my own cert? Could the login page be http, and have a line stating that I use a self-signed cert and here is it's fingerprint and then post the form to an https page? Safari's method isn't too bad or sound too scary. I'm afraid, however, that firefox 3's method will scare people away and give me a tonne of emails saying that my site is being hacked or something. I don't know how IE responds to self-signed certs. (There is also the issue of why pay for something I can create myself with no effort, but I'm not going to pose the philosophical part of it, this is a more practical question.)</p> <p>In sum, do I give GoDaddy $30 a year or do I just tell people in a small paragraph what I'm doing and give the few people that will actually want my fingerprint it?</p> <p>Edit: Some on a forum I was reading for more info mentioned that GoDaddy certs are only given if it's on a GoDaddy server, which this isn't. Two things: (1) is this true? and There are other CA's at about the same price, so the argument should still be the same.</p>
<p>The SSL certificate solves two purposes: encryption of traffic <em>(for RSA key exchange, at least)</em> and verification of trust. As you know, you can encrypt traffic with <em>(or without, if we're talking SSL 3.0 or TLS)</em> any self-signed certificate. But trust is accomplished through a chain of certificates. I don't know you, but I do trust verisign (or at least Microsoft does, because they've been paid lots of money to get it installed in their operating systems by default), and since Verisign trusts you, then I trust you too. As a result, there's no scary warning when I go to such an SSL page in my Web browser because somebody that I trust has said you are who you are.</p> <p>Generally, the more expensive the certificate, the more investigating that the issuing certificate authority does. So for the Extended Validation certificates, the requesters have to submit more documents to prove that they are who they say they are, and in return they get a bright, happy green bar in modern Web browsers (I think Safari doesn't do anything with it quite yet).</p> <p>Finally, some companies go with the big boys like Verisign purely for the brand name alone; they know that their customers have at least heard of Verisign and so that for people shopping on their online store, their seal looks a little less sketch-ball than, say, GoDaddy's.</p> <p>If the branding is not important to you or if your site is not prone to phishing attacks, then the cheapest SSL cert that you can buy that has its root installed in most Web browsers by default will be fine. Usually, the only verification done is that you must be able to reply to an e-mail sent to the DNS's administrative contact, thus "proving" that you "own" that domain name.</p> <p>You can use those cheap-o certificates on non-GoDaddy servers, sure, but you'll probably have to install an intermediate certificate on the server first. This is a certificate that sits between your cheap-o $30 certificate and the GoDaddy "real deal" root certificate. Web browsers visiting your site will be like "hmm, looks like this was signed with an intermediate, you got that?" which <s>requires</s> <em>may require</em> an extra trip. But then it'll request the intermediate from your server, see that it chains up to a trusted root certificate that it knows about, and there is no problem.</p> <p>But if you are not allowed to install the intermediate on your server (such as in a shared hosting scenario), then you are out of luck. This is why most people say that GoDaddy certs can't be used on non-GoDaddy servers. Not true, but true enough for many scenarios.</p> <p>(At work we use a Comodo certificate for our online store, and a cheapo $30 GoDaddy cert to secure the internal connection to the database.)</p> <p>Edited <em>in italics</em> to reflect erickson's insightful clarifications below. Learn something new every day!</p>
<p>If that van around the corner is capable of hijacking your internet connection already, you've got worse problems than self-signed certificates.</p> <p>Banks should use client certificates for authentication. That would make it impossible for that van to do anything.... since it doesn't have the banks private key. </p> <p>Self-signed certs are perfectly fine... assuming your internet connection hasn't been compromised. If your connection <em>has</em> been compromised... you're probably dogged anyway.</p>
37,351
<p>I'm working in a team environment where each developer works from their local desktop and deploys to a virtual machine that they own on the network. What I'm trying to do is set up the Visual Studio solution so that when they build the solution each projects deployment is handled in the post-build event to that developers virtual machine.</p> <p>What I'd really like to do is give ownership of those scripts to the individual developer as well so that they own their post build steps and they don't have to be the same for everyone.</p> <p>A couple of questions:</p> <ul> <li>Is a post build event the place to execute this type of deployment operation? If not what is the best place to do it?</li> <li>What software, tools, or tutorials/blog posts are available to assist in developing an automatic deployment system that supports these scenarios?</li> </ul> <p><strong>Edit:</strong> MSBuild seems to be the way to go in this situation. Anyone use alternative technologies with any success?</p> <p><strong>Edit:</strong> If you are reading this question and wondering how to execute a different set of MSBuild tasks for each developer please see this question; <a href="https://stackoverflow.com/questions/78018/executing-different-set-of-msbuild-tasks-for-each-user">Executing different set of MSBuild tasks for each user?</a></p>
<p>A slightly different question that I looked for here: "How do you pass an object to a tag file?"</p> <p>Answer: Use the "type" attribute of the attribute directive:</p> <pre><code>&lt;%@ attribute name="field" required="true" type="com.mycompany.MyClass" %&gt; </code></pre> <p>The type <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags5.html#wp89854" rel="noreferrer">defaults to java.lang.String</a>, so without it you'll get an error if you try to access object fields saying that it can't find the field from type String.</p>
<p>Use expression language:</p> <pre> &lt;wf:my-tag obj="${myObject}" /&gt; </pre>
10,124
<p>What is the best way to extract RSS/ATOM URLs from HTML LINK tags? I know regex is not the best way to do this, so I'm wondering what alternatives I have. Surely some kind of horrible string munging using .Contains after loading the HTML into a string is not optimal either. Anyone got a decent strategy for this?</p>
<p>I recommend that you use username/password combos for website accounts, and API keys for any web services. Here are the advantages of this technique:</p> <ol> <li>By linking API keys to an account, you could have many API keys for the same user. Perhaps this could be used for many remote web servers that consume this data service, or to perform unique tracking.</li> <li>Attaching API keys to an account also lets you keep the user's username and password uncompromised since an API key will not contain them. Many users use the same username and password on many services, so you are helping to protect them.</li> <li>You could limit access to portions of functionality for each API key, but give their username access to everything their account should have access to. Additionally, you can even give them the ability to limit how much access an API key might have.</li> </ol> <p>Most of the major services (Yahoo! API, Flickr, Google API, etc) use accounts with a username and password to login to the web account, and API keys for integration points.</p>
<p>The github approach is bootstrapping on top of existing git practices, however it's not a bad idea since presumably each user will have their own private key to match a published public one in the central authority. Since key-agent's already furnish a means of safe authentication this seems like a very safe approach. Public/private keys are a well thought out authentication scheme, which has unfortunately been reinvented many times to limited success.</p> <p>The problem with the API key is that anyone who gets a copy of the API key can do whatever that authorizes. Storing the API key somewhere in the project begs the users to share a key. If you are associating public keys with a user, it is possible to grant rights to the client on a per user basis, and a proper key-agent approach suggests that those will not be stored in an SCM anywhere.</p> <p>I'm not sure I follow what the distinction between config/serviceName.yml, or serviceName/config.yml is. It doesn't seem as if it would be pertinent if you have public/private keys as an authentication method for the client.</p>
44,020
<p>Is there a way to separate a C# class into a header that contains the class definition and then an actual .cs file that contains the implementation? I suppose one can do this by creating an interface, but that doesn't seem right. I just want a file where I can just see the class design, and not all the detail. It's easy enough to do in C++, but I haven't seen it done with C#.</p> <p>Thanks in advance.</p>
<p>That's a wrong approach. C# isn't C++. <strong>Forget about header files</strong>.</p> <p>If you want the class summary, just open the <strong>Object Browser</strong> in Visual Studio. It will give you the signature of all the methods within your classes.</p>
<p>Isn't this what the IDE is for?</p> <p>EDIT: Otherwise inferfaces and abstract classes is the way to go.</p>
13,717
<p>I had a discussion with a colleague at work, it was about SQL queries and sorting. He has the opinion that you should let the server do any sorting before returning the rows to the client. I on the other hand thinks that the server is probably busy enough as it is, and it must be better for performance to let the client handle the sorting after it has fetched the rows. </p> <p>Anyone which strategy is best for the overall performance of a multi-user system?</p>
<p>In general, you should let the database do the sorting; if it doesn't have the resources to handle this effectively, you need to upgrade your database server.</p> <p>First off, the database may already have indexes on the fields you want so it may be trivial for it to retrieve data in sorted order. Secondly, the client can't sort the results until it has all of them; if the server sorts the results, you can process them one row at a time, already sorted. Lastly, the database is probably more powerful than the client machine and can probably perform the sorting more efficiently.</p>
<p>Situations vary, and measuring performance is important.</p> <p>Sometimes it's obvious - if you have a big dataset and you're interested in a small range of the sorted list (e.g. paging in a UI app) - sorting on the server saves the data transfer.</p> <p>But often you have one DB and several clients, and the DB may be overloaded while the clients are idle. Sorting on the client isn't heavy, and in this situation it could help you scale.</p>
42,319
<p>I've searched around for a while today, but I haven't been able to come up with an AutoComplete TextBox code sample for Silverlight 2 Beta 2. The most promising reference was found on <a href="http://www.nikhilk.net/Silverlight-AutoComplete.aspx/" rel="nofollow noreferrer">nikhilk.net</a> but the online demo doesn't currently render and after downloading a getting the code to compile with Beta 2, I couldn't get the Silverlight plugin it to render either. I think it is fair to say it is a compatibility issue, but I'm not sure. Does anyone have any alternate sample code or implementation suggestions?</p>
<p>You may want to take a look at my blog: <a href="http://weblogs.manas.com.ar/ary/2008/09/26/autocomplete-in-silverlight/" rel="nofollow noreferrer">http://weblogs.manas.com.ar/ary/2008/09/26/autocomplete-in-silverlight/</a></p> <p>You simply write in your XAML:</p> <pre><code>manas:Autocomplete.Suggest="DoSuggest" </code></pre> <p>and then in the class file, you need to implement that method, which report suggestions to a delegate. The options can be hardcoded, requested to a web service, or whaterver.</p>
<p>There is also another good example here:</p> <p><a href="http://silvermail.com.au" rel="nofollow noreferrer">http://silvermail.com.au</a></p> <p>This is a Silverlight based mail client that looks a little like Outlook. When I go to send mail and start typing in the "To" text box, an auto-complete pops up and populates the control for me based on values in a list... I think it automatically stores the addresses in isolated storage, but that's just a guess.</p> <p>This is a really handy tool for checking mail while away from my home PC... at work for example... and it is loaded with impressive Silverlight functionality.</p> <p>S.</p>
16,596
<p>I'm thinking of forming a <a href="http://www.catb.org/~esr/jargon/html/H/hacker.html" rel="nofollow noreferrer">Hacker</a>s Club at work. My idea is that we would meet monthly and at each meeting one member would present an interesting hack he had created. (The hacks presented wouldn't necessarily have to be software hacks; they could also be the sort of things you read about in <em>MAKE</em> magazine.) </p> <p>There would also be <a href="http://www.catb.org/~esr/jargon/html/A/ANSI-standard-pizza.html" rel="nofollow noreferrer">ANSI standard pizza</a>, veggie pizza, and beer and pop available for socializing afterward. I'm even thinking of calling the club "<a href="http://www.catb.org/~esr/jargon/html/T/TMRC.html" rel="nofollow noreferrer">TMRC</a>" even though it will have nothing to do with model railroads.</p> <p>Has anyone ever tried doing something like this or have any advice?</p>
<p>We do this at the office. I call it 'Developer Fight Club'</p> <p>Usually do challenges of varying difficulty and compete against one another.</p> <p>At the end of it, we go over our solutions, do code-reviews and discussions, and then use either benchmark results or other people as the deciding factor for who wins.</p> <p>Typically, the loser has to buy lunch for the winner :)</p> <p>For ideas of things to do, try stuff from <a href="http://www.topcoder.com/tc" rel="nofollow noreferrer">Top Coder</a>, programming questions on Stack Overflow, or even simple "<a href="http://en.wikipedia.org/wiki/Crackme" rel="nofollow noreferrer">crackme</a>" applications available on different programming sites.</p> <p>The main rules you'll need to adhere to are:</p> <ul> <li>Make It Fun</li> <li>Make It Educational Make</li> <li>Make It Fair</li> </ul> <p>Try to rotate the challenges, so either everyone is really good at the subject, equally bad, or at least mix it up often enough that it doesn't favor one person's skillset too much.</p>
<p>If there are women in your 'hacker' group, consider the advice given in the <a href="http://www.tldp.org/HOWTO/Encourage-Women-Linux-HOWTO/" rel="nofollow noreferrer">Howto Encourage Women in Linux</a>. Especially the 'meeting places and times' section.</p>
37,040
<p>Is there a way to "align" columns in a data repeater control? </p> <p>I.E currently it looks like this:</p> <pre><code>user1 - colA colB colC colD colE user2 - colD colE </code></pre> <p>I want it to look like:</p> <pre><code> user1 -colA -colB -colC -colD -colE user1 -colD -colE </code></pre> <p>I need to columns for each record to align properly when additional records might not have data for a given column.</p> <p>The requirements call for a repeater and not a grid control.</p> <p>Any ideas?</p>
<p>If you have access to how many columns are mising in the repeat, then just the following as the table tag. I you don't have access to this, can you post the source for your data repeater and what DataSource you're going against?</p> <pre><code>&lt;td colspan='&lt;%# MissingCount(Contatiner.DataItem) %&gt;'&gt; </code></pre>
<p></p> <pre><code> &lt;tr class="RadGridItem"&gt; &lt;td width="100"&gt; &lt;asp:Label ID="lblFullName" runat="server" Text ='&lt;%# DataBinder.Eval(Container.DataItem, "FullName") %&gt;' ToolTip='&lt;%# "Current Grade: " + DataBinder.Eval(Container.DataItem,"CurrentGrade") + "%" + " Percent Complete: " + DataBinder.Eval(Container.DataItem,"PercentComplete") + "%" %&gt;' /&gt; &lt;/td&gt; &lt;asp:Repeater ID="rptAssessments" runat="server" DataSource='&lt;%# DataBinder.Eval(Container.DataItem, "EnrollmentAssessments") %&gt;'&gt; &lt;ItemTemplate&gt; &lt;td style="padding :0px 0px 0px 0px; width:20px; height: 20px;"&gt; &lt;asp:LinkButton ID="lnkEdit" runat="server" OnClick="AssessmentClick" style=' &lt;%# "color:" + this.GetAssessmentColor(Container.DataItem) %&gt;' ToolTip='&lt;%# DataBinder.Eval(Container.DataItem, "AssessmentName") + Environment.NewLine + DataBinder.Eval(Container.DataItem, "EnrollmentAssessmentStateName") + "(" + DataBinder.Eval(Container.DataItem, "PercentGradeDisplay") + "%) " + GetPointsPossible(Container.DataItem) + " pts possible" %&gt;' CommandArgument='&lt;%# DataBinder.Eval(Container.DataItem, "EnrollmentAssessmentID") %&gt;' Text='&lt;%# this.GetAssessmentDisplay(Container.DataItem) %&gt;' /&gt; &lt;/td&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; </code></pre> <p>This is the code. The number of columns will be dynamic based on the criteria used to generate the list.</p> <p>Thanks.</p>
12,773
<p>I find Google's <a href="http://labs.google.com/inquotes/" rel="nofollow noreferrer">In Quotes</a> a really nifty application, and as a CS guy, I have to understand how it works. How do you think it turns news articles into a list of quotes attributed to specific persons? Sure, there are some mistakes, but their algorithm seems to be smarter than just a simple heuristic or multiple regular expressions. For example, a quote can be attributed to someone even though his/her name was only mentioned in the last paragraph.</p> <p>Any ideas? Any known paper on the subject?</p>
<p>It's simple, it checks for the words, but there can be anything in between them, as long as they're still in order. "Hello world!" would become the regex /hello [ .]* world/</p>
<p>I do not have any paper but some idea. Google take quotes from a set of person. Easy for them with Google News and other media access.</p> <p>They have an other set of subject. Google match subject set with the set of person (both set are finite). The last set is all quote,</p> <p>If you notice, the subject contain 1 word that is highlighted in the quote. So it has a relation between the set of subject and the set of quote for each set of person. Since Google is the master of information, it must be very easy to get a link between all these set.</p>
29,293
<p>I've been working on a program to read a dbf file, mess around with the data, and save it back to dbf. The problem that I am having is specifically to do with the writing portion.</p> <pre><code> private const string constring = "Driver={Microsoft dBASE Driver (*.dbf)};" + "SourceType=DBF;" + "DriverID=277;" + "Data Source=¿;" + "Extended Properties=dBASE IV;"; private const string qrystring = "SELECT * FROM [¿]"; public static DataTable loadDBF(string location) { string filename = ConvertLongPathToShort(Path.GetFileName(location)); DataTable table = new DataTable(); using(OdbcConnection conn = new OdbcConnection(RTN(constring, filename))) { conn.Open(); table.Load(new OdbcCommand(RTN(qrystring, filename), conn).ExecuteReader()); conn.Close(); } return table; } private static string RTN(string stmt, string tablename) { return stmt.Replace("¿", tablename); } [DllImport("Kernel32", CharSet = CharSet.Auto)] static extern Int32 GetShortPathName( String path, // input string StringBuilder shortPath, // output string Int32 shortPathLength); // StringBuilder.Capacity public static string ConvertLongPathToShort(string longPathName) { StringBuilder shortNameBuffer; int size; shortNameBuffer = new StringBuilder(); size = GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity); if (size &gt;= shortNameBuffer.Capacity) { shortNameBuffer.Capacity = size + 1; GetShortPathName(longPathName, shortNameBuffer, shortNameBuffer.Capacity); } return shortNameBuffer.ToString(); } </code></pre> <p>This is what I'm working with. I've tried a number of methods to write a new file, none of them productive. To be honest, while normally I would be an advocate of form and function, I just want the damn thing to work, this app is supposed to do one very specific thing, it's not going to simulate weather.</p> <p>-=# Edit #=-</p> <p>I've since discontinued the app due to time pressure, but before I scrapped it I realised that the particular format of dbf I was working with had no primary key information. This of course meant that I had to essentially read the data out to DataTable, mess with it, then wipe all the records in the dbf and insert everything from scratch. Screw that for a lark.</p>
<p>For people coming here in the future: I wrote this today and it works well. The filename is without the extension (.dbf). The path (used for connection) is the directory path only (no file). You can add your datatable to a dataset and pass it in. Also, some of my datatypes are foxpro data types and may not be compatible with all DBF files. Hope this helps.</p> <pre><code> public static void DataSetIntoDBF(string fileName, DataSet dataSet) { ArrayList list = new ArrayList(); if (File.Exists(Path + fileName + ".dbf")) { File.Delete(Path + fileName + ".dbf"); } string createSql = "create table " + fileName + " ("; foreach (DataColumn dc in dataSet.Tables[0].Columns) { string fieldName = dc.ColumnName; string type = dc.DataType.ToString(); switch (type) { case "System.String": type = "varchar(100)"; break; case "System.Boolean": type = "varchar(10)"; break; case "System.Int32": type = "int"; break; case "System.Double": type = "Double"; break; case "System.DateTime": type = "TimeStamp"; break; } createSql = createSql + "[" + fieldName + "]" + " " + type + ","; list.Add(fieldName); } createSql = createSql.Substring(0, createSql.Length - 1) + ")"; OleDbConnection con = new OleDbConnection(GetConnection(Path)); OleDbCommand cmd = new OleDbCommand(); cmd.Connection = con; con.Open(); cmd.CommandText = createSql; cmd.ExecuteNonQuery(); foreach (DataRow row in dataSet.Tables[0].Rows) { string insertSql = "insert into " + fileName + " values("; for (int i = 0; i &lt; list.Count; i++) { insertSql = insertSql + "'" + ReplaceEscape(row[list[i].ToString()].ToString()) + "',"; } insertSql = insertSql.Substring(0, insertSql.Length - 1) + ")"; cmd.CommandText = insertSql; cmd.ExecuteNonQuery(); } con.Close(); } private static string GetConnection(string path) { return "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=dBASE IV;"; } public static string ReplaceEscape(string str) { str = str.Replace("'", "''"); return str; } </code></pre>
<p>What kind of dbf file are you working with? (There are several, e.g. dBase, FoxPro etc that are not 100% compatible.) I have gotten this to work with the Microsoft Visual FoxPro OleDB Provider from C#, you might give that a shot instead of using the dBase ODBC driver.</p>
41,776
<p>Would using WSDualHttpBinding for duplex callbacks work in real-world scenarios? Say, I have a .NET application that uses a random port, would the service be able to resolve the client's base addresses and port for callbacks?</p>
<p>A complete answer to your question depends on the "real-world scenario" being either an Intranet or an Internet scenario. Although WSDualHttpBinding works in both scenarios there are specifics to be aware of:</p> <p><strong>Intranet</strong></p> <p>WSDualHttpBinding will work with your .NET application using a preconfigured custom port in an Intranet scenario and "Yes" the service will be able to resolve the client's base addresses and port for callbacks: exactly how is explained below. The reason it's explained below is that WSDualHttpBinding is primarily designed to be used over the Internet.</p> <p>Duplex callbacks in an Intranet scenario when you can use WCF on both client and server is best achieved by using NetTcpBinding or NetNamedPipeBinding. These bindings use TCP and ICP respectively as transport (rather than HTTP) and a custom binary encoding which is why WCF is required on both sides. For calls-back to the client the same channel used to connect to the Service via the Binding is re-used without requiring a new port to be opened.</p> <p><strong>Internet</strong></p> <p>In an Internet scenario valid HTTP requests and responses only travel in one direction, HTTP is designed as a one-way protocol. When using the WSDualHttpBinding WCF therefore creates a seperate HTTP channel for callbacks. In answer to your second question: the destination address for this call-back to the client is composed of the client machine hostname and port 80 by default. If the client is a development machine for example and has IIS installed, port 80 will be exclusively reserved in some scenarios which will cause conflicts with your prototype application. This is what <a href="http://blogs.msdn.com/wenlong/archive/2006/10/19/how-to-use-wsdualhttpbinding-on-windows-xp-for-hosted-services.aspx" rel="noreferrer">this blog post</a> presents a solution for and what the ClientBaseAddress property is designed to help with. Regardless of which port you go with - the default or a custom one, you must ensure all firewalls and routers on both sides are configured correctly to allow both the outgoing channel and the seperate callback channel to be established.</p> <p>A .NET application can also denote a Silverlight application. Because of the fact that a Silverlight application running in a browser cannot accept new incoming HTTP connections, WSDualHttpBinding with it's seperate back channel will not work. Hence PollingDuplexHttpBinding was created firstly in Silverlight 2 which can be thought of as a clever 'trick' to get around the fact that HTTP is unidirectional by keeping the request channel open for a long time (long polling) and using it as a back channel for calls back to the client. This has a number of implications on both the client and server side particularly relevant to scaling, for more detail please see <a href="http://petermcg.wordpress.com/2008/09/03/silverlight-polling-duplex-part-1-architecture/" rel="noreferrer">this post from my blog</a>.</p> <p>With an idea of your particular "real-world scenario" and your use-cases hopefully this will help you work out the correct binding to use for duplex callbacks.</p>
<p>If it's an application behind a firewall, theoretically yes. It depends on what you mean by "real world"; if by that you mean "high performance" perhaps NetTcpBinding is a better appraoch.</p>
8,435
<p>I would like to know if there is a way to disable automatic loading of child records in nHibernate ( for one:many relationships ).</p> <p>We can easily switch off lazy loading on properties but what I want is to disable any kind of automatic loading ( lazy and non lazy both ). I only want to load data via query ( i.e. HQL or Criteria )</p> <p>I would still like to define the relationship between parent child records in the mapping file to facilitate HQL and be able to join parent child entities, but I do not want the child records to be loaded as part of the parent record unless a query on the parent record explicitly states that ( via eager fetch, etc ).</p> <p>Example: Fetching Department record from the database should not fetch all employee records from the database because it may never be needed.</p> <p>One option here is to set the Employees collection on Department as lazy load. The problem with this approach is that once the object is given to the calling API it can 'touch' the lazy load property and that will fetch the entire list from the db.</p> <p>I tried to use 'evict' - to disconnect the object but it does not seem to be working at all times and does not do a deep evict on the object. Plus it abstracts the lazy loaded property type with a proxy class that plays havoc later in the code where we are trying to operate on the object via reflection and it encounters unexpended type on the object.</p> <p>I am a beginner to nHibernate, any pointers or help would be of great help.</p>
<p>Given your request, you could simply not map from Department to Employees, nor have an Employees property on your department. This would mean you <em>always</em> have to make a database hit to find the employees of a database.</p> <p><em>Aplogies if these code examples don't work out of the box, I'm not near a compiler at the moment</em></p> <p>So, your department class might look like:</p> <pre><code> public class Department { public int Id { get; protected set; } public string Name { get; set; } /* Equality and GetHashCode here */ } </code></pre> <p>and your Employee would look like:</p> <pre><code> public class Employee { public int Id { get; protected set; } public Name Name { get; set; } public Department Department { get; set; } /* Equality and GetHashCode here */ } </code></pre> <p>Any time you wanted to find Employees for a department, you've have to call:</p> <pre><code>/*...*/ session.CreateCriteria(typeof(Employee)) .Add(Restrictions.Eq("Department", department) .List&lt;Employee&gt;(); </code></pre> <p>Simply because your spec says "Departments have many Employees", doesn't mean you have to map it as a bi-directional association. If you can keep your associated uni-directional, you can really get your data-access to fly too.</p> <p>Google <a href="http://www.google.com/search?q=%22Domain+Driven+Design%22+aggregate" rel="nofollow noreferrer">"Domain Driven Design" Aggregate</a>, or see Page 125 of Eric Evan's book on Domain Driven Design for more information</p>
<p>You can have the lazy attribute on the collection. In your example, Department has n employees, if lazy is enabled, the employees will not be loaded by default when you load a department : <a href="http://www.nhforge.org/doc/nh/en/#collections-lazy" rel="nofollow noreferrer" title="documentation on lazy">http://www.nhforge.org/doc/nh/en/#collections-lazy</a></p> <p>You can have queries that explicitly load department AND employees together. It's the "fetch" option : <a href="http://www.nhforge.org/doc/nh/en/#performance-fetching-lazy" rel="nofollow noreferrer" title="fetch option">http://www.nhforge.org/doc/nh/en/#performance-fetching-lazy</a></p>
26,760
<p>At my job we make &amp; sell websites. Usually we install our .NET C# based site on a customer's server and maintain and support it remotely. However, every once in a while, for bigger development works and just to make things simpler (and faster!), we will copy the site to a local server.</p> <p>This is great, but has one pain - moving the site back to the customer. Now, If nothing was change on the customer's copy - no problem. However, it is the sad truth that sometime (read more often than I would like) some fixes were needed to be applied on the production server. Either because the customer needed it NOW or simply because it was major bug.</p> <p>I know that you can easily apply those bug fixes to the local copy as well, but this is an error prone process. So I'm setting my hopes on a distributed version control to help synchronize the two copies.</p> <p>Here is what I need:</p> <ul> <li>Easy to install - nothing else needed except the installer and admin rights.</li> <li>Can integrated in an existing website as a virtual directory and works on port 80 - no hassle with new DNS required.</li> <li>Excellent software</li> </ul> <p>That's it. Any ideas?</p> <hr> <h2>Some comments on the answers</h2> <p>First, thanks! much appreciated.</p> <p>I've looked at Mercurial and Bazaar and both look very good. The only caveat is the installation as a virtual directory on IIS. Mercurial, as far as I understand, use a special protocol (wire) and Bazaar needs and addition of python extensions. Is there another system which is easier to integrate with IIS? I'm willing to take a performance hit for that.</p>
<p>I'd look at either <a href="http://www.selenic.com/mercurial/wiki/" rel="nofollow noreferrer">Mercurial</a> or <a href="http://bazaar-vcs.org/" rel="nofollow noreferrer">Bazaar</a>. I'm told Git also works on windows, but I suspect the windows port is still a second class port at best.</p> <p>You'll probably need to be able to run python scripts on your webserver to host either of them.</p>
<p>Maybe not exactly what you request but checkout <a href="http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp" rel="nofollow noreferrer">DeltaCopy</a> which is a windows version of <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer">rsync</a>. You can also read about another rsync solution <a href="http://hype-free.blogspot.com/2007/02/using-rsync-on-windows.html" rel="nofollow noreferrer">here</a></p>
4,972
<p>In WPF:</p> <p>Can someone please explain the relationship between DependencyProperty and Databinding?</p> <p>I have a property in my code behind I want to be the source of my databinding. When does a DependencyProperty (or does it) come into play if I want to bind this object to textboxes on the XAML.</p>
<p>The target in a binding must always be a <code>DependencyProperty</code>, but any property (even plain properties) can be the source.</p> <p>The problem with plain properties is that the binding will only pick up the value once and it won't change after that because change notification is missing from the plain source property.</p> <p>To provide that change notification without making it a <code>DependencyProperty</code>, one can:</p> <ol> <li><p>Implement <code>INotifyPropertyChanged</code> on the class defining the property.</p></li> <li><p>Create a <em><code>PropertyName</code></em><code>Changed</code> event. (Backward compatibility.)</p></li> </ol> <p>WPF will work better with the first choice.</p>
<h2><em>What is the DependencyProperty?</em></h2> <p>The <strong>DependencyProperty</strong> class is one of the most important design bases hidden deep in the .Net Framework WPF.</p> <p>This class is protected by <code>sealed</code> from the .NET Framework. This property differs from the one-dimensional general property in that it not only stores field values, but also takes advantage of the various functions provided within the class. Most importantly, there is a full foundation for data binding. You can also send notifications whenever you bind something.</p> <p><a href="https://github.com/devncore/dependencyproperty#what-is-the-dependencyproperty" rel="nofollow noreferrer">DependencyProperty</a><br /> <a href="https://github.com/devncore/wpf-xaml-binding#datacontext-is-always-the-reference-point-for-binding" rel="nofollow noreferrer">Wpf Xaml Binding</a></p> <p>It's already a late answer, but I'll introduce the results of my research.</p>
19,246
<p>So I am following this guide: <a href="http://technotes.1000lines.net/?p=23" rel="noreferrer">http://technotes.1000lines.net/?p=23</a> and I am going through the steps. I have a VPN (slicehost.com) with Debian Etch, serving a website (static so far) with nginx. I used wget to download FastCGI and I did the usual make make install routine. </p> <p>So I guess since FastCGI can't normally run CGI scripts you have to use some type of perl wrapper to interpret the perl.</p> <p>Now I run this script</p> <p><a href="http://technotes.1000lines.net/fastcgi-wrapper.pl" rel="noreferrer">http://technotes.1000lines.net/fastcgi-wrapper.pl</a></p> <p>and I run into the exact same problem that a person ran into on the page that the script was submitted: </p> <p><a href="http://www.ruby-forum.com/topic/145858" rel="noreferrer">http://www.ruby-forum.com/topic/145858</a></p> <p>(I'm not a ruby person and there is nothing ruby oriented in there)</p> <p>I keep getting a </p> <pre><code># bind/listen: No such file or directory </code></pre> <p>And I have no idea how to proceed. I would appreciate any help and I can give any more details that anyone would need.</p>
<p>The webserver needs a Unix domain socket to connect to the FastCGI application, but the socket can't be created. Most likely the directory you want it to be in doesn't exist (because they are automatically created when you do a <code>bind</code>).</p>
<p>I'm gonna try and "water down" fastcgi-wrapper.pl, so it can be used with <a href="http://redmine.lighttpd.net/projects/spawn-fcgi/Blockquote" rel="nofollow noreferrer">spawn-fcgi</a>.</p> <p>I use two of those sockets allready:</p> <pre><code>spawn-fcgi -C 3 -u www-data -s /var/run/php-fcgi.sock -P /var/run/php-fcgi.pid -- /usr/bin/php5-cgi spawn-fcgi -F 3 -u www-data -s /var/run/lua-fcgi.sock -P /var/run/lua-fcgi.pid -- /usr/bin/wsapi.fcgi </code></pre> <p>Inside /var/run I have:</p> <pre><code>-rw-r--r-- 1 root root 14 2010-08-07 12:14 /var/run/lua-fcgi.pid srwxr-xr-x 1 www-data www-data 0 2010-08-07 12:14 /var/run/lua-fcgi.sock= -rw-r--r-- 1 root root 4 2010-08-07 12:14 /var/run/php-fcgi.pid srwxr-xr-x 1 www-data www-data 0 2010-08-07 12:14 /var/run/php-fcgi.sock= </code></pre> <p>I can easily start and stop the FastCGI wrappers, and I want to do that with Perl too.</p> <p>If anyone has already a script, that works with spawn-fcgi, I'd be happt to use that, or at least have a look at it.</p> <p>Cheers, --polemon</p>
48,308
<p>How can I force the input's onchange script to run <em>before</em> the RangeValidator's script? </p> <p>I want to prevent a failed validation when the user enters a dollar sign or comma.</p> <pre><code>function cleanUp(str) { re = /^\$|,/g; return str.replace(re, ""); // remove "$" and "," } &lt;input type="text" id="salary" runat="server" onchange="this.value=cleanUp(this.value)" /&gt; &lt;asp:RangeValidator ID="salaryValidator" runat="server" ErrorMessage="Invalid Number" ControlToValidate="salary" Type="Double" /&gt; </code></pre> <p><strong>UPDATE:</strong> <br /> I decided to use a CustomValidator that checks the range and uses a currency RegEx. Thanks Michael Kniskern.</p> <pre><code>function IsCurrency(sender, args) { var input = args.Value; // Check for currency formatting. // Expression is from http://regexlib.com/REDetails.aspx?regexp_id=70 re = /^\$?([0-9]{1,3},([0-9]{3},)*[0-9]{3}|[0-9]+)(.[0-9][0-9])?$/; isCurrency = input.match(re); if (isCurrency) { // Convert the string to a number. var number = parseFloat(CleanUp(input)); if (number != NaN) { // Check the range. var min = 0; var max = 1000000; if (min &lt;= number &amp;&amp; max &gt;= number) { // Input is valid. args.IsValid = true; return; } } } // Input is not valid if we reach this point. args.IsValid = false; return; } function CleanUp(number) { re = /^\$|,/g; return number.replace(re, ""); // remove "$" and "," } &lt;input type="text" id="salary" runat="server" /&gt; &lt;asp:CustomValidator ID="saleryValidator" ControlToValidate="salary" runat="server" ErrorMessage="Invalid Number" ClientValidationFunction="IsCurrency" /&gt; </code></pre>
<p>Have you tried using a CustomerValidator control and combined the functionality of the JS cleanup methods and the RangeValidator method.</p>
<p>There is a way to do this by registering the script; however why not use a Regular Expression Validator to make sure the input is proper?</p> <p>Also, the Range validator executes on the fields onBlur js event, not on change.</p>
46,155
<p>I'm using <b>Struts 2</b>.</p> <p>I'd like to return from an Action to the page which invoked it.</p> <p>Say I'm in page <strong>x.jsp</strong>, I invoke Visual action to change CSS preferences in the session; I want to return to <strong>x.jsp</strong> rather than to a fixed page (i.e. <strong>home.jsp</strong>)<br/></p> <p>Here's the relevant <strong>struts.xml</strong> fragment: <br/></p> <pre> &lt;action name="Visual" class="it.___.web.actions.VisualizationAction"&gt; &lt;result name="home"&gt;/pages/home.jsp&lt;/result&gt; &lt;/action&gt; </pre> <p>Of course my <code>VisualizationAction.execute()</code> returns <strong>home</strong>.</p> <p>Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?<br/></p> <p>Must I use a more involved method (i.e. extracting the request page and forwarding to it)?<br/></p> <p>T.I.A.</p>
<p>You can use a dynamic result in struts.xml. For instance:</p> <pre><code>&lt;action name="Visual" class="it.___.web.actions.VisualizationAction"&gt; &lt;result name="next"&gt;${next}&lt;/result&gt; &lt;/action&gt; </code></pre> <p>Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns "next" and struts will know which page to go to.</p> <p>There is a nicer explanation on this post: <a href="https://stackoverflow.com/questions/173846/struts2-how-to-do-dynamic-url-redirects">Stack Overflow</a></p>
<p>I prefer the way when you navigating users by particular actions. </p> <p><a href="http://domain.com/myAction.action" rel="nofollow noreferrer">http://domain.com/myAction.action</a></p> <p>You could use some parameter as indicator, that you want to change current design: i.e.</p> <p><a href="http://domain.com/myAction.action?changeDesign=silver_theme" rel="nofollow noreferrer">http://domain.com/myAction.action?changeDesign=silver_theme</a></p> <p>So then, you write some struts 2 interceptor, which logic is to check the presence of such parameter 'changeDesign', and this interceptor will do nessesary work of changing design and will control workflow. With interceptor you decouple your actions from crosscutting logic.</p>
6,730
<p>I am aware that Javascript WYSIWYG editors use the inbuilt editor mode of the browser to function, but that comes up with various problems and issues.</p> <p>Can an editor be built from scratch in JS, something like what Buzzword people have done with flash/flex? I came across <a href="http://manishjethani.com/blog/2008/04/13/how-does-buzzword-work/" rel="nofollow noreferrer">this blog post</a> recently and I am just wondering if this can be built (atleast to a moderate extent) using Javascript?</p>
<p>It depends what you mean by "from scratch". <a href="http://docs.google.com/" rel="nofollow noreferrer">Google Docs</a> provides a pretty good text editor in JS. Is that what you mean ?</p>
<p>Of course you can do it and it is not very difficult. But before reinventing the wheel please take a look at all the existing ones. Many of them are really very well written and open source.</p>
48,896
<p>I need to store the timezone an email was sent from. Which is the best way to extract it from the email's 'Date:' header (an RFC822 date)? And what is the recommended format to store it in the database (I'm using hibernate)?</p>
<p>Probably easiest to parse with JodaTime as it supports ISO8601 see <a href="http://johannburkard.de/blog/programming/java/date-time-parsing-formatting-joda-time.html" rel="nofollow noreferrer">Date and Time Parsing and Formatting in Java with Joda Time</a>.</p> <pre><code>DateTimeFormatter parser2 = ISODateTimeFormat.dateTimeNoMillis(); System.out.println(parser2.parseDateTime(your_date_string)); </code></pre> <p>Times must always be stored in UTC (GMT) with a timezone - i.e. after parsing convert from the timezone to GMT and remove daylight savings offset and save the original timezone.</p> <p>You must store the date with the timezone after converting to UTC.</p> <p>If you remove or don't handle the timezone it will cause problems when dealing with data that has come from a different timezone.</p>
<p>Extract the data from the header using some sort of substring or regular expression. Parse the date with a SimpleDateFormatter to create a Date object.</p>
13,358
<p>I'm researching this for a project and I'm wondering what other people are doing to prevent stale CSS and JavaScript files from being served with each new release. I don't want to append a timestamp or something similar which may prevent caching on every request. </p> <p>I'm working with the Spring 2.5 MVC framework and I'm already using the google api's to serve prototype and scriptaculous. I'm also considering using Amazon S3 and the new Cloudfront offering to minimize network latency.</p>
<p>I add a parameter to the request with the revision number, something like:</p> <pre><code>&lt;script type="text/javascript" src="/path/to/script.js?ver=456"&gt;&lt;/script&gt; </code></pre> <p>The 'ver' parameter is updated automatically with each build (read from file, which the build updates). This makes sure the scripts are cached only for the current revision.</p>
<p>If you get the "modified time" of the file as a timestamp it will be cached until the file is modified. Just use a helper function (or whatever it is called in other frameworks) to add script/css/image tags that get the timestamp from the file. On a unix like system (wich most survers are) you could simply <code>touch</code> the files to force the modified time to change if necessary. </p> <p>Ruby on Rails uses this strategy in production mode (by default I beleave), and uses a normal timestamp in development mode (to be really sure something isn't cached).</p>
46,488
<p>I have a web application that comprises the following:</p> <ul> <li>A web project (with a web.config file containing a connection string - but no data access code in the web project)</li> <li>A data access project that uses LINQ-SQL classes to provide entities to the web project UI (this project has a settings file and an app.config - both of which have connection strings)</li> </ul> <p>When I build and deploy, there is no settings file or app.config in the Bin directory with the data access .dll, but changing the connection string in the web.config file doesn't change the database accordingly - so the connection string must be compiled into the data access dll. </p> <p>What I need is one config file for my entire deployment - website, data access dlls, everything - that has one connection string which gets used. At the moment there appear to be multiple connection strings getting used or hardcoded all over the place. </p> <p>How do I best resolve this mess?</p> <p>Thanks for any help.</p>
<p>I've never had a problem with the <em>Data Access Layer</em> (DAL) being able to use the connection strings from my <code>web.config</code> file. Usually I just copy the connection strings section from the DAL and paste it into the <code>web.config</code>. I'm using the DBML designer to create the data context.</p> <p>If this won't work for you, you can specify the connection string in the data context constructor. In your web project have a static class that loads your settings, including your connection strings, and when you create your DAL object (or data context, if creating it directly) just pass it in to the constructor.</p> <pre><code>public static class GlobalSettings { private static string dalConnectionString; public static string DALConnectionString { get { if (dalConnectionString == null) { dalConnectionString = WebConfigurationManager .ConnectionStrings["DALConnectionString"] .ConnectionString; } return dalConnectionString; } } } ... using (var context = new DALDataContext(GlobalSettings.DALConnectionString)) { ... } </code></pre>
<p>How about defining a ConnectionFactory object, that takes an enum as a parameter and returns a fully-formed connection object?</p>
29,260
<p>I'm building an app in Ruby on Rails, and I'm including 3 of my models (and their migration scripts) to show what I'm trying to do, and what isn't working. Here's the rundown: I have users in my application that belong to teams, and each team can have multiple coaches. I want to be able to pull a list of the coaches that are applicable to a user. </p> <p>For instance, User A could belong to teams T1 and T2. Teams T1 and T2 could have four different coaches each, and one coach in common. I'd like to be able to pull the list of coaches by simply saying: </p> <pre><code>u = User.find(1) coaches = u.coaches </code></pre> <p>Here are my migration scripts, and the associations in my models. Am I doing something incorrectly in my design? Are my associations correct?</p> <pre><code>class CreateUsers &lt; ActiveRecord::Migration def self.up create_table :users do |t| t.column :login, :string, :default =&gt; nil t.column :firstname, :string, :default =&gt; nil t.column :lastname, :string, :default =&gt; nil t.column :password, :string, :default =&gt; nil t.column :security_token, :string, :default =&gt; nil t.column :token_expires, :datetime, :default =&gt; nil t.column :legacy_password, :string, :default =&gt; nil end end def self.down drop_table :users end end class CreateTeams &lt; ActiveRecord::Migration def self.up create_table :teams do |t| t.column :name, :string end end def self.down drop_table :teams end end class TeamsUsers &lt; ActiveRecord::Migration def self.up create_table :teams_users, :id =&gt; false do |t| t.column :team_id, :integer t.column :user_id, :integer t.column :joined_date, :datetime end end def self.down drop_table :teams_users end end </code></pre> <p>Here are the models (not the entire file):</p> <pre><code>class User &lt; ActiveRecord::Base has_and_belongs_to_many :teams has_many :coaches, :through =&gt; :teams class Team &lt; ActiveRecord::Base has_many :coaches has_and_belongs_to_many :users class Coach &lt; ActiveRecord::Base belongs_to :teams end </code></pre> <p>This is what happens when I try to pull the coaches:</p> <pre><code>u = User.find(1) =&gt; #&lt;User id: 1, firstname: "Dan", lastname: "Wolchonok"&gt; &gt;&gt; u.coaches ActiveRecord::StatementInvalid: Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT `coaches`.* FROM `coaches` INNER JOIN teams ON coaches.team_id = teams.id WHERE ((`teams`.user_id = 1)) </code></pre> <p>Here's the error in sql:</p> <p>Mysql::Error: #42S22Unknown column 'teams.user_id' in 'where clause': SELECT <code>coaches</code>.* FROM <code>coaches</code> INNER JOIN teams ON coaches.team_id = teams.id WHERE ((<code>teams</code>.user_id = 1)) </p> <p>Am I missing something in my :through clause? Is my design totally off? Can someone point me in the right direction?</p>
<p>You can't do a has_many :through twice in a row. It'll tell you that its an invalid association. If you don't want to add finder_sql like above, you can add a method that mimics what you're trying to do.</p> <pre><code> def coaches self.teams.collect do |team| team.coaches end.flatten.uniq end </code></pre>
<p>While I love to write SQL, I don't think it's the ideal solution in this instance. Here's what I ended up doing in the User model:</p> <pre><code> def coaches self.teams.collect do |team| team.coaches end.flatten.uniq end def canCoach(coachee) u = User.find(coachee) coaches = u.coaches c = [] coaches.collect do |coach| c.push(coach.user_id) end return c.include?(self.id) end </code></pre> <p>I thought about just doing it all in one fell swoop, but I liked the ability to return an array of coach objects from within the user object. If there's a better way to do it, I'm very interested in seeing the improved code.</p>
24,231
<p>I've written a simple Flash player for a Shoutcast stream. At first it seemed to work reliably, however about 5% of the time users experience slow playback where the stream plays at roughly half of normal speed.</p> <p>All files being streamed are MP3, encoded at 128kbps/44.1kHz, the same settings as used in the Shoutcast config files, so the issue is not caused by mismatched bit rates as suggested on a number of forums I have read. Has anyone else encountered this problem and possibly found a solution?</p> <p>Regards,<br> Alan</p> <p>EDIT: A sample player can be found at <a href="http://radionations.com/utils/players/pulse.swf" rel="nofollow noreferrer">http://radionations.com/utils/players/pulse.swf</a> There is no graphical display as the player is designed to run in the background.</p> <p>The problem only occurs a small proportion of the time, and only when the player is being loaded in the browser. It does not occur mid-stream.</p> <p>The player has been tested on a number of different machines running Windows XP, Vista, Ubuntu, and MacOS X. Various different hardware configurations are involved. The problem occurs across all of these test platforms so I am inclined to believe it is not an issue with problematic / buggy audio drivers.</p> <p>I have encountered the problem both with and without other applications using the audio device.</p> <p>EDIT: I'm surprised I still haven't found a solution to this problem. So I've decided to come back to it now in the hopes that somebody might know something. Any help is greatly appreciated.</p> <p>Thanks, Alan</p>
<p>This is a flash player bug unfortunately. It seems like the only reliable solution is to roll it back to AS2.</p> <p><a href="https://bugs.adobe.com/jira/browse/FP-173" rel="nofollow noreferrer">https://bugs.adobe.com/jira/browse/FP-173</a></p>
<p>I believe that the slow playing is caused by audio drivers problems. Can you give a link to the player?</p>
11,696
<p>I want to take html, including the text and images and turn it into one image containing everything. Is there a free way to do it?</p> <p>This is using .net 3.5.</p> <h3>See also:</h3> <p><a href="https://stackoverflow.com/questions/119116/server-generated-web-screenshots">Server Generated web screenshots?</a><br /> <a href="https://stackoverflow.com/questions/65078/what-is-the-best-way-to-create-a-web-page-thumbnail">What is the best way to create a web page thumbnail?</a></p>
<p>You might check out <a href="http://www.codeproject.com/KB/graphics/IECapture.aspx" rel="nofollow noreferrer">this project</a> or <a href="http://www.developerfusion.co.uk/show/4712/" rel="nofollow noreferrer">this page</a>.</p> <p>Hope that helps.</p>
<p>Here's some code that I posted on my blog a few weeks ago that does this:</p> <p><a href="http://pietschsoft.com/post.aspx?id=2a628f30-fe83-4e44-a34b-f31be76d1b4f" rel="nofollow noreferrer">C#: Generate WebPage Thumbnail Screenshot Image</a></p> <p>I'll also post the code for it below:</p> <pre><code>public Bitmap GenerateScreenshot(string url) { // This method gets a screenshot of the webpage // rendered at its full size (height and width) return GenerateScreenshot(url, -1, -1); } public Bitmap GenerateScreenshot(string url, int width, int height) { // Load the webpage into a WebBrowser control WebBrowser wb = new WebBrowser(); wb.ScrollBarsEnabled = false; wb.ScriptErrorsSuppressed = true; wb.Navigate(url); while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } // Set the size of the WebBrowser control wb.Width = width; wb.Height = height; if (width == -1) { // Take Screenshot of the web pages full width wb.Width = wb.Document.Body.ScrollRectangle.Width; } if (height == -1) { // Take Screenshot of the web pages full height wb.Height = wb.Document.Body.ScrollRectangle.Height; } // Get a Bitmap representation of the webpage as it's rendered in the WebBrowser control Bitmap bitmap = new Bitmap(wb.Width, wb.Height); wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height)); wb.Dispose(); return bitmap; } </code></pre> <p>Here's some example usages:</p> <pre><code>// Generate thumbnail of a webpage at 1024x768 resolution Bitmap thumbnail = GenerateScreenshot("http://pietschsoft.com", 1024, 768); // Generate thumbnail of a webpage at the webpage's full size (height and width) thumbnail = GenerateScreenshot("http://pietschsoft.com"); // Display Thumbnail in PictureBox control pictureBox1.Image = thumbnail; /* // Save Thumbnail to a File thumbnail.Save("thumbnail.png", System.Drawing.Imaging.ImageFormat.Png); */ </code></pre>
17,709
<p>I am looking to use Cocoon for a couple of sites I am creating. I will make heavy use of xml, xsl and conversion to html, pdf and excel on the sites. I am attracted to coccon as it implements these functions quite well.</p> <p>I guess I am just wondering if anyone has used it and like it, or if they found it was more trouble than it's worth.</p>
<p>Cocoon is a very powerful framework. But it's not easy to understand all aspects of it. (see Ulysses answer). Once you have understood the basic concepts though there is hardly anything comparable in the XML space.</p> <p>It has been integrated with so many things that you really need to strip it down to what you really need. The initial sitemap is huge. That's were most newbies already fail. (see meadandale's answer)</p> <p>So it really comes down to what you really want to do with it. Today I would not use it for web applications anymore. There are other frameworks that have that focus and do a better job at it. You probably can still integrate those with Coocoon. Well, it probably has already been done by someone ;)</p> <p>If you really make heavy use of xml/xsl and need different output formats, there is probably nothing really better for it than Cocoon. Properly tuned it even serves a couple of really big sites out there.</p> <p>If you got questions it has one of the most welcoming open source communities. Just make sure it's the right tool for the right job. But from your description it sounds like. Even if you just use it for the rendering.</p> <p>It has a bit of a learning curve - but don't get frustrated.</p> <p>Disclaimer: I am one of the developers :)</p>
<p>Just had a quick look for alternatives you could look at:</p> <ul> <li><a href="http://wiki.apache.org/cocoon/CocoonCompared" rel="nofollow noreferrer">Cocoon Comparison</a></li> <li><a href="http://wiki.apache.org/cocoon/WorkflowImplementationComparison" rel="nofollow noreferrer">Workflow comparisons</a></li> <li><a href="http://axkit.org/" rel="nofollow noreferrer">Apache AxKit</a></li> <li><a href="http://xml.apache.org/xang/" rel="nofollow noreferrer">Xang</a></li> </ul>
23,025
<p>There are some HTML based games (ie bootleggers.us) that have a simple login form and after that your entire game experience revolves around submitting various forms and reading information from the website itself.</p> <p>My Question is, <strong>what is the best way to go about writing a bot / automate the html-based game using C#</strong>? </p> <p>My initial thought is to use the System.Net.HttpRequest and WebRequest classes to get the source html and parse using regexs to get the desired information.</p> <p>However, I would like to avoid this if it is at all possible. Are there any solutions that abstract away some of this and make automating website interaction easier? Ie filling out forms, submitting forms, reading values from the website, etc? Some library?</p>
<p>You could use Watin: <a href="http://watin.sourceforge.net/" rel="nofollow noreferrer">http://watin.sourceforge.net/</a></p>
<p>No, you're pretty much going to have to "screen scrape" every page. You might consider writing most this in JavaScript instead of C#. Depending on the HTML of the game site, this could be more or less difficult depending on whether they provide good id attributes on the page elements, etc...</p>
13,047
<p>I have two threads in an Android application, one is the view thread, and the other is the worker thread. What I want to do is, sleep the worker thread until the view thread terminates the handling of the onDraw method.</p> <p>How i can do this? is there any wait for the signal or something?</p>
<p>Share a java.lang.Object between the two threads, whose sole purpose is to tell the worker thread when it can continue its work. Whenever the worker thread reaches a point where it should sleep, it does this:</p> <pre><code>stick.wait(); </code></pre> <p>When the view thread finishes its onDraw work, it calls this:</p> <pre><code>stick.notify(); </code></pre> <p>Note the requirement that the view thread owns the monitor on the object. In your case, this should be fairly simple to enforce with a small sync block:</p> <pre><code>void onDraw() { ... synchronized (stick) { stick.notify(); } } // end onDraw() </code></pre> <p>Consult the javadoc for java.lang.Object on these methods (and notifyAll, just in case); they're very well written. </p>
<p>If you want a higher-level concurreny API (with things like Barriers), you could try the backport of the java 5 concurrency API, which works on java 1.3 and above, and may work on Android. The likes of Object.wait/notify will work, but they can be a bit terse.</p> <p><a href="http://backport-jsr166.sourceforge.net/" rel="nofollow noreferrer">Backport-util-concurrent</a></p>
14,805
<p>I'm writing an application using Qt4.</p> <p>I need to download a very short text file from a given http address.</p> <p>The file is short and is needed for my app to be able to continue, so I would like to make sure the download is blocking (or will timeout after a few seconds if the file in not found/not available).</p> <p>I wanted to use QHttp::get(), but this is a non-blocking method.</p> <p>I thought I could use a thread : my app would start it, and wait for it to finish. The thread would handle the download and quit when the file is downloaded or after a timeout.</p> <p>But I cannot make it work :</p> <pre><code>class JSHttpGetterThread : public QThread { Q_OBJECT public: JSHttpGetterThread(QObject* pParent = NULL); ~JSHttpGetterThread(); virtual void run() { m_pHttp = new QHttp(this); connect(m_pHttp, SIGNAL(requestFinished(int, bool)), this, SLOT(onRequestFinished(int, bool))); m_pHttp-&gt;setHost("127.0.0.1"); m_pHttp-&gt;get("Foo.txt", &amp;m_GetBuffer); exec(); } const QString&amp; getDownloadedFileContent() const { return m_DownloadedFileContent; } private: QHttp* m_pHttp; QBuffer m_GetBuffer; QString m_DownloadedFileContent; private slots: void onRequestFinished(int Id, bool Error) { m_DownloadedFileContent = ""; m_DownloadedFileContent.append(m_GetBuffer.buffer()); } }; </code></pre> <p>In the method creating the thread to initiate the download, here is what I'm doing :</p> <pre><code>JSHttpGetterThread* pGetter = new JSHttpGetterThread(this); pGetter-&gt;start(); pGetter-&gt;wait(); </code></pre> <p>But that doesn't work and my app keeps waiting. It looks lit the slot 'onRequestFinished' is never called.</p> <p>Any idea ?</p> <p>Is there a better way to do what I'm trying to do ?</p>
<p>Instead of using a thread you can just go into a loop which calls <code>processEvents</code>:</p> <pre><code>while (notFinished) { qApp-&gt;processEvents(QEventLoop::WaitForMore | QEventLoop::ExcludeUserInput); } </code></pre> <p>Where <code>notFinished</code> is a flag which can be set from the <code>onRequestFinished</code> slot.</p> <p>The <code>ExcludeUserInput</code> will ensure that GUI related events are ignored while waiting. </p>
<p>How about giving the GUI some amount of time to wait on the thread and then give up.</p> <p>Something like:</p> <pre><code>JSHttpGetterThread* pGetter = new JSHttpGetterThread(this); pGetter-&gt;start(); pGetter-&gt;wait(10000); //give the thread 10 seconds to download </code></pre> <p>Or...</p> <p>Why does the GUI thread have to wait for the "downloader thread" at all? When the app fires up create the downloader thread, connect the finished() signal to some other object, start the downloader thread, and return. When the thread has finished, it will signal the other object which can resume your process.</p>
31,209
<p>How do I calculate distance between two GPS coordinates (using latitude and longitude)?</p>
<p><a href="http://www.movable-type.co.uk/scripts/latlong.html" rel="noreferrer">Calculate the distance between two coordinates by latitude and longitude</a>, including a Javascript implementation.</p> <p><em>West</em> and <em>South</em> locations are negative. Remember minutes and seconds are out of 60 so S31 30' is -31.50 degrees.</p> <p>Don't forget to <em>convert degrees to radians</em>. Many languages have this function. Or its a simple calculation: <code>radians = degrees * PI / 180</code>.</p> <pre><code>function degreesToRadians(degrees) { return degrees * Math.PI / 180; } function distanceInKmBetweenEarthCoordinates(lat1, lon1, lat2, lon2) { var earthRadiusKm = 6371; var dLat = degreesToRadians(lat2-lat1); var dLon = degreesToRadians(lon2-lon1); lat1 = degreesToRadians(lat1); lat2 = degreesToRadians(lat2); var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return earthRadiusKm * c; } </code></pre> <p>Here are some examples of usage:</p> <pre><code>distanceInKmBetweenEarthCoordinates(0,0,0,0) // Distance between same // points should be 0 0 distanceInKmBetweenEarthCoordinates(51.5, 0, 38.8, -77.1) // From London // to Arlington 5918.185064088764 </code></pre>
<p>I think a version of the algorithm in <strong>R</strong> is still missing:</p> <pre><code>gpsdistance&lt;-function(lat1,lon1,lat2,lon2){ # internal function to change deg to rad degreesToRadians&lt;- function (degrees) { return (degrees * pi / 180) } R&lt;-6371e3 #radius of Earth in meters phi1&lt;-degreesToRadians(lat1) # latitude 1 phi2&lt;-degreesToRadians(lat2) # latitude 2 lambda1&lt;-degreesToRadians(lon1) # longitude 1 lambda2&lt;-degreesToRadians(lon2) # longitude 2 delta_phi&lt;-phi1-phi2 # latitude-distance delta_lambda&lt;-lambda1-lambda2 # longitude-distance a&lt;-sin(delta_phi/2)*sin(delta_phi/2)+ cos(phi1)*cos(phi2)*sin(delta_lambda/2)* sin(delta_lambda/2) cc&lt;-2*atan2(sqrt(a),sqrt(1-a)) distance&lt;- R * cc return(distance) # in meters } </code></pre>
47,759
<p>I have a strange encounter when creating a GridView using <code>SELECT..WHERE..&lt;field&gt; IN (value1, val2...)</code>.</p> <p>In the "Configure datasource" tab, if i hard code the values <code>SELECT .... WHERE field1 in ('AAA', 'BBB', 'CCC')</code>, the system works well.</p> <p>However, if I define a new parameter and pass in a concatenated string of values using a variable; be it a @session, Control or querystring; e.g. <code>SELECT .... WHERE field1 in @SESSION</code> the result is always empty.</p> <p>I did another experiment by reducing the parameter content to only one single value, it works well.</p> <p>in short, if I hardcode a string of values, it works, if I pass a variable with single value only, it works, but if i pass a varialbe with two values; it failed.</p> <p>Pls advise if I have make any mistake or it is a known bug.</p> <p>BR SDIGI</p>
<p>This works. Not sure how efficient it is though.</p> <pre><code>CREATE PROCEDURE [dbo].[get_bars_in_foo] @bars varchar(255) AS BEGIN DECLARE @query AS varchar(MAX) SET @query = 'SELECT * FROM [foo] WHERE bar IN (' + @bars + ')' exec(@query) END -- exec [get_bars_in_foo] '1,2,3,4' </code></pre>
<p>If you go to using a stored procedure, you can use <a href="http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/232/pageid/119.aspx" rel="nofollow noreferrer">this method</a>, which I discussed in regards to how to do it in SQL.</p>
44,553
<p>How can I bring my WPF application to the front of the desktop? So far I've tried:</p> <pre><code>SwitchToThisWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle, true); SetWindowPos(new WindowInteropHelper(Application.Current.MainWindow).Handle, IntPtr.Zero, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); SetForegroundWindow(new WindowInteropHelper(Application.Current.MainWindow).Handle); </code></pre> <p>None of which are doing the job (<code>Marshal.GetLastWin32Error()</code> is saying these operations completed successfully, and the P/Invoke attributes for each definition do have <code>SetLastError=true</code>).</p> <p>If I create a new blank WPF application, and call <code>SwitchToThisWindow</code> with a timer, it works exactly as expected, so I'm not sure why it's not working in my original case.</p> <p><strong>Edit</strong>: I'm doing this in conjunction with a global hotkey.</p>
<pre><code>myWindow.Activate(); </code></pre> <p><em>Attempts to bring the window to the foreground and activates it.</em></p> <p>That should do the trick, unless I misunderstood and you want Always on Top behavior. In that case you want:</p> <pre><code>myWindow.TopMost = true; </code></pre>
<p>I built an extension method to make for easy reuse.</p> <pre><code>using System.Windows.Forms; namespace YourNamespace{ public static class WindowsFormExtensions { public static void PutOnTop(this Form form) { form.Show(); form.Activate(); }// END PutOnTop() }// END class }// END namespace </code></pre> <p>Call in the Form Constructor </p> <pre><code>namespace YourNamespace{ public partial class FormName : Form { public FormName(){ this.PutOnTop(); InitalizeComponents(); }// END Constructor } // END Form }// END namespace </code></pre>
32,144
<p>Instead of writing my ASP.NET C# applications in Visual Studio, I used my favorite text editor UltraEdit32.</p> <p>Is there any way I can implement MVC without the use of VS?</p>
<p>There is nothing VS specific with the MVC framework - it is just a bunch of DLLs that you can use. The wizards in VS just build you a quick-start framework.</p> <p>ASP.NET MVC is "bin-deployable" - there is nothing too clever to set up on the server either - just point the wildcard ISAPI filter to ASP.NET</p>
<p>For small to mid size mvc project <a href="http://www.microsoft.com/web/webmatrix/" rel="nofollow">WebMatrix</a> is not bad at all. Also for simple changes to the projects I often use SublimeText.</p>
2,434
<p>I was asked for a comprehensive breakdown on space used within a specific database. I know I can use <em>sys.dm_db_partition_stats</em> in SQL Server 2005 to figure out how much space each <em>table</em> in a database is using, but is there any way to determine the individual and total size of the <em>stored procedures</em> in a database? (Short of opening each one and counting the characters, of course.)</p> <p>Total space used by stored procs is not likely to be significant (compared to actual <em>data</em>), but with hundreds of them, it could add up.</p>
<pre><code>;WITH ROUTINES AS ( -- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit SELECT o.type_desc AS ROUTINE_TYPE ,o.[name] AS ROUTINE_NAME ,m.definition AS ROUTINE_DEFINITION FROM sys.sql_modules AS m INNER JOIN sys.objects AS o ON m.object_id = o.object_id ) SELECT SUM(LEN(ROUTINE_DEFINITION)) FROM ROUTINES </code></pre>
<p>A slightly better way than counting the characters, is to use information schema.routines. You could sum the length of each Routine Definition as (Note each routine definition will max out at 4,000 characters, see below for a method that doesn't have this restriction):</p> <pre> select Sum(Len(Routine_Definition)) from information_schema.routines where routine_type = 'PROCEDURE' </pre> <p>Or you could return the length of each sp</p> <pre> select Len(Routine_Definition), * from information_schema.routines where routine_type = 'PROCEDURE' </pre> <p>It's unlikely that the length of your stored procedures is the problem. Usually running out of space with a database is due to things like not backing up the log file (and then shrinking it using dbcc shrinkfile or dbcc shrinkdatabase).</p> <p>In Sql 2000, here is a routine that would provide the length without the 4000 character limit of above:</p> <pre> DECLARE @Name VarChar(250) DECLARE RoutineCursor CURSOR FOR select Routine_Name from information_schema.routines where routine_type = 'PROCEDURE' DECLARE @Results TABLE ( SpName VarChar(250), SpLength Int ) CREATE TABLE ##SpText ( SpText VarChar(8000) ) OPEN RoutineCursor FETCH NEXT FROM RoutineCursor INTO @Name WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO ##SpText (SpText) EXEC sp_helptext @Name INSERT INTO @Results (SpName, SpLength) (SELECT @Name, Sum(Len(SpText)) FROM ##SpText) TRUNCATE TABLE ##SpText FETCH NEXT FROM RoutineCursor INTO @Name END CLOSE RoutineCursor DEALLOCATE RoutineCursor DROP TABLE ##SpText SELECT SpName, SpLength FROM @Results ORDER BY SpLength DESC SELECT Sum(SpLength) FROM @Results </pre>
27,030
<p>Let's say I have some pointers called:</p> <pre><code>char * pChar; int * pInt; </code></pre> <p>I know they both simply hold memory addresses that point to some other location, and that the types declare how big the memory location is pointed to by the particular pointer. So for example, a char might be the size of a byte on a system, while an int may be 4 bytes.. So when I do:</p> <pre><code>pChar++; // I am actually incrementing the address pointed to by pChar by 1 byte; pInt++; // I am actually incrementing the address pointed to by pInt by 4 bytes; </code></pre> <p>But what if I do this:</p> <pre><code>pChar+2; // increment the address pointed to by pChar by 2 bytes? pInt+2; // increment the address pointed to by pInt by 2 bytes? what happens to the other two bytes? </code></pre> <p>Thanks.. Would appreciate any clarification here.. Is the pointer type simply for the ++ operation?</p> <p>EDIT: So avp answered my question fittingly, but I have a follow up question, what happens when I do:</p> <pre><code>memcpy(pChar,pInt,2); </code></pre> <p>Will it copy 2 bytes? or 4 bytes? Will I have an access violation?</p> <p>EDIT: THe answer, according to Ryan Fox, is 2 bytes, because they are typecasted to a (void*). Thanks! CLOSED!</p> <p>EDIT: Just so that future searchers may find this.. Another piece of info I discovered.. </p> <pre><code>memcpy(pChar+5,pInt+5,2); </code></pre> <p>doesnt copy 2 bytes of the memory block pointed to by pInt+5bytelocations,to pChar+5bytelocations.. what happens is that 2 bytes are copied to pChar+5bytelocations from pInt(4*5)bytelocations.. no wonder I got access violations, I was trying to read off somewhere I wasn't supposed to be reading.. :)</p>
<p>"++" is just another name for X = X + 1;</p> <p>For pointers it doesn't matter if you increment by 1 or by N. Anyway, sizeof(type)*N is used. In the case of 1 it will be just sizeof(type).</p> <p>So, when you increment by 2 (your second case):<br> for char is 2*sizeof(char)=2*1=2 bytes,<br> for int will be 2*sizeof(int)=2*4=8 bytes.</p>
<p>I would have said that the point of pointer types in <strong>C++</strong> is to account for vtable offsets.</p>
49,855
<p>I was trying to figure out how to implement method_missing in C# 4, based on all of 2 blog posts floating around on IDynamicObject. </p> <p>What I want to do is have a Business Logic Layer that has a Repository, and if the method is missing from the Business Logic Layer, just call the Repository and pass through its result. So i have a class that looks like this:</p> <pre><code>public class CustomerServices : IDynamicObject { protected CustomerRepository _Repository = new CustomerRepository(); MetaObject IDynamicObject.GetMetaObject(Expression parameter) { return new RepositoryMetaObject&lt;CustomerRepository&gt;(_Repository, parameter); } } </code></pre> <p>In RepositoryMetaObect I implement the Call method like so:</p> <pre><code> public override MetaObject Call(CallAction action, MetaObject[] args) { typeof(T).GetMethod(action.Name).Invoke(_Repository, getParameterArray(args)); return this; } </code></pre> <p>(The rest of RepositoryMetaObject code probably isn't interesting, but I've included it here: <a href="http://pastie.org/312842" rel="noreferrer">http://pastie.org/312842</a>)</p> <p>The problem I think is that I'm never doing anything with the result of the Invoke, I'm just returning the MetaObject itself. </p> <p>Now when I do this:</p> <pre><code> dynamic service = new CustomerServices(); var myCustomer = service.GetByID(1); </code></pre> <p>GetByID is called, but if I try to access a property on myCustomer, is just hangs. </p> <p>Can anyone please help?</p> <p>Complete code can be downloaded ehre: <a href="https://dl.getdropbox.com/u/277640/BusinessLogicLayer.zip" rel="noreferrer">https://dl.getdropbox.com/u/277640/BusinessLogicLayer.zip</a></p>
<p>I believe you need to return a new MetaObject with the returned value as a constant expression.</p> <p>That's certainly what happens on <a href="http://www.codeproject.com/KB/cs/moemeka.aspx?display=Print" rel="nofollow noreferrer">this CodeProject page</a>. Worth a try :)</p>
<blockquote> <p>but if I try to access a property on myCustomer, is just hangs</p> </blockquote> <p>Can you set a breakpoint on the line after service.GetByID(1)? See what you've really got back from that call. Otherwise it's hard to tell what exactly happened.</p>
35,878
<p>This is related to a chapter from <a href="https://rads.stackoverflow.com/amzn/click/com/0596510047" rel="noreferrer" rel="nofollow noreferrer">beautiful code</a>. And in that chapter I read about the nested <code>if</code>s.</p> <p>The author was talking about deeply nested <code>if</code>s as originator of bugs and less readable. And he was talking about replacing nested <code>if</code>s with <code>case</code> statements and <a href="https://en.wikipedia.org/wiki/Decision_table" rel="noreferrer">decision tables</a>. </p> <p>Can anybody illustrate how to remove nested <code>if</code>s with <code>case</code> (<code>select case</code>) and decision tables ? </p>
<p>Well, not directly an answer to your question since you specifically ask about switch/case statements, but here is a similar question.</p> <p><a href="https://stackoverflow.com/questions/268132/invert-if-statement-to-reduce-nesting">Invert “if” statement to reduce nesting</a></p> <p>This talks about replacing nested if's with guard-statements, that return early, instead of progressively checking more and more things before settling on a return value.</p>
<p>Another example some languages allow is this</p> <pre><code> switch true{ case i==0 //action break case j==2 //action break case i&gt;j //action break } </code></pre>
43,729
<p>I am wondering how to naturally sort a DataView... I really need help on this. I found articles out there that can do lists with IComparable, but I need to sort the numbers in my dataview.</p> <p>They are currently alpha sorted because they are numbers with 'commas' in them. Please help me out.</p> <p>I would like to find something instead of spending the time to create it my self.</p> <p>P.S. expression and sortdirection work, but they of course Alpha sort. Please help.</p>
<p>I often like to add a "SortOrder" column to results that I want to sort in a way other than is provided by the data. I usually use an integer and just add it when I am getting the data.</p> <p>I don't show this column and only use it for the purposes of establishing the order.</p> <p>I'm not sure if this is what you are looking for, but it is quick and easy and gives you a great deal of control.</p>
<p>See these related questions:</p> <ul> <li><a href="https://stackoverflow.com/questions/89987/how-to-naturally-sort-a-dataview-with-something-like-icomparable">How to Naturally Sort a DataView with something like IComparable</a></li> <li><a href="https://stackoverflow.com/questions/91766/how-do-i-sort-an-aspnet-datagrid-by-the-length-of-a-field">How do I sort an ASP.NET DataGrid by the length of a field?</a></li> </ul>
12,409