instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p><a href="http://tomcat.apache.org/tomcat-5.5-doc/deployer-howto.html" rel="noreferrer">Tomcat documentation</a> says: </p>
<p>The locations for Context Descriptors are;</p>
<p>$CATALINA_HOME/conf/[enginename]/[hostname]/context.xml<br>
$CATALINA_HOME/webapps/[webappname]/META-INF/context.xml</p>
<p>On my server, I have at least 3 files floating around:</p>
<pre><code>1 ...tomcat/conf/context.xml
2 ...tomcat/Catalina/localhost/myapp.xml
3 ...tomcat/webapps/myapp/META-INF/context.xml
</code></pre>
<p>What is the order of precedence? </p>
|
<p>For the files you listed, the simple answer assuming you are using all the defaults, the order is (note the <strong>conf</strong>/Catalina/localhost):</p>
<pre><code>...tomcat/conf/context.xml
...tomcat/conf/Catalina/localhost/myapp.xml
...tomcat/webapps/myapp/META-INF/context.xml
</code></pre>
<p>I'm basing this (and the following discussion) on the <a href="http://tomcat.apache.org/tomcat-5.5-doc/config/context.html" rel="noreferrer">Tomcat 5.5 official documentation for the <strong>Context Container</strong></a>. </p>
<p>So if that's the simple answer, whats the complete answer?</p>
<p>Tomcat 5.5. will look in a couple of other places for <code><Context></code> elements beyond those you've listed (see the official docs).</p>
<p>The <code>META-INF/context.xml</code> will never be opened if Tomcat finds a <code>Catalina/localhost/myapp.xml</code>. So if you actually have all the files above, its more correct to say the the <code>META-INF/context.xml</code> is <strong>irrelevant</strong>, not that it's the lowest precedence.</p>
<p>If you say <code><Context override="true" ...></code> in your <code>Catalina/localhost/myapp.xml</code> that will make it the <strong>highest</strong> precedence, regardless of <code>conf/context.xml</code>. Same thing in your <code>META-INF\context.xml</code>, as long as you don't have a <code>Catalina/localhost/myapp.xml</code> (see previous paragraph).</p>
<p>Also, the <code>/Catalina/localhost/</code> portion of the path in the files above actually comes out of the "default" <code>conf/server.xml</code> and matches the <code><Engine name="Catalina" defaultHost="localhost"></code>. If your <code>server.xml</code> uses different values for <code>name</code> and <code>defaultHost</code> in the <code><Engine></code>, that's the dir structure where Tomcat will look.</p>
<p>Finally, for the <code>...tomcat\</code> portion of the files you listed, Tomcat uses the dir from the <code>$CATALINA_BASE</code> environment variable. If that's not set, then it uses the dir from the <code>$CATALINA_HOME</code> environment variable, which is the directory of the Tomcat installation. I like to set and use <code>$CATALINA_BASE</code> so that I don't "pollute" my Tomcat installation.</p>
|
<p>I haven't found any official documentation, but I have observed the load order to be:</p>
<pre><code>1 tomcat_home/conf/context.xml
2 tomcat_home/webapps/myapp/META-INF/context.xml
</code></pre>
<p>Where #2 is the last one applied (so its settings override all previous ones, where applicable).</p>
<p>I have never used the webapp named context files (your option #2).</p>
| 41,717
|
<p>A very well known major drawback of using CGI is poor webserver performance. But how secure are CGI (mainly C/C++) based applications? Are there any major security holes in CGI architecture built on C/C++? </p>
<p>I would like to know some real life implementations of CGI based web apps/web sites. One that I know of is javaranch.com. </p>
|
<p>The major security hole I would see anywhere, C/C++ included, would be not using a standard, open CGI library, not reading its documentation, and thinking you're secure anyway.</p>
<ul>
<li>don't re-invent the wheel. Use a CGI library. Some languages have this built-in (PHP probably does), others have it included (Perl comes to mind), others need you to grab it from elsewhere (C/C++). Make sure you know what it is, and that you use it. Do <strong>not</strong> try to implement it yourself. If you have to ask about security, you, like me, are not qualified to write it.</li>
<li>Read the documentation. If you're using a well-established library, there will be documentation on security issues and what you can do to avoid them.</li>
<li>Do not ever assume you're secure. I'm quite sure I'm not secure, even though I've followed all the rules in the CGI library for Perl, and the rules in the database interface library, etc. But I still assume I'm not secure, and keep it on the forefront of my mind when doing anything there. Should I ever be an expert on security, maybe I'll change my assumption. Not sure yet.</li>
</ul>
<p>Security is always multi-faceted, and always incomplete. There are holes being found in all sorts of software all the time - software that may have been previously thought secure. And now we have many more best-practices for security than we did, say, 15 years ago. And we have SELinux for more security.</p>
<p>Of course, the question is - do you have enough security for your app? Does a reasonable effort get you a reasonable level of security? Of course, that's why I don't use C/C++, but I use Perl instead. It takes a lot less effort to ensure I don't overwrite memory in Perl than it does in C++. That's a level of security right there with no actual work involved.</p>
|
<p>Many sites are CGI based. Many PHP sites that are located on hosting are run in CGI mode - mod_php is hard to used in shared environment - no suid.</p>
<p>In general, running as CGI has lower performance, but better for security - you have no access to webserver internals (as with mod_perl and mod_php) so using vulnerabilities is harder. If you use cgi-bin, you non-execute files are not visible (a common bug of PHP programmers is that they have libraries with extension like .inc so source is shown when this file is requested directly).</p>
| 25,835
|
<p>In .NET there is the <code>CultureInfo</code> class in the <code>System.Globalization</code> namespace. It has two similar properties both returning values of the <code>CultureInfo</code> type: <code>CurrentCulture</code> and <code>CurrentUICulture</code>.</p>
<p>What is the difference between them? </p>
<p>Which one should I use when and why?</p>
|
<p><code>CurrentCulture</code> is the .NET representation of the default user locale of the system. This controls default number and date formatting and the like.</p>
<p><code>CurrentUICulture</code> refers to the default user interface language, a setting introduced in Windows 2000. This is primarily regarding the UI localization/translation part of your app.</p>
<p>Whatever regional options the system is configured to have will be the "Current" values in your .NET app.</p>
<p>Often times they are both the same. But on my system they would be different: I prefer my numbers and dates in the German format, so the <code>CurrentCulture</code> would be German, but I also prefer all my applications in English, so the <code>CurrentUICulture</code> would be English.</p>
<p>There is a nice article on the topic: <a href="http://www.siao2.com/2007/01/11/1449754.aspx" rel="noreferrer">Sorting it all Out: Why we have both CurrentCulture and CurrentUICulture</a></p>
|
<p><strong>Differences:</strong></p>
<ol>
<li><a href="https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture" rel="noreferrer"><code>CurrentCulture</code></a> is for formatting of dates and currency while <a href="https://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture" rel="noreferrer"><code>CurrentUICulture</code></a> goes with language/translations. It will be used by <a href="http://msdn2.microsoft.com/en-us/library/system.resources.resourcemanager.aspx" rel="noreferrer"><code>ResourceManager</code></a> to look up resources by culture.</li>
<li>Namespace of <a href="https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture" rel="noreferrer"><code>CurrentCulture</code></a> class is in <code>System.Globalization</code> while <a href="https://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture" rel="noreferrer"><code>CurrentUICulture</code></a> comes from <code>System.Threading</code>.</li>
<li><a href="https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.currentculture" rel="noreferrer"><code>CurrentCulture</code></a> is persisted across different requests in the session while <a href="https://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture" rel="noreferrer"><code>CurrentUICulture</code></a> needs to be set with every request.</li>
</ol>
<p><strong>Likeness:</strong></p>
<p>They both are <a href="https://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo" rel="noreferrer"><code>System.Globalization.CultureInfo</code></a> instances.</p>
| 42,634
|
<p>I'm trying to read the contents of a text file, in this case a list of computer names (Computer1, computer2 etc,) and I thought that StreamReader would be what you would use but when I do the following:</p>
<pre><code>StreamReader arrComputer = new StreamReader(FileDialog.filename)();
</code></pre>
<p>I got this exception:</p>
<pre><code>The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?)
</code></pre>
<p>I'm very new to C# so I'm sure I'm making a newbie mistake.</p>
|
<p>You need to import the <code>System.IO</code> namespace. Put this at the top of your .cs file:</p>
<pre><code>using System.IO;
</code></pre>
<p>Either that, or explicitly qualify the type name:</p>
<pre><code>System.IO.StreamReader arrComputer = new System.IO.StreamReader(FileDialog.filename);
</code></pre>
|
<p>You need to add a reference to the System.IO assembly. You can do this via the "My Project" properties page under the References tab.</p>
| 35,251
|
<p>I was wondering about the best way to manage projects dependencies from ant. What are the pros and cons of the Maven Ant task and of Ivy?</p>
|
<p>Since what you're wanting to do is add dependency management to an existing Ant project, that's precisely what Ivy's designed to do. Dependency management is a big part of Maven, but far from all of it. Maven is more of a project-oriented tool that does several other things in addition to dependencies. It would be worth considering if you were planning to migrate to Maven and use additional Maven features as well, but it's a bit much if all you'd use it for is to spin off Ant.</p>
<p>Your type of dependencies and your expectations for how they behave will also make a difference. Pulling third-party dependencies is almost trivial in Maven, while Ivy excels in rebuilding your own dependent components. In either case, the tools won't provide decent build, versioning, and repository <em>policies</em>, those are still up to you and needed to get the configuration right.</p>
|
<p>I've just spent 2 days reading through the Ivy documentation and I have to say, USE MAVEN if you have any kind of choice. Ivy is complete and utter garbage as far as I can tell. I just wasted 2 days trying to incorporate it into my build and am cutting my losses now. Why?</p>
<ul>
<li>Ivy is a half-assed attempt at dependency management</li>
<li>Ivy documentation is a total joke</li>
<li>Ivy examples and tutorial are useless</li>
</ul>
<p>As soon as I introduced 'configurations' (read as maven profiles), Ivy started going bezerk downloading all sorts of junk I don't need then failing. The documentation for Ivy is an utter joke. Maven documentation in comparison reads like a dream. If you want an example of how impenetrable and badly written the Ivy documentation is, take a look at the reference page for <a href="http://ant.apache.org/ivy/history/latest-milestone/ivyfile/configurations.html" rel="nofollow noreferrer">configurations</a>. These are an essential part of any build, but in Ivy they seem to be a badly designed after thought. </p>
| 41,212
|
<p>I'm wonder what the best way to convert a byte array (length 4) to an integer is in vb.net? I'm aware of BitConverter, but it seems like quite a waste to do a function call to do something that should be able to be done by copying 4 bytes of memory. Along the same lines, what about converting a single/double from it's binary representation to an single/double variable.</p>
|
<p>"Copying bytes of memory" is something that .NET isn't particularly suited for (and VB.NET even less so). So, unless switching to C is an option for you, a function call is pretty much unavoidable for this.</p>
<p>BitConverter is a well-thought-out, tested function. Of course, you can avoid it by doing something like (in C#):</p>
<pre><code>myInt = (*pbyte) | (*(pbyte + 1) << 8) | (*(pbyte + 2) << 16) | (*(pbyte + 3) << 24);
</code></pre>
<p>(which is, incidentally, <i>exactly</i> what BitConverter does for you when converting a byte array to an Integer...).</p>
<p>However, this code:</p>
<ul>
<li>Is much, much harder to read and understand than the BitConverter equivalent;</li>
<li>Doesn't do any of the error checking that BitConverter does for you;</li>
<li>Doesn't differentiate between little-endian and big-endian representations, like BitConverter does.</li>
</ul>
<p>In other words: you might "save" a function call, but you will be significantly worse off in the end (even assuming you don't introduce any bugs). In general, the .NET Framework is very, very well designed, and you shouldn't think twice about using its functionality, unless you encounter actual (performance) issues with it.</p>
|
<p>You can block copy byte[] to int[] using System.Buffer class.</p>
| 28,097
|
<p>Running Mongrel 1.1.5 on Rails 2.1.2 using PostgreSQL 8.3 via ruby-pg 0.7.9 on OS X 10.4 server...</p>
<p>Added restful_authentication and exception_notification, the latter of which appears to be doing me no good when Mongrel simply dies with "Illegal instruction" every time I select /RESOURCE_NAME/new.</p>
<p>Doesn't matter what resource.</p>
<p>In development.log I see it's declaring its intent to render /layouts/RESOURCE_NAME.html.erb and then ... nothing. No stack trace, no anything. server.log is empty.</p>
<p>This is something of a showstopper and I'm not sure what to do. I tried running webbrick, a la:</p>
<p>script/server webbrick --force</p>
<p>But it ignores my wishes and loads mongrel anyway.</p>
<p>Any pointers would be appreciated.</p>
|
<p>You probably want to create a "UNIQUE" constraint on the field "Domain" - this constraint will raise an error if you create two rows that have the same domain in the database. For an explanation, see <a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow noreferrer">this tutorial in W3C school</a> -</p>
<p><a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow noreferrer">http://www.w3schools.com/sql/sql_unique.asp</a></p>
<p>If this doesn't solve your problem, please clarify the database you have chosen to use (MySql?).</p>
<p>NOTE: This constraint is completely separate from your choice of PHP as a programming language, it is a SQL database definition thing. A huge advantage of expressing this constraint in SQL is that you can trust the database to preserve the constraint even when people import / export data from the database, your application is buggy or another application shares the database.</p>
|
<p>I'm not really sure I understood your question, but perhaps you are looking for SQL's <a href="http://www.w3schools.com/sql/sql_unique.asp" rel="nofollow noreferrer">"UNIQUE" constraint</a>. If the query tries to insert a pre-existing value to a field, you (PHP) will be notified about this constraint breach.</p>
| 34,877
|
<p>I am a bit confused why this code compiles. I leave out the "necessary" <code>#include <OpenGL/gl.h></code> and still the program can compile. How is this possible when my program is calling functions from the GL library, without including them.</p>
<pre><code>int main(int argc, char** argv)
{
glClearColor(1.0,1.0,1.0,1.0);
return 0;
}
</code></pre>
<p>I use this compilation command:</p>
<pre><code> gcc -framework GLUT -framework OpenGL test.c
</code></pre>
<p>I was under the assumption that adding -framework just specifies to the linker where the library is, but I thought I still need the headers?</p>
|
<p>glClearColor isn't a macro so you don't <em>need</em> the headers to define it. If you add warnings:</p>
<pre><code>gcc -o test -Wall -W test.c -framework GLUT -framework OpenGL
</code></pre>
<p>Then you'll get a warning about the implicit declaration of glClearColor. You also won't be able to use any macros as the compiler will give you an error that they are undefined. Since the glClearColor symbol gets properly resolved by the linker, you never get an error.</p>
<p>It also occurs to me that you might have been wondering this because you thought you were compiling for C++. The example you gave actually compiles C code where it is not an error to fail to declare function prototypes. If you meant to compile this as C++ code, you would need the following command line:</p>
<p>g++ -o test test.cpp -framework OpenGL</p>
<p>In that case you most certainly would get an error for not including gl.h and your code would fail to compile. When executing GCC from the command line, g++ is the C++ compiler while gcc is the general C compiler.</p>
|
<p>This actually relates to the classic C&R hello world snippet:<br>
<a href="http://en.wikipedia.org/wiki/Hello_world#History" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Hello_world#History</a></p>
| 34,977
|
<p>Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out.</p>
<p>Where can one find a good list of swear words in various languages and dialects? </p>
<p>Are there APIs available to sources that contain good lists? Or maybe an API that simply says "yes this is clean" or "no this is dirty" with some parameters?</p>
<p>What are some good methods for catching folks trying to trick the system, like a$$, azz, or a55?</p>
<p>Bonus points if you offer solutions for PHP. :)</p>
<h2><em>Edit: Response to answers that say simply avoid the programmatic issue:</em></h2>
<p>I think there is a place for this kind of filter when, for instance, a user can use public image search to find pictures that get added to a sensitive community pool. If they can search for "penis", then they will likely get many pictures of, yep. If we don't want pictures of that, then preventing the word as a search term is a good gatekeeper, though admittedly not a foolproof method. Getting the list of words in the first place is the real question.</p>
<p>So I'm really referring to a way to figure out of a single token is dirty or not and then simply disallow it. I'd not bother preventing a sentiment like the totally hilarious "long necked giraffe" reference. Nothing you can do there. :)</p>
|
<p><a href="http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/" rel="noreferrer">Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?</a></p>
<p>Also, one can't forget <a href="http://habitatchronicles.com/2007/03/the-untold-history-of-toontowns-speedchat-or-blockchattm-from-disney-finally-arrives/" rel="noreferrer">The Untold History of Toontown's SpeedChat</a>, where even using a "safe-word whitelist" resulted in a 14-year-old quickly circumventing it with:
<em>"I want to stick my long-necked Giraffe up your fluffy white bunny."</em></p>
<p>Bottom line: Ultimately, for any system that you implement, there is absolutely no substitute for human review (whether peer or otherwise). Feel free to implement a rudimentary tool to get rid of the drive-by's, but for the determined troll, you absolutely must have a non-algorithm-based approach.</p>
<p>A system that removes anonymity and introduces accountability (something that Stack Overflow does well) is helpful also, particularly in order to help combat <a href="http://www.penny-arcade.com/comic/2004/03/19/" rel="noreferrer">John Gabriel's G.I.F.T.</a></p>
<p>You also asked where you can get profanity lists to get you started -- one open-source project to check out is <a href="http://dansguardian.org" rel="noreferrer">Dansguardian</a> -- check out the source code for their default profanity lists. There is also an additional third party <a href="http://contentfilter.futuragts.com/phraselists/" rel="noreferrer">Phrase List</a> that you can download for the proxy that may be a helpful gleaning point for you.</p>
<p><strong>Edit in response to the question edit:</strong> Thanks for the clarification on what you're trying to do. In that case, if you're just trying to do a simple word filter, there are two ways you can do it. One is to create a single long regexp with all of the banned phrases that you want to censor, and merely do a regex find/replace with it. A regex like:</p>
<pre><code>$filterRegex = "(boogers|snot|poop|shucks|argh)"
</code></pre>
<p>and run it on your input string using <a href="http://us.php.net/preg_match" rel="noreferrer">preg_match()</a> to wholesale test for a hit,</p>
<p>or <a href="http://us.php.net/preg_replace" rel="noreferrer">preg_replace()</a> to blank them out.</p>
<p>You can also load those functions up with arrays rather than a single long regex, and for long word lists, it may be more manageable. See the <a href="http://us.php.net/preg_replace" rel="noreferrer">preg_replace()</a> for some good examples as to how arrays can be used flexibly.</p>
<p>For additional PHP programming examples, see this page for a <a href="http://www.bitrepository.com/advanced-word-filter.html" rel="noreferrer">somewhat advanced generic class</a> for word filtering that *'s out the center letters from censored words, and this <a href="https://stackoverflow.com/questions/24515/bad-words-filter">previous Stack Overflow question</a> that also has a PHP example (the main valuable part in there is the SQL-based filtered word approach -- the leet-speak compensator can be dispensed with if you find it unnecessary).</p>
<p>You also added: "<em>Getting the list of words in the first place is the real question.</em>" -- in addition to some of the previous Dansgaurdian links, you may find <a href="http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/" rel="noreferrer">this handy .zip</a> of 458 words to be helpful.</p>
|
<p>Don't.</p>
<p>Because:</p>
<ul>
<li><strong><a href="http://www.urbandictionary.com/define.php?term=clbuttic" rel="nofollow noreferrer">Clbuttic</a></strong></li>
<li>Profanity is not OMG EVIL</li>
<li>Profanity cannot be effectively defined</li>
<li>Most people quite probably don't appreciate being "protected" from profanity</li>
</ul>
<p>Edit: While I agree with the commenter who said "censorship is wrong", that is not the nature of this answer.</p>
| 34,461
|
<p>I am developing a website using SQL Server Express on my development machine. My web hosting company is providing me with SQL Server 2005.</p>
<p>At the moment all I have is a database that I develop with and a database that is on the live server. I do not have the original scripts to generate the schema but I can auto generate the create scripts individually or for the entire database.</p>
<p>I am now putting my code into source control and I would like to know how I manage my database schema. What do I put into it? Create commands? Alter scripts?</p>
<p>The database is very small at the moment and it is not hard to maintain the two databases, but I am concerned that going forward but it will get out of hand. Do you have any tips for getting the live database in sync when deploying new code?</p>
<p><strong>EDIT</strong> Any ideas as to what should go into source control? Should the DDL scripts go here?</p>
|
<p>Deploy schema changes as DDL upgrade scripts and, if you haven't already, add a table to contain the schema version number which you update at the end of each upgrade script.</p>
<p>EDIT: Yes, all your scripts should go into source control, including DDL scripts.</p>
|
<p>I typically keep a testing copy of the live database on my local or virtual development box, which I flush routinely from the prod database down to testing. The testing copy is meant for my total exploitation. When I have something that I believe is ready for deployment, I move it to my development dataset, which mirrors the prod db and is not used for playing around. If the development db passes all my tests, I deploy the script to the production db</p>
| 31,370
|
<p>I've recently become aware that there's a distinction between IP multicasting (which apparently doesn't work that well on the public internet) and application multicasting (which is apparently used in IRC and PSYC, per <a href="http://en.wikipedia.org/wiki/Multicast" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Multicast</a>).</p>
<p>Is there a good tutorial on implementing application-level multicasting?</p>
<p>I thought the whole point of multicast was to reduce bandwidth for common network segments, so it's hard for me to understand what application-level multicast does.</p>
|
<p>The purpose of IP level multicasting is to reduce bandwidth for common network segments where many users wish to receive the same traffic. It's usually limited to one particular subnet and an IP router won't propagate the multicast beyond the subnet. This is done for scalability reasons - it wouldn't be a good idea to allow one host to originate multicast packets which are propagated to every IP address on the internet.</p>
<p>There are different ways to think of "application level" multicasting. One approach is to build a multicast tree using the host computers participating in the multicast. Dijkstra's algorithm could be used to do this (Wikipedia has a reasonable description of this). However, maintaining the list of participating computers - and keeping the tree up to date - can be a fair amount of work if hosts are joining and leaving the network at a substantial rate. And you probably don't have a good estimate of hop cost available at the application level.</p>
<p>Another approach you should review is the flooding algorithm used in the Gnutella network's query routing protocol. (Wikipedia also has a good description of this.) This approach alleviates the need to build a multicast tree, but it has the downside of generating more network traffic. In fact, a LOT more network traffic, as the traffic grows with the square of the number of nodes, i.e. O(n**2).</p>
|
<p>Another example of application multicasting is using <a href="http://www.jgroups.org/" rel="nofollow noreferrer">JGroups</a> in <a href="http://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud" rel="nofollow noreferrer">Amazon EC2</a> or <a href="http://en.wikipedia.org/wiki/Google_App_Engine" rel="nofollow noreferrer">Google App Engine</a> as they do not support IP multicast but developers want to use multicasting functionality.</p>
| 31,959
|
<p><a href="http://www.springframework.net/" rel="nofollow noreferrer">Spring.NET</a> 1.2.0 M1 comes with several XSD files for the <objects> node, database stuff, etc. However, it is an incomplete collection because it does not seem to include <spring> (used in <code>App.config</code>), <context>, or <parsers> elements. Additionally, <a href="http://netcommon.sourceforge.net/" rel="nofollow noreferrer">Common.Logging</a> doesn't appear to have <em>any</em> XSD's included in the source or distribution.</p>
<p>We'd like to have these so that Visual Studio won't complain about them on compile time when it validates the <code>App.config</code>. It's nice having the schemas in place, because of the compile-time check which helps you find XML bugs <em>before</em> your program throws up in Spring.</p>
<p>Do these exist anywhere / are in development or, alternatively, has anyone written some themselves?</p>
<p>On the same token, has anyone seen/resolved the following message?</p>
<blockquote>
<p>Could not find schema information for the attribute
'<a href="http://schemas.microsoft.com/Visual-Studio-Intellisense:friendlyname" rel="nofollow noreferrer">http://schemas.microsoft.com/Visual-Studio-Intellisense:friendlyname</a>'
(spring-objects-1.1.xsd)</p>
</blockquote>
|
<p>They don't exist for or or the other top level elements that are used in App.config. Please enter a JIRA issue for Spring <a href="http://jira.springframework.org/secure/BrowseProject.jspa?id=10020" rel="nofollow noreferrer">here</a> as well as for Common Logging - <a href="http://sourceforge.net/tracker/?group_id=182424&atid=901159" rel="nofollow noreferrer">here</a>.</p>
|
<p>Have you tried using the XSD tool to reverse engineer an XML output file into the XSD you need? I did something similar when writing my own tool for log4net to get an XSD file.</p>
| 27,613
|
<p>Inside an asp.net page, should I use</p>
<pre><code><html><title>My page's title from México</title></html>
</code></pre>
<p>Or </p>
<pre><code><html><title>My page&rsquo;s title from M&eacute;xico</title></html>
</code></pre>
<p>Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right?</p>
|
<p>I'm having a similar issue. You might be able to do something like this:</p>
<pre><code>SET arithabort arith_overflow off
SET @the_date = CAST(@date_string AS DATETIME)
IF @the_date is NULL
set @the_date = getdate()
SET arithabort arith_overflow on
</code></pre>
<p>However, this doesn't work well in a select. It will work well in a cursor (boo) or in logic before / after a SQL batch.</p>
|
<p>Found <a href="http://blog.sqlauthority.com/2007/07/12/sql-server-validate-field-for-date-datatype-using-function-isdate/" rel="nofollow noreferrer">this in the second result</a> in Google when searching for "validate date string sql".</p>
<pre><code>----Invalid date
SELECT ISDATE('30/2/2007')
RETURNS : 0 (Zero)
----Valid date
SELECT ISDATE('12/12/20007')
RETURNS : 1 (ONE)
----Invalid DataType
SELECT ISDATE('SQL')
RETURNS : 0 (Zero)
</code></pre>
| 3,050
|
<p>This is a C# console application. I have a function that does something like this:</p>
<pre><code>static void foo()
{
Application powerpointApp;
Presentation presentation = null;
powerpointApp = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
}
</code></pre>
<p>That's all it does. When it is called there is a fifteen second delay before the function gets hit. I added something like this:</p>
<pre><code>static void MyAssemblyLoadEventHandler(object sender, AssemblyLoadEventArgs args)
{
Console.WriteLine(DateTime.Now.ToString() + " ASSEMBLY LOADED: " + args.LoadedAssembly.FullName);
Console.WriteLine();
}
</code></pre>
<p>This gets fired telling me that my interop assemblies have been loaded about 10 milliseconds before my foo function gets hit. What can I do about this? The program needs to call this function (and eventually do something else) once and then exit so I need for these assemblies to be cached or something. Ideas?</p>
|
<p>It could be the certificate revocation list - the time-out on this is 15 seconds.
Is there anything in the event log? Can you check if any network connections are happening during the time-out?</p>
<p><a href="http://blogs.conchango.com/anthonysteele/archive/2007/02/07/Delay-when-starting-up-a-web-service.aspx" rel="nofollow noreferrer">I blogged some details about certificate revocation delay</a> a while ago. Follow the link, I won't cut and paste it here.</p>
|
<p>Just guessing, but it is probably the time for PowerPoint to start up after the interop assemblies have loaded.</p>
| 35,324
|
<p>The problem: I have a class which contains a template method <code>execute</code> which calls another method <code>_execute</code>. Subclasses are supposed to overwrite <code>_execute</code> to implement some specific functionality. This functionality should be documented in the docstring of <code>_execute</code>.
Advanced users can create their own subclasses to extend the library. However, another user dealing with such a subclass should only use <code>execute</code>, so he won't see the correct docstring if he uses <code>help(execute)</code>.</p>
<p>Therefore it would be nice to modify the base class in such a way that in a subclass the docstring of <code>execute</code> is automatically replaced with that of <code>_execute</code>. Any ideas how this might be done?</p>
<p>I was thinking of metaclasses to do this, to make this completely transparent to the user.</p>
|
<p>Well, if you don't mind copying the original method in the subclass, you can use the following technique.</p>
<pre><code>import new
def copyfunc(func):
return new.function(func.func_code, func.func_globals, func.func_name,
func.func_defaults, func.func_closure)
class Metaclass(type):
def __new__(meta, name, bases, attrs):
for key in attrs.keys():
if key[0] == '_':
skey = key[1:]
for base in bases:
original = getattr(base, skey, None)
if original is not None:
copy = copyfunc(original)
copy.__doc__ = attrs[key].__doc__
attrs[skey] = copy
break
return type.__new__(meta, name, bases, attrs)
class Class(object):
__metaclass__ = Metaclass
def execute(self):
'''original doc-string'''
return self._execute()
class Subclass(Class):
def _execute(self):
'''sub-class doc-string'''
pass
</code></pre>
|
<p>Well the doc-string is stored in <code>__doc__</code> so it wouldn't be too hard to re-assign it based on the doc-string of <code>_execute</code> after the fact.</p>
<p>Basically:</p>
<p><code></p>
<pre>
class MyClass(object):
def execute(self):
'''original doc-string'''
self._execute()
class SubClass(MyClass):
def _execute(self):
'''sub-class doc-string'''
pass
# re-assign doc-string of execute
def execute(self,*args,**kw):
return MyClass.execute(*args,**kw)
execute.__doc__=_execute.__doc__
</pre>
<p></code></p>
<p>Execute has to be re-declared to that the doc string gets attached to the version of execute for the <code>SubClass</code> and not for <code>MyClass</code> (which would otherwise interfere with other sub-classes).</p>
<p>That's not a very tidy way of doing it, but from the POV of the user of a library it should give the desired result. You could then wrap this up in a meta-class to make it easier for people who are sub-classing.</p>
| 9,737
|
<p>Can somebody please give me an example of a unidirectional @OneToOne primary-key mapping in Hibernate ? I've tried numerous combinations, and so far the best thing I've gotten is this :</p>
<pre><code>@Entity
@Table(name = "paper_cheque_stop_metadata")
@org.hibernate.annotations.Entity(mutable = false)
public class PaperChequeStopMetadata implements Serializable, SecurityEventAware {
private static final long serialVersionUID = 1L;
@Id
@JoinColumn(name = "paper_cheque_id")
@OneToOne(cascade = {}, fetch = FetchType.EAGER, optional = false, targetEntity = PaperCheque.class)
private PaperCheque paperCheque;
}
</code></pre>
<p>Whenever Hibernate tries to automatically generate the schema for the above mapping, it tries to create the primary key as a blob, instead of as a long, which is the id type of PaperCheque. Can somebody please help me ? If I can't get an exact solution, something close would do, but I'd appreciate any response.</p>
|
<p>I saved <a href="http://forum.hibernate.org/viewtopic.php?p=2381079" rel="nofollow noreferrer">this discussion</a> when I implemented a couple of @OneToOne mappings, I hope it can be of use to you too, but we don't let Hibernate create the database for us.</p>
<p>Note the GenericGenerator annotation.</p>
<p>Anyway, I have this code working:</p>
<pre><code>@Entity
@Table(name = "message")
public class Message implements java.io.Serializable
{
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn(name = "id", referencedColumnName = "message_id")
public MessageContent getMessageContent()
{
return messageContent;
}
}
@Entity
@Table(name = "message_content")
@GenericGenerator(name = "MessageContent", strategy = "foreign",
parameters =
{
@org.hibernate.annotations.Parameter
(
name = "property", value = "message"
)
}
)
public class MessageContent implements java.io.Serializable
{
@Id
@Column(name = "message_id", unique = true, nullable = false)
// See http://forum.hibernate.org/viewtopic.php?p=2381079
@GeneratedValue(generator = "MessageContent")
public Integer getMessageId()
{
return this.messageId;
}
}
</code></pre>
|
<p>You should stay away from hibernate's OneToOne mapping, it is very dangerous. see <a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-2128" rel="nofollow noreferrer">http://opensource.atlassian.com/projects/hibernate/browse/HHH-2128</a></p>
<p>you are better off using ManyToOne mappings.</p>
| 40,594
|
<p>I've been struggling coming up with a good solution to separate my testing data from unit
tests (hard coded values). Until it dawned on me that I could create beans with spring
and use those beans to hold my data. </p>
<p>Are there any draw backs to coding my unit tests this way? Albeit they run a bit slower
seeing as how spring has to configure all the beans and what not.</p>
|
<p>That was an interesting one...<br>
<strong>The OnInfoMessage event from the ADOConnection works but the Devil is in the details!</strong></p>
<p><strong>Main points:</strong><br>
use CursorLocation = clUseServer instead of the default clUseClient.<br>
use Open and not ExecProc with your ADOStoredProc.<br>
use NextRecordset from the current one to get the following, but be sure to check you have one open.<br>
use SET NOCOUNT = ON in your stored procedure. </p>
<p><strong>SQL side:</strong> your stored procedure</p>
<pre><code>SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[FG_TEST]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[FG_TEST]
GO
-- =============================================
-- Author: François
-- Description: test multi ADO with info
-- =============================================
CREATE PROCEDURE FG_TEST
AS
BEGIN
-- SET NOCOUNT ON absolutely NEEDED
SET NOCOUNT ON;
PRINT '*** start ***'
SELECT 'one' as Set1Field1
PRINT '*** done once ***'
SELECT 'two' as Set2Field2
PRINT '*** done again ***'
SELECT 'three' as Set3Field3
PRINT '***finish ***'
END
GO
</code></pre>
<p><strong>Delphi side:</strong><br>
Create a new VCL Forms Application.<br>
Put a Memo and a Button in your Form. </p>
<p>Copy the following text, change the Catalog and Data Source and Paste it onto your Form </p>
<pre><code>object ADOConnection1: TADOConnection
ConnectionString =
'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security In' +
'fo=False;Initial Catalog=xxxYOURxxxDBxxx;Data Source=xxxYOURxxxSERVERxxx'
CursorLocation = clUseServer
LoginPrompt = False
Provider = 'SQLOLEDB.1'
OnInfoMessage = ADOConnection1InfoMessage
Left = 24
Top = 216
end
object ADOStoredProc1: TADOStoredProc
Connection = ADOConnection1
CursorLocation = clUseServer
ProcedureName = 'FG_TEST;1'
Parameters = <>
Left = 24
Top = 264
end
</code></pre>
<p>In the OnInfoMessage of the ADOConnection put</p>
<pre><code>Memo1.Lines.Add(Error.Description);
</code></pre>
<p>For the ButtonClick, paste this code</p>
<pre><code>procedure TForm1.Button1Click(Sender: TObject);
const
adStateOpen = $00000001; // or defined in ADOInt
var
I: Integer;
ARecordSet: _Recordset;
begin
Memo1.Lines.Add('==========================');
ADOStoredProc1.Open; // not ExecProc !!!!!
ARecordSet := ADOStoredProc1.Recordset;
while Assigned(ARecordSet) do
begin
// do whatever with current RecordSet
while not ADOStoredProc1.Eof do
begin
Memo1.Lines.Add(ADOStoredProc1.Fields[0].FieldName + ': ' + ADOStoredProc1.Fields[0].Value);
ADOStoredProc1.Next;
end;
// switch to subsequent RecordSet if any
ARecordSet := ADOStoredProc1.NextRecordset(I);
if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then
ADOStoredProc1.Recordset := ARecordSet
else
Break;
end;
ADOStoredProc1.Close;
end;
</code></pre>
|
<p>Some enhancements to Francois' code (as tested with DXE2) to cater for multiple print statements and the results from a variable number of selects. The changes are subtle.</p>
<pre><code>procedure TForm1.ADOConnection1InfoMessage(Connection: TADOConnection;
const Error: Error; var EventStatus: TEventStatus);
var
i: integer;
begin
// show ALL print statements
for i := 0 to AdoConnection1.Errors.Count - 1 do
begin
// was: cxMemo1.Lines.Add(Error.Description);
cxMemo1.Lines.Add(
ADOConnection1.Errors.Item[i].Description);
end;
end;
procedure TForm1.cxButton1Click(Sender: TObject);
const
adStateOpen = $00000001; // or uses ADOInt
var
records: Integer;
ARecordSet: _RecordSet;
begin
cxMemo1.Lines.Add('==========================');
ADOStoredProc1.Open;
try
ARecordSet := ADOStoredProc1.RecordSet; // initial fetch
while Assigned(ARecordSet) do
begin
// assign the recordset to a DataSets recordset to traverse
AdoDataSet1.Recordset := ARecordSet;
// do whatever with current ARecordSet
while not ADODataSet1.eof do
begin
cxMemo1.Lines.Add(ADODataSet1.Fields[0].FieldName +
': ' + ADODataSet1.Fields[0].Value);
AdoDataSet1.Next;
end;
// fetch next recordset if there is one
ARecordSet := ADOStoredProc1.NextRecordSet(records);
if Assigned(ARecordSet) and ((ARecordSet.State and adStateOpen) <> 0) then
ADOStoredProc1.Recordset := ARecordSet
else
Break;
end;
finally
ADOStoredProc1.Close;
end;
end;
</code></pre>
| 31,749
|
<p>I need write an update statement that used multiple tables to determine which rows to update, since in Oracle, multiple tables aren't allowed. The following query will return a "ORA-00971: Missing SET keyword" error</p>
<pre><code>UPDATE
TABLE1 a,
TABLE2 b
SET
a.COL1 = 'VALUE'
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
</code></pre>
<p>Looking up the UPDATE statement syntax on oracle, I found the following <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/update_statement.htm" rel="noreferrer">link</a>, which shows that you can use a subquery in place of a table name.</p>
<p>When I tried to write the query like this, I got a "ORA-01779: Cannot modify a column which maps to a non key-preserved table"</p>
<pre><code>UPDATE
(
SELECT
a.COL1
FROM
TABLE1 a,
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
) update_tbl
SET
update_tbl.COL1 = 'VALUE'
</code></pre>
<p>I did rewrite the query (show below) using an EXISTS statement instead and it works fine, but would still like to know how this is done.</p>
<pre><code>UPDATE
TABLE1 update_tbl
SET
update_tbl.COL1 = 'VALUE'
WHERE
EXISTS (
SELECT
1
FROM
TABLE1 a
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
AND update_tbl.PK = a.PK
)
</code></pre>
<p>Thanks!
-Nate</p>
|
<p>Another option:</p>
<pre><code>UPDATE TABLE1 a
SET a.COL1 = 'VALUE'
WHERE a.FK IN
( SELECT b.PK FROM TABLE2 b
WHERE b.COL2 IN ('SET OF VALUES')
)
</code></pre>
<p>Your second example would work if (a) the view included the <strong>declared</strong> PK of TABLE1:</p>
<pre><code>UPDATE
(
SELECT
a.COL1, a.PKCOL
FROM
TABLE1 a,
TABLE2 b
WHERE
a.FK = b.PK
AND b.COL2 IN ('SET OF VALUES')
) update_tbl
SET
update_tbl.COL1 = 'VALUE'
</code></pre>
<p>... and (b) TABLE1.FK was a <strong>declared</strong> foreign key to TABLE2</p>
<p>(By declared I mean that a constraint exists and is enabled).</p>
|
<p>Each row in the result set of the query in your UPDATE clause must map back to one and only one row in the table you are trying to update, and in a way that Oracle can follow automatically. Since the query is really a view, one way to think about it is that Oracle needs to be able to join the view back to the target table, in order to know what row to update.</p>
<p>This essentially means that you need to include the primary key of the destination table in that query. You might be able to use some other unique index field(s) too, but I can't guarantee the Oracle DBMS is smart enough to allow that.</p>
| 28,494
|
<pre><code>class Foo
{
static bool Bar(Stream^ stream);
};
class FooWrapper
{
bool Bar(LPCWSTR szUnicodeString)
{
return Foo::Bar(??);
}
};
</code></pre>
<p><code>MemoryStream</code> will take a <code>byte[]</code> but I'd <em>like</em> to do this without copying the data if possible.</p>
|
<p>You can avoid the copy if you use an <a href="http://msdn.microsoft.com/en-us/library/system.io.unmanagedmemorystream.aspx" rel="nofollow noreferrer"><code>UnmanagedMemoryStream()</code></a> instead (class exists in .NET FCL 2.0 and later). Like <code>MemoryStream</code>, it is a subclass of <code>IO.Stream</code>, and has all the usual stream operations.</p>
<p>Microsoft's description of the class is:</p>
<blockquote>
<p>Provides access to unmanaged blocks of memory from managed code.</p>
</blockquote>
<p>which pretty much tells you what you need to know. Note that <code>UnmanagedMemoryStream()</code> is not CLS-compliant.</p>
|
<p>If I had to copy the memory, I think the following would work:</p>
<pre><code>
static Stream^ UnicodeStringToStream(LPCWSTR szUnicodeString)
{
//validate the input parameter
if (szUnicodeString == NULL)
{
return nullptr;
}
//get the length of the string
size_t lengthInWChars = wcslen(szUnicodeString);
size_t lengthInBytes = lengthInWChars * sizeof(wchar_t);
//allocate the .Net byte array
array^ byteArray = gcnew array(lengthInBytes);
//copy the unmanaged memory into the byte array
Marshal::Copy((IntPtr)(void*)szUnicodeString, byteArray, 0, lengthInBytes);
//create a memory stream from the byte array
return gcnew MemoryStream(byteArray);
}</code></pre>
| 6,392
|
<p>I have what is essentially a jagged array of name value pairs - i need to generate a set of unique name values from this. the jagged array is approx 86,000 x 11 values.
It does not matter to me what way I have to store a name value pair (a single string "name=value" or a specialised class for example KeyValuePair).<br>
<strong>Additional Info:</strong> There are 40 distinct names and a larger number of distinct values - probably in the region 10,000 values.</p>
<p>I am using C# and .NET 2.0 (and the performance is so poor I am thinking that it may be better to push my entire jagged array into a sql database and do a select distinct from there).</p>
<p>Below is the current code Im using:</p>
<pre><code>List<List<KeyValuePair<string,string>>> vehicleList = retriever.GetVehicles();
this.statsLabel.Text = "Unique Vehicles: " + vehicleList.Count;
Dictionary<KeyValuePair<string, string>, int> uniqueProperties = new Dictionary<KeyValuePair<string, string>, int>();
foreach (List<KeyValuePair<string, string>> vehicle in vehicleList)
{
foreach (KeyValuePair<string, string> property in vehicle)
{
if (!uniqueProperties.ContainsKey(property))
{
uniqueProperties.Add(property, 0);
}
}
}
this.statsLabel.Text += "\rUnique Properties: " + uniqueProperties.Count;
</code></pre>
|
<p><strong>I have it running in 0.34 seconds</strong> down from 9+ minutes</p>
<p>The problem is when comparing the KeyValuePair structs.
I worked around it by writing a comparer object, and passing an instance of it to the Dictionary.</p>
<p>From what I can determine, the KeyValuePair.GetHashCode() returns the hashcode of it's <code>Key</code> object (in this example the least unique object).</p>
<p>As the dictionary adds (and checks existence of) each item, it uses both Equals and GetHashCode functions, but has to rely on the Equals function when the hashcode is less unique.</p>
<p>By providing a more unique GetHashCode function, it excerises the Equals function far less often. I also optimised the Equals function to compare the more unique Values before the less unqiue Keys.</p>
<p>86,000 * 11 items with 10,000 unique properties runs in 0.34 seconds using the comparer object below (without the comparer object it takes 9 minutes 22 seconds)</p>
<p>Hope this helps :)</p>
<pre><code> class StringPairComparer
: IEqualityComparer<KeyValuePair<string, string>>
{
public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
{
return x.Value == y.Value && x.Key == y.Key;
}
public int GetHashCode(KeyValuePair<string, string> obj)
{
return (obj.Key + obj.Value).GetHashCode();
}
}
</code></pre>
<p><strong>EDIT</strong>: If it was just one string (instead of a KeyValuePair, where string = Name+Value) it would be approx twice as fast. It's a nice intresting problem, and I have spent <em>faaaaaar too much time on it</em> (I learned quiet a bit though)</p>
|
<p>if you don't need any specific correlation between each key/value pair and the unique values you're generating, you could just use a GUID? I'm assuming the problem is that your current 'Key' isn't unique in this jagged array.</p>
<pre><code>Dictionary<System.Guid, KeyValuePair<string, string>> myDict
= new Dictionary<Guid, KeyValuePair<string, string>>();
foreach of your key values in their current format
myDict.Add(System.Guid.NewGuid(), new KeyValuePair<string, string>(yourKey, yourvalue))
</code></pre>
<p>Sounds like it would store what you need but I don't know how you would pull data back from this as there would be no semantic relationship between the generate Guid & what you originally had...</p>
<p>Can you provide any more info in your question?</p>
| 28,837
|
<p>I'm designing a multi-tiered database driven web application – SQL relational database, Java for the middle service tier, web for the UI. The language doesn't really matter.</p>
<p>The middle service tier performs the actual querying of the database. The UI simply asks for certain data and has no concept that it's backed by a database.</p>
<p>The question is how to handle large data sets? The UI asks for data but the results might be huge, possibly too big to fit in memory. For example, a street sign application might have a service layer of:</p>
<pre><code>StreetSign getStreetSign(int identifier)
Collection<StreetSign> getStreetSigns(Street street)
Collection<StreetSign> getStreetSigns(LatLonBox box)
</code></pre>
<p>The UI layer asks to get all street signs meeting some criteria. Depending on the criteria, the result set might be huge. The UI layer might divide the results into separate pages (for a browser) or just present them all (serving up to Goolge Earth). The potentially huge result set could be a performance and resource problem (out of memory).</p>
<p>One solution is not to return fully loaded objects (StreetSign objects). Rather return some sort of result set or iterator that lazily loads each individual object.</p>
<p>Another solution is to change the service API to return a subset of the requested data:</p>
<pre><code>Collection<StreetSign> getStreetSigns(LatLonBox box, int pageNumber, int resultsPerPage)
</code></pre>
<p>Of course the UI can still request a huge result set:</p>
<pre><code>getStreetSigns(box, 1, 1000000000)
</code></pre>
<p>I'm curious what is the standard industry design pattern for this scenario?</p>
|
<p>The very first question should be:</p>
<p>¿The user needs to, or is capable of, manage this amount of data?</p>
<p>Although the result set should be paged, if its potentially size is so huge, the answer will be "probably not", so the UI shouldn't try to show it.</p>
<p>I worked on J2EE projects on Health Care Systems, that deal with enormous amount of stored data, literally millions of patients, visits, forms, etc, and the general rule is not to show more than 100 or 200 rows for any user search, advising the user that those set of criteria produces more information that he can understand.</p>
<p>The way to implement this varies from one project to another, it is possible to force the UI to ask the service tier the size of a query before launching it, or it is possible to throw an Exception from the service tier if the result set grows too much (however this way couples the service tier with the limited implementation of an UI).</p>
<p>Be careful! This not means that every method on the service tier must throw an Exception if its result sizes more than 100, this general rule only applies to result sets that are shown to the user directly, that is a better reason to place the control in the UI instead on the service tier.</p>
|
<p>In ASP.NET I would use server-side paging, where you only retrieve the page of data the user has requested from the data store. This is opposed to retrieving the entire result set, putting it into memory and paging through it on request.</p>
| 28,696
|
<p>Do you have any strategies for retrofitting unit tests onto a code base that currently has no unit tests ?</p>
|
<p>Read <a href="https://rads.stackoverflow.com/amzn/click/com/0131177052" rel="noreferrer" rel="nofollow noreferrer">Working Effectively With Legacy Code by Feathers</a>.</p>
<p>Jimmy Bogard has a <a href="http://www.lostechies.com/blogs/jimmy_bogard/archive/tags/Refactoring/default.aspx" rel="noreferrer">good blog series on SOC</a>.</p>
|
<p>Is it possible that we are in a panic and are getting confused between unit tests and performance tests? Is it that your application works fine with few users, but starts throwing errors when under heavier load? If so, unit tests are not the answer. Unit tests != Load tests.</p>
<p>If unit tests are in fact the answer, retrofitting unit tests is a good idea as it will help clean up the code. Just be prepared to refactor a lot. Code written with TDD turns out looking a lot different than code written without TDD. In my case, I had a method HandleDisposition() which took care of a lot of cases. This kind of method would not have existed if we had written the code with TDD. When retrofitting unit tests, we refactored that function and now have methods like XDisposition(), YDisposition(), ZDisposition(), which are a lot easier to write unit tests against.</p>
| 6,436
|
<p>I've done this before in C++ by including sqlite.h but is there a similarly easy way in C#?</p>
|
<p><a href="https://www.nuget.org/packages/Microsoft.Data.Sqlite" rel="nofollow noreferrer">Microsoft.Data.Sqlite</a> by Microsoft has over 9000 downloads every day, so I think you are safe using that one.</p>
<p>Example usage from <a href="https://learn.microsoft.com/dotnet/standard/data/sqlite/" rel="nofollow noreferrer">the documentation</a>:</p>
<pre><code>using (var connection = new SqliteConnection("Data Source=hello.db"))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText =
@"
SELECT name
FROM user
WHERE id = $id
";
command.Parameters.AddWithValue("$id", id);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString(0);
Console.WriteLine($"Hello, {name}!");
}
}
}
</code></pre>
|
<p>if you have any problem with the library you can use <code>Microsoft.Data.Sqlite;</code></p>
<pre><code> public static DataTable GetData(string connectionString, string query)
{
DataTable dt = new DataTable();
Microsoft.Data.Sqlite.SqliteConnection connection;
Microsoft.Data.Sqlite.SqliteCommand command;
connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source= YOU_PATH_BD.sqlite");
try
{
connection.Open();
command = new Microsoft.Data.Sqlite.SqliteCommand(query, connection);
dt.Load(command.ExecuteReader());
connection.Close();
}
catch
{
}
return dt;
}
</code></pre>
<p>you can add NuGet Package Microsoft.Data.Sqlite</p>
| 4,560
|
<p>[<em>Of course, the question is not restricted to a specific "friend" implementation, feel free though to point out implementation specifics if relevant</em>]</p>
<p>Reading through the unanswered questions, I stumbled upon the <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx" rel="noreferrer"><code>InternalsVisibleTo</code></a> attribute:</p>
<blockquote>
<p>Specifies that types that are
ordinarily visible only within the
current assembly are visible to
another assembly.</p>
</blockquote>
<p>The <a href="http://msdn.microsoft.com/en-us/library/67ef8sbd.aspx" rel="noreferrer">C# Programming Guide</a> on <a href="http://msdn.microsoft.com/en-us/library/" rel="noreferrer">MSDN</a> has a section <a href="http://msdn.microsoft.com/en-us/library/0tke9fxk.aspx" rel="noreferrer">Friend Assemblies</a> describing how to use the attribute to allow the use of <code>internal</code> methods and types to another assembly.</p>
<p>I'm wondering whether it would be a Good Idea to use this to create a "hidden" interface for instrumenting a library for use by the unit testing assembly. It seems to increase coupling massively in both directions (testing code in the production assembly, intimate internal knowledge about the production assembly in testing code), but on the other hand it might help in creating fine-grained tests without cluttering the public interface.</p>
<p>What is your experience with using friend declarations when testing? Was it your Silver Bullet, or did it start the Death March? </p>
|
<p>I've made extensive use of this technique - it means that my unit tests can test aspects of the code library that aren't visible to normal consumers.</p>
<p>While using <code>[InternalsVisibleTo]</code> does increase coupling, I believe the (minor) increase is well worth the gains.</p>
<p>My unit tests are already tightly coupled to the code under test - though I try to write tests that assure specific outcomes, not specific implementations, by accessing things not visible to regular consumers, I do somewhat constrain the implementation.</p>
<p>Going the other way, the coupling is minimal - in having the <code>[InternalsVisibleTo]</code> attribute on the code assembly, and in marking some things as <strong>internal</strong> instead of <strong>private</strong> (or <strong>protected internal</strong> instead of <strong>protected</strong>).</p>
<p>(Note that I'm ignoring here any design changes that are provoked by the use of Unit Testing, which is a whole other discussion.)</p>
<p>The <code>[InternalsVisibleTo]</code> attribute requires strong naming your assemblies. If you're not doing this already, you may find this a bit burdensome as a strongly named assembly may only depend on other strongly named assemblies, which may end up with you needing to alter several assemblies.</p>
<p>Getting the attribute right can be a bit fiddly, as it needs to include the public key of your test assembly. IDesign have a useful <a href="http://www.idesign.net/idesign/DesktopDefault.aspx?tabindex=5&tabid=11#Essentials" rel="noreferrer">Friend Assembly tool</a> that creates the attribute on your clipboard, ready for pasting. Recommended.</p>
|
<p>I think using <code>InternalsVisibleToAttribute</code> to enable unit testing is perfectly reasonable. My "unit" in "unit testing" is a class, and that includes <code>internal</code> classes, so I want to test them. <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods#52054">I don't want to unit test <code>private</code> methods</a>, though.</p>
<p>I don't think creating a special, private interface just for tests is a good idea. One of the values of unit testing is that it gives you a chance to think about the interface to your class from the point of view of a consumer of that class; providing a back door takes that benefit away.</p>
<p>My preference, however, is to put my unit tests in the same assembly as my production code. It doesn't usually affect my customer, but it does simplify things for me, so I do it. When I do, it makes the <code>InternalsVisibleTo</code> question go away.</p>
| 32,651
|
<p>A quick question about elf file headers, I can't seem to find anything useful on how to add/change fields in the elf header. I'd like to be able to change the magic numbers and to add a build date to the header, and probably a few other things. </p>
<p>As I understand it the linker creates the header information, but I don't see anything in the LD script that refers to it (though i'm new to ld scripts).</p>
<p>I'm using gcc and building for ARM.</p>
<p>thanks!</p>
<p>Updates:</p>
<ul>
<li>ok maybe my first question should be: is it possible to create/edit the header file at link time?</li>
</ul>
|
<p>I don't know of linker script commands that can do this, but you can do it post-link using the <strong>objcopy</strong> command. The <strong>--add-section</strong> option can be used to add a section containing arbitrary data to the ELF file. If the ELF header doesn't contain the fields you want, just make a new section and add them there.</p>
|
<p>In Linux Console:</p>
<p>$ man ld</p>
<p>$ ld --verbose</p>
<p>HTH</p>
| 28,886
|
<p>Lets assume my classes are loaded from a compressed .war file or loaded elsewhere,
how can I discover all the resources in a given package? Enumerating files will not really work, since this is a war file. Most likely this will involve using the current classloader?</p>
<p>Is there a library out there that does something like that? Googling revealed only some hacks with listing files.</p>
|
<p>Yes. You can use <code>ClassLoader.getResources("")</code>;<br/><br/>
Or you could use ferret API:
<br/>
<a href="https://www.ohloh.net/p/pureperfect-ferret">https://www.ohloh.net/p/pureperfect-ferret</a></p>
<p>This API allows you to scan the class path as well as arbitrary archives and directories using the Visitor pattern.</p>
|
<p>I do this:
- before packaging, <code>ls myResources/*.ext > myResources/list.txt</code>
- then just read the file first</p>
| 22,565
|
<p>Can anybody explain the idea behind JSP custom tag libraries and the JSP 2 tag files?</p>
<p>Are they just different ways to do the same thing?</p>
<p>How do they compare? What are their pros and cons, and which is better?</p>
|
<p>I <3 tag files, but that lead developer of JSTL is smoking crack if they really said that. You CANNOT re-write all tag library tags as tag file tags, for one very important reason: tag files can't do:</p>
<p>return EVAL_BODY_INCLUDE;</p>
<p>In other words, tag files only have three options for their body-content:</p>
<p><strong>empty:</strong> no inner content, ie. <someTag/></p>
<p><strong>scriptless:</strong> no JSP inner content, ie. <someTag><p>hello world</p></someTag> is ok, but not <someTag><p><%= helloWorld.toString() %></p></someTag></p>
<p><strong>tagdependent:</strong> you can have JSP inner content, but it won't be processed as such; instead you have to parse/render it however you see fit</p>
<p>But with the old style tag library tags, you can have:
<body-content>JSP</body-content>
(in the tld file) and then "return EVAL_BODY_INCLUDE;" from your "doStartTag". If you do this, all of your JSP directives will get parsed just as if they were a normal part of your page, and your tag simply wraps them with the appropriate content.</p>
<p>Personally, my rule of thumb is: use tag files whenever you can, ie. whenever you don't need JSP directives to work inside the tag, because they are a million times cleaner, easier for a non-programmer to work with, don't require a tld (well, if you keep them in a seperate namespace from your tag library tags).</p>
<p>But if you want JSP content inside your tag, your only option is tag library tags. Hopefully, someday, the JSP people will release a way to do JSP directive processing inside a tag file tag, and then we really can abandon the old class-based tags, but until then please don't try to do all tags with tag files, as you'll quickly be reduced to making custom tags for every last piece of logic (since that's the only way to do logic without using JSP directives).</p>
|
<p><strong>Problems Developing Custom Tags</strong></p>
<p>Traditional custom tags require Java programming
skills.</p>
<p>All but the simplest custom tags are not easy to write.</p>
<p>The purpose of JSP, in contrast to servlets, is to use
markup language to manage layout with embedded
dynamic content.</p>
<p>Having to write complex Java code
in custom tags that focus on markup language is going
backwards.</p>
<p>We might want to use the JSP expression language or
other custom tags when implementing a new custom
tag.</p>
<p><strong>The Solution</strong>
<strong>JSP 2.0 Tag Files</strong></p>
<ul>
<li>Tag files are one of the important new concepts introduced with JSP 2.0.</li>
<li>Tag files permit easier and more rapid development of custom tags.</li>
<li>Tag files are developed using normal JSP syntax,including scripting elements, and used just like any other custom tag.</li>
<li>Each custom tag is a separate tag file.</li>
</ul>
<p><strong>How Do Tag Files Differ?</strong></p>
<p>Written using JSP syntax.</p>
<ul>
<li>Not all JSP directives are permitted in a tag file.</li>
<li>Supported by new tag file specific directives, actions and implicit objects.</li>
</ul>
<p>Identified by either a <strong>.tag</strong> or <strong>.tagx</strong> suffix.</p>
<p>Intended to provide custom tag developers ease of development without loss of functionality.</p>
<ul>
<li>One of the lead developers of JSTL has commented thatif she had the time, she would rewrite all of JSTL using tag files.</li>
</ul>
| 28,289
|
<p>Is there any way to save an object using Hibernate if there is already an object using that identifier loaded into the session?</p>
<ul>
<li>Doing <code>session.contains(obj)</code> seems to only return true if the session contains that exact object, not another object with the same ID.</li>
<li>Using <code>merge(obj)</code> throws an exception if the object is new</li>
</ul>
|
<p>Have you tried calling .SaveOrUpdateCopy()?
It should work in all instances, if there is an entity by the same id in the session or if there is no entity at all. This is basically the catch-all method, as it converts a transient object into a persistent one (Save), updates the object if it is existing (Update) or even handles if the entity is a copy of an already existing object (Copy).</p>
<p>Failing that, you may have to identify and .Evict() the existing object before Attaching (.Update()) your "new" object.
This should be easy enough to do:</p>
<pre><code>IPersistable entity = Whatever(); // This is the object we're trying to update
// (IPersistable has an id field)
session.Evict(session.Get(entity.GetType(), entity.Id));
session.SaveOrUpdate(entity);
</code></pre>
<p>Although the above code could probably do with some null checking for the .Get() call.</p>
|
<p>How about:</p>
<pre><code>session.replicate(entity, ReplicationMode.OVERWRITE);
</code></pre>
<p>?</p>
| 4,599
|
<p>How do I detect if the system has a default recording device installed?
I bet this can be done through some calls to the Win32 API, anyone has any experience with this?</p>
<p>I'm talking about doing this through code, not by opening the control panel and taking a look under sound options.</p>
|
<p>Using the <a href="https://www.microsoft.com/en-in/download/details.aspx?id=6812" rel="nofollow noreferrer">DirectX SDK</a>, you can call DirectSoundCaptureEnumerate, which will call your DSEnumCallback function for each DirectSoundCapture device on the system. The first parameter passed to your DSEnumCallback is an LPGUID, which is the "Address of the GUID that identifies the device being enumerated, or NULL for the primary device".</p>
<p>If all you need to do is find out if a recording device is present (I don't think this is good enough if you really need to know the default device), you can use waveInGetNumDevs:</p>
<pre><code>#include <tchar.h>
#include <windows.h>
#include "mmsystem.h"
int _tmain( int argc, wchar_t *argv[] )
{
UINT deviceCount = waveInGetNumDevs();
if ( deviceCount > 0 )
{
for ( int i = 0; i < deviceCount; i++ )
{
WAVEINCAPSW waveInCaps;
waveInGetDevCapsW( i, &waveInCaps, sizeof( WAVEINCAPS ) );
// do some stuff with waveInCaps...
}
}
return 0;
}
</code></pre>
|
<p>There is an Open Source Audio API called <a href="http://www.portaudio.com/" rel="nofollow noreferrer">PortAudio</a> that has a method you could use. I think the method is called Pa_GetDeviceInfo() or something.</p>
| 6,263
|
<p>I have a <a href="http://en.wikipedia.org/wiki/Pseudorandom_number_generator" rel="nofollow noreferrer">pseudorandom number generator</a> (PRNG) with nice properties which uses six <code>UInt32</code>s as state. I need to come up with a reasonable way to seed it. Two obvious possibilities are: 1) generate six random numbers using <code>System.Random</code> and use them as seeds; 2) generate two <code>GUID</code>s with <code>Guid.NewGuid()</code>. Which would be better?</p>
<p>I do <em>not</em> need cryptographic security.</p>
|
<p>If it needs <code>UInt32</code>, then <code>Random</code> is more convenient? just <code>Next()</code>, <code>Next()</code>, <code>Next()</code> etc (and cast)... (use the same <code>Random</code> instance however - don't create <code>new Random()</code> each time).</p>
<p>It depends on what the intent is as to whether this offers enough randomness. Since this is just the seed, it should be OK...</p>
|
<p>Try this for your seed value...</p>
<pre><code>(UInt32)Math.Pow(System.DateTime.Now.TimeOfDay.TotalMilliseconds, 11.0 / 7.0)
</code></pre>
<p>It just raises the current time's milliseconds to the 11/7th power, which is just arbitrary.
You can experiment with other fractions to see if they work better for you.</p>
<p>Beware that if your fraction's decimal equivalent is greater than about 2.5, you might get an overflow and your seed value will be zero. :(</p>
<p>I've used this for awhile and it seems to give pretty good seed values.</p>
| 48,279
|
<p>We are using SourceForge Enterprise Edition 4.4 in one of our project.</p>
<p>My question is, in CollabNet SFEE (SourceForge Enterprise Edition 4.4), how will we get attachments associated with an Artifacts Using SFEE SOAP API?</p>
<p>We have made our own .net 2.0 client. We are not using .net SDK provided by Collabnet,</p>
|
<p>If you commit with a message you can add "[artf1000]" (where artf1000 is your artifact number) to the beginning or end of your commit message. Then it will associate to that artifact you can also do this with documents using doc1000, to get the id of the item you can use the URL it is what is after the <a href="http://sfeeserver/sf/go/" rel="nofollow noreferrer">http://sfeeserver/sf/go/</a>.</p>
<p>Documents and artifacts are the only item I have used this for so I am not sure about other types of links, but I would imagine anything that has a /go/ID could be referenced by the ID.</p>
<p>ie:</p>
<ul>
<li><a href="http://sfeeserver/sf/go/artf1000" rel="nofollow noreferrer">http://sfeeserver/sf/go/artf1000</a> </li>
<li><a href="http://sfeeserver/sf/go/doc1000" rel="nofollow noreferrer">http://sfeeserver/sf/go/doc1000</a></li>
</ul>
<p>Edited to add:
I have seemingly successfully tried this with releases, tasks, and discussions as well.</p>
|
<p>You can cheat a little bit and have a look at the scripts from SFEE. Log into your SFEE via SSH and take a look at the following script: </p>
<pre><code>/usr/local/sourceforge/sourceforge_home/integration/post-commit.py
</code></pre>
<p>Maybe it helps...</p>
| 5,885
|
<p>I have a multi file C program. I'd like the user to be able to specify different debugging levels at run time.</p>
<p>What is the best way to implement this?</p>
<p>I was thinking of having a debug(level, "message") type function exported and used everywhere. Any better/other ideas?</p>
|
<p>Jonathan's suggestion is good but since C99 we have variadic macros so one doesn't need to use double braces for debug macro.</p>
<p>There is a light version of logging header I use:</p>
<pre><code>#define LOG_FATAL (1)
#define LOG_ERR (2)
#define LOG_WARN (3)
#define LOG_INFO (4)
#define LOG_DBG (5)
#define LOG(level, ...) do { \
if (level <= debug_level) { \
fprintf(dbgstream,"%s:%d:", __FILE__, __LINE__); \
fprintf(dbgstream, __VA_ARGS__); \
fprintf(dbgstream, "\n"); \
fflush(dbgstream); \
} \
} while (0)
extern FILE *dbgstream;
extern int debug_level;
</code></pre>
<p>So wherever I need to log something, I just add line like</p>
<p><code>LOG(LOG_ERR, "I/O error %s occured while opening file %s", strerror(errno), filename);</code></p>
<p>During program initialisation you need to specify values for <code>dbgstream</code> (usually defaults to <code>stderr</code>) and <code>debug_level</code>.</p>
<p>For real projects instead of calling <code>fprintf</code> many times I just call my function from <code>LOG</code> macro and pass <code>__FILE__</code>, <code>__LINE__</code> and <code>__VA_ARGS_</code> as argument - that function also prints date, time and pid in log line, and don't do <code>fflush()</code> every time - only when buffering counter exceeds preset value - itsignificantly increases logging performance.</p>
<p>But please be aware that some compilers may not support variadic macros as it was introduced only in C99.</p>
|
<p>There is a very good C port of log4j, <a href="http://log4c.sourceforge.net/" rel="nofollow noreferrer">log4c</a>.</p>
| 42,494
|
<p>I am running following <code>PHP</code> code to interact with a MS Access database.</p>
<pre><code>$odbc_con = new COM("ADODB.Connection");
$constr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . $db_path . ";";
$odbc_con -> open($constr);
$rs_select = $odbc_con -> execute ("SELECT * FROM Main");
</code></pre>
<p>Using <code>($rs_select -> RecordCount)</code> gives -1 though the query is returning non-zero records.</p>
<p>(a) What can be the reason?
(b) Is there any way out?</p>
<p>I have also tried using <code>count($rs_select -> GetRows())</code>. This satisfies the need but looks inefficient as it will involve copying of all the records into an array first.</p>
|
<p>ADODB has its own rules for what recordcount is returned depending on the type of recordset you've defined. See:</p>
<p><a href="http://support.microsoft.com/kb/194973" rel="nofollow noreferrer">MS Knowledge Base article 194973</a></p>
<p><a href="http://www.w3schools.com/ADO/prop_rs_recordcount.asp" rel="nofollow noreferrer">W3C Schools article</a></p>
<p>In the example above, the PHP COM() object is used to instantiate ADODB, a COM interface for generic database access. According to the <a href="http://us3.php.net/manual/en/class.com.php" rel="nofollow noreferrer">PHP documentation</a>, the object reference produced is overloaded, so you can just use the same properties/methods that the native ADODB object would have. This means that you need to use the ADODB methods to set the recordset type to one that will give an accurate recordcount (if you must have it). The alternative, as others have mentioned, is to use a second query to get the COUNT() of the records returned by the SELECT statement. This is easier, but may be inappropriate in the particular environment.</p>
<p>I'm not an ADO guru, so can't provide you with the exact commands for setting your recordset type, but from the articles cited above, it is clear that you need a static or keyset cursor. It appears to me that the proper method of setting the CursorType is to use a parameter in the command that opens the recordset. <a href="http://www.w3schools.com/ADO/prop_rs_cursortype.asp" rel="nofollow noreferrer">This W3C Schools article on the CursorType property</a> gives the appropriate arguments for that command.</p>
<p>Hopefully, this information will help the original poster accomplish his task, one way or the other.</p>
|
<p>If you're using a dynamic cursor type of connection, then it could actually change. Someone may delete a record from that database while you're browsing through pages of records. To avoid, use a static sort of snapshot cursor. I have this bookmarked which will explain it well. This always got me and the bookmark always reminded me why.</p>
<p><a href="http://support.microsoft.com/kb/194973" rel="nofollow noreferrer">http://support.microsoft.com/kb/194973</a></p>
| 15,388
|
<p>Is a Star-Schema design essential to a data warehouse? Or can you do data warehousing with another design pattern?</p>
|
<p>Using <a href="http://en.wikipedia.org/wiki/Star_schema" rel="noreferrer">star schemas</a> for a data warehouse system gets you several benefits and in most cases it is appropriate to use them for the top layer. You may also have an operational data store (ODS) - a normalised structure that holds 'current state' and facilitates operations such as data conformation. However there are reasonable situations where this is not desirable. I've had occasion to build systems with and without ODS layers, and had specific reasons for the choice of architecture in each case.</p>
<p>Without going into the subtlties of data warehouse architecture or starting a Kimball vs. Inmon flame war the main benefits of a star schema are:</p>
<ul>
<li><p>Most database management systems
have facilities in the query optimiser
to do 'Star Transformations' that
use <a href="http://en.wikipedia.org/wiki/Bitmap_index" rel="noreferrer">Bitmap Index</a> structures or
<a href="http://www.databasejournal.com/features/mssql/article.php/1438821" rel="noreferrer">Index Intersection</a> for fast
predicate resolution. This means that selection from a star schema can be done without hitting the fact table (which is usually much bigger than the indexes) until the selection is resolved.</p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Partition_(database)" rel="noreferrer">Partitioning</a> a star schema is relatively straightforward as only the fact table needs to be partitioned (unless you have some biblically large dimensions). <a href="http://blogs.msdn.com/sqlcat/archive/2006/02/17/Partition-Elimination-in-SQL-Server-2005.aspx" rel="noreferrer">Partition elimination</a> means that the query optimiser can ignore patitions that could not possibly participate in the query results, which saves on I/O. </p></li>
<li><p><a href="http://en.wikipedia.org/wiki/Slowly_changing_dimension" rel="noreferrer">Slowly changing dimensions</a> are much easier to implement on a star schema than a snowflake.</p></li>
<li><p>The schema is easier to understand and tends to involve less joins than a <a href="http://en.wikipedia.org/wiki/Snowflake_schema" rel="noreferrer">snowflake</a> or E-R schema. Your reporting team will love you for this</p></li>
<li><p>Star schemas are much easier to use and (more importantly) make perform well with ad-hoc query tools such as <a href="http://en.wikipedia.org/wiki/Business_Objects_(company)" rel="noreferrer">Business Objects</a> or <a href="http://msdn.microsoft.com/en-us/library/ms155933.aspx" rel="noreferrer">Report Builder</a>. As a developer you have very little control over the SQL generated by these tools so you need to give the query optimiser as much help as possible. Star schemas give the query optimiser relatively little opportunity to get it wrong.</p></li>
</ul>
<p>Typically your reporting layer would use star schemas unless you have a specific reason not to. If you have multiple source systems you may want to implement an <a href="http://www.dmreview.com/issues/19980701/469-1.html" rel="noreferrer">Operational Data Store </a> with a normalised or snowflake schema to accumulate the data. This is easier because an ODS typically does not do history. Historical state is tracked in star schemas where this is much easier to do than with normalised structures. A normalised or snowflaked Operational Data Store reflects 'current' state and does not hold a historical view over and above any that is inherent in the data.</p>
<p>ODS load processes are concerned with data scrubbing and conforming, which is easier to do with a normalised structure. Once you have clean data in an ODS, dimension and fact loads can track history (changes over time) with generic or relatively simple mechanisms relatively simply; this is much easier to do with a star schema, Many ETL tools (for example) provide built-in facilities for slowly changing dimensions and implementing a generic mechanism is relatively straightforward. </p>
<p>Layering the system in this way providies a separation of responsibilities - business and data cleansing logic is dealt with in the ODS and the star schema loads deal with historical state.</p>
|
<p>It's possible to do without. However, you will make life hard for yourself -- your organization will want to use standard tools that live on top of DWs, and those tools will expect a star schema -- a lot of effort will be spent fitting a square peg in a round hole.</p>
<p>A lot of database-level optimizations assume that you have a star schema; you will spend a lot of time optimizing and restructuring to get the DB to do "the right thing" with your not-quite-star layout. </p>
<p>Make sure that the pros outweigh the cons..</p>
<p>(Does it sound like I've been there before?)</p>
<p>-D</p>
| 13,529
|
<p>I've just created a new Windows XP VM on my Mac using VMware Fusion. The VM is using NAT to share the host's internet connection.</p>
<p>How do I access a Rails application, which is accessible on the Mac itself using <code>http://localhost:3000</code>?</p>
|
<p>On the XP machine, find your IP address by going to the command prompt and typing <code>ipconfig</code>. Try replacing the last number with 1 or 2. For example, if your IP address is 192.168.78.128, use <a href="http://192.168.78.1:3000" rel="noreferrer">http://192.168.78.1:3000</a>.</p>
|
<ol>
<li>On the XP machine, Start -> Connect To -> Show all connections.</li>
<li>Double click Local Area Connection.</li>
<li>Click the Support tab.</li>
<li>Take the Default Gateway IP <code><gateway-ip</code>> and hit http://<code><gateway-ip</code>>:3000 in your browser.</li>
</ol>
<p>Gotcha: You must have http:// in the address or IE will give you "The webpage cannot be displayed".</p>
| 8,669
|
<p>What is the difference between the selectitem and selectitems tags in jsf?</p>
|
<p>The difference is exactly what you would expect. The <code>selectitem</code> tag adds a single item to the HTML list while <code>selectitems</code> adds multiple items.</p>
<p>From <a href="http://www.jsftoolbox.com/documentation/help/12-TagReference/core/f_selectItem.html" rel="nofollow noreferrer">JSF Core Tag Reference</a>:</p>
<h3>SelectItem:</h3>
<p>The <code>SelectItem</code> tag adds a child <code>UISelectItem</code> component to the component associated with the enclosing tag. In the HTML renderkit, this creates a single element. It can be used with any of the select tags in the JSF HTML tag library. The body content of this tag must be empty.</p>
<p><em>Example:</em></p>
<pre><code><h:selectOneMenu id="list1">
<f:selectItem itemLabel="Option 1" itemValue="1"></f:selectItem>
</h:selectOneMenu>
</code></pre>
<p><em>HTML Output:</em></p>
<pre><code><select id="list1" name="list1" size="1">
<option value="1">Option 1</option>
</select>
</code></pre>
<h3>SelectItems:</h3>
<p>The <code>SelectItems</code> tag adds a child <code>UISelectItems</code> component to the component associated with enclosing tag. You can use this tag to set a list of objects in your domain model as the options for a select component. The body content of this tag must be empty.</p>
<p><em>Example:</em></p>
<pre><code><h:selectManyListbox id="list">
<f:selectItems value="#{optionBean.optionList}"></f:selectItem>
</h:selectManyListbox>
</code></pre>
<p><em>HTML Output:</em></p>
<pre><code><select id="list" name="list" multiple="true" size="-2147483648">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
</code></pre>
|
<p>Its also nice to remember that the f:selectItems can point to a SelectItem, an array or Collection of SelectItem objects, or a Map mapping labels to values.</p>
| 42,818
|
<p>A program receives a list of Messages (base type). Each message in the list has to be processed according to it's type (descendant type). However, different messages need different inputs in order to be processed correctly.</p>
<p>What is the following technique called? (I haven't checked this code in a compiler)</p>
<pre><code>abstract class MessageProcessor
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
public abstract void Process();
}
</code></pre>
<p>And this one?</p>
<pre><code>static class MessageProcessorFactory
{
public static MessageProcessor GetProcessor(Message message, DataDomain data)
{
if (message.GetType() == typeof(FooMessage))
{
return new FooMessageProcessor(message, data.Name, data.Classification);
}
else if (message.GetType() == typeof(BarMessage))
{
return new BarMessageProcessor(message, data.AccountNo, data.CreditLimit);
}
else
throw new SomeException("Unrecognized type");
}
}
</code></pre>
<p>And what is it called if I can inject the ProcessBuilder class into a MessageProcessor (using a property or Setter) and then call Process?</p>
<p>What technique would be the best pattern for solving this problem?</p>
|
<p>They are both examples of the <em>factory method</em> pattern. The only difference is that the second example has the method in its own static class. </p>
<p>This would be an example of the <em>abstract factory</em> pattern:</p>
<pre><code>abstract class MessageProcessorFactory
{ public abstract MessageProcessor GetProcessor
(Message message, DataDomain data);
}
class FooMessageProcessorFactory : MessageProcessorFactory
{ public override MessageProcessor GetProcessor
(Message message, DataDomain data)
{ return new FooMessageProcessor(data.Name, data.Classification);
}
}
</code></pre>
<p>Each MessageProcessor gets its own factory class which makes use of polymorphism.</p>
<p>Passing a ProcessBuilder to create the process would be the <em>strategy</em> pattern:</p>
<pre><code>class MessageProcessor
{ ProcessBuilder builder;
public MessageProcessor(ProcessBuilder builder)
{ this.builder = builder;
}
public void Process()
{ builder.BuildMessage();
builder.BuildProcess();
builder.Process();
}
}
var mp = new MessageProcessor(new FooProcessBuilder());
</code></pre>
<p>The simplest solution would be to encapsulate a factory method:</p>
<pre><code>static void Process(Message msg, DataDomain data)
{ var p = getProcessor(msg.GetType());
p.Process(msg, data);
}
</code></pre>
<p>If it's a small known number of types, you can use the series of type checks:</p>
<pre><code>private static MessageProcessor getProcessor(Type msgType)
{ return (msgType == typeof(FooMessage)) ? new FooMessageProcessor()
: (msgType == typeof(BarMessage)) ? new BarMessageProcessor()
: new DefaultMessageProcessor();
}
</code></pre>
<p>Otherwise use a dictionary:</p>
<pre><code>Dictionary<Type,MessageProcessor> processors;
private static MessageProcessor getProcessor(Type msgType)
{ return processors[msgType];
}
</code></pre>
|
<p>In my understanding <em>factory method</em> defnies the abstract type of class with which to work with but delegates the creation of the concrete type to the succeeding/implementing classes.
<em>Abstract factory</em> would define an interface for a manufactorer of a set of corresponding classes.
A <em>builder</em> works simply to build an object step by step giving some control to the calling instance.</p>
| 22,219
|
<p>How can I create a file dsn for connecting to an AS400 system using the iSeries ODBC driver?</p>
<p>The iSeries ODBC driver allows many settings to be configured. Where can I find a list of all properties that can be set in the file DSN?</p>
|
<p><em>Driver={iSeries Access ODBC Driver};System=server;Uid=user;Pwd=password;</em></p>
<p>Where server is the system to connect (either IP address or hostname), username and password.</p>
<p>You can have a .dsn file like this:</p>
<pre><code>[ODBC]
DRIVER=iSeries Access ODBC Driver
System=server;
Uid=user;
Pwd=password;
Initial Catalog=library;
</code></pre>
|
<p>I just discovered you can create a file DSN using the ODCB Administration tool, for any type of ODBC driver.</p>
| 46,763
|
<p>I'm starting a new project here (Windows Forms). What's the best option today for a small (free as in beer) DBMS?</p>
<p>I've used SQL Server Express on the past projects, but time and time again I hear people saying that the product from Oracle is faster and more powerful.</p>
<p>It will be used in a small company (around 20 users) and will not reach the 4 GB limit any time soon :)</p>
<p>I don't want to start a flame war on my first post, so please point me to some link showing a good (and actual) comparison between the 2 products, if possible.</p>
<p>PS: I've heard about <a href="http://en.wikipedia.org/wiki/IBM_DB2_Express-C" rel="nofollow noreferrer">IBM DB2 Express</a> too, but I coudn't find any information about it. (Marketing material from IBM doesn't count :) )</p>
|
<p>I would go for the <strong>SQL Server Express</strong> solution, unless you absolutely have to use a feature in Oracle that SQL Server does not have and you have no usable workaround.</p>
<p>Example of Oracle's strengths: </p>
<ul>
<li>Analytical Functions in Oracle ROCK!</li>
<li><a href="http://en.wikipedia.org/wiki/PL/SQL" rel="noreferrer">PL/SQL</a> is better than <a href="http://en.wikipedia.org/wiki/Transact-SQL" rel="noreferrer">T-SQL</a>. </li>
<li>If you're going to scale up the system to 1,000's of users all updating the same small dataset </li>
<li>You scale upto multi-TB databases, </li>
<li>You need to scale to need big numbers of CPU's in your server (over 8). </li>
<li>need instant failover (<a href="http://en.wikipedia.org/wiki/Oracle_RAC" rel="noreferrer">RAC</a>)</li>
<li>you <em>really cannot</em> afford to lose a transaction.</li>
</ul>
<p>Maybe you can tell, I'm a big Oracle fan! But I think that Oracle Express is a commercial reaction to SQL Server Express and I don't think Oracle <em>really deep deep down</em> likes it.</p>
<ul>
<li>You know with SQL Server that there is an upgrade path (SQL Server 2008 is soon) plus service packs.</li>
<li>SQL Express is also more "install and forget" than Oracle.</li>
<li>and it will integrate better with your IDE (if your using .NET)</li>
</ul>
<p>In terms of speed, both are going to be lighting quick with such a small dataset size.</p>
|
<p>Is this any use:</p>
<p><a href="https://web.archive.org/web/1/http://downloads.techrepublic%2ecom%2ecom/5138-9592-6028761.html" rel="nofollow noreferrer">https://web.archive.org/web/1/http://downloads.techrepublic%2ecom%2ecom/5138-9592-6028761.html</a></p>
<p>NB Registration is required</p>
| 3,115
|
<p>I'm using Office Automation in .NET. It is leaving behind the excel.exe program. I know the fix - it is all about explicitely defining the variables. Once defined, I can properly de-allocate the ram and the GC will clean them up.</p>
<p>The problem is, I have literally thousands of lines of code to go through. So I'm wondering: Is there some sort of a utility in .net (or 3rd party) that is capable of showing me a list of variables for which I have ram allocated still? If so, I would be able to target those items and specificially de-allocate them.</p>
<p>Thanks</p>
<p>Ryan</p>
|
<p><a href="http://www.automatedqa.com/techpapers/net_allocation_profiler.asp" rel="nofollow noreferrer">http://www.automatedqa.com/techpapers/net_allocation_profiler.asp</a></p>
|
<p>Just to be clear, you need to explicitly Quit Excel after you are done using it through automation. If you don't an instance will keep running, even if your variables go out of scope and garbage collection runs. I believe the command it Quit():</p>
<pre><code>Excel.ApplicationClass excel = new Excel.ApplicationClass();
//do some work with Excel
excel.Quit();
</code></pre>
<p>I would recommend you do this with a try/catch/finally</p>
<pre><code>Excel.ApplicationClass excel = null;
try
{
excel = new Excel.ApplicationClass();
//do some Excel work
}
catch(Exception ex)
{
//log exception
throw;
}
finally
{
if(excel != null)
excel.Quit();
}
</code></pre>
| 44,385
|
<p>When you cut or break a PLA model (for example to remove support) it often leaves an ugly while mark where the removed piece was connected.</p>
<p>Sanding also tend to leave dull white scratches on the sanded surface.</p>
<p>What can I do to restore the white areas to the original filament color?</p>
|
<p>A quick blast from a heat gun will very slightly reflow the surface texture and eliminate white marks. </p>
<p>However, it's important to avoid over-heating the perimeter layers or you'll see them soften and sag into the infill. So wait for the heat gun to get fully hot and then use a short duration of high heat. Let the part cool between attempts if you don't get it all the first time, or need to clean up a large area. </p>
<p>Incidentally, the heat gun will also help clean up strings from travel moves.</p>
|
<p>Note that on lighter colours these light scratches can be hard to see. On white PLA they're almost invisible unless you hold it against the light at an angle and look at the specular reflection.</p>
<p>I've had some luck on a flat surface (the face of a game tile I printed) by going through various grades of sand paper. 240, 600, 1000, 2000. Finally, finishing with a regular metal polisher like Brasso brings up a shine that doesn't seem to wash off, unlike vaseline/vegetable oil.</p>
<p>It's quite a lot of work though, and even more work on curved surfaces. If heat treatment works for you, it may be preferable.</p>
| 202
|
<p>When should I include PDB files for a production release? Should I use the <code>Optimize code</code> flag and how would that affect the information I get from an exception?</p>
<p>If there is a noticeable performance benefit I would want to use the optimizations but if not I'd rather have accurate debugging info. What is typically done for a production app?</p>
|
<p>When you want to see source filenames and line numbers in your stacktraces, generate PDBs using the pdb-only option. Optimization is separate from PDB generation, i.e. you can optimize <em>and</em> generate PDBs without a performance hit.</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/8cw0bt21(VS.80).aspx" rel="noreferrer">the C# Language Reference</a></p>
<blockquote>
<p>If you use /debug:full, be aware that there is some impact on the speed and size of JIT optimized code and a small impact on code quality with /debug:full. We recommend /debug:pdbonly or no PDB for generating release code.</p>
</blockquote>
|
<p>There is no need to include them in your distribution, but you should definitely be building them and keeping them. Otherwise debugging a crash dump is practically impossible.</p>
<p>I would also turn on optimizations. Whilst it does make debugging more difficult the performance gains are usually very non-trivial depending on the nature of the application. We easily see over 10x performance on release vs debug builds for some algorithms.</p>
| 6,325
|
<p>I'm completely new at C# and NUnit.</p>
<p>In Boost.Test there is a family of <code>BOOST_*_THROW</code> macros. In Python's test module there is <code>TestCase.assertRaises</code> method.</p>
<p>As far as I understand it, in C# with NUnit (2.4.8) the only method of doing exception test is to use <code>ExpectedExceptionAttribute</code>.</p>
<p>Why should I prefer <code>ExpectedExceptionAttribute</code> over - let's say - Boost.Test's approach? What reasoning can stand behind this design decision? Why is that better in case of C# and NUnit?</p>
<p>Finally, if I decide to use <code>ExpectedExceptionAttribute</code>, how can I do some additional tests after exception was raised and catched? Let's say that I want to test requirement saying that object has to be valid after some setter raised <code>System.IndexOutOfRangeException</code>. How would you fix following code to compile and work as expected?</p>
<pre><code>[Test]
public void TestSetterException()
{
Sth.SomeClass obj = new SomeClass();
// Following statement won't compile.
Assert.Raises( "System.IndexOutOfRangeException",
obj.SetValueAt( -1, "foo" ) );
Assert.IsTrue( obj.IsValid() );
}
</code></pre>
<hr>
<p>Edit: Thanks for your answers. Today, I've found an <em>It's the Tests</em> <a href="http://nunit.com/blogs/?p=63" rel="nofollow noreferrer">blog entry</a> where all three methods described by you are mentioned (and one more minor variation). It's shame that I couldn't find it before :-(.</p>
|
<p>I'm surprised I haven't seen this pattern mentioned yet. David Arno's is very similar, but I prefer the simplicity of this:</p>
<pre><code>try
{
obj.SetValueAt(-1, "foo");
Assert.Fail("Expected exception");
}
catch (IndexOutOfRangeException)
{
// Expected
}
Assert.IsTrue(obj.IsValid());
</code></pre>
|
<p>I've always adopted the following approach:</p>
<pre><code>bool success = true;
try {
obj.SetValueAt(-1, "foo");
} catch () {
success = false;
}
assert.IsFalse(success);
...
</code></pre>
| 32,132
|
<p>In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming.</p>
<p>What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language?</p>
|
<p>One key feature in a functional language is the concept of first-class functions. The idea is that you can pass functions as parameters to other functions and return them as values.</p>
<p>Functional programming involves writing code that does not change state. The primary reason for doing so is so that successive calls to a function will yield the same result. You can write functional code in any language that supports first-class functions, but there are some languages, like Haskell, which do not allow you to change state. In fact, you're not supposed to make any side effects (like printing out text) at all - which sounds like it could be completely useless.</p>
<p>Haskell instead employs a different approach to IO: monads. These are objects that contain the desired IO operation to be executed by your interpreter's toplevel. At any other level they are simply objects in the system.</p>
<p>What advantages does functional programming provide? Functional programming allows coding with fewer potentials for bugs because each component is completely isolated. Also, using recursion and first-class functions allows for simple proofs of correctness which typically mirror the structure of the code.</p>
|
<p>I find <a href="http://blog.jenkster.com/2015/12/what-is-functional-programming.html" rel="nofollow">What Is Functional Programming?</a> to be useful</p>
<blockquote>
<p>Functional programming is about writing pure functions, about removing
hidden inputs and outputs as far as we can, so that as much of our
code as possible just describes a relationship between inputs and
outputs.</p>
</blockquote>
<p>Prefer explicit <code>when</code> param</p>
<pre><code>public Program getProgramAt(TVGuide guide, int channel, Date when) {
Schedule schedule = guide.getSchedule(channel);
Program program = schedule.programAt(when);
return program;
}
</code></pre>
<p>over</p>
<pre><code>public Program getCurrentProgram(TVGuide guide, int channel) {
Schedule schedule = guide.getSchedule(channel);
Program current = schedule.programAt(new Date());
return current;
}
</code></pre>
<blockquote>
<p>A functional language is actively hostile to side-effects. Side-effects are complexity and complexity is bugs and bugs are the devil. A functional language will help you be hostile to side-effects too.</p>
</blockquote>
| 4,401
|
<p>I am very new in the 3D printing scene.
After a lot of searching for my specific problem (and didn't find any answers, of course) I decided to reach out.</p>
<p>I bought a Creality Ender 3 Pro in November and after a few days of lovely prints
I decided to upgrade the printer with a glass bed and "Aluminum Dual Gear Pulley Dual Drive Extruder Kit".</p>
<p>The Problem, as you might expected already, is with the installation of the dual gear extruder. I have watched a dozen of YouTube videos, and all of them have something I don't – a screw in the stock gold gear on the extruder motor.</p>
<p>How can I install the Aluminum Dual Gear Pulley Dual Drive Extruder Kit if I take the gear out? Should I try remove it with force?
Please if someone has come across the same situation, that there isn’t a screw In the stock gear on the extruder motor and mange to take it out, please tell me.
I'm adding a picture so you understand what I mean.</p>
<p><img src="https://i.stack.imgur.com/7F5YQ.jpg" alt="" />
<img src="https://i.stack.imgur.com/MIBeb.jpg" alt="" /></p>
|
<p>This is an older Ender 3 Pro, they at one point came with these press-fit gears, these are not intended to be removed which is a poor design decision. I would recommend buying a new motor than going through the hassle of removing it.</p>
|
<p>Same problem here. I removed it by force using a pliers and a hammer, then drill a spot on the shaft using ikea drill. Everything works fine so far.</p>
| 1,811
|
<p>How do you configure cruiseControl to send out emails that contains the error log whenever a build fails? I've gotten it to send out emails to users when the build fails, but it does not include the actual error that caused the build to fail. I know that if I only configure it to send out emails to the users that have made modifications, the error log is included in those emails. This is a sample of what I have:</p>
<p>< publishers><br/>
< rss/><br/>
< xmllogger/> <br/>
< email from="abc@abc.com" mailhost="abc.abc.com" includeDetails="TRUE"><br/>
< users><br/>
< user name="Joe" group="devs" address="joe@abc.com"/><br/>
< user name="Jim" group="devs" address="jim@abc.com"/><br/>
< /users><br/>
< groups><br/>
< group name="devs" notification="Failed"/><br/>
< /groups><br/>
< /email><br/>
< /publishers></p>
|
<p>You can check if \cruisecontrol.net\server\xsl\compile.xsl is the same as \cruisecontrol.net\webdashboard\xsl\compile.xsl.</p>
<p>Compile.xsl is the default file used to print the error messages from your error log. The one in \webdashboard\ is used for the web dashboard (as the name implies) and the one under \server\ is used for emails.</p>
<p>You can also check ccnet.exe.config whether or not \cruisecontrol.net\server\xsl\compile.xsl is used for emails.</p>
<p>Mine's for example points to compile.xsl on \server:</p>
<pre><code><!-- Specifies the stylesheets that are used to transform the build results when using the EmailPublisher -->
<xslFiles>
<file name="xsl\header.xsl" />
<file name="xsl\compile.xsl" />
<file name="xsl\unittests.xsl" />
<file name="xsl\fit.xsl" />
<file name="xsl\modifications.xsl" />
<file name="xsl\fxcop-summary.xsl" />
</xslFiles>
</code></pre>
|
<p>The build log is getting generated. I can see the error. It's just not included in the email.</p>
| 29,093
|
<p>I'm interested in learning some (ideally) database agnostic ways of selecting the <em>n</em>th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases: </p>
<ul>
<li>SQL Server</li>
<li>MySQL</li>
<li>PostgreSQL</li>
<li>SQLite</li>
<li>Oracle</li>
</ul>
<p>I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches:</p>
<pre><code>WITH Ordered AS (
SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate
FROM Orders)
SELECT *
FROM Ordered
WHERE RowNumber = 1000000
</code></pre>
<p>Credit for the above SQL: <a href="https://web.archive.org/web/20101103031717/http://weblogs.asp.net/Firoz/archive/2005/06/12/411949.aspx" rel="noreferrer">Firoz Ansari's Weblog</a></p>
<p><strong>Update:</strong> See <a href="https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765">Troels Arvin's answer</a> regarding the SQL standard. <em>Troels, have you got any links we can cite?</em></p>
|
<p>There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it.</p>
<p>A really good site that talks about this and other things is <a href="http://troels.arvin.dk/db/rdbms/#select-limit" rel="noreferrer">http://troels.arvin.dk/db/rdbms/#select-limit</a>.</p>
<p>Basically, PostgreSQL and MySQL supports the non-standard:</p>
<pre><code>SELECT...
LIMIT y OFFSET x
</code></pre>
<p>Oracle, DB2 and MSSQL supports the standard windowing functions:</p>
<pre><code>SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,
columns
FROM tablename
) AS foo
WHERE rownumber <= n
</code></pre>
<p>(which I just copied from the site linked above since I never use those DBs)</p>
<p><em>Update:</em> As of PostgreSQL 8.4 the standard windowing functions are supported, so expect the second example to work for PostgreSQL as well.</p>
<p><em>Update:</em> SQLite added window functions support in version 3.25.0 on 2018-09-15 so both forms also work in SQLite.</p>
|
<p>unbelievable that you can find a SQL engine executing this one ...</p>
<pre><code>WITH sentence AS
(SELECT
stuff,
row = ROW_NUMBER() OVER (ORDER BY Id)
FROM
SentenceType
)
SELECT
sen.stuff
FROM sentence sen
WHERE sen.row = (ABS(CHECKSUM(NEWID())) % 100) + 1
</code></pre>
| 3,730
|
<p>There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a <code>java.util.HashMap</code> in this way?</p>
<p>(Currently, I'm happily using a <code>java.util.concurrent.ConcurrentHashMap</code>, and have no measured need to improve performance, but am simply curious if a simple <code>HashMap</code> would suffice. Hence, this question is <em>not</em> "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")</p>
|
<p>Your idiom is safe <strong>if and only if</strong> the reference to the <code>HashMap</code> is <em>safely published</em>. Rather than anything relating the internals of <code>HashMap</code> itself, <em>safe publication</em> deals with how the constructing thread makes the reference to the map visible to other threads.</p>
<p>Basically, the only possible race here is between the construction of the <code>HashMap</code> and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the <code>HashMap</code> reference is published. </p>
<p>For example, imagine you publish the map like this:</p>
<pre><code>class SomeClass {
public static HashMap<Object, Object> MAP;
public synchronized static setMap(HashMap<Object, Object> m) {
MAP = m;
}
}
</code></pre>
<p>... and at some point <code>setMap()</code> is called with a map, and other threads are using <code>SomeClass.MAP</code> to access the map, and check for null like this:</p>
<pre><code>HashMap<Object,Object> map = SomeClass.MAP;
if (map != null) {
.. use the map
} else {
.. some default behavior
}
</code></pre>
<p>This is <strong>not safe</strong> even though it probably appears as though it is. The problem is that there is no <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html" rel="noreferrer"><em>happens-before</em></a> relationship between the set of <code>SomeObject.MAP</code> and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do <em>anything</em> and even in practice it does things like <a href="http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html" rel="noreferrer">put the reading thread into an infinite loop</a>.</p>
<p>To safely publish the map, you need to establish a <em>happens-before</em> relationship between the <em>writing of the reference</em> to the <code>HashMap</code> (i.e., the <em>publication</em>) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to <a href="https://stackoverflow.com/q/5458848/149138">accomplish</a> that<sup>[1]</sup>:</p>
<ol>
<li>Exchange the reference through a properly locked field (<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5" rel="noreferrer">JLS 17.4.5</a>)</li>
<li>Use static initializer to do the initializing stores (<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4" rel="noreferrer">JLS 12.4</a>)</li>
<li>Exchange the reference via a volatile field (<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5" rel="noreferrer">JLS 17.4.5</a>), or as the consequence of this rule, via the AtomicX classes</li>
<li>Initialize the value into a final field (<a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5" rel="noreferrer">JLS 17.5</a>).</li>
</ol>
<p>The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of <code>MAP</code> to:</p>
<pre><code>public static volatile HashMap<Object, Object> MAP;
</code></pre>
<p>then everything is kosher: readers who see a <em>non-null</em> value necessarily have a <em>happens-before</em> relationship with the store to <code>MAP</code> and hence see all the stores associated with the map initialization.</p>
<p>The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using <em>final</em>) imply that you cannot set <code>MAP</code> dynamically at runtime. If you don't <em>need</em> to do that, then just declare <code>MAP</code> as a <code>static final HashMap<></code> and you are guaranteed safe publication.</p>
<p>In practice, the rules are simple for safe access to "never-modified objects":</p>
<p>If you are publishing an object which is not <em>inherently immutable</em> (as in all fields declared <code>final</code>) and:</p>
<ul>
<li>You already can create the object that will be assigned at the moment of declaration<sup>a</sup>: just use a <code>final</code> field (including <code>static final</code> for static members).</li>
<li>You want to assign the object later, after the reference is already visible: use a volatile field<sup>b</sup>.</li>
</ul>
<p>That's it!</p>
<p>In practice, it is very efficient. The use of a <code>static final</code> field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a <code>final</code> member field allows <em>most</em> architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizations<sup>c</sup>. </p>
<p>Finally, the use of <code>volatile</code> does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one <code>HashMap</code>, you can store as many more not-modified <code>HashMap</code>s as you want to the same reference and be assured that all readers will see a safely published map.</p>
<p>For more gory details, refer to <a href="https://shipilev.net/blog/2014/safe-public-construction/" rel="noreferrer">Shipilev</a> or <a href="https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight" rel="noreferrer">this FAQ by Manson and Goetz</a>.</p>
<hr>
<p>[1] Directly quoting from <a href="https://shipilev.net/blog/2014/safe-public-construction/" rel="noreferrer">shipilev</a>.</p>
<hr>
<p><sup>a</sup> That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields).</p>
<p><sup>b</sup> Optionally, you can use a <code>synchronized</code> method to get/set, or an <code>AtomicReference</code> or something, but we're talking about the minimum work you can do.</p>
<p>c Some architectures with very weak memory models (I'm looking at <em>you</em>, Alpha) may require some type of read barrier before a <code>final</code> read - but these are very rare today.</p>
|
<p><a href="http://www.docjar.com/html/api/java/util/HashMap.java.html" rel="nofollow noreferrer">http://www.docjar.com/html/api/java/util/HashMap.java.html</a></p>
<p>here is the source for HashMap. As you can tell, there is absolutely no locking / mutex code there.</p>
<p>This means that while its okay to read from a HashMap in a multithreaded situation, I'd definitely use a ConcurrentHashMap if there were multiple writes.</p>
<p>Whats interesting is that both the .NET HashTable and Dictionary<K,V> have built in synchronization code.</p>
| 12,973
|
<p>I wonder if there is any good guideline for system administrators to calculate the resources needed to host an ASP.NET website? I want to do some estimates on the processing power needed so I know what kind of VPS/Cloud I need to get.</p>
|
<p>Load testing will be your best solution.</p>
<p>Applications differ in how they scale depending on a large number of variables including types of problem solving, approach to solution and other factors.</p>
<p>100 concurrent users consuming 10% CPU does not mean 500 concurrent at 50%, it could be 20% or it could be 100%.</p>
<p>Your bottleneck could be processor or memory or network bandwidth.</p>
<p>Without actually placing the load on your application, any estimation will be merely a guess and will quite likely be proven incorrect.</p>
|
<p>Totally depends on the application. <br><br>
If your looking at requirements for a specific application, then put it on whatever hardware you have that looks like a server, start perfmon running with a good selection of counters & then run some automated tools for load testing, performing some common tasks against the application. See how it performs, then take a guesstimate based on the hardware you have, the load you ran against it & how it measured up .
<br><br>
From experience the bottlenecks i see appearing with ASP.NET apps at the webserver end is usually RAM.
<br><br>
It's the database that runs the back-end of the ASP.NET application you need to worry about :-) I'd say 9/10 times I've seen performance issues with ASP.NET apps, the DB has been the bottleneck.</p>
| 23,134
|
<p>I am looking for a Java open source beautifier or reformatter for SQL that I can use to clean up DDL statements that I am generating with <a href="http://www.openarchitectureware.org" rel="nofollow noreferrer">openArchitectureWare</a>.</p>
<p>Nothing in the answer to "<a href="https://stackoverflow.com/questions/206441/online-code-beautifier-and-formatter">Online Code Beautifier And Formatter</a>" is of use to me and I have not been able to get <a href="http://www.ohloh.net/projects/simplesqlformatter" rel="nofollow noreferrer">Simple SQL Formatter</a> to work for me.</p>
|
<p><strong>UPDATE 2:</strong></p>
<p><code>org.hibernate.jdbc.util.BasicFormatterImpl</code> got moved in release 4.0. It is now located at: <code>org.hibernate.engine.jdbc.internal.BasicFormatterImpl</code>.</p>
<p><strong>UPDATE 1:</strong></p>
<p>Technology marches on. As noted by Alex, <strong><code>org.hibernate.pretty.Formatter</code> no longer exists as of version 3.3.2.GA</strong>. The replacement is <code>org.hibernate.jdbc.util.BasicFormatterImpl</code>:</p>
<pre><code>String formattedSQL = new BasicFormatterImpl().format(sql);
</code></pre>
<hr>
<p><strong>ORIGINAL ANSWER:</strong></p>
<p>If you're using Hibernate, they've got one built-in: <code>org.hibernate.pretty.Formatter</code></p>
<pre><code>String formattedSQL = new Formatter(sql).format();
</code></pre>
|
<p>You could just use a <a href="http://antlr.org/grammar/list" rel="nofollow noreferrer">SQL grammar</a> and build the AST with <a href="http://antlr.org" rel="nofollow noreferrer">antlr</a>. Then you can output the tree in any format you like.</p>
| 40,282
|
<p><strong>First a bit of background.</strong> </p>
<p>I have been working on the MS platform for my entire development career. Up until 2 weeks ago, I had never booted any other OS than 98/XP/Vista. I started using VSS long long ago, and made the change to SVN about 2 years ago. With SVN I use TortiseSVN and use the standard branch/tag/trunk setup.</p>
<p>My projects are also self contained, meaning I can go to a fresh dev box, pull down a single repository, open VS, press F5 and it will run (most of the time). All dependencies are stored in a <code>lib</code> folder, source code is in a <code>src</code> folder, etc...</p>
<p>In an effort to learn new things, I've decided to build a Ruby on Rails application and have created a Ubuntu based development machine. I have a SVN server up and running and am working with another person on this project. He happens to be using a Mac for his development machine.</p>
<p><strong>And now for the issues.</strong></p>
<p>I seem to be struggling with how to manage the various versions of ruby, rails and all of the plugin's I'm working with. I also seem to be struggling with using SVN on Ubuntu. </p>
<p>So Ubuntu comes with Ruby pre-installed. I want to say it's version 1.8.5. Either way, I had a bunch of gems to install for the plugin I'm using (Community Engine). Being new to *nix, I didn't use <code>sudo</code> when installing them and ran into all sorts of issues. I ended up blowing away Ruby completely and starting fresh. That seemed to work.</p>
<p>The problem is though, that after I commit my code, and the other guy gets latest, he has to go through the whole process of installing gems.</p>
<p><strong>What is the best practice for managing gems and plug-ins in a RoR application?</strong> I don't care if a zillion files get added to SVN. Diskspace and network bandwidth are cheap. I just don't know how to do this correctly.</p>
<p>So on to SVN.</p>
<p>I have installed RapidSVN, but very frequently run into issues with folders getting locked. A couple times I realized my mistake, others, I had no clue why. But in both scenarios, i couldn't fix it. I ended up making a backup of my code, pulling down a new working copy, then manually moving over changes and being a bit smarter when committing them to the project.</p>
<p>I actually RTFM a bit last night and found that I'm supposed to create a bookmark for my repos, then do a "checkout working copy" from that bookmark. I'm not sure why, but ok, that's what the manual says...</p>
<p><strong>What are some best practices for using SVN on a RoR project on Ubuntu?</strong></p>
<p>I'm literally looking for a step by step process on this one.</p>
<p><em>edit</em>
I forgot to mention, I use NetBeans for my IDE, although i have not looked to see what kind of SVN support it has, if any. I looked at RubyMine, and would love to use it, but it appears to be too unstable right now.</p>
|
<p>For plugins, I'd personally recommend just sticking them in the vendor folder and add them to SVN as if you'd written the code yourself. Piston was also a great solution, but switched away from it when all the common plugins started moving to github (piston has been unreliable since then)</p>
<p>For gems, hopefully you're using rails 2 or higher. You should be listing the gems you require in your <code>config/environment.rb</code> using <code>config.gem</code>. <a href="http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies" rel="nofollow noreferrer">Here's a bunch of information about that feature</a></p>
<p>What this means is that if you add a new gem, the next time your co-worker updates, his rails app <em>won't boot</em> until he's got the neccessary gems. He can then install them in one step using <code>sudo rake gems:install</code></p>
<p>You can take this one step further, and put your gems in the vendor directory. This is commonly known as "vendor everything." The easiest way to do this is to list all the gems you use in <code>environment.rb</code> as above, and then run <code>rake gems:unpack</code>. There are 2 problems with this approach however, so I prefer not to use it myself.</p>
<ol>
<li><p>If you have 10 apps and they each vendor their gems, you end up keeping 10 copies of common gems in subversion, which makes updating all your sites a whole lot slower.<br>
This may not be an issue for you, or may be worth putting up with, it's just a personal preference.</p></li>
<li><p>Some gems (such as mongrel or hpricot) have native extensions written in C. What this means is that when you install them, the <code>.c</code> source code is downloaded, and <code>gcc</code> gets run to compile it specifically for your system.<br>
If you installed a native C extension on ubuntu, then put it in the vendor folder, and later on tried to run that on OS X (or even possibly a different version of ubuntu) it would most likely crash your ruby process and bring your app down.<br>
If all your gems are pure-ruby ones, then this is not a problem, but it's just something to be aware of.</p></li>
</ol>
|
<p>Orion mentioned having to rebuild gems that have been vendored when sharing them between different OS's - you can use the gems:build rake task to rebuild them automatically.</p>
| 36,126
|
<p>This most be the second most simple rollover effect, still I don't find any simple solution.</p>
<p><strong>Wanted:</strong> I have a list of items and a corresponding list of slides (DIVs). After loading, the first list item should be selected (bold) and the first slide should be visible. When the user hovers over another list item, that list item should be selected instead and the corresponding slide be shown.</p>
<p>The following code works, but <em>is awful</em>. How can I get this behaviour in an elegant way? jquery has dozens of animated and complicated rollover effects, but I didn't come up with a clean way for this effect.</p>
<pre><code><script type="text/javascript">
function switchTo(id) {
document.getElementById('slide1').style.display=(id==1)?'block':'none';
document.getElementById('slide2').style.display=(id==2)?'block':'none';
document.getElementById('slide3').style.display=(id==3)?'block':'none';
document.getElementById('slide4').style.display=(id==4)?'block':'none';
document.getElementById('switch1').style.fontWeight=(id==1)?'bold':'normal';
document.getElementById('switch2').style.fontWeight=(id==2)?'bold':'normal';
document.getElementById('switch3').style.fontWeight=(id==3)?'bold':'normal';
document.getElementById('switch4').style.fontWeight=(id==4)?'bold':'normal';
}
</script>
<ul id="switches">
<li id="switch1" onmouseover="switchTo(1);" style="font-weight:bold;">First slide</li>
<li id="switch2" onmouseover="switchTo(2);">Second slide</li>
<li id="switch3" onmouseover="switchTo(3);">Third slide</li>
<li id="switch4" onmouseover="switchTo(4);">Fourth slide</li>
</ul>
<div id="slides">
<div id="slide1">Well well.</div>
<div id="slide2" style="display:none;">Oh no!</div>
<div id="slide3" style="display:none;">You again?</div>
<div id="slide4" style="display:none;">I'm gone!</div>
</div>
</code></pre>
|
<p>Rather than displaying all slides when JS is off (which would likely break the page layout) I would place inside the switch LIs real A links to server-side code which returns the page with the "active" class pre-set on the proper switch/slide.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() {
switches = $('#switches > li');
slides = $('#slides > div');
switches.each(function(idx) {
$(this).data('slide', slides.eq(idx));
}).hover(
function() {
switches.removeClass('active');
slides.removeClass('active');
$(this).addClass('active');
$(this).data('slide').addClass('active');
});
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>#switches .active {
font-weight: bold;
}
#slides div {
display: none;
}
#slides div.active {
display: block;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
<title>test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="switch.js"></script>
</head>
<body>
<ul id="switches">
<li class="active">First slide</li>
<li>Second slide</li>
<li>Third slide</li>
<li>Fourth slide</li>
</ul>
<div id="slides">
<div class="active">Well well.</div>
<div>Oh no!</div>
<div>You again?</div>
<div>I'm gone!</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
|
<p>The only thing that's wrong with this code (at least to me) is that you're not using a loop to process all elements. Other than that, why not to it like that?</p>
<p>And with loop, I mean grabbing the container element via a JQuery and iterating over all child elements – basically a one-liner.</p>
| 5,484
|
<p>SqlDataReader is a faster way to process the stored procedure. What are some of the advantage/disadvantages of using SQLDataReader?</p>
|
<p>I assume you mean "instead of loading the results into a DataTable"?</p>
<p>Advantages: you're in control of how the data is loaded. You can ask for specific data types, and you don't end up loading the whole set of data into memory all at the same time unless you want to. Basically, if you want the data but don't need a data table (e.g. you're going to populate your own kind of collection) you don't get the overhead of the intermediate step.</p>
<p>Disadvantages: you're in control of how the data is loaded, which means it's easier to make a mistake and there's more work to do.</p>
<p>What's your use case here? Do you have a good reason to believe that the overhead of using a normal (or strongly typed) data table is significantly hurting performance? I'd only use SqlDataReader directly if I had a good reason to do so.</p>
|
<p>The data might not be concluesive and you are not in control of your actions that why the milk man down the road has always got to carry data with him or else they gona get cracked by the data and the policeman will not carry any data because they think that is wrong to keep other people's data and its wrong to do so. There is a girl who lives in Sheffield and she loves to go out and play most the times that she s in the house that is why I dont like to talk to her because her parents and her other fwends got taken to peace gardens thats a place that everyone likes to sing and stay. usually famous Celebs get to hang aroun dthere but there are always top security because we dont want to get skanked down them ends. KK see u now I need 2 go and chill in the west end PEACE!!!£"$$$ Made of MOney MAN$$$$</p>
| 23,402
|
<p>I have the following solution project structure:</p>
<blockquote>
<p>Application.Core.Entities</p>
<p>Application.Xtend.CustomerName.Entities</p>
</blockquote>
<p>In the Core project I have an entity <strong>Customer</strong> defiend. In the XTend project, I have an entity defined that subclasses Customer named <strong>xCustomer</strong> (for lack of a better name at this time...).</p>
<p>The idea here is that we have a Core domain model in our application. A customer can then create a new assembly that contains extensions to our core model. When the extension assembly is present a smart <a href="http://martinfowler.com/eaaCatalog/repository.html" rel="noreferrer">IRepository</a> class will return a subclass of the core class instead.</p>
<p>I am attempting to map this relationship in <a href="http://nhforge.org/" rel="noreferrer">NHibernate</a>. Using <a href="http://code.google.com/p/fluent-nhibernate/" rel="noreferrer">Fluent NHibernate</a> I was able to generate this mapping:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
default-lazy="false"
assembly="NHibernate.Core.Entites"
namespace="NHibernate.Entites"
default-access="field.camelcase-underscore">
<!-- Customer is located in assembly Application.Core.Entities -->
<class name="Customer" table="Customers" xmlns="urn:nhibernate-mapping-2.2">
<id name="Id" column="Id" type="Int64">
<generator class="native" />
</id>
<component name="Name" insert="true" update="true">
<property name="LastName" column="LastName" length="255" type="String" not-null="true">
<column name="LastName" />
</property>
<property name="FirstName" column="FirstName" length="255" type="String" not-null="true">
<column name="FirstName" />
</property>
</component>
<!-- xCustomer is located in assembly Application.XTend.CustomerName.Entities -->
<joined-subclass name="xCustomer" table="xCustomer">
<key column="CustomerId" />
<property name="CustomerType" column="CustomerType" length="255" type="String" not-null="true">
<column name="CustomerType" />
</property>
</joined-subclass>
</class>
</hibernate-mapping>
</code></pre>
<p>But NHib throws the following error:</p>
<blockquote>
<p>NHibernate.MappingException:
persistent class
Application.Entites.xCustomer,
Application.Core.Entites not found
---> System.TypeLoadException: Could not load type
'Application.Entites.xCustomer' from
assembly 'Application.Core.Entites,
Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'..</p>
</blockquote>
<p>Which makes sense xCustomer is not defined in the Core library.</p>
<p>Is it possible to span different assemblies like this? Am I approaching the problem wrong?</p>
|
<p>I asked this same question on the NHibernate Users mailing list and the solution was so obvious that I am somewhat embarrassed that I couldn't see it. </p>
<p>The hibernate-mapping attributes assembly and namespace are convenient short cuts that allow you to not have to fully qualify your class names. This lets you have the nice mark up , but the name attribute of both class and joined-subclass elements can take a fully qualified assembly name as well.</p>
<p>So the above broken mapping file can be fixed like so:</p>
<pre><code><joined-subclass name="Application.XTend.CustomerName.Entities.xCustomer,
Application.XTend.CustomerName.Entities, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=null"
table="xCustomer">
<key column="CustomerId" />
<property name="CustomerType" column="CustomerType" length="255"
type="String" not-null="true">
<column name="CustomerType" />
</property>
</joined-subclass>
</code></pre>
<p>This works as I expected it to. So I then took a look at the Fluent-NHibernate source and created a patch complete with working unit tests to resolve the issue and <a href="http://code.google.com/p/fluent-nhibernate/issues/detail?id=70" rel="noreferrer">submitted it to the project</a>.</p>
<p>Thanks for you help @David Kemp</p>
|
<p>You need to map using the <code>extends</code> attribute of the <code><class></code> element (AFAIK, this is new in NHibernate 2.0). Then you can have your subclass mapping (<code>.hbm.xml</code>) in the XTend assembly. </p>
<p>You might have to use the AddAttribute/AddProperty (can't remember what it's called) to do this using Fluent NHibernate. (Or submit a patch).</p>
| 32,481
|
<p>From a <a href="http://www.joelonsoftware.com/items/2007/01/26.html" rel="nofollow noreferrer">Joel's post on Copilot</a>:</p>
<blockquote>
<p>Direct Connect! We’ve always done
everything we can to make sure that
Fog Creek Copilot can connect in any
networking situation, no matter what
firewalls or NATs are in place. To
make this happen, both parties make
outbound connections to our server,
which relays traffic on their behalf.
Well, in many cases, this isn’t
necessary. So version 2.0 does
something rather clever: it sets up
the initial connection through our
servers, so you get connected right
away with 100% reliability. But then
once you’re all connected, it quietly,
in the background, looks for a way to
make a direct connection. If it can’t,
no big deal: you just keep relaying
through our server. If you can make a
direct peer-to-peer connection, it
silently shifts your data onto the
direct connection. You won’t notice
anything except, probably, much faster
communication.</p>
</blockquote>
<p>How do they change the server connection to a P2P connection?</p>
|
<p>It's pretty tricky and interesting. I'm sure I have some details wrong, but the overview is this:</p>
<p>The programs can already talk to each other through Joel's server, so they can exchange information with each other and Joel's server. Further, Joel has their external IP addresses, and they give joel information about their internal IP addresses.</p>
<p>They decide to try this hole punch technique. Computer A initiates a TCP connection with Computer B using B's external IP address. It won't go through, but what it does is tell's A's router that it needs to allow incoming packets from B on a given port.</p>
<p>Computer B does the same thing, but its message gets through to A since A's router opened a port/ip combination that matches what B sent (there's some port magic that happens here - this is non trivial, but doable).</p>
<p>B's router remembers that B initiated a connection with A on a given port and IP, and so A's packets now flow into B past their router correctly as well.</p>
<p>So it's actually pretty straight forward, but the implementation has details, especially regarding how ports are given to new TCP connections, and how NAT routers <em>typically</em> deal with TCP requests and how they map to external ports. These details are the interesting, and difficult, bit.</p>
<p>-Adam</p>
|
<p>There is a technique called "<a href="https://en.wikipedia.org/wiki/Hole_punching_(networking)" rel="nofollow noreferrer">Hole Punching</a>" that works well with "Cone" NAT (Cone is a technical familly of router). That's not an 100% sure technique, today, it works well with UDP on about 80% of the router.</p>
<p>There is some implementations of library to realize Hole Punching: <a href="http://sourceforge.net/projects/stun/" rel="nofollow noreferrer">STUN</a> (<a href="http://en.wikipedia.org/wiki/STUN" rel="nofollow noreferrer">wikipedia</a>)</p>
| 6,591
|
<p>How do I check to see if a column exists in a <code>SqlDataReader</code> object? In my data access layer, I have create a method that builds the same object for multiple stored procedures calls. One of the stored procedures has an additional column that is not used by the other stored procedures. I want to modified the method to accommodate for every scenario.</p>
<p>My application is written in C#.</p>
|
<pre><code>public static class DataRecordExtensions
{
public static bool HasColumn(this IDataRecord dr, string columnName)
{
for (int i=0; i < dr.FieldCount; i++)
{
if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return true;
}
return false;
}
}
</code></pre>
<p>Using <code>Exception</code>s for control logic like in some other answers is <a href="https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/exception-throwing" rel="noreferrer">considered bad practice</a> and has performance costs. It also sends false positives to the profiler of # exceptions thrown and god help anyone setting their debugger to break on exceptions thrown.</p>
<p>GetSchemaTable() is also another suggestion in many answers. This would not be a preffered way of checking for a field's existance as it is not implemented in all versions (it's abstract and throws NotSupportedException in some versions of dotnetcore). GetSchemaTable is also overkill performance wise as it's a pretty heavy duty function if you <a href="https://github.com/microsoft/referencesource/blob/24a17c0c3b23ddeac0926acc13b13c54b650d3be/System.Data/System/Data/SqlClient/SqlDataReader.cs#L422" rel="noreferrer">check out the source</a>.</p>
<p>Looping through the fields can have a small performance hit if you use it a lot and you may want to consider caching the results.</p>
|
<p>You can also call <a href="http://support.microsoft.com/kb/310107" rel="nofollow noreferrer">GetSchemaTable()</a> on your DataReader if you want the list of columns and you don't want to have to get an exception...</p>
| 48,805
|
<p>Does anyone have any suggestions (or a regular expression) for parsing the HTTP Accept header?</p>
<p>I am trying to do some content-type negotiation in ASP.NET MVC. There doesn't seem to be a built in way (which is fine, because there are a lot of schools of thought here), but the parsing is not entirely trivial and I would rather not re-invent the wheel if someone has already done it well and is willing to share.</p>
|
<p>Have you seen <a href="http://www.xml.com/pub/a/2005/06/08/restful.html" rel="noreferrer">this article</a>? It gives a pretty comprehensive implementation for parsing the Accept header and subsequently doing something useful with it.</p>
|
<p>The <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="nofollow noreferrer">RFC</a> is quite complex. If the regex where to follow these rules to the letter, it would become several lines long.</p>
<p>If you already have the Accept-header, and ignore the quotes and the parameters, you could do something like this to match each pair:</p>
<pre><code>/([^()<>@,;:\\"\/[\]?={} \t]+)\/([^()<>@,;:\\"\/[\]?={} \t]+)/
</code></pre>
<p><code>*</code> is included in the character class, so it does not need any special case in the regex.</p>
| 31,870
|
<p>I have a couple of tables which are used to log user activity for an application. The tables looks something like this (pseudo code from memory, may not be syntactically correct):</p>
<pre><code>create table activity (
sessionid uniqueidentifier not null,
created smalldatetime not null default getutcdate()
);
create table activity_details (
sessionid uniqueidentifier not null,
activity_description varchar(100) not null,
created smalldatetime not null default getutcdate()
);
</code></pre>
<p>My goal is to populate a summary table for reporting purposes that looks something like this:</p>
<pre><code>create table activity_summary (
sessionid uniqueidentifier not null,
first_activity_desc varchar(100) not null,
last_activity_desc varchar(100) not null
);
</code></pre>
<p>First and last activity descriptions would be determined chronologically. My initial thought is to update the summary table like so:</p>
<pre><code>truncate table activity_summary;
insert into activity_summary (sessionid)
select sessionid from activity;
update table activity_summary set
first_activity_desc = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created asc),
last_activity_summary = (select top 1 activity_desc from activity_detail where sessionid = as.sessionid order by created desc)
from activity_summary as;
</code></pre>
<p>However, this seems incredibly verbose and unnecessary to me. I'm just not sure how to shrink it down. My gut feel is that I could do it somehow all within the insert statement, but I'm stumped. Any suggestions? </p>
|
<p>There's probably more efficient ways to do this as well, but this is closest to your original:</p>
<pre><code>truncate table activity_summary;
insert into activity_summary (sessionid, first_activity_desc, last_activity_summary)
select a.sessionid
,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a.sessionid order by ad.created asc) AS first_activity_desc
,(select top 1 ad.activity_desc from activity_detail AS ad where ad.sessionid = a.sessionid order by ad.created desc) AS last_activity_summary
from activity AS a;
</code></pre>
<p>Something like this might be more efficient:</p>
<pre><code>truncate table activity_summary;
WITH firsts AS (
SELECT ad.sessionid
,ad.activity_desc
,ROW_NUMBER() OVER (ORDER BY ad.created ASC) as RowNumber
FROM activity_detail AS ad
)
,lasts AS (
SELECT ad.sessionid
,ad.activity_desc
,ROW_NUMBER() OVER (ORDER BY ad.created DESC) as RowNumber
FROM activity_detail AS ad
)
insert into activity_summary (sessionid, first_activity_desc, last_activity_summary)
select a.sessionid
,firsts.activity_desc
,lasts.activity_desc
from activity AS a
INNER JOIN firsts ON firsts.sessionid = a.sessionid AND firsts.RowNumber = 1
INNER JOIN lasts ON lasts.sessionid = a.sessionid AND lasts.RowNumber = 1
</code></pre>
|
<p>Roughly,</p>
<p>INSERT etc.</p>
<pre><code>SELECT a.sessionid, d1.activity_description, d2.activity_description
FROM activity a
JOIN detail d1 ON a.sessionid = d1.sessionid
JOIN detail d2 ON a.sessionid = d2.sessionid
WHERE NOT EXISTS
(SELECT 1 FROM detail WHERE sessionid = a.sessionid AND created < d1.created)
AND NOT EXISTS
(SELECT 1 FROM detail WHERE sessionid = a.sessionid AND created > d2.created)
</code></pre>
| 41,156
|
<p>Is tight looping in a program bad?</p>
<p>I have an application that has two threads for a game-physics simulator. An updateGame thread and a render thread. The render thread is throttled by causing the thread to sleep for some milliseconds (to achieve the frame-rate I want) and the updateGame thread (that updates my in game objects positions based off some physics equations) was previously throttled by a 10 millisecond sleep.</p>
<p>However, I recently unthrottled the updateGame thread and the simulation of my objects movement seems to be significantly more realistic now that I have taken out that 10ms sleep. Is it bad to hot loop or have a tight loop?</p>
<pre><code>private class UpdateTask implements Runnable
{
private long previousTime = System.currentTimeMillis();
private long currentTime = previousTime;
private long elapsedTime;
public void run()
{
while(true)
{
currentTime = System.currentTimeMillis();
elapsedTime = (currentTime - previousTime); // elapsed time in seconds
updateGame(elapsedTime / 1000f);
try {
Thread.currentThread().sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
previousTime = currentTime;
}
}
}
</code></pre>
<p>In this example I'm just sleeping for 1ms (and from my understanding with how millisecond accuracy and the sleep function works this is probably more like 5-10ms. If I sleep for any more than this it starts to have impacts on the accuracy of my collision detection and physics model.</p>
<p>Is it a bad practice to have tight loops or loops with 1ms sleeps in them? Is there something else I should do instead?</p>
|
<p>I read a really great post about efficiently and effectively executing physics calculations loop: <a href="http://gafferongames.com/game-physics/fix-your-timestep/" rel="nofollow noreferrer">Fix Your Timestep!</a></p>
<p>When a game is running that is usually the main application that the user cares about so tight looping is not that big of a deal. What you really should do though schedule your updates. You should know how long -- at your target framerate -- that your frame has to execute. You should measure the time that your frame took and only sleep for the time that your frame took minus that known frame time. That way your system will lock into a frame rate and not vary with the amount of time that your frame takes to render.</p>
<p>Another thing is that I don't believe that Thread.sleep has a very good resolution, well over 5 milliseconds, you may want to look for a more accurate timer available for Java.</p>
|
<p>For a game, probably not. Just make sure your game pauses when the switches tasks.</p>
| 47,216
|
<p>The situation is this. I have an asp.net webservice application...say a page called api.asmx</p>
<p>In the code behind I have several methods, for example:</p>
<pre><code>[WebMethod(Description="Method1")]
public int GetSomething(int num1, int num2){
try{
return SomeObject.DatabaseCall.DoSomething(num1, num2);
}
catch(Exception ex){
object[] pars = new object[] { num1, num2 };
LogError("GetSomething", pars, ex);
}
}
[WebMethod(Description="Method2")]
public int GetSomething2(string w, string j, int f){
try{
return AnotherObject.DoSomething(w, j, f);
}
catch(Exception ex){
object[] pars = new object[] { w, j, f };
LogError("GetSomething2", pars, ex);
}
}
</code></pre>
<p>Of course these are just two simple examples where, if an exception is thrown, I can log the method call and parameters passed in.</p>
<p>Is there another way to do this? Is there some way that I can extract the method being called and/or the parameters. I guess I'm hoping someone will tell me that I can just have some kind of function like:</p>
<pre><code>LogError(ex);
</code></pre>
<p>And within that function I can access some Server or Environment variables that will expose the method being called. Maybe something like CurrentContext.WebServiceCall.Magic property... Do I need to wrap all my calls in a try/catch and then type out the method name and parameters, or is there another way to access this information.</p>
<p>Hopefully this question ins't too stupid.</p>
|
<p>Any unhandled exceptions will be bubbled up to your Application_Error event in the Global.asax file. From there, you can call Server.GetLastError() to retrieve the Exception instance. </p>
<p>Once you have the exception, you can look at the stack trace. You will also have access to the Request object so you can see exactly what came from the client.</p>
|
<p>Your LogError method could call <a href="http://msdn.microsoft.com/en-us/library/system.environment.stacktrace.aspx" rel="nofollow noreferrer">Environment.StackTrace</a>. Then it would "know" what method called it. </p>
| 34,060
|
<p>I currently don't know any thing about web services, except that they are used to allow an application to share its functions.</p>
<ul>
<li>Where & how to start? </li>
<li>Does any book on web services work with me if I use PHP as my programming language?</li>
<li>Does anyone know any IRC channel for help? </li>
<li>Does anyone know of a directory for tutorials for a beginner?</li>
<li>Is it complicated?</li>
<li>Does it take a long time to learn?</li>
</ul>
|
<p>I've used two good books in the past that focus on web services and PHP. <a href="https://rads.stackoverflow.com/amzn/click/com/0764589547" rel="noreferrer" rel="nofollow noreferrer">Professional Web APIs with PHP</a> is good if you want to quickly get started <em>using</em> 3rd party APIs (like Amazon, Google, eBay, etc.). It has tons of example PHP code to get you started. <a href="https://rads.stackoverflow.com/amzn/click/com/1590596331" rel="noreferrer" rel="nofollow noreferrer">Pro PHP XML and Web Services</a> is what you want if you're interested in <em>implementing</em> web services of your own using PHP.</p>
|
<p>Web services are not hard to learn. If you already have PHP experience then you know most of what you need to do a web service. This <a href="http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html" rel="nofollow noreferrer">article</a> might start you off creating your first web service in php.</p>
| 32,048
|
<p>I've downloaded a tutorial that had fonts included in the source. When I try to build the project, I always get the following error message:</p>
<blockquote>
<p>Error 1 The font family "Joystick"
could not be found. Please ensure the
requested font is installed, and is a
TrueType or OpenType font.</p>
</blockquote>
<p>The font was added via the control panel, and is a TrueType font.</p>
|
<p>Do you see the Font in the Windows\Fonts directory? If the font is installed, it should be there. Have you try to use this font in Word or other program to see if it's really installed?</p>
<p>You might contact the person who is the source code is coming and ask him the question, or you could try to use his source code and just change the font.</p>
|
<p>Just Restart your editor once. It works. Because the editor loads the fonts only in the beginning.</p>
| 31,775
|
<p>My PHP/MS Sql Server 2005/win 2003 Application occasionally becomes very unresponsive, the memory/cpu usage does not spike. If i try to open any new connection from sql management studio, then the it just hangs at the open connection dialog box.
how to deterime the total number of active connections ms sql server 2005</p>
|
<p>This shows the number of connections per each DB:</p>
<pre><code>SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
loginame as LoginName
FROM
sys.sysprocesses
WHERE
dbid > 0
GROUP BY
dbid, loginame
</code></pre>
<p>And this gives the total:</p>
<pre><code>SELECT
COUNT(dbid) as TotalConnections
FROM
sys.sysprocesses
WHERE
dbid > 0
</code></pre>
<p>If you need more detail, run:</p>
<pre><code>sp_who2 'Active'
</code></pre>
<p><strong>Note:</strong> The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)</p>
|
<p>see <a href="http://msdn.microsoft.com/en-us/library/ms174313.aspx" rel="nofollow">sp_who</a> it gives you more details than just seeing the number of connections </p>
<p>in your case i would do something like this </p>
<pre><code> DECLARE @temp TABLE(spid int , ecid int, status varchar(50),
loginname varchar(50),
hostname varchar(50),
blk varchar(50), dbname varchar(50), cmd varchar(50), request_id int)
INSERT INTO @temp
EXEC sp_who
SELECT COUNT(*) FROM @temp WHERE dbname = 'DB NAME'
</code></pre>
| 26,552
|
<p>I know this is a longshot but I was wondering if anyone knows if this is possible.</p>
|
<p>Most browsers set the <a href="http://en.wikipedia.org/wiki/Referer" rel="nofollow noreferrer">HTTP_REFERRER</a> header to the current URL when requesting a linked document. However, it can be spoofed so don't use it for security.</p>
|
<p>I know nothing about air. </p>
<p>But if AIR has JavaScript access, and you can access the container document ( <a href="https://stackoverflow.com/questions/193130/how-do-i-share-a-javascript-object-between-different-pages-in-adobe-air">How do I share a javascript object between different pages in Adobe AIR?</a> ) then all you need to work out is how to obtain Document.location from it. </p>
| 42,595
|
<p>I've been trying to deal with some delimited text files that have non standard delimiters (not comma/quote or tab delimited). The delimiters are random ASCII characters that don't show up often between the delimiters. After searching around, I've seem to have only found no solutions in .NET will suit my needs and the custom libraries that people have written for this seem to have some flaws when it comes to gigantic input (4GB file with some field values having very easily several million characters). </p>
<p>While this seems to be a bit extreme, it is actually a standard in the Electronic Document Discovery (EDD) industry for some review software to have field values that contain the full contents of a document. For reference, I've previously done this in python using the csv module with no problems.</p>
<p>Here's an example input:</p>
<pre><code>Field delimiter =
quote character = þ
þFieldName1þþFieldName2þþFieldName3þþFieldName4þ
þValue1þþValue2þþValue3þþSomeVery,Very,Very,Large value(5MB or so)þ
...etc...
</code></pre>
<p>Edit:
So I went ahead and created a delimited file parser from scratch. I'm kind of weary using this solution as it may be prone to bugs. It also doesn't feel "elegant" or correct to have to write my own parser for a task like this. I also have a feeling that I probably didn't have to write a parser from scratch for this anyway. </p>
|
<p>Use the <a href="http://filehelpers.sourceforge.net/" rel="nofollow noreferrer">File Helpers API</a>. It's .NET and open source. It's extremely high performance using compiled IL code to set fields on strongly typed objects, and supports streaming.</p>
<p>It supports all sorts of file types and custom delimiters; I've used it to read files larger than 4GB.</p>
<p>If for some reason that doesn't do it for you, try just reading line by line with a string.split:</p>
<pre><code>public IEnumerable<string[]> CreateEnumerable(StreamReader input)
{
string line;
while ((line = input.ReadLine()) != null)
{
yield return line.Split('þ');
}
}
</code></pre>
<p>That'll give you simple string arrays representing the lines in a streamy fashion that you can even Linq into ;) Remember however that the IEnumerable is lazy loaded, so don't close or alter the StreamReader until you've iterated (or caused a full load operation like ToList/ToArray or such - given your filesize however, I assume you won't do that!).</p>
<p>Here's a good sample use of it:</p>
<pre><code>using (StreamReader sr = new StreamReader("c:\\test.file"))
{
var qry = from l in CreateEnumerable(sr).Skip(1)
where l[3].Contains("something")
select new { Field1 = l[0], Field2 = l[1] };
foreach (var item in qry)
{
Console.WriteLine(item.Field1 + " , " + item.Field2);
}
}
Console.ReadLine();
</code></pre>
<p>This will skip the header line, then print out the first two field from the file where the 4th field contains the string "something". It will do this without loading the entire file into memory.</p>
|
<p>While this doesn't help address the large input issue, a possible solution to the parsing issue might include a custom parser that users the strategy pattern to supply a delimiter.</p>
| 44,085
|
<p>I'm trying to reorder/group a set of results using SQL. I have a few fields (which for the example have been renamed to something a bit less specific), and each logical group of records has a field which remains constant - the address field. There are also fields which are present for each address, these are the same for every address.</p>
<pre><code>id forename surname address
1 John These Address1
2 Lucy Values Address1
3 Jenny Are Address1
4 John All Address2
5 Lucy Totally Address2
6 Jenny Different Address2
7 Steve And Address2
8 Richard Blah Address2
address John Lucy Jenny Steve Richard
Address1 These Values Are (null) (null)
Address2 All Totally Different And Blah
</code></pre>
<p>For example: John,Lucy,Jenny,Steve and Richard are the only possible names at each address. I know this because it's stored in another location.</p>
<p>Can I select values from the actual records in the left hand image, and return them as a result set like the one on the right? I'm using MySQL if that makes a difference.</p>
|
<p>Assuming that the column headings "john", "lucy" etc are fixed, you can group by the address field and use if() functions combined with aggregate operators to get your results:</p>
<pre><code>select max(if(forename='john',surname,null)) as john,
max(if(forename='lucy',surname,null)) as lucy,
max(if(forename='jenny',surname,null)) as jenny,
max(if(forename='steve',surname,null)) as steve,
max(if(forename='richard',surname,null)) as richard,
address
from tablename
group by address;
</code></pre>
<p>It is a bit brittle though.</p>
<p>There is also the group_concat function that can be used (within limits) to do something similar, but it will be ordered row-wise rather than column-wise as you appear to require.</p>
<p>eg.</p>
<pre><code>select address, group_concat( concat( forename, surname ) ) tenants
from tablename
group by address;
</code></pre>
|
<p>I'm not certain, but I think what you're trying to do is GROUP BY.</p>
<pre><code>SELECT Address,Name FROM Table GROUP BY Name
</code></pre>
<p>if you want to select more columns, make sure they're included in the GROUP BY clause. Also, you can now do aggregate functions, like MAX() or COUNT().</p>
| 36,890
|
<p>I'm trying to scrape a price from a web page using PHP and Regexes. The price will be in the format £123.12 or $123.12 (i.e., pounds or dollars).</p>
<p>I'm loading up the contents using libcurl. The output of which is then going into <code>preg_match_all</code>. So it looks a bit like this:</p>
<pre><code>$contents = curl_exec($curl);
preg_match_all('/(?:\$|£)[0-9]+(?:\.[0-9]{2})?/', $contents, $matches);
</code></pre>
<p>So far so simple. The problem is, PHP isn't matching anything at all - even when there are prices on the page. I've narrowed it down to there being a problem with the '£' character - PHP doesn't seem to like it.</p>
<p>I think this might be a charset issue. But whatever I do, I can't seem to get PHP to match it! Anyone have any ideas?</p>
<p>(Edit: I should note if I try using the <a href="http://www.spaweditor.com/scripts/regex/index.php" rel="nofollow noreferrer">Regex Test Tool</a> using the same regex and page content, it works fine)</p>
|
<p>Have you try to use \ in front of £</p>
<pre><code>preg_match_all('/(\$|\£)[0-9]+(\.[0-9]{2})/', $contents, $matches);
</code></pre>
<p>I have try this expression with .Net with \£ and it works. I just edited it and removed some ":".
<a href="https://i.stack.imgur.com/DwYIJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DwYIJ.png" alt="alt text"></a><br>
<sub>(source: <a href="http://clip2net.com/clip/m12122/1227972904-clip-9kb.png" rel="nofollow noreferrer">clip2net.com</a>)</sub> </p>
<p>Read my comment about the possibility of Curl giving you bad encoding (comment of this post).</p>
|
<p>maybe pound has it's html entity replacement? i think you should try your regexp with some sort of couching program (i.e. match it against fixed text locally).</p>
<p>i'd change my regexp like this: <code>'/(?:\$|£)\d+(?:\.\d{2})?/'</code></p>
| 42,462
|
<p>We have two versions of a managed C++ assembly, one for x86 and one for x64. This assembly is called by a .net application complied for AnyCPU. We are deploying our code via a file copy install, and would like to continue to do so.</p>
<p>Is it possible to use a Side-by-Side assembly manifest to loading a x86 or x64 assembly respectively when an application is dynamically selecting it's processor architecture? Or is there another way to get this done in a file copy deployment (e.g. not using the GAC)?</p>
|
<p>I created a simple solution that is able to load platform-specific assembly from an executable compiled as AnyCPU. The technique used can be summarized as follows:</p>
<ol>
<li>Make sure default .NET assembly loading mechanism ("Fusion" engine) can't find either x86 or x64 version of the platform-specific assembly</li>
<li>Before the main application attempts loading the platform-specific assembly, install a custom assembly resolver in the current AppDomain</li>
<li>Now when the main application needs the platform-specific assembly, Fusion engine will give up (because of step 1) and call our custom resolver (because of step 2); in the custom resolver we determine current platform and use directory-based lookup to load appropriate DLL.</li>
</ol>
<p>To demonstrate this technique, I am attaching a short, command-line based tutorial. I tested the resulting binaries on Windows XP x86 and then Vista SP1 x64 (by copying the binaries over, just like your deployment).</p>
<p><strong>Note 1</strong>: "csc.exe" is a C-sharp compiler. This tutorial assumes it is in your path (my tests were using "C:\WINDOWS\Microsoft.NET\Framework\v3.5\csc.exe")</p>
<p><strong>Note 2</strong>: I recommend you create a temporary folder for the tests and run command line (or powershell) whose current working directory is set to this location, e.g.</p>
<pre><code>(cmd.exe)
C:
mkdir \TEMP\CrossPlatformTest
cd \TEMP\CrossPlatformTest
</code></pre>
<p><strong>Step 1</strong>: The platform-specific assembly is represented by a simple C# class library:</p>
<pre><code>// file 'library.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Library
{
public static class Worker
{
public static void Run()
{
System.Console.WriteLine("Worker is running");
System.Console.WriteLine("(Enter to continue)");
System.Console.ReadLine();
}
}
}
</code></pre>
<p><strong>Step 2</strong>: We compile platform-specific assemblies using simple command-line commands:</p>
<pre><code>(cmd.exe from Note 2)
mkdir platform\x86
csc /out:platform\x86\library.dll /target:library /platform:x86 library.cs
mkdir platform\amd64
csc /out:platform\amd64\library.dll /target:library /platform:x64 library.cs
</code></pre>
<p><strong>Step 3</strong>: Main program is split into two parts. "Bootstrapper" contains main entry point for the executable and it registers a custom assembly resolver in current appdomain:</p>
<pre><code>// file 'bootstrapper.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Program
{
public static class Bootstrapper
{
public static void Main()
{
System.AppDomain.CurrentDomain.AssemblyResolve += CustomResolve;
App.Run();
}
private static System.Reflection.Assembly CustomResolve(
object sender,
System.ResolveEventArgs args)
{
if (args.Name.StartsWith("library"))
{
string fileName = System.IO.Path.GetFullPath(
"platform\\"
+ System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")
+ "\\library.dll");
System.Console.WriteLine(fileName);
if (System.IO.File.Exists(fileName))
{
return System.Reflection.Assembly.LoadFile(fileName);
}
}
return null;
}
}
}
</code></pre>
<p>"Program" is the "real" implementation of the application (note that App.Run was invoked at the end of Bootstrapper.Main):</p>
<pre><code>// file 'program.cs' in C:\TEMP\CrossPlatformTest
namespace Cross.Platform.Program
{
public static class App
{
public static void Run()
{
Cross.Platform.Library.Worker.Run();
}
}
}
</code></pre>
<p><strong>Step 4</strong>: Compile the main application on command line:</p>
<pre><code>(cmd.exe from Note 2)
csc /reference:platform\x86\library.dll /out:program.exe program.cs bootstrapper.cs
</code></pre>
<p><strong>Step 5</strong>: We're now finished. The structure of the directory we created should be as follows:</p>
<pre><code>(C:\TEMP\CrossPlatformTest, root dir)
platform (dir)
amd64 (dir)
library.dll
x86 (dir)
library.dll
program.exe
*.cs (source files)
</code></pre>
<p>If you now run program.exe on a 32bit platform, platform\x86\library.dll will be loaded; if you run program.exe on a 64bit platform, platform\amd64\library.dll will be loaded. Note that I added Console.ReadLine() at the end of the Worker.Run method so that you can use task manager/process explorer to investigate loaded DLLs, or you can use Visual Studio/Windows Debugger to attach to the process to see the call stack etc.</p>
<p>When program.exe is run, our custom assembly resolver is attached to current appdomain. As soon as .NET starts loading the Program class, it sees a dependency on 'library' assembly, so it tries loading it. However, no such assembly is found (because we've hidden it in platform/* subdirectories). Luckily, our custom resolver knows our trickery and based on the current platform it tries loading the assembly from appropriate platform/* subdirectory.</p>
|
<p>This solution can work for non managed assemblies as well. I have created a simple example similar to Milan Gardian's great example. The example I created dynamically loads a Managed C++ dll into a C# dll compiled for the Any CPU platform. The solution makes use of the InjectModuleInitializer nuget package to subscribe to the AssemblyResolve event before the dependencies of the assembly are loaded. </p>
<p><a href="https://github.com/kevin-marshall/Managed.AnyCPU.git" rel="nofollow noreferrer">https://github.com/kevin-marshall/Managed.AnyCPU.git</a></p>
| 13,426
|
<p>How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner.</p>
|
<h3>2015 Update</h3>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy" rel="noreferrer">Content security policy</a> will prevent this from working in many sites now. For example, the code below won't work on Facebook.</p>
<h3>2008 answer</h3>
<p>Use a bookmarklet that creates a script tag which includes your external JS.</p>
<p>As a sample:</p>
<pre><code>javascript:(function(){document.body.appendChild(document.createElement('script')).src='** your external file URL here **';})();
</code></pre>
|
<p>I always prefer to use a popular open source project <a href="https://github.com/muicss/loadjs/blob/master/dist/loadjs.min.js" rel="nofollow noreferrer">loadjs</a> </p>
<p>it is cross browser tested and has more functionality/comfort features.</p>
<p>So the code will look like this:</p>
<pre><code>loadjs=function(){function e(e,n){var t,r,i,c=[],o=(e=e.push?e:[e]).length,f=o;for(t=function(e,t){t.length&&c.push(e),--f||n(c)};o--;)r=e[o],(i=s[r])?t(r,i):(u[r]=u[r]||[]).push(t)}function n(e,n){if(e){var t=u[e];if(s[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function t(e,n,r,i){var o,s,u=document,f=r.async,a=(r.numRetries||0)+1,h=r.before||c;i=i||0,/(^css!|\.css$)/.test(e)?(o=!0,(s=u.createElement("link")).rel="stylesheet",s.href=e.replace(/^css!/,"")):((s=u.createElement("script")).src=e,s.async=void 0===f||f),s.onload=s.onerror=s.onbeforeload=function(c){var u=c.type[0];if(o&&"hideFocus"in s)try{s.sheet.cssText.length||(u="e")}catch(e){u="e"}if("e"==u&&(i+=1)<a)return t(e,n,r,i);n(e,u,c.defaultPrevented)},!1!==h(e,s)&&u.head.appendChild(s)}function r(e,n,r){var i,c,o=(e=e.push?e:[e]).length,s=o,u=[];for(i=function(e,t,r){if("e"==t&&u.push(e),"b"==t){if(!r)return;u.push(e)}--o||n(u)},c=0;c<s;c++)t(e[c],i,r)}function i(e,t,i){var s,u;if(t&&t.trim&&(s=t),u=(s?i:t)||{},s){if(s in o)throw"LoadJS";o[s]=!0}r(e,function(e){e.length?(u.error||c)(e):(u.success||c)(),n(s,e)},u)}var c=function(){},o={},s={},u={};return i.ready=function(n,t){return e(n,function(e){e.length?(t.error||c)(e):(t.success||c)()}),i},i.done=function(e){n(e,[])},i.reset=function(){o={},s={},u={}},i.isDefined=function(e){return e in o},i}();
loadjs('//path/external/js', {
success: function () {
console.log('something to run after the script was loaded');
});
</code></pre>
| 13,193
|
<p>In vs2008, is it possible to write an extension methods which would apply to any enumeration.</p>
<p>I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible?</p>
|
<p>Yes, just code against the base <code>Enum</code> type, e.g.</p>
<pre><code>public static void Something(this Enum e)
{
// code here
}
</code></pre>
<p>The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using <a href="http://msdn.microsoft.com/en-us/library/system.enum.getunderlyingtype.aspx" rel="noreferrer"><code>Enum.GetUnderlyingType</code></a>, casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have <code>IsOneOf</code> and <code>IsCombinationOf</code> methods that apply to all enums).</p>
<p>PS: Remember when writing the method that, although ill advised, you can use <code>float</code> and <code>double</code> as the base types for enums so you'll need some special cases for those as well as unsigned values.</p>
|
<p>Another example of making Enum extension - but this time it returns the input enum type.</p>
<pre><code>public static IEnumerable<T> toElementsCollection<T>(this T value) where T : struct, IConvertible
{
if (typeof(T).IsEnum == false) throw new Exception("typeof(T).IsEnum == false");
return Enum.GetValues(typeof(T)).Cast<T>();
}
</code></pre>
<p>Example of usage:</p>
<pre><code>public enum TestEnum { A,B,C };
TestEnum.A.toElementsCollection();
</code></pre>
| 34,878
|
<p>My goal is to make sure that in most scenarios objects are used via a "read-only interface" that is a subset of the full interface.</p>
<ul>
<li>As an example, if I were using C++, I would just return a <code>const</code> object.</li>
<li>In C#, if I could achieve this with interfaces, I would just implement a read-only interface and use it everywhere. However, I need operator overloading, which is not allowed for interfaces. That's why I have to use an abstract base class.</li>
<li>But if I define an abstract base class, I am not allowed to change accessibility in the derived type.</li>
</ul>
<p>So, how can I achieve my goal in C#?</p>
|
<p>You could implement the readonly behaviour via state in the object, and throw an exception if a modifying method is called?</p>
|
<p>If anyone is interested in what I did, I finally went for an abstract class instead of interface, and I did hide the method in the derived class to get the right accessors:</p>
<p>Like, in the base abstract class (readonly interface):</p>
<pre><code>protected double accuracy;
public double Accuracy { get { return accuracy; } }
</code></pre>
<p>In the derived class:</p>
<pre><code>public new double Accuracy
{
get { return accuracy; }
set { accuracy = value; }
}
</code></pre>
<p>Of course, ugly with the "new" keyword, but in this case it will do for me.</p>
| 48,779
|
<p>If I need to test out some of the components of a RAMPS 1.4 based 3D Printer, can I only plug some of them into the board (not all of them) and test them out?</p>
<p>I'd like to test out the NEMA 17 motors without testing the heated bed or extruder. Is this safe and why?</p>
|
<p>If by components you mean motors, fans, or heated bed, then yes. This is even suggested in the <a href="http://reprap.org/wiki/RAMPS_1.4#Final_Setup" rel="noreferrer">Final Setup</a> instructions on the RAMPS wiki.</p>
<blockquote>
<p>If you think you may have mistakes (in your setup) you can install only one stepper driver during initial testing and risk only one stepper driver.</p>
</blockquote>
<p>There are also printers using RAMPS with no heated bed and other machines that have no extruder at all. Furthermore, from an electronics perspective: if nothing is connected across a terminal no current will flow and therefore there is no damage that can be done. Obviously if you short out the unused connections there will be problems.</p>
|
<p>Yes, you can. By leaving components unplugged you would simply have some pins powered that are not in use. But even with all your components plugged in, you would still have some unused, powered pins on your board, so I wouldn't think too hard about that. In some cases it might be needed to mount e.i. fans to cool your electronics while running, but for testing a few stepper motors, you will be just fine.</p>
<p>Exactly how you would address each individual motor depends on your setup, however. My best bet would be to simply rely on your "default" firmware (such as Marlin), and then run commands for testing through Pronterface/PrintRun or similar. </p>
<p>Alternatively, you could upload your own sketch/firmware to the Arduino, and manipulate each stepper driver individually. This is a somewhat more advanced option, though.</p>
| 169
|
<p>I often run into problems where I can't get something to connect to something else. I usually forget to check something obvious. Can you help with:</p>
<ul>
<li>A tip/technique for diagnosing a connection issue</li>
<li>The name of a tool or application that can help (and the situation in which it's useful)</li>
</ul>
<p><em>I know the question is a little non-specific, but hopefully the answers can form a useful starting point for anybody who's stuck trying to get computers/programs talking to each other.</em></p>
<p><em>Please can you give one answer per answer so the best ones can be voted up.</em></p>
|
<p>Simple checks to run when debugging network problems:</p>
<ol>
<li>Has each machine got an IP address, Go to command prompt and run ipconfig. Key things to check here are the interfaces and ensuring the appropriate ones have IP addresses.</li>
<li>Check both machines IP addresses are in the same range and subnet if you are running it on an internal or Virtual network.</li>
<li>Try pinging each machine from the other to see if they can communicate with each other. Note that some firewalls will block ping requests.</li>
<li>If Pinging fails then check to see if firewalls are active. If the communication is within a 'safe' internal network then try disabling the firewalls and re-pinging. </li>
<li>If the connections are over a wireless network then check signal strength.</li>
<li>If pinging fails and you are connecting through several networks then try running a tracert to see at which will may show you where on the network the connection is failing.</li>
<li>If you are able to ping but not connect then check firewall settings and network connection settings. Windows 2000+ has the capability of setting port an ip access on a connection properties.</li>
<li>Try drawing a network diagram of the connections to help in visualising the problem.</li>
<li>If you are connecting through routers, firewalls and loadbalancers then check that all devices are not tied to any specific ip addresses and that the IP address redirection (if in place) is correct. Also check any NAT logs to see if connections are being received and properly re-directed.</li>
</ol>
|
<p>You need to be use the process of elimination, for example if you can ping the ip address but not the hostname then there's DNS issues. If you can ping the system but not connect to a share etc.</p>
| 27,425
|
<p>I have an SQLite table that contains a BLOB I need to do a size/length check on. How do I do that?</p>
<p>According to documentation <code>length(blob)</code> only works on texts and will stop counting after the first NULL. My tests confirmed this. I'm using SQLite 3.4.2.</p>
|
<p>I haven't had this problem, but you could try <code>length(hex(glob))/2</code></p>
<p><strong>Update (Aug-2012):</strong>
For SQLite 3.7.6 (released April 12, 2011) and later, <code>length(blob_column)</code> works as expected with both text and binary data.</p>
|
<p>Example of a <code>select</code> query that does this, getting the length of the blob in column <code>myblob</code>, in table <code>mytable</code>, in row 3:</p>
<pre><code>select length(myblob) from mytable where rowid=3;
</code></pre>
| 31,239
|
<p>I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case). </p>
<p>If that is the case then the question becomes what is the best way to sort a DataTable?</p>
<p>The combo box bindings are set in the designer initialize using</p>
<p><pre><code>myCombo.DataSource = this.typedDataSet;
myCombo.DataMember = "Table1";
myCombo.DisplayMember = "ColumnB";
myCombo.ValueMember = "ColumnA";</pre></code></p>
<p>I have tried setting
<pre><code>this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC";</pre></code>
But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.</p>
|
<p>If you're using a DataTable, you can use the (DataTable.DefaultView) <a href="http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx" rel="nofollow noreferrer">DataView.Sort</a> property. For greater flexibility you can use the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx" rel="nofollow noreferrer">BindingSource</a> component. BindingSource will be the DataSource of your combobox. Then you can change your data source from a DataTable to List without changing the DataSource of the combobox.</p>
<blockquote>
<p>The BindingSource component serves
many purposes. First, it simplifies
binding controls on a form to data by
providing currency management, change
notification, and other services
between Windows Forms controls and
data sources.</p>
</blockquote>
|
<p>Does the data need to be in a DataTable?
Using a SortedList and binding that to a combo box would be a simpler way.</p>
<p>If you need to use a DataTable you can use the Select method to retrieve a DataView and pass in a sort parameter.</p>
<pre><code>DataView dv = myDataTable.Select("filter expression", "sort");
</code></pre>
| 4,947
|
<p>I've written (most of) an application in Flex and I am concerned with protecting the source code. I fired up a demo of <a href="http://www.flash-decompiler.com/" rel="noreferrer">Trillix swf decompiler</a> and opened up the swf file that was installed to my Program Files directory. I saw that all of the actionscript packages I wrote were there. I'm not too concerned with the packages, even though there is a substantial amount of code, because it still seems pretty unusable without the mxml files. I think they are converted to actionscript, or atleast I hope. However, I would still like to explore obfuscation.</p>
<p>Does anyone have any experience with Flash / Actionscript 3 / Flex obfuscators? Can you recommend a good product?</p>
|
<p>Here's what I would do.</p>
<ul>
<li><p>Compile your application to a SWF file. Then encrypt the SWF using AES.</p></li>
<li><p>Make a "wrapper" application that loads the encrypted SWF into a ByteArray using URLLoader</p></li>
<li><p>Use the <a href="http://code.google.com/p/as3crypto/" rel="noreferrer">as3crypto</a> library to decrypt the swf at runtime.</p></li>
<li><p>Once decrypted, use Loader.loadBytes to load the decrypted swf into the wrapper application.</p></li>
</ul>
<p>This will make it a lot harder to get your code. Not impossible, but harder.</p>
<p>For AIR applications you could leave the SWF encrypted when delivering the application to the end-user. Then you could provide a registration key that contains the key used to decrypt the SWF.</p>
<p>Also, here is a link to an AS3 obfuscator. I am not sure how well it works though.
<a href="http://www.ambiera.com/irrfuscator/index.html" rel="noreferrer">http://www.ambiera.com/irrfuscator/index.html</a></p>
|
<p>I recently released an iOS and Android game using Flash. I looked around the internet for a good free program to protect the source code in my SWF and couldn't find anything so I wrote one. It's still in development and it's "use at your own risk" but it worked for me.</p>
<p>It's released on github. Check it out and let me know what you think.</p>
<p><a href="https://github.com/Teesquared/flasturbate" rel="nofollow">https://github.com/Teesquared/flasturbate</a></p>
<p>I uploaded a windows binary but I recommend you follow the instructions to build it yourself if you want to give it a try.</p>
<p>This obfuscator works directly on the SWF file. It currently only renames symbols but it is built on a framework that could support altering bytecodes in the future.</p>
| 2,678
|
<p>I have 6 links on a page to an mp3.</p>
<p>The plugin I installed replaces those links with a swf and plays that mp3 inline.</p>
<p>The problem I <em>had</em> was that it was possible to activate all 6 links and have all audio playing at once. I <em>solved</em> that problem (I feel in a clumsy novice way though) by catching the <code><a></code> tag before it was replaced with the embed tag and then putting it back when another one was clicked.</p>
<p><strong>However, this is my problem now</strong>: the <code><a></code> tag I put back looses it's onClick event (i think that's what is happening) and so, if clicked a second time, fails to switch like the first time.</p>
<pre><code>$(".storyplayer a").bind("click", function() {
// replace the <a> tag from the previous media player installation
if (previousplayerlocation != null) {$("#" + previousplayerlocation + " .storyplayer").html(graboldcode);}
// now remember this installation's <a> tag before it's replaced
graboldcode = $(this).parent().html();
// remember where I grabbed this <a> tag from
previousplayerlocation = $(this).parents("div.storylisting").attr("id");
// replaces the <a> tag with the media player.
$(this).media({width: 190,height: 30});
return false;
});
</code></pre>
<p>Is a way to re-assign the click event to the <code>if</code> statement?</p>
|
<p>Use event delegation - this means binding the click to some container and let that handle the event. You can then query the event.target to see if it was an anchor that was clicked then do you required behaviour. This is better for a number of reasons.</p>
<ol>
<li>Less events bound to elements (performance)</li>
<li>No need to rebind events after adding/removing content as the container remains a constant and will always be there to handle the bubbled click event.</li>
</ol>
<p>The code would be something like</p>
<pre><code>$('#someContainer').click( function(ev){
var $el=$(ev.target);
if ( $el.is('a') ){
//do your stuff
}
});
</code></pre>
<p>See this <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery" rel="nofollow noreferrer">post</a> for more reading</p>
|
<p>Have a look at the <a href="http://brandonaaron.net/docs/livequery/" rel="nofollow noreferrer">livequery</a> plugin. With this plug-in you can bind event listeners even for elements that aren't available in DOM ready. </p>
<pre><code>$('a').livequery('click', function(){
});
</code></pre>
<p>The plug-in monitors the DOM and binds the listeners. You can also force the evaluation yourself:</p>
<pre><code>$.livequery.run()
</code></pre>
<p>Some other powerful features:</p>
<p>You can expire listeners:</p>
<pre><code>$('a').livequery.expire('click')
</code></pre>
<p>You can register onmatch listeners:</p>
<pre><code>$('a').livequery(
function(){ onmatchHandler},
function(){ onmismatchHandler }
);
</code></pre>
| 42,105
|
<p>I'm using jQuery in conjunction with the <a href="http://malsup.com/jquery/form/" rel="nofollow noreferrer">form plugin</a> and I'd like to intercept the form data before submission and make changes. </p>
<p>The form plugin has a property called beforeSubmit that should do this, but I seem to be having trouble getting the function I specify to run.</p>
<p>Here's the markup for the form (some style details omitted):</p>
<pre><code><form id="form1">
<fieldset id="login">
<legend>Please Log In</legend>
<label for="txtLogin">Login</label>
<input id="txtLogin" type="text" />
<label for="txtPassword">Password</label>
<input id="txtPassword" type="password" />
<button type="submit" id="btnLogin">Log In</button>
</fieldset>
</form>
</code></pre>
<p>And here's the javascript that I have so far:</p>
<pre><code>$(document).ready(function() {
var options = {
method: 'post',
url: 'Login.aspx',
beforeSubmit: function(formData, form, options) {
$.each(formData, function() { log.info(this.value); });
return true;
}
};
$('form#form1').ajaxForm(options);
});
</code></pre>
<p>(log.info() is from the <a href="http://www.gscottolson.com/blackbirdjs/" rel="nofollow noreferrer">Blackbird</a> debugger library I'm using)</p>
<p>When I click the submit button, rather than the POST verb I specified it uses a GET instead, and nothing is logged from my beforeSubmit function. It seems that the ajaxForm plugin is not being applied to the form at all, but I don't see why. Can anybody help with this?</p>
|
<p>I ran the following code through firebug and it appears to work as advertised, but the formData variable in the beforeSubmit callback is empty because you didn't set the name attribute on the text boxes.</p>
<pre><code><script type="text/javascript">
$(document).ready(function() {
var options = {
beforeSubmit: showData
};
$('form#form1').ajaxForm(options);
});
function showData(formData, form, options) {
//var formData = [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ];
$.each(formData, function(i, obj) { log.info(obj.name + " | " + obj.value); });
return true;
}
</script>
<form id="form1" action="Login.aspx" method="post">
<fieldset id="login">
<legend>Please Log In</legend>
<label for="txtLogin">Login</label>
<input id="txtLogin" type="text" name="User" />
<label for="txtPassword">Password</label>
<input id="txtPassword" type="password" name="Pass" />
<button type="submit" id="btnLogin">Log In</button>
</fieldset>
</form>
</code></pre>
|
<p>For starters, according to <a href="http://malsup.com/jquery/form/#options-object" rel="nofollow noreferrer">this API</a>, your options object should use <code>type</code> and not <code>method</code>, or just specify the method attribute on the form in the HTML. </p>
<p>(now I'll throw in a couple minor stylistic notes; you can stop reading here if you want):</p>
<ol>
<li>You can replace <code>$(document).ready(function...</code> with just <code>$(function...</code>. </li>
<li><code>$.each(formData, function...</code> looks more natural as <code>$(formData).each(function...</code></li>
</ol>
| 44,804
|
<p>I would like to know how can i escape a # in velocity. Backslash seems to escape it but it prints itself as well</p>
<p>This: </p>
<pre><code>\#\#
</code></pre>
<p>prints: </p>
<pre><code>\#\#
</code></pre>
<p>I would like: </p>
<pre><code>##
</code></pre>
|
<p>If you don't want to bother with the EscapeTool, you can do this:</p>
<pre><code>#set( $H = '#' )
$H$H
</code></pre>
|
<p>The set technique is a good way to get around any characters you need escaping, like if you want to have $name followed by "_lastname" then you can do:</p>
<pre><code>set ($n = '_lastname)
</code></pre>
<p>and have this in your template: </p>
<pre><code>$name$n
</code></pre>
<p>and it's all good.</p>
| 7,729
|
<p>Simple question really - how do I use <code>text_field_with_auto_complete</code> inside a <code>form_for</code> block?</p>
<p>I've tried doing <code>f.text_field_with_auto_complete</code> but that gives an error, and just using <code>text_field_with_auto_complete</code> by itself doesn't seem to do anything.</p>
<p>Am I missing something here?</p>
|
<p>I personally use this:</p>
<pre><code><%= f.text_field :name, :autocomplete => "off" %><div class="auto_complete" id="customer_name_auto_complete"></div>
</code></pre>
<p>And add the auto-generated Javascript and CSS manually. Here's the Javascript:</p>
<pre><code>new Ajax.Autocompleter('customer_name', 'customer_name_auto_complete', '/customers/auto_complete_for_customer_name', {
method:'get',
paramName:'customer[name]',
minChars: 3
});
</code></pre>
<p>and here's the CSS:</p>
<pre><code>div.auto_complete {
width: 350px;
background: #fff;
}
div.auto_complete ul {
border:1px solid #888;
margin:0;
padding:0;
width:100%;
list-style-type:none;
}
div.auto_complete ul li {
margin:0;
padding:3px;
}
div.auto_complete ul li.selected {
background-color: #ffb;
}
div.auto_complete ul strong.highlight {
color: #800;
margin:0;
padding:0;
}
</code></pre>
|
<p>I had this problem too, but the solution I used might not apply to you.</p>
<p>Since the object I was querying in the autocomplete belonged to a different model, I used a fields_for like this, which solved the autocomplete problem.</p>
<pre><code><% fields_for :model, @formobject.model do %>
<p>
<%= text_field_with_auto_complete :object, :field, :skip_style => true %>
</p>
<% end %>
</code></pre>
<p>Good luck!</p>
| 30,361
|
<p>I've got an Anycubic Predator (aka Anycubic D). I followed the official instructions and leveled my printer. </p>
<p>The first annoying problem I ran into is that after the auto-leveling, the level test printing shows that the printer wasn't leveled at all. I tried about 4-5 times, and finally leveled the printer (I thought I just got lucky).</p>
<p>The second problem that isn't solved is that the prints I get are of poor quality. Shown in <em>figure 1</em> and <em>figure 2</em>. The cube should be 20x20x20 mm, but what I got here is 19.6(x) x 20.4(y) x 20.5(z) mm.</p>
<p><a href="https://i.stack.imgur.com/xeclv.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xeclv.jpg" alt="fig1"></a>
<em>Figure 1 - X-Y (side) view of calibration square</em></p>
<p><a href="https://i.stack.imgur.com/4YkU0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4YkU0.jpg" alt="fig2"></a>
<em>Figure 2 - Z (top) view of calibration square</em></p>
<p>Does anyone have any idea about how to improve the printer's printing quality? Thanks in advance.</p>
|
<p>A wide line works if there is something below it to squeeze the filament against, but if you don't have a full layer below it, it will stay thinner and it will droop. I would not use extreme ratios on overhangs. Still, do a parametric test: a overhang tower (a compact one) at different line widths and layer heights. If you test 3 layer heights and 3 line widths, it's only 9 short prints.</p>
<p>However, as you can see in filament reviews, different materials behave differently. I think there is no <em>a priori</em> optimal value.</p>
|
<p>In terms of Cura's model for showing overhangs, I'm nearly sure it's just the ratio - rise over run, or rather run over rise. And indeed that's what makes sense mathematically:</p>
<p>At least some portion of the wall extrusion in layer N+1 needs to sit on top of the corresponding wall extrusion in layer N. For a given 3D surface slope, the "run" - the distance the cross-section moves from one layer to the next, which needs to be bounded by some fraction of the line width - varies proportionally to the "rise" - the layer height.</p>
| 1,664
|
<p>I have an XML definition that contains an element with child elements. For example:</p>
<pre><code><a>
<b>
<c>C</c>
<d>D</d>
</b>
</a>
</code></pre>
<p>I have an XSLT with an output of text. For example:</p>
<pre><code><xsl...>
<xsl:output method="text" indent="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/a/b" />
...
</code></pre>
<p>I want to copy the entire b element and its children into a whitespace-removed string so that I can generate a SQL query. For example:</p>
<pre><code>select * from some-table where xml = '<b><c>C</c><d>D</d></b>'
</code></pre>
<p>At the moment copy-of is finding the b element but dropping off all element and attribute information leaving only the text content within each. I think this might be to do with the output type.</p>
<p>Any ideas?</p>
|
<p>Your SQL statement scares me. XML is case-sensitive, and your comparison there is likely to fail if the input XML and XSLT (including all elements, attributes, and values) aren't cased exactly like that used in the original database insert.</p>
<p>I believe both Oracle (certain) and SQL Server (think so) have mechanisms to do a query against a column containing XML in a more XML-friendly way (for instance, using XPath).</p>
<p>What exactly are you trying to do? Your problem seems deeper than just getting this XSLT to transform correctly.</p>
|
<p>Here is how it can be done:</p>
<pre><code><xsl:output method="xml" />
<xsl:template match="/"><xsl:apply-templates select="/a/b" mode="normalize-space" /></xsl:template>
<xsl:template match="text()" mode="normalize-space"><xsl:value-of select="normalize-space(.)" /></xsl:template>
<xsl:template match="@*|node()" mode="normalize-space"><xsl:copy><xsl:apply-templates select="@*|node()" mode="normalize-space" /></xsl:copy></xsl:template>
</code></pre>
<p>This method copies nodes, nodes with namespaces and attributes.</p>
<p>Method requires output to be "xml" (not "text" as in original sample). It uses custom template for all TEXT nodes to normalize space inside them (remove leading/trailing whitespace, condense multiple spaces into a single space). Then, it uses simple "identity" template that copies all nodes and their attributes. Both templates use special mode to not to interfere with the rest of XSL.</p>
<p>Unforunately, XSLT processor copies all "unknown" nodes inside xsl:template tag into output document and spaces are one of such nodes. That's why all those templates need to be written in one line with no extra spaces.</p>
<p>PS Although, I agree that searching a normalized XML in RDBMS is kind of weird.</p>
| 41,259
|
<p>I have a custom action in a workflow and would like to report an error to the user when something goes wrong. What's the best way of doing that?</p>
<p><strong>UPD:</strong> Ideally I would like to put the workflow in the error state and log a message to the workflow log. That doesn't seem possible. What's the closest I can get to it? I want to a reusable solution,something that's easy for users to set up when using my custom action in SharePoint Designer.</p>
<hr>
<p>Added more details to the question.</p>
<p>@mauro that takes care of storing the error, but how do I display the error to the user in a way which makes sense?</p>
<p>@AdamSane That's seems like a rather fragile solution. It's not a matter of setting this up once on a single site. I need something others can add using SPD.</p>
|
<p>when you throw the error your error handler can then email the user, or better if the list is massive, add the error state to the workflow item - i think this is default functionality though as the error would be mentioned there.</p>
<p><a href="http://www.sharepointsecurity.com/blog/sharepoint/sharepoint-2007-development/fault-handling-in-sharepoint-workflows/" rel="nofollow noreferrer">http://www.sharepointsecurity.com/blog/sharepoint/sharepoint-2007-development/fault-handling-in-sharepoint-workflows/</a></p>
|
<p>Add the error to a hidden list with that users name. Set the visibility on the list (for users) to only read/write their own values. Then use a custom web part or FlexListViewer to view the contents of that list and display it to the user. Once they acknowledge that error, remove it from the list.</p>
<p>If necessary, you can add a different workflow action on that message list, that says pause for 2 days and then email. Whatever, depending on your requirements.</p>
<p>Otherwise you can have a custom db table that you use for pretty much the same thing, this way sharepoint does most of the work for you.</p>
<p><strong>Update</strong> This can be packaged up as a feature and deployed to each site as needed. The strengths of this approach (adding a list item to a list, querying, alerting a user, and emailing a user) are all built into the sharepoint itself. In this case you can focus on your custom logic only, while letting sharepoint focus on the implementation details.</p>
| 3,688
|
<p>We have a page of search results which the user can hit in several ways. 90% of the ways will set up a 'Search Criteria' session object, which the results page will use to retrieve the search results.</p>
<p>When the session object isn't found, we will typically show the user an 'invalid search' message, and give them a link to the main search page.</p>
<p>The exception is the case where the user hits a webpage which has the search results page as it's default page (we use .NET's themes to provide private labels for our site, skinning it with our affiliates' colors and logos). If the search results page is the default page for the site, there is a special search that is preformed when there is no session criteria.</p>
<p>This is working fairly well in our testing, but there is an edge case we would like to handle: When a session expires while someone is on the search results page (having come from the search page) and they then click on the next page of results, they will get this special search instead of the 'expired session' message.</p>
<p>This is the basic format we're using, where searchCriteria is set from session.</p>
<pre><code>if (searchCriteria == null)
{
if (/*Check if this is the default url for this site*/)
{
//Preform special search
}
else
{
//Display 'session expired message'
}
}
</code></pre>
<p>Is there a way we can check Session in the inner if block to see if the user's session is new due to expiration of an existing? Or do browsers just throw away the session cookies when they expire?</p>
<p>Is there a browser difference? Do some return the expired session cookie to the server, while other's delete them on expiration? Or is it consistent?</p>
|
<p>This is an excellent <a href="http://www.eggheadcafe.com/articles/20051228.asp" rel="noreferrer">article</a> which is based off of <a href="http://aspalliance.com/520" rel="noreferrer">this one</a>. I think you will find your answers here (Page 2 of the second article specifically)</p>
|
<p>All the browsers will return the expired session cookie. They'll do so until the browser is restarted or it's rewritten by a server response.</p>
<p>The answer from bnkdev uses this fact to detect new vs expired by seeing if the cookie is already set. It's simple and easy and will likely work for you, but it only works when cookies are used for session ids. It won't work for cookieless sessions.</p>
<p>Also, rather than hard coding "ASP.NET_SessionId", you should probably fetch it from the cookieName attribute of the sessionState configuration element.</p>
| 44,036
|
<p>I've created a seperate assembly with a class that is intended to be
published through wmi. Then I've created a windows forms app that
references that assembly and attempts to publish the class. When I try to
publish the class, I get an exception of type
System.Management.Instrumentation.WmiProviderInstallationException. The
message of the exception says "Exception of type
'System.Management.Instrumentation.WMIInfraException' was thrown.". I have
no idea what this means. I've tried .Net2.0 and .Net3.5 (sp1 too) and get the same results.</p>
<p>Below is my wmi class, followed by the code I used to publish it.</p>
<pre><code>//Interface.cs in assembly WMI.Interface.dll
using System;
using System.Collections.Generic;
using System.Text;
[assembly: System.Management.Instrumentation.WmiConfiguration(@"root\Test",
HostingModel =
System.Management.Instrumentation.ManagementHostingModel.Decoupled)]
namespace WMI
{
[System.ComponentModel.RunInstaller(true)]
public class MyApplicationManagementInstaller :
System.Management.Instrumentation.DefaultManagementInstaller { }
[System.Management.Instrumentation.ManagementEntity(Singleton = true)]
[System.Management.Instrumentation.ManagementQualifier("Description",
Value = "Obtain processor information.")]
public class Interface
{
[System.Management.Instrumentation.ManagementBind]
public Interface()
{
}
[System.Management.Instrumentation.ManagementProbe]
[System.Management.Instrumentation.ManagementQualifier("Descriiption",
Value="The number of processors.")]
public int ProcessorCount
{
get { return Environment.ProcessorCount; }
}
}
}
</code></pre>
<p><BR/></p>
<pre><code>//Button click in windows forms application to publish class
try
{
System.Management.Instrumentation.InstrumentationManager.Publish(new
WMI.Interface());
}
catch (System.Management.Instrumentation.InstrumentationException
exInstrumentation)
{
MessageBox.Show(exInstrumentation.ToString());
}
catch (System.Management.Instrumentation.WmiProviderInstallationException
exProvider)
{
MessageBox.Show(exProvider.ToString());
}
catch (Exception exPublish)
{
MessageBox.Show(exPublish.ToString());
}
</code></pre>
|
<p>To summarize, this is the final code that works:</p>
<p>Provider class, in it's own assembly:</p>
<pre><code>// the namespace used for publishing the WMI classes and object instances
[assembly: Instrumented("root/mytest")]
using System;
using System.Collections.Generic;
using System.Text;
using System.Management;
using System.Management.Instrumentation;
using System.Configuration.Install;
using System.ComponentModel;
namespace WMITest
{
[InstrumentationClass(System.Management.Instrumentation.InstrumentationType.Instance)]
//[ManagementEntity()]
//[ManagementQualifier("Description",Value = "Obtain processor information.")]
public class MyWMIInterface
{
//[System.Management.Instrumentation.ManagementBind]
public MyWMIInterface()
{
}
//[ManagementProbe]
//[ManagementQualifier("Descriiption", Value="The number of processors.")]
public int ProcessorCount
{
get { return Environment.ProcessorCount; }
}
}
/// <summary>
/// This class provides static methods to publish messages to WMI
/// </summary>
public static class InstrumentationProvider
{
/// <summary>
/// publishes a message to the WMI repository
/// </summary>
/// <param name="MessageText">the message text</param>
/// <param name="Type">the message type</param>
public static MyWMIInterface Publish()
{
// create a new message
MyWMIInterface pInterface = new MyWMIInterface();
Instrumentation.Publish(pInterface);
return pInterface;
}
/// <summary>
/// revoke a previously published message from the WMI repository
/// </summary>
/// <param name="Message">the message to revoke</param>
public static void Revoke(MyWMIInterface pInterface)
{
Instrumentation.Revoke(pInterface);
}
}
/// <summary>
/// Installer class which will publish the InfoMessage to the WMI schema
/// (the assembly attribute Instrumented defines the namespace this
/// class gets published too
/// </summary>
[RunInstaller(true)]
public class WMITestManagementInstaller :
DefaultManagementProjectInstaller
{
}
}
</code></pre>
<p>Windows forms application main form, publishes provider class:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Management.Instrumentation;
namespace WMI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
WMITest.MyWMIInterface pIntf_m;
private void btnPublish_Click(object sender, EventArgs e)
{
try
{
pIntf_m = WMITest.InstrumentationProvider.Publish();
}
catch (ManagementException exManagement)
{
MessageBox.Show(exManagement.ToString());
}
catch (Exception exPublish)
{
MessageBox.Show(exPublish.ToString());
}
}
}
}
</code></pre>
<p>Test web application, consumer:</p>
<pre><code>using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Management.Instrumentation;
using System.Management;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ManagementClass pWMIClass = null;
pWMIClass = new ManagementClass(@"root\interiorhealth:MyWMIInterface");
lblOutput.Text = "ClassName: " + pWMIClass.ClassPath.ClassName + "<BR/>" +
"IsClass: " + pWMIClass.ClassPath.IsClass + "<BR/>" +
"IsInstance: " + pWMIClass.ClassPath.IsInstance + "<BR/>" +
"IsSingleton: " + pWMIClass.ClassPath.IsSingleton + "<BR/>" +
"Namespace Path: " + pWMIClass.ClassPath.NamespacePath + "<BR/>" +
"Path: " + pWMIClass.ClassPath.Path + "<BR/>" +
"Relative Path: " + pWMIClass.ClassPath.RelativePath + "<BR/>" +
"Server: " + pWMIClass.ClassPath.Server + "<BR/>";
//GridView control
this.gvProperties.DataSource = pWMIClass.Properties;
this.gvProperties.DataBind();
//GridView control
this.gvSystemProperties.DataSource = pWMIClass.SystemProperties;
this.gvSystemProperties.DataBind();
//GridView control
this.gvDerivation.DataSource = pWMIClass.Derivation;
this.gvDerivation.DataBind();
//GridView control
this.gvMethods.DataSource = pWMIClass.Methods;
this.gvMethods.DataBind();
//GridView control
this.gvQualifiers.DataSource = pWMIClass.Qualifiers;
this.gvQualifiers.DataBind();
}
}
}
</code></pre>
|
<p>I used gacutil - installutil to to test your class (as a dll). The gacutil part worked, but installutil (actually mofcomp) complained about a syntax error:</p>
<p>...</p>
<p>error SYNTAX 0X80044014:
Unexpected character in class name (must be an identifier)</p>
<p>Compiler returned error 0x80044014</p>
<p>...</p>
<p>So I changed the class name to 'MyInterface' the installutil part worked, but the class didn't return any instances. Finally I changed the hosting model to Network Service and got it to work.</p>
| 9,110
|
<p>I am using a service component through ASP.NET MVC.
I would like to send the email in a asynchronous way to let the user do other stuff without having to wait for the sending.</p>
<p>When I send a message without attachments it works fine.
When I send a message with at least one in-memory attachment it fails.</p>
<p>So, I would like to know if it is possible to use an async method with in-memory attachments.</p>
<p>Here is the sending method</p>
<pre><code>
public static void Send() {
MailMessage message = new MailMessage("from@foo.com", "too@foo.com");
using (MemoryStream stream = new MemoryStream(new byte[64000])) {
Attachment attachment = new Attachment(stream, "my attachment");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
smtp.Credentials = new NetworkCredential("foo", "bar");
smtp.SendAsync(message, null);
}
}
</code></pre>
<p>Here is my current error</p>
<pre><code>
System.Net.Mail.SmtpException: Failure sending mail.
---> System.NotSupportedException: Stream does not support reading.
at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult)
at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)
--- End of inner exception stack trace ---
</code></pre>
<hr>
<p>Solution</p>
<pre><code> public static void Send()
{
MailMessage message = new MailMessage("from@foo.com", "to@foo.com");
MemoryStream stream = new MemoryStream(new byte[64000]);
Attachment attachment = new Attachment(stream, "my attachment");
message.Attachments.Add(attachment);
message.Body = "This is an async test.";
SmtpClient smtp = new SmtpClient("localhost");
//smtp.Credentials = new NetworkCredential("login", "password");
smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
System.Diagnostics.Trace.TraceError(e.Error.ToString());
}
MailMessage userMessage = e.UserState as MailMessage;
if (userMessage != null)
{
userMessage.Dispose();
}
};
smtp.SendAsync(message, message);
}
</code></pre>
|
<p>Don't use "using" here. You are destroying the memory stream immediately after calling SendAsync, e.g. probably before SMTP gets to read it (since it's async). Destroy your stream in the callback.</p>
|
<p>I have tried your function and it works even for email with in memory attachments. But here are some remarks:</p>
<ul>
<li>What type of attachments did you try to send ? Exe ?</li>
<li>Are both sender and receiver on the same email server ?</li>
<li>You should “catch” exception and not just swallow it, than you will get more info about your problem.</li>
<li><p>What does the exception says ?</p></li>
<li><p>Does it work whan you use Send instead of SendAsync ? You are using 'using' clause and closing Stream before email is sent.</p></li>
</ul>
<p>Here is good text about this topic:</p>
<p><a href="http://blogs.claritycon.com/blog/2006/01/sending-mail-in-net-2-0/" rel="nofollow noreferrer">Sending Mail in .NET 2.0</a></p>
| 35,385
|
<p>In short: How do you specify a BIGINT in Django models?</p>
<p>In a current project I am doing using Django (0.97-svn release), I've all the integer fields in all the models defined as IntegerField. It was working immaculately during the development cycle where I was using SQLite for the DB backend. However, as soon as I rolled off to MySQL, I noticed that for one of the IntegerFields, MySQL was truncating data---apparently, for reasons still unknown to me, SQLite didn't complain. I looked at the schema and found out that an IntegerField in Django is represented as an INT(11) field in MySQL. Naturally, the reason MySQL was truncating data was because the data was more than 11-digit in length. To workaround, I had to manually update the column to, in this case, be a BIGINT(20). Django and MySQL coexist peacefully with that. But whenever I reset the application in which rests the model containing that BIGINT, Django again creates it as an INT(11). I've looked at Django docs, and not found anything. Have I overlooked something?</p>
<p>Thanks.</p>
|
<p><a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#bigintegerfield" rel="noreferrer">BigIntegerField</a> was added in changeset 11887, 2009-12-17 09:10:38 and is part of Django 1.2 and newer.</p>
|
<p>Try a DecimalField.</p>
| 35,978
|
<p>We have are relatively simple Reporting Services report that our users commonly export to Excel. I've noticed that the files produced by the Excel export seem unusually large. If I open one of these files and just click save, without making any changes, the file size reduces to about half of it's previous size. Has anyone else run into this and is there a known workaround?</p>
|
<p>You've mentioned that the report is relatively simple, but this is important to check. The export to Excel will go to extraordinary lengths to try and maintain how your report looks.</p>
<p>If you have lots of different borders or colours (particularly if different formatting is determined by the data in your report) this will bloat the file.</p>
<p>Also check if many columns with very small and unusual sizes are created in the exported worksheet. The export does this to try and match alignment in Excel with the original report.</p>
<p>Try recreating your report as a basic table with no formatting or headers/footers and see if you can reproduce the problem. If Excel's behaviour is acceptable then add each piece of formatting back until it goes awry. Please let us know what you find.</p>
|
<p>May be I am answering your question very late. Here's the solution for exporting to CSV.</p>
<p>You need to give the a name that you want to see as a column header for the field (not the column name) in the designer.</p>
<p>By default all the text headers are exported as a separate columns along with the table columns and make sure that you name the Design name in the properties with the name you want to see.</p>
<p>The other important thing to note about the option <code>DataElementOutput</code> which is set to Auto meaning it will be exported. You can change that if you don't want it to be exported.</p>
<p>The last but not least thing ... after you export the data looks messed up. You need select the whole first column and go to the <code>Data tab</code> - > <code>convert text to column</code> -> <code>use the delimiter</code> as comma and say Finish. That should solve your issue.</p>
| 30,271
|
<p>I am looking for a program to make mockup screenshots with. I first found out I could do it with Visual Basic (uglier names I have yet to hear a programming language being called) from <a href="http://www.joelonsoftware.com/articles/fog0000000033.html" rel="nofollow noreferrer">joelonsoftware.com</a>. I don't want to start learning VB now, especially since I am still in the process of learning Java. I then found <a href="http://www.mockupscreens.com" rel="nofollow noreferrer">mockupscreens.com</a>, with the searchstring "how to make mockup screenshots". But seeing as I am going to use this program quite infrequently, I don't think paying $80 for it is worth it.</p>
<p>The mockups I'd like to do would be mainly for Windows XP (perhaps also for GNOME, KDE and Mac OSX, but these are not top-priority).</p>
<p>Edit: Balsamiq is suggested, but this is also a non-free program.</p>
|
<p><a href="http://www.balsamiq.com/" rel="nofollow noreferrer">Balsamiq</a></p>
|
<p>wxGlade would work as well, plus it's free software.</p>
| 38,482
|
<p>I just want a quick way (and preferably not using a while loop)of createing a table of every date between date @x and date @y so I can left outer join to some stats tables, some of which will have no records for certain days in between, allowing me to mark missing days with a 0</p>
|
<p>Strictly speaking this doesn't exactly answer your question, but its pretty neat.</p>
<p>Assuming you can live with specifying the number of days after the start date, then using a Common Table Expression gives you:</p>
<pre><code>WITH numbers ( n ) AS (
SELECT 1 UNION ALL
SELECT 1 + n FROM numbers WHERE n < 500 )
SELECT DATEADD(day,n-1,'2008/11/01') FROM numbers
OPTION ( MAXRECURSION 500 )
</code></pre>
|
<p>Just: WHERE col > start-date AND col < end-date</p>
| 12,087
|
<p>Linux 2.6.18-92.el5, ruby 1.8.7, Rails 2.2.2, mysql gem 2.7</p>
<p>I installed the MySQL binary distribution under /usr/local, then installed the mysql gem like this:</p>
<pre><code>gem install mysql --no-rdoc --no-ri \
-- --with-mysql-include=/usr/local/mysql/include \
--with-mysql-lib=/usr/local/mysql/lib \
--with-mysql-config=/usr/local/mysql/bin/mysql_config
</code></pre>
<p>When I run <code>irb> require 'mysql'</code> I get the error shown below:</p>
<pre><code>irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'mysql'
LoadError: libmysqlclient.so.16: cannot open shared object file:
No such file or directory -
/usr/local/lib/ruby/gems/1.8/gems/mysql-2.7/lib/mysql.so
from /usr/local/lib/ruby/gems/1.8/gems/mysql-2.7/lib/mysql.so
from /usr/local/lib/ruby/site_ruby/1.8/rubygems/
custom_require.rb:36:in `require' from (irb):2
</code></pre>
<p>After some Googling I found that I could use <code>ldconfig</code> to configure
mysql.so to be available to the whole system. Once I added "/usr/local/
mysql/lib" to /etc/ld.so.conf and ran ldconfig, it worked fine:</p>
<pre><code>irb(main):002:0> require 'rubygems'
=> true
irb(main):003:0> require 'mysql'
=> true
</code></pre>
<p>OK, so I got it to work. But my question is, why was I getting that error? You used to be able to just <code>gem install mysql</code> and it would work. Has anyone else encountered the same error? Using <code>ldconfig</code> seems kind of brittle and unmaintainable. Is there a better solution?</p>
<p>Any insight would be greatly appreciated.</p>
<p>Thanks,</p>
<p>Ethan</p>
|
<p>I had issues as well (on Mac OS X), and was just as frustrated that <code>gem install mysql</code> wasn't as simple as it used to be.</p>
<p>The short-sighted answer is that the mysql gem needs to build native extensions, and to do that, it needs some path information (specific to your system) about MySQL libraries. The most reliable way to get that information is for you to provide it.</p>
<p>The larger answer is that this is a design bug in the gem system. When nearly every other gem installs with <code>gem install foo</code>, the system and the gem submitters need to provide users with some kind of instruction for important exceptional cases - even if it's just feedback with the error message that tells you that you must provide more information to install this gem, and what that information is.</p>
<p>A bit of googling around eventually got me to the answer, but got me a lot more instances of other people blindsided by a simple process that turned complex without warning.</p>
|
<p>Possibly it had something to do with the prefix you used when installing mysql?
--with-mysql-lib=/usr/local/mysql/lib</p>
<p>Presumably, if that been /usr/local/lib (or somewhere ldconfig was already set to look) and/or if you had just used a top-level prefix of something like /usr/local, you may not have run into problems(?)</p>
| 44,508
|
<p>In one of my applications I have a 1gb database table that is used for reference data. It has a huge amounts of reads coming off that table but there are no writes ever. I was wondering if there's any way that data could be loaded into RAM so that it doesn't have to be accessed from disk?</p>
<p>I'm using SQL Server 2005</p>
|
<p>If you have enough RAM, SQL will do an outstanding job determining what to load into RAM and what to seek on disk. </p>
<p>This question is asked a lot and it reminds me of people trying to manually set which "core" their process will run on -- let the OS (or in this case the DB) do what it was designed for.</p>
<p>If you want to verify that SQL is in fact reading your look-up data out of cache, then you can initiate a load test and use Sysinternals <a href="http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx" rel="nofollow noreferrer">FileMon</a>, <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx" rel="nofollow noreferrer">Process Explorer</a> and <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">Process Monitor</a> to verify that the 1GB table is not being read from. For this reason, we sometimes put our "lookup" data onto a separate filegroup so that it is very easy to monitor when it is being accessed on disk.</p>
<p>Hope this helps.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/ms178015(SQL.90).aspx" rel="nofollow noreferrer">DBCC PINTABLE</a> will explicitly pin a table in core if you want to make sure it remains cached.</p>
| 6,454
|
<p>I have a java String that contains the unicode character U+9996 (that's what I get if I do codePointAt()). </p>
<p>If I look at it in the debugger expressions panel (in eclipse) then all is well and it looks like "<strong>首</strong>". However if I print it out to the console I get simply "<strong>?</strong>". It doesn't seem to be the font that's the problem as I've tried setting that differently.</p>
<p>My real problem is that I'm trying to put the string into a MySQL database (with utf8 encoding). Lots of other wide characters show up fine in the db but, again, this one and some others like it show up as "?". All of which leads me to believe that the problem is on the java side.</p>
<p>In chasing down this bug I've learnt a little about <a href="http://en.wikipedia.org/wiki/Unicode_normalization" rel="nofollow noreferrer">Unicode Normalization</a> and java.text.<a href="http://java.sun.com/javase/6/docs/api/java/text/Normalizer.html" rel="nofollow noreferrer">Normalizer</a> which looks like it might be relevant in this case. I've learnt that U+9996 is the canonical version of U+2FB8. U+2FB8 has exactly the same problems above though as regards display and anyway why would I want to transform to a non-canonical representation (even if I could, which I don't think I can)?</p>
<p>Anyway, there's one potential clue I've found which I've been unable to comprehend. <a href="http://www.fileformat.info/info/unicode/char/9996/index.htm" rel="nofollow noreferrer">This page</a> contains the words "U+9996 is not a valid unicode character" with no further explanation. It then proceeds to show how to encode this supposedly non-valid unicode character in various unicode encodings. So my question is this basically: WTF?</p>
<hr>
<h2>UPDATES</h2>
<ul>
<li>I'm on a Mac.</li>
<li>I'm talking about the Eclipse console.
<ul>
<li>I set the console encoding to UTF-8 under Run > Common</li>
<li>I added <code>-Dfile.encoding=UTF-8</code> to the JVM arguments (the default was MacRoman)</li>
<li>The console (Eclipse and Terminal.app) now show the right chars. Hooray!</li>
</ul></li>
<li>I'm mostly interested in the data getting into the database correctly though of course I'd like to get a total understanding of what's going on here. </li>
<li>I think I've fixed the database problem. I forgot to set the encoding on the <em>connection</em>. Now I don't understand why some asian characters were getting through and not others.</li>
<li>Phew, stackoverflow moves fast. It's hard to keep up. Thanks people.</li>
</ul>
|
<p>Have you verified that the value that gets stored in the database is actually U+003f (question mark)? There are all sorts of conventions for how to display characters that don't exist in the chosen font, and displaying them as ?' is fairly common.</p>
<p>So most likely, the character gets stored correctly, and for whatever reasons, simply gets displayed as '?'. Basically, ignore how it gets rendered, and look at what codepoint gets stored in the database. Is it U+9996 or U+003f (or something else entirely)?
Don't blindly assume that just because it gets rendered as a question mark, it is actually a question mark that is stored in the database.</p>
|
<p>I don't know about the problems, but it's <a href="http://unicode.org/cgi-bin/GetUnihanData.pl?codepoint=9996" rel="nofollow noreferrer">definitely a valid Unicode character</a> (and has been since Unicode 1.1).</p>
| 44,512
|
<p>I'm trying to pull data from an ODBC app to SQL2005(dev ed) DB on an hourly basis. When I run SSIS the option to import all tables and views is grayed out and forces your to write a query. How would I go about setting up a SSIS integration service to update ALL 250 some tables on an hourly basis. </p>
|
<p>What kind of database is your ODBC data source pointing to? SSIS might not give you a GUI for selecting tables/views for all DB types.</p>
|
<p>perhaps you could rephrase your question a little, I am not 100% sure what you are asking here. Are you trying to get data into SQL Server from an application via SSIS with the Data Transform task using an ODBC connection to the Application? </p>
<p>Anyhoo, the simple answer to the MS Access part of your question is "hell no" MS Access is never, ever the answer to anything ;-)</p>
<p>I would be inclined to find out why the tables and views are greyed out and fix that issue. (not enough info in this question to determine why they are greyed out)</p>
| 35,736
|
<p>A few years ago I worked on a system where a numeric primary key was stored in a [SQL Server] varchar column, so I quickly came unstuck when querying with a BETWEEN operator:</p>
<pre><code>SELECT ID FROM MyTable WHERE ID BETWEEN 100 AND 110;
</code></pre>
<p>Results:</p>
<pre><code>100
102
103
109
110
11
</code></pre>
<p>This was simply bad design. However, I'm working on an 3rd-party ERP system, which as you can imagine needs to be generic and flexible; thus we have various tables where alphanumeric fields are provided where the business only uses numerics - so similar problems can occur.</p>
<p>I'm guessing that this is a common enough issue; I have a simple enough solution, but I'm curious as to how others approach such problems.</p>
<p>My simple solution is:</p>
<pre><code>SELECT ID FROM MyTable
WHERE ID BETWEEN iStartValue AND iEndValue
AND (LENGTH(ID) = LENGTH(iStartValue)
OR LENGTH(ID) = LENGTH(iEndValue));
</code></pre>
<p>As you can possibly tell, this is an Oracle system, but I'm usually working in SQL Server - so perhaps database-agnostic solutions are preferable.</p>
<p>Edit 1: Scratch that - I don't see why proprietary solutions aren't welcomed as well.</p>
<p>Edit 2: Thanks for all the responses. I'm not sure whether I'm disappointed there is not an obvious, sophisticated solution, but I'm correspondingly glad that it doesn't appear that I've missed anything obvious!</p>
<p>I think I still prefer my own solution; it's simple and it works - is there any reason why I shouldn't use it? I can't believe it is much, if any, less efficient that the other solutions offered.</p>
<p>I realise that in an ideal world, this problem wouldn't exist; but unfortunately, I don't work in an ideal world, and often it's a case of making the best of a bad situation.</p>
|
<p>If you're sure that the values in ID are numeric only, why not just CAST them</p>
<pre><code>WHERE CAST(ID as int) BETWEEN iStartValue AND iEndValue
</code></pre>
<p>EDIT 1:
An extension to the casting method which should work is to use a sub-query to pull out all numeric records. Please note - I do not think this method is better than the one suggested above, I include it as it answers the problem!!!</p>
<pre><code>SELECT ID
FROM (
SELECT ID
FROM MyTable
WHERE ISNUMERIC(ID) = 1
AND CHARINDEX ('.', ID) = 0
AND CHARINDEX ('-', ID) = 0
) a
WHERE CONVERT(bigint, ID) BETWEEN 0 AND 12000
ORDER BY LENGTH(ID) ASC, ID
</code></pre>
<p>The check for "-" and "." characters isn't really required. I'm assuming your IDs can't be negative or decimal. </p>
|
<p>How about a cast instead.</p>
<pre><code>SELECT ID FROM MyTable
WHERE cast(ID as signed) BETWEEN cast(iStartValue as signed) AND cast(iEndValue as signed)
</code></pre>
<p>This syntax given is MySQL but there are similar CAST operators for T-SQl.</p>
| 46,457
|
<p>How can I write G-code for a triangle without sharp tips?</p>
<p><a href="https://i.stack.imgur.com/T0hpu.jpg" rel="nofollow noreferrer" title="Example of required triangle"><img src="https://i.stack.imgur.com/T0hpu.jpg" alt="Example of required triangle" title="Example of required triangle"></a></p>
<p>I want to generate the corners manually, rather than using a slicer to generate them, just to know how it is done.</p>
|
<p>First, convert the given measurements into a sketch...</p>
<p><a href="https://i.stack.imgur.com/ivxIW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ivxIW.png" alt="Sketched out dimensions" /></a></p>
<h2>G-code shenanigans</h2>
<p>we actually have the printer do circles.. let's plot that out...</p>
<p><a href="https://i.stack.imgur.com/hGFSc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hGFSc.png" alt="Plotted all start-ends and centers" /></a></p>
<p>Using that, it's easy to write the G-code using the Documentation for <a href="http://marlinfw.org/docs/gcode/G000-G001.html" rel="nofollow noreferrer">G1</a> and <a href="http://marlinfw.org/docs/gcode/G002-G003.html" rel="nofollow noreferrer">G2</a>. You'll have to add the E values to extrude something along the paths, but your sketch would turn into this path:</p>
<pre><code>G92 X0 Y0 ; the current position is now (0,0) on the XY
G90 ;Abolute mode for everything...
M83 ;...but for the E-argument, so you can just put the length into the extrusions that are to be done
G0 X10.66 Y2
G2 R5 X6.33 Y9.5 ; Alternate: G3 I0 J5 X6.33 Y9.5
G1 X45.66 Y77.638
G2 R5 X54.33 Y77.638 ; Alternate: G3 I4.33 Y-2.5 X54.33 Y77.638
G1 93.67 Y9.5
G2 R5 X89.33 Y2 ; Alternate: G3 I-4.33 Y-2.5 X89.33 Y2
G1 X10.66 Y2
G0 X0 Y0
G91 ; return to relative coordinates
</code></pre>
<p><strong>This code has to be prefixed by a move to where you want to start the pattern</strong> and will <strong>not</strong> know if you move it off the build plate, so keep 100 mm X and 87 mm in Y of the allowable build plate. It will end exactly where you started it.</p>
<h2>Iterative approach</h2>
<p>In many uses of g-code, <em>rounded</em> corners are actually n-gons with a very high number n. then we only need <code>G1</code> and can easily calculate the length of the stretches and fill in the G1. We need to iterate down to somewhat circular...</p>
<p>Let's start iterating with n=3 aka a triangle, which gives a direct line over the corner gives this:</p>
<p><a href="https://i.stack.imgur.com/ANEnx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ANEnx.png" alt="Iteration 1" /></a></p>
<p>going to n=6 (hexagon) follows the curve a lot better...</p>
<p><a href="https://i.stack.imgur.com/JRSMV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JRSMV.png" alt="Iteration 2" /></a></p>
<p>going to n=12 looks almost round on a larger scale...</p>
<p><a href="https://i.stack.imgur.com/STTXL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/STTXL.png" alt="Iteration 3" /></a></p>
<p>and when we reach n=24, we are pretty close to the circle..</p>
<p><a href="https://i.stack.imgur.com/rO7dr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rO7dr.png" alt="iteration 4" /></a></p>
<p>And as we go above n=6, we also get easier math for the corners, as we always get the same lengths of movement along X and Y just swapped around due to symmetry.</p>
<p>With all these stretches defined, we could start to work in <em>relative</em> coordinates easily, again without E, and only for the bottom left corner:</p>
<pre><code>G0 X10.66 Y2
G1 X-1.294 Y0.17
G1 X-1.206 Y0.5
G1 X-1.036 Y0.795
G1 X-0.795 X1.036
G1 X-0.5 Y1.206
G1 X-0.17 Y1.294
G1 X0.17 Y1.294
G1 X0.5 Y1.036
...
</code></pre>
|
<p>Marlin has <code>G2</code> (clockwise arc) and <code>G3</code> (counterclockwise arc) commands that could be used to do this. <a href="http://marlinfw.org/docs/gcode/G002-G003.html" rel="nofollow noreferrer">You can find detailed documentation for the command here.</a></p>
<p>Basically, you can use</p>
<blockquote>
<p>G2 R1 X5 Y5</p>
</blockquote>
<p>to draw a (clockwise) arc from the current position to <span class="math-container">$(X,Y)=(5,5)$</span> with a radius of <span class="math-container">$1$</span>.</p>
<p>So, your rounded triangle could be drawn with 3 straight line moves and 3 arc moves. Figuring out the exact coordinates for each move would be a quite challenging geometry exercise, as you'd need to know where the straight line portion of each side ends and the rounded portion starts.</p>
| 1,393
|
<p>There are numerous libraries providing Linq capabilities to C# code interacting with a MySql database. Which one of them is the most stable and usable on Mono?</p>
<p>Background (mostly irrelevant): I have a simple C# (.Net 2.0) program updating values in a MySql database. It is executed nightly via a cron job and runs on a Pentium 3 450Mhz, Linux + Mono. I want to rewrite it using Linq (.Net 3.5) mostly as an exercise (I have not yet used Linq).</p>
|
<p>The only (free) linq provider for MySql is <a href="http://code2code.net/DB_Linq/" rel="nofollow noreferrer">DbLinq</a>, and I believe it is a long way from production-ready.</p>
<p>There is also <a href="http://www.devart.com/mysqlnet/" rel="nofollow noreferrer">MyDirect.Net</a> which is commercial, but I have heard mixed reviews of it's capability.</p>
<p>I've read that MySql will be implementing the Linq to Entities API for the 5.3 version of the .net connector, but I don't know if there's even a timeline for that. In fact, MySql has been totally silent about Entity Framework support for months.</p>
<hr>
<p>Addendum: The latest release of the MySql Connector/Net 6.0 has support for the EF according to the release notes. I have no idea how stable/useful this is, so I'd love to hear from anybody who have tried it.</p>
|
<p>at this time you cannot use linq to sql, you might look into a third party linq mysql provider or linq to entities. linq to sql only works for sql server databases.</p>
| 6,364
|
<p>I have checked the whole site and googled on the net but was unable to find a simple solution to this problem.</p>
<p>I have a datatable which has about 20 columns and 10K rows. I need to remove the duplicate rows in this datatable based on 4 key columns. Doesn't .Net have a function which does this? The function closest to what I am looking for was datatable.DefaultView.ToTable(true, array of columns to display), But this function does a distinct on <strong>all</strong> the columns.</p>
<p>It would be great if someone could help me with this.</p>
<p>EDIT: I am sorry for not being clear on this. This datatable is being created by reading a CSV file and not from a DB. So using an SQL query is not an option.</p>
|
<p>You can use Linq to Datasets. Check <a href="http://msdn.microsoft.com/en-us/library/bb669119.aspx" rel="noreferrer">this</a>. Something like this:</p>
<pre><code>// Fill the DataSet.
DataSet ds = new DataSet();
ds.Locale = CultureInfo.InvariantCulture;
FillDataSet(ds);
List<DataRow> rows = new List<DataRow>();
DataTable contact = ds.Tables["Contact"];
// Get 100 rows from the Contact table.
IEnumerable<DataRow> query = (from c in contact.AsEnumerable()
select c).Take(100);
DataTable contactsTableWith100Rows = query.CopyToDataTable();
// Add 100 rows to the list.
foreach (DataRow row in contactsTableWith100Rows.Rows)
rows.Add(row);
// Create duplicate rows by adding the same 100 rows to the list.
foreach (DataRow row in contactsTableWith100Rows.Rows)
rows.Add(row);
DataTable table =
System.Data.DataTableExtensions.CopyToDataTable<DataRow>(rows);
// Find the unique contacts in the table.
IEnumerable<DataRow> uniqueContacts =
table.AsEnumerable().Distinct(DataRowComparer.Default);
Console.WriteLine("Unique contacts:");
foreach (DataRow uniqueContact in uniqueContacts)
{
Console.WriteLine(uniqueContact.Field<Int32>("ContactID"));
}
</code></pre>
|
<p>Use a query instead of functions:</p>
<pre><code>DELETE FROM table1 AS tb1 INNER JOIN
(SELECT id, COUNT(id) AS cntr FROM table1 GROUP BY id) AS tb2
ON tb1.id = tb2.id WHERE tb2.cntr > 1
</code></pre>
| 44,196
|
<p>I'm using MediaTemple's Grid Server (shared/grid hosting) to run some MySQL/PHP sites I'm writing and noticed that I wasn't closing one of my MySQL connections, which caused my site to error out: </p>
<pre><code>"Too Many Connections"
</code></pre>
<p>I can't log in anywhere to close the connections manually. </p>
<p><strong>Is that any way to close open connections using a script or other type of command?.</strong> </p>
<p>Should I just wait?</p>
|
<p>If you can't log into MySQL at all, you will probably have to contact your hosting provider to kill the connections.</p>
<p>If you can use the MySQL shell, you can use the <a href="http://dev.mysql.com/doc/refman/5.0/en/show-processlist.html" rel="nofollow noreferrer">show processlist</a> command to view connections, then use the <a href="http://dev.mysql.com/doc/refman/5.0/en/kill.html" rel="nofollow noreferrer">kill</a> command to remove the connections.</p>
<p>It's been my experience that hung SQL connections tend to stay that way, unfortunately.</p>
|
<p>Make sure that you're closing the connections with your PHP code. Also, you could increase the maximum connections allowed in /etc/my.cnf.</p>
<pre><code>max_connections=500
</code></pre>
<p>Finally, you can login to a mysql prompt and type <code>show status</code> or <code>show processlist</code> to view various statistics with your server.</p>
<p>If all else fails, restarting the server daemon should clear the persistent connections.</p>
| 9,461
|
<p>One problem I have with a modern office is that people still tend to create physical copies of digital media (such as program manuals and specifications). I understand that for somethings it is prudent to create a physical copy but many of these physical copies go mostly unused, they just sit on a shelf to maybe one day be flipped through to look up a single piece of information. This is not only a waste of paper but also space and the time that it takes to print out and collate all of these printed documents. It also takes more time to utilize because these items are not capable of being indexed and searched like digital copies.</p>
<p>What are some good ways to promote a paperless environment in the workplace? My company has already implemented a company Wiki. So far the it seems to have made an impact on our use of paper, but some people still think of it as being too much of a hassle. </p>
|
<p>It won't work for everybody, for sure, but I recently spent a year at a small web development company (under 25 employees) that had no printers and no copiers. Only the owner had one little printer in his locked office. Since they never had any printers or copiers, their work patterns had evolved to not use paper.</p>
<p>This was such a shock to me, as I traditionally work with a lot of paper. I use it to partly control my own workflow -- if it needs to be done, there's a piece of paper (email, Word doc, printed-out bug tracker task) on my desk about it. I'd make notes on the document about the steps I needed to do to complete the task.</p>
<p>Of course, we used a bug tracking/change control system. So, all of my to-do's for my web coding were in that system.</p>
<p>I learned to organize my email better, and to have a good file folder structure in Windows. Ironically, I was more meticulous about deleting unnecessary electronic documents. I only kept the useful stuff. My email inbox was always empty, because everything got promptly moved to a folder.</p>
<p>Everybody's desk was really clean, and we had no file drawers. We did all have at least two monitors.</p>
|
<p>This all depends on personal preference. Some people like to read on computer screen. But some people might do not prefer screen. They tend to take the print out of every possible thing.</p>
<p>IMO you can promote the use of duplex printing. Infact printing multiple pages on same A4 sheet. This should reduce the wastage to some limit.</p>
<p>Otherwise I know a company which publishes the weekly list of people who got maximum print outs on working areas. This will certainly discourage some people who just take a print out for the sake of taking print out.</p>
| 34,336
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.