instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>What tag libraries you know for Java EE - JSP, something like <a href="http://displaytag.sourceforge.net/11/" rel="nofollow noreferrer">displaytag</a> ?</p>
<p>Looking for an alternative to displaytag I came across <a href="http://code.google.com/p/jmesa/" rel="nofollow noreferrer">jmesa</a>. Haven't tried it yet, tough.</p>
<p>There is also the <a href="https://github.com/customweb/jsp-data-grid" rel="nofollow">jsp data grid</a> library. It allows easy styling of all the elements (table, td, tr etc.). It is also integrated with Hibernate and Spring. It has also a AJAX mode.</p>
43,650
<p>Microsoft has chosen to not release a 64-bit version of Jet, their database driver for Access. Does anyone know of a good alternative?</p> <p>Here are the specific features that Jet supports that I need:</p> <ul> <li>Multiple users can connect to database over a network.</li> <li>Users can use Windows Explorer to copy the database while it is open without risking corruption. Access currently does this with enough reliability for what my customers need.</li> <li>Works well in C++ without requiring .Net.</li> </ul> <p>Alternatives I've considered that I do not think could work (though my understanding could be incorrect):</p> <ul> <li>SQLite: If multiple users connect to the database over a network, it will become corrupted.</li> <li>Firebird: Copying a database that is in use can corrupt the original database.</li> <li>SQL Server: Files in use are locked and cannot be copied.</li> <li>VistaDB: This appears to be .Net specific.</li> <li>Compile in 32-bit and use WOW64: There is another dependency that requires us to compile in 64-bit, even though we don't use any 64-bit functionality.</li> </ul>
<p>Luckily, things have changed in the past two years:</p> <p>Since Office 2010 is available in a 64-bit version, Microsoft had to create a 64-bit version of their Jet Engine. According to the <a href="https://learn.microsoft.com/en-us/archive/blogs/psssql/how-to-get-a-x64-version-of-jet" rel="nofollow noreferrer">Microsoft Customer Service blog</a>, the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=13255" rel="nofollow noreferrer">Microsoft Access Database Engine 2010 Redistributable</a> contains a 64-bit driver, which is able to access recent versions of the Microsoft Access database format.</p>
<p>What you're looking for is SQL Server Express with the portable .mdf files. To get around the copying limitation you need to make sure that the software in question doesn't keep connections open (i.e. create a disconnected data access layer).</p>
14,910
<p>I need to layout a html datatable with CSS. </p> <p>The actual content of the table can differ, but there is always one main column and 2 or more other columns. I'd like to make the main column take up as MUCH width as possible, regardless of its contents, while the other columns take up as little width as possible. I can't specify exact widths for any of the columns because their contents can change.</p> <p>How can I do this using a simple semantically valid html table and css only?</p> <p>For example:</p> <pre> | Main column | Col 2 | Column 3 | &lt;------------------ fixed width in px -------------------&gt; &lt;------- as wide as possible ---------&gt; Thin as possible depending on contents: &lt;-----&gt; &lt;--------&gt; </pre>
<p>I'm far from being a CSS expert but this works for me (in IE, FF, Safari and Chrome):</p> <pre><code>td.zero_width { width: 1%; } </code></pre> <p>Then in your HTML:</p> <pre><code>&lt;td class="zero_width"&gt;...&lt;/td&gt; </code></pre>
<p>I've not had success with <code>width: 100%;</code> as it seems that without a container div that has a fixed width this will not get the intended results. Instead I use something like the following and it seems to give me my best results.</p> <pre><code>.column-fill { min-width: 325px; } </code></pre> <p>This way it can get larger if it needs to, and it seems that the browser will give all the extra space to whichever column is set this way. Not sure if it works for everyone but did for me in chrome (haven't tried others)... worth a shot.</p>
14,442
<p>I have a Canvas in a Flex application which has items inside it that cover only about 50% of the area of the main canvas.</p> <p>i want the canvas to respond to <code>rollOver</code> events for the full area, and not just the area that is covered by the items inside.</p> <p>I have been setting the following attributes to achieve this :</p> <pre><code>&lt;mx:Canvas backgroundColor="white" backgroundAlpha=".01" rollOver="rollOver(event)"&gt;... </code></pre> <p>This causes the entire canvas to respond to rollOver events. It works great - I'm just not happy with it and figure there must be a better way to achieve it. </p> <p>Is there a way to force mouse events to act on the entire area of a UIComponent?</p>
<p>What you are doing is perfectly acceptable, although using the arbitrary alpha value of 0.01 is unnecessary, you can set it's backgroundAlpha to a simple 0.</p> <p>I routinely use Canvases for complicated multi layered UI's and set up my default Canvas style via css to have a backgroundAlpha of 0 and a backgroundColor of #ffffff, then, if I need a canvas to actually be visible I adjust it's individual backgroundAlpha and backgroundColor properties.</p> <p>There's nothing wrong with setting a graphic object's alpha to 0 so that it still responds to events but hasn't been 'turned off' entirely, us AS coders do it all the time!</p>
<p>You could do this:</p> <pre> <code> import flash.event.MouseEvent; ... canvas.addEventListener(MouseEvent.ROLL_OVER,function(event:MouseEvent):void { ... }); </code> </pre> <p>where "canvas" is the ID of the canvas in your mxml.</p>
37,244
<p>Is there <em>anything</em> available that isn't trivially breakable?</p>
<blockquote> <p><em>This 2008 answer is now dangerously out of date.</em> SHA (all variants) is now trivially breakable, and best practice is now (as of Jan 2013) to use a key-stretching hash (like PBKDF2) or ideally a RAM intensive one (like <a href="https://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage">Bcrypt</a>) and to add a per-user salt too.</p> <p>Points 2, 3 and 4 are still worth paying attention to.</p> <p>See the <a href="http://security.stackexchange.com">IT Security SE site</a> for more.</p> </blockquote> <hr /> <p>Original 2008 answer:</p> <ol> <li><p>Use a proven algorithm. SHA-256 uses 64 characters in the database, but with an index on the column that isn't a problem, and it is a proven hash and more reliable than MD5 and SHA-1. It's also implemented in most languages as part of the standard security suite. However don't feel bad if you use SHA-1.</p> </li> <li><p>Don't just hash the password, but put other information in it as well. You often use the hash of &quot;username:password:salt&quot; or similar, rather than just the password, but if you play with this then you make it even harder to run a dictionary attack.</p> </li> <li><p>Security is a tough field, do not think you can invent your own algorithms and protocols.</p> </li> <li><p>Don't write logs like &quot;[AddUser] Hash of GeorgeBush:Rep4Lyfe:ASOIJNTY is xyz&quot;</p> </li> </ol>
<p>MD5 / SHA1 hashes are both good choices. MD5 is slightly weaker than SHA1.</p>
14,217
<p>this is a question that when programming I always wonder: What to use when we are writing code: </p> <pre><code>var myFiles = Directory.GetFiles(fullPath); </code></pre> <p>or</p> <pre><code>string[] myFiles = Directory.GetFiles(fullPath); </code></pre> <p><strong><em>var</em></strong> is new and is a <em>Implicitly Typed Local Variables</em>, so we can only use locally and it has rules like can't be null, etc., but I wonder if we get any advantage of using it "normally". </p> <p>The "normally" part says, not in <strong>Anonymous Types</strong>, <strong>Object and Collection Initializers</strong> and <strong>Query Expressions</strong> where that was the intent to use the var anonymous object, so what I mean is... just like the example above.</p> <p>what are your thoughts?</p>
<p>Beyond the obvious use of <code>var</code> with LINQ, I also use it to abbreviate hairy variable declarations for readability, e.g.:</p> <pre><code>var d = new Dictionary&lt;string, Dictionary&lt;string, Queue&lt;SomeClass&gt;&gt;&gt;(); </code></pre> <p>In general, I get a kind of comfort (for want of a better word) from static typing that makes me reluctant to give it up. I like the feeling that I know what I'm doing when I'm declaring a variable. Declaring a variable isn't just telling the compiler something, it's telling the person reading your code something.</p> <p>Let me give you an example. Suppose I have a method that returns a <code>List&lt;string&gt;</code>. This code is certainly correct, and I think it's how 90% of C# developers would probably write it:</p> <pre><code>List&lt;string&gt; list = MyMethod(); </code></pre> <p>Obviously, right? In fact, here's a place you could just as easily use <code>var</code>.</p> <p>True enough. But <em>this</em> version of the code isn't just declaring a variable, it's telling me what the person who wrote it is intending to do:</p> <pre><code>IEnumerable&lt;string&gt; list = MyMethod(); </code></pre> <p>The developer who wrote that code is telling me "I'm not going to be changing this list, nor am I going to use an index to access its members. All I'm going to do is iterate across it." That's a lot of information to get across in a single line of code. It's something you give up if you use <code>var</code>.</p> <p>Of course, you're not giving it up if you weren't using it in the first place. If you're the kind of developer who would write that line of code, you already know that you wouldn't use <code>var</code> there.</p> <p><strong>Edit:</strong> </p> <p>I just reread Jon Skeet's post, and this quote from Eric Lippert jumped out at me:</p> <blockquote> <p>Implicitly typed locals are just one small way in which you can deemphasize the how and thereby emphasize the what.</p> </blockquote> <p>I think that actually in a lot of cases using implicit typing is leaving the what implicit. It's just OK to not dwell on the what. For instance, I'll casually write a LINQ query like:</p> <pre><code>var rows = from DataRow r in parentRow.GetChildRows(myRelation) where r.Field&lt;bool&gt;("Flag") orderby r.Field&lt;int&gt;("SortKey") select r; </code></pre> <p>When I read that code, one of the things I think when I'm reading it is "<code>rows</code> is an <code>IEnumerable&lt;DataRow&gt;</code>." Because I know that what LINQ queries return is <code>IEnumerable&lt;T&gt;</code>, and I can see the type of the object being selected right there.</p> <p>That's a case where the what <em>hasn't</em> been made explicit. It's been left for me to infer.</p> <p>Now, in about 90% of the cases where I use LINQ, this doesn't matter one tiny little bit. Because 90% of the time, the next line of code is:</p> <pre><code>foreach (DataRow r in rows) </code></pre> <p>But it's not hard to envision code in which it would be very useful to declare <code>rows</code> as <code>IEnumerable&lt;DataRow&gt;</code> - code where a lot of different kinds of objects were being queried, it wasn't feasible to put the query declaration next to the iteration, and it would be useful to be able inspect <code>rows</code> with IntelliSense. And that's a what thing, not a how thing.</p>
<p>I think it's interesting to note how this is usually handled in Haskell. Thanks to the <a href="http://en.wikipedia.org/wiki/Curry-Howard_correspondence" rel="nofollow noreferrer">Curry-Howard isomorphism</a>, the (most general) type of any expression in Haskell can be inferred, and thus type declarations are essentially not required anywhere, with a few exceptions; for example, sometimes you deliberately want to limit the type to something more specific than would be inferred.</p> <p>Of course, what is required and what is recommended are not the same thing; in practice, the convention seems to be that top-level definitions always have type declarations, while localised definitions have the type declarations left out. This seems to strike a good balance between explicitness-for-readability of the definition as a whole, contrasted with brevity-for-readability of the local "helper" or "temporary" definitions. If I understand correctly, you can't use <code>var</code> for "top-level" definitions (like a method or global function) in the first place, so I guess this translates to "use <code>var</code> everywhere you can" in C# world. Of course, typing "<code>int</code>" is the same number of keystrokes as "<code>var</code>", but most examples will be longer than that.</p>
29,310
<p>I can access my calendar entries as:</p> <pre><code>$folder = $namespace-&gt;Folders("Joe Cool")-&gt;Folders("Calendar"); </code></pre> <p>How do I open "Jane Cool" Calendar? Outlook shows that calendar as:</p> <pre><code>People's Calendar Jane Cool </code></pre>
<p>I believe you are looking for the <a href="http://msdn.microsoft.com/en-us/library/aa220116(office.11).aspx" rel="nofollow noreferrer">GetSharedDefaultFolder</a>() method.</p>
<p>Have you tried looking at the whole $namespace datastructure?</p> <p>Try:</p> <p>use Data::Dumper;print Dumper $namespace;exit;</p> <p>somewhere shortly after $namespace gets created/initialised.</p> <p>Iain</p>
39,128
<p>Assuming I have an open source web server or proxy I can enhance, let's say apache or squid. </p> <p>Is there a way to determine the time each client spends on a web page?</p> <p>HTTP is of course stateless, so it's not trivial, but maybe someone has an idea on how to approach this problem?</p>
<p>Not without having some javascript constantly hit your server on the client side and then checking when it stops (but of course that assumes the user has javascript enabled). There are also various (ugly) ways to detect windows being closed with javascript, but of course these won't always trigger. eg. browser crash.</p> <p>I sort of wonder why you want this anyway. What if a person looks at the web page for 3 seconds, gets distracted by another tab/window but leaves your page open for 2 hours? The answer you get is 2 hours, the answer you (probably) want is 3 seconds.</p>
<p>This kind of metric was actually pretty popular several years ago, before PCs got more powerful and tabbed browsers became popular, and it became harder to measure as accurately. The standard way to do it in the past was to assume people are usually just loading one page at a time, and just use server log data to determine the time between page views. Your standard analytics vendors like Omniture and Urchin (now Google Analytics) calculate this.</p> <p>Normally, you set a tracking cookie to be able to identify a specific person/browser over time, but in the short term you can just use an IP address/user-agent combo.</p> <p>So, basically you just crunch the log data and count the delta between to page views as how long the person was on the page. You set some rules (or your analytics vendor does this behind the curtain) like discarding/truncating times beyond some cutoff (say 10 minutes) where you assume the person wasn't actually reading but left the page open in a window/tab.</p> <p>Is this data perfect? Obviously not. But you just need enough "good enough" data to do statistical analysis and draw some conclusions.</p> <p>It's still useful for longitudinal analysis (readers' habits over time) and qualitative comparison between different pages on your site. (i.e. between two 700-word articles, if one has a mean reading time twice as long as the other, then more people are actually reading the first article.) Of course, your site has to be busy enough to have enough data points for statistically sound analysis after you throw out all the "bad" outlier data points.</p> <p>Yes, you could use Javascript to send keep-alives to improve the data. You could just poll at given intervals after document.onload or set mouseover events on sections of your pages.</p> <p>Another technique is to use Javascript to add an onclick event to every <code>&lt;a href&gt;</code> that hits your server. Not only do you then know when someone clicks a link to take them off your site, really sophisticated "hotspot" analysis looks at the fact that if someone clicked a link 6 paragraphs down a page, then they must have read that far.</p>
19,591
<p>I'm thinking about how limiting it is for AJAX apps to have to poll for updates, when what would be ideal is for javascript to be able to set up a real two way connection to the server. I'm wondering if there is some method of integrating javascript with a browser plugin that can make a tcp connection so that I could pass data into and out of the browser plugin. </p>
<p>Here is an implementation with a similar approach: </p> <ul> <li><a href="http://sly.w3m.hu/socketjs" rel="noreferrer">socketjs</a></li> </ul> <p>It uses a Java Applet and bridges its API to JavaScript, interesting...</p> <p>And here another one:</p> <ul> <li><a href="http://code.google.com/p/jsocket/" rel="noreferrer">jSocket</a></li> </ul> <p>This one is a wrapper of the Actionscript 3 Socket API, bridged to JavaScript...</p>
<p><a href="http://code.google.com/p/jsocket/wiki/Introduction" rel="nofollow noreferrer">jSocket</a> and <a href="http://stream.stormtide.ca/" rel="nofollow noreferrer">Stream</a> are two options that utilize Flash's built-in XML sockets, though neither appears to be production-ready. I'd lean towards using a Flash-based solution rather than Java, as browser penetration is <a href="http://www.realchat.com/blog/java-vs-flash/" rel="nofollow noreferrer">higher</a> and generally offers a better user experience (load times &amp; stability).</p>
39,584
<p>I have a class with a <code>ToString</code> method that produces XML. I want to unit test it to ensure it is producing valid xml. I have a DTD to validate the XML against. </p> <p><strong>Should I include the DTD as a string within the unit test to avoid a dependency</strong> on it, or is there a smarter way to do this?</p>
<p>If your program validates the XML against the DTD during normal execution, then you should just get the DTD from wherever your program will get it.</p> <p>If not and the DTD is extremely short (only a few lines), then storing it as a string in your code is probably okay.</p> <p>Otherwise, I'd put it in an external file and have your unit test read it from that file.</p>
<p>Using a DTD in the unit test to test its validity is one thing, testing for the correct content is another.</p> <p>You can use the DTD to check for the validity of the generated xml which I would simply read the way you do in your program. I personally would not include it inline (as a String); there is always a dependency between you application code and the unit test. When the generated xml changes, the DTD will also change.</p> <p>To test for the correct content I would go for <a href="http://www.xmlunit.org" rel="nofollow">XMLUnit</a>. </p> <p>Asserting xml using XMLUnit:</p> <pre><code>XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true); Diff diff = new Diff(expectedDocument, obtainedDocument); XMLAssert.assertXMLIdentical("xml invalid", diff, true); </code></pre> <p>One thing you might come across is the fact that the generated xml might contain changing identifiers (id/uid attributes or alike). This can be solved by using a <a href="http://www.xmlunit.org/api/java/master/org/custommonkey/xmlunit/DifferenceListener.html" rel="nofollow">DifferenceListener</a> when asserting the generated xml.</p> <p>Example implementation of such DifferenceListener:</p> <pre><code>public class IgnoreVariableAttributesDifferenceListener implements DifferenceListener { private final List&lt;String&gt; IGNORE_ATTRS; private final boolean ignoreAttributeOrder; public IgnoreVariableAttributesDifferenceListener(List&lt;String&gt; attributesToIgnore, boolean ignoreAttributeOrder) { this.IGNORE_ATTRS = attributesToIgnore; this.ignoreAttributeOrder = ignoreAttributeOrder; } @Override public int differenceFound(Difference difference) { // for attribute value differences, check for ignored attributes if (difference.getId() == DifferenceConstants.ATTR_VALUE_ID) { if (IGNORE_ATTRS.contains(difference.getControlNodeDetail().getNode().getNodeName())) { return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } } // attribute order mismatch (optionally ignored) else if (difference.getId() == DifferenceConstants.ATTR_SEQUENCE_ID &amp;&amp; ignoreAttributeOrder) { return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } // attribute missing / not expected else if (difference.getId() == DifferenceConstants.ATTR_NAME_NOT_FOUND_ID) { if (IGNORE_ATTRS.contains(difference.getTestNodeDetail().getValue())) { return RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL; } } return RETURN_ACCEPT_DIFFERENCE; } @Override public void skippedComparison(Node control, Node test) { // nothing to do } } </code></pre> <p>using DifferenceListener:</p> <pre><code> XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true); Diff diff = new Diff(expectedDocument, obtainedDocument); diff.overrideDifferenceListener(new IgnoreVariableAttributesDifferenceListener(Arrays.asList("id", "uid"), true)); XMLAssert.assertXMLIdentical("xml invalid", diff, true); </code></pre>
7,496
<p>I can make Firefox not display the ugly dotted focus outlines on <b>links</b> with this:</p> <pre class="lang-css prettyprint-override"><code>a:focus { outline: none; } </code></pre> <p>But how can I do this for <code>&lt;button&gt;</code> tags as well? When I do this:</p> <pre class="lang-css prettyprint-override"><code>button:focus { outline: none; } </code></pre> <p>the buttons still have the dotted focus outline when I click on them.</p> <p>(and yes, I know this is a usability issue, but I would like to provide my own focus hints which are appropriate to the design instead of ugly grey dots)</p>
<pre class="lang-css prettyprint-override"><code>button::-moz-focus-inner { border: 0; } </code></pre>
<p>You can try <code>button::-moz-focus-inner {border: 0px solid transparent;}</code> in your CSS.</p>
9,651
<p>When developing WPF UserControls, what is the best way to expose a DependencyProperty of a child control as a DependencyProperty of the UserControl? The following example shows how I would currently expose the Text property of a TextBox inside a UserControl. Surely there is a better / simpler way to accomplish this?</p> <pre class="lang-xml prettyprint-override"><code> &lt;UserControl x:Class=&quot;WpfApplication3.UserControl1&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;&gt; &lt;StackPanel Background=&quot;LightCyan&quot;&gt; &lt;TextBox Margin=&quot;8&quot; Text=&quot;{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}&quot; /&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </code></pre> <pre class="lang-cs prettyprint-override"><code> using System; using System.Windows; using System.Windows.Controls; namespace WpfApplication3 { public partial class UserControl1 : UserControl { public static DependencyProperty TextProperty = DependencyProperty.Register(&quot;Text&quot;, typeof(string), typeof(UserControl1), new PropertyMetadata(null)); public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public UserControl1() { InitializeComponent(); } } } </code></pre>
<p>That is how we're doing it in our team, without the RelativeSource search, rather by naming the UserControl and referencing properties by the UserControl's name.</p> <pre><code>&lt;UserControl x:Class="WpfApplication3.UserControl1" x:Name="UserControl1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;StackPanel Background="LightCyan"&gt; &lt;TextBox Margin="8" Text="{Binding Path=Text, ElementName=UserControl1}" /&gt; &lt;/StackPanel&gt; &lt;/UserControl&gt; </code></pre> <p>Sometimes we've found ourselves making too many things UserControl's though, and have often times scaled back our usage. I'd also follow the tradition of naming things like that textbox along the lines of PART_TextDisplay or something, so that in the future you could template it out yet keep the code-behind the same.</p>
<p>You can set DataContext to this in UserControl's constructor, then just bind by only path.</p> <p>CS:</p> <pre><code>DataContext = this; </code></pre> <p>XAML:</p> <pre><code>&lt;TextBox Margin="8" Text="{Binding Text} /&gt; </code></pre>
10,205
<p>I'm trying to integrate a NSURLConnection object with UIProgressView, so I can update the user while a file download is happening in the background.</p> <p>I created a separate object to download the file in the background, and I'm having problems figuring out how to update the progress property in the UIProgressView object with the correct value. It's probably something very simple, but I cannot figure it out with Googling around.</p> <p>Here's the code that I have:</p> <pre><code>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.resourceData setLength:0]; self.filesize = [NSNumber numberWithLongLong:[response expectedContentLength]]; NSLog(@"content-length: %d bytes", self.filesize); } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.resourceData appendData:data]; NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]]; NSLog(@"resourceData length: %d", [resourceLength intValue]); NSLog(@"filesize: %d", self.filesize); NSLog(@"float filesize: %f", [self.filesize floatValue]); progressView.progress = [resourceLength floatValue] / [self.filesize floatValue]; NSLog(@"progress: %f", [resourceLength floatValue] / [self.filesize floatValue]); } </code></pre> <p>As you can see, the <b>resourceData</b> member variable holds the file data as it is being downloaded. The <b>filesize</b> member variable holds the full size of the file, as returned by my web service in its Content-Length header.</p> <p>It all works sort of OK, I keep getting the downloaded data with multiple executions of <b>didReceiveData</b> as I should, but when I try to calculate the progress value, no proper value is returned. See below for a small sample of what I get in my console log:</p> <pre><code>content-length: 4687472 bytes resourceData length: 2904616 filesize: 4687472 float filesize: -1.000000 progress: -2904616.000000 </code></pre> <p>For reference, <b>progressView.progress</b> is a float. <b>filesize</b> is a NSNumber that holds a long long. Finally, <b>resourceLength</b> is a NSNumber that holds a NSUInteger.</p> <p>What am I missing here?</p>
<p>Not sure what I'm missing here, but your <code>filesize</code> being -1 seems to be your problem. The <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSURLResponse_Class/Reference/Reference.html#//apple_ref/occ/instm/NSURLResponse/expectedContentLength" rel="noreferrer">API docs</a> clearly state that <code>expectedContentLength</code> may not be available and that <code>NSURLResponseUnknownLength</code> is returned in these cases. <code>NSURLResponseUnknownLength</code> is defined as:</p> <pre><code>#define NSURLResponseUnknownLength ((long long)-1) </code></pre> <p>In these cases, you cannot get an accurate progress. You'll need to handle this and display an indeterminate progress meter of some sort.</p>
<p>In your code, filesize appears to be an NSNumber object (!). So</p> <p><code> NSLog(@"filesize: %d", self.filesize); </code></p> <p>and</p> <p><code> NSLog(@"content-length: %d bytes", self.filesize); </code></p> <p>will likely report something like the address (id) of that object (or something else). This is the</p> <p><code> filesize: 4687472 </code></p> <p>you see. As pointed out by others, the file size returned by the response is indeed -1, i.e.,</p> <p><code> NSURLResponseUnknownLength </code></p> <p>i.e., the server did not return the file size.</p>
40,316
<p>I'd like to check if the user input is an email address in JavaScript, before sending it to a server or attempting to send an email to it, to prevent the most basic mistyping. How could I achieve this?</p>
<p>Using <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expressions</a> is probably the best way. You can see a bunch of tests <a href="http://jsfiddle.net/ghvj4gy9/embedded/result,js/" rel="noreferrer">here</a> (taken from <a href="https://cs.chromium.org/chromium/src/third_party/blink/web_tests/fast/forms/resources/ValidityState-typeMismatch-email.js?q=ValidityState-typeMismatch-email.js&amp;sq=package:chromium&amp;dr" rel="noreferrer">chromium</a>)</p> <pre class="lang-js prettyprint-override"><code>const validateEmail = (email) =&gt; { return String(email) .toLowerCase() .match( /^(([^&lt;&gt;()[\]\\.,;:\s@&quot;]+(\.[^&lt;&gt;()[\]\\.,;:\s@&quot;]+)*)|(&quot;.+&quot;))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }; </code></pre> <p>Here's the example of a regular expression that accepts unicode:</p> <pre class="lang-js prettyprint-override"><code>const re = /^(([^&lt;&gt;()[\]\.,;:\s@\&quot;]+(\.[^&lt;&gt;()[\]\.,;:\s@\&quot;]+)*)|(\&quot;.+\&quot;))@(([^&lt;&gt;()[\]\.,;:\s@\&quot;]+\.)+[^&lt;&gt;()[\]\.,;:\s@\&quot;]{2,})$/i; </code></pre> <p>But keep in mind that one should not rely only upon JavaScript validation. JavaScript can easily be disabled. This should be validated on the server side as well.</p> <p>Here's an example of the above in action:</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>const validateEmail = (email) =&gt; { return email.match( /^(([^&lt;&gt;()[\]\\.,;:\s@\"]+(\.[^&lt;&gt;()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ ); }; const validate = () =&gt; { const $result = $('#result'); const email = $('#email').val(); $result.text(''); if (validateEmail(email)) { $result.text(email + ' is valid :)'); $result.css('color', 'green'); } else { $result.text(email + ' is not valid :('); $result.css('color', 'red'); } return false; } $('#email').on('input', validate);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;label for="email"&gt;Enter an email address: &lt;/label&gt; &lt;input id="email" /&gt; &lt;h2 id="result"&gt;&lt;/h2&gt;</code></pre> </div> </div> </p>
<p>One of my coworker shared this regex with me. I like it a lot.</p> <pre><code>function isValidEmailAddress (email) { var validEmail = false; if (email) { email = email.trim().toLowerCase(); var pattern = /^[\w-']+(\.[\w-']+)*@([a-zA-Z0-9]+[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*?\.[a-zA-Z]{2,6}|(\d{1,3}\.){3}\d{1,3})(:\d{4})?$/; validEmail = pattern.exec(email); } return validEmail; } if (typeof String.prototype.trim !== 'function') { String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }; } </code></pre>
6,822
<p>On Apache/PHP sites if I want to put a senstive file within my website folders, I put a .htaccess file in that folder so users can't download the sensitive file.</p> <p><strong>Is there a similar practice for IIS/ASP.NET sites</strong>, i.e. if I have a shared hosting account and don't have access to IIS server. Can I do this in web.config for instance?</p> <p>e.g. the ASPNETDB.MDF file that ASP.NET Configuration put in the App_Data directory. I would assume this is protected by default but where can I change the settings for this folder as I could with a .htaccess file?</p>
<p>Inside of an ASP.Net web.config you can setup locations to add security to specific files and folders. In addition, you can remove all verbs from those directories:</p> <pre><code>&lt;location path="Secret" allowOverride="false"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;deny users="*" /&gt; &lt;/authorization&gt; &lt;httpHandlers&gt; &lt;remove path="*.*" verb="*"/&gt; &lt;/httpHandlers&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p>I have only used the authorization portion of that snippet and it works great. The handler should further lock it down and using a ISAPI filter would be able to put the finishing touches on it.</p>
<p>There are some things you can do with web.config like defining security settings etc... Other times you have to use HttpModules or HttpHandlers, look here: <a href="http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx</a></p> <p>If not, you can find different ISAPI, but in this case you need access to IIS. For example, the ISAPI for emulating rewrite mod apache:</p> <p><a href="http://www.codeplex.com/IIRF" rel="nofollow noreferrer">> http://www.codeplex.com/IIRF</a></p> <p>The other question, yes ASPNETDB.MDF in APP_Data is protected normally (it depends on your administrator). To change the path, change the connectionstring.</p>
40,965
<p>After staring at <a href="http://maettig.com/code/javascript/3d_dots.html" rel="noreferrer">this 3D cube</a> and <a href="http://www.uselesspickles.com/triangles/demo.html" rel="noreferrer">these triangles</a> for a while I started wondering if there's any good reliable Javascript graphics library with basic 3D support.</p> <p>Any suggestion?</p>
<p>John Resig's port of the Processing library to Javascript:</p> <p><a href="http://ejohn.org/blog/processingjs" rel="noreferrer">http://ejohn.org/blog/processingjs</a></p>
<p>Check out Walter Zorn's library</p> <p><a href="http://www.walterzorn.de/en/jsgraphics/jsgraphics_e.htm" rel="nofollow noreferrer">www.walterzorn.de/en</a></p>
27,334
<p>Alright, so I have a query that looks like this:</p> <pre><code>SELECT `orders`.*, GROUP_CONCAT( CONCAT( `menu_items`.`name`, ' ($', FORMAT(`menu_items`.`price`,2), ')' ) SEPARATOR '&lt;br&gt;' ) as `items`, SUM(`menu_items`.`price`) as `additional`, `children`.`first_name`, `children`.`last_name`, `organizations`.`base_price` FROM `orders`, `order_items`, `menu_items`, `children`, `organizations` WHERE `order_items`.`menu_item_id` = `menu_items`.`id` AND `order_items`.`order_id` = `orders`.`id` AND `orders`.`added_by` = {$user_id} AND `orders`.`date` &gt; '{$cutoff}' AND `children`.`id` = `orders`.`child_id` AND `organizations`.`id` = `children`.`organization_id` GROUP BY `orders`.`id` </code></pre> <p>I know it's a monstrosity and that some people will die before not using explicit joins. Ignoring that, however, what I wish to do is to only use the <code>CONCAT</code> inside the <code>GROUP_CONCAT</code> if the <code>menu_items.price</code> is greater than 0, otherwise only return <code>menu_items.name</code>. I have had, however, no success trying to throw an <code>IF</code> in there. I've read the manual but all the ways that I've tried aren't working and I'm pretty sure I'm missing something on the whole conditional statements thing.</p>
<p>Have you tried using something like this?</p> <pre><code>CASE WHEN 'menu_items'.'price' = 0 THEN 'menu.items'.'name' ELSE CONCAT (etc) END </code></pre> <p>Replacing the <code>CONCAT</code> statement of course.</p>
<p>Something like this should work (but I didn't test it, sorry):</p> <pre><code>GROUP_CONCAT( CONCAT( `menu_items`.`name`, IF(`menu_items`.`price` &gt; 0, -- &lt;condition&gt; CONCAT(' ($', FORMAT(`menu_items`.`price`,2), ')'), -- &lt;true-expr&gt; '' -- &lt;false-expr&gt; ) ) SEPARATOR '&lt;br&gt;' ) as `items`, </code></pre> <p>The <code>IF()</code> function is really simple:</p> <pre><code>IF( &lt;condition&gt;, &lt;true-expr&gt;, &lt;false-expr&gt; ) </code></pre> <p>The function has three arguments: the first is <code>&lt;condition&gt;</code>. If the condition evaluates to true, the function returns the result of <code>&lt;true-expr&gt;</code>. Else the function returns the result of <code>&lt;false-expr&gt;</code>.</p> <p>Things get harder to get right when you use really long, multi-line expressions that contain parentheses and commas and so on. You just have to do it carefully. I suggest starting with more simple expressions and then build up.</p>
28,697
<p>I've been getting some OutOfMemory errors lately in my application. Is it possible to detect ahead of time when the virtual machine is running low on memory? In other words to preemptively deal with OutOfMemory errors before they actually occur?</p>
<p>Java (as of Java 5) now has a standard JMX bean that can be used to receive low memory notification. See <code>java.lang.management.MemoryMXBean</code>.</p>
<p>I suggest that a better question is "Why is my application running out of memory?"</p> <p>You may need to increase the memory available to the JVM at startup; You may have a memory leak (objects that aren't getting released when they're no longer needed.)</p> <p>More information on the application might also be helpful</p> <ul> <li>Does it run continuously, 24x7x365?</li> <li>Does it run once and exit?</li> </ul> <p>Using performance monitoring/profiling tools to find the cause of the memory problem is really your best bet.</p>
29,159
<p>I'm looking for a good, preferably free, test planning and documentation tool. Ideally something that will keep track of which tests have been run against which software version, with reporting ability. There's a whole bunch of tools listed <a href="http://www.opensourcetesting.org/testmgt.php" rel="nofollow noreferrer">here</a> but are there any others, and which ones have you had the best experience with? (You do run tests, right?)</p> <p><strong>UPDATE 2008-01-29</strong></p> <p>So far <a href="http://testlink.sourceforge.net/docs/testLink.php" rel="nofollow noreferrer">TestLink</a> and <a href="http://fitnesse.org/" rel="nofollow noreferrer">Fitness</a> have been mentioned. <a href="https://stackoverflow.com/questions/166103/free-program-for-building-managing-test-plans">A related question</a> yielded also a link to the <a href="http://readyset.tigris.org/" rel="nofollow noreferrer">ReadySet</a> project, an open collection of software planning documentation templates.</p> <p>I have used TestLink and found it okayish, but I cannot say I enjoyed using it. Has anyone had any experience with Fitnesse? Or are there any other free tools out there that you have used and found satisfactory?</p>
<p>I've used QualityCenter/TestDirectory for a long time.</p> <p>I'm now using testlink and I must say that I prefer QualityCenter/TestDirectory by far, even if it based on some buggy ActiveX control.</p> <p>QualityCenter/TestDirectory is more easier to use and the interface is quite better.</p> <p>TestLink and QualityCenter/TestDirectory are mainly for manual test case (however, you can use Quick Test Pro on QualityCenter/TestDirectory to automatize your tests).</p> <p>Fitnesse is another kind of tool in my mind : basically, you write your test case on a wiki and link that to a JUnit test. Another tools like that are GreenPepper, Concordion, etc.</p>
<p>One thought, and perhaps not a good one, would be to have every test submit a ticket to your ticketing system when it's run indicating the test name, build version, and date, and test results.</p> <p>That would make the results searchable later-on.</p>
12,551
<p>I'm setting up a dedicated SQL Server 2005 box on Windows Server 2008 this week, and would like to pare it down to be as barebones as possible while still being fully functional.</p> <p>To that end, the "Server Core" option sounds appealing, but I'm not clear about whether or not I can run SQL Server on that SKU. Several services are addressed on the <a href="http://www.microsoft.com/windowsserver2008/en/us/compare-core-installation.aspx" rel="noreferrer">Microsoft website</a>, but I don't see any indication about SQL Server.</p> <p>Does anyone know definitively?</p>
<p>Not sure how credible <a href="http://www.builderau.com.au/program/windows/soa/Getting-started-with-Windows-Server-2008-Core-edition/0,339024644,339288700,00.htm" rel="noreferrer">this source is</a>, but:</p> <blockquote> <p>The Windows Server 2008 Core edition can:</p> <ul> <li><p>Run the file server role.</p></li> <li><p>Run the Hyper-V virtualization server role.</p></li> <li><p>Run the Directory Services role.</p></li> <li><p>Run the DHCP server role.</p></li> <li><p>Run the IIS Web server role.</p></li> <li><p>Run the DNS server role.</p></li> <li><p>Run Active Directory Lightweight Directory Services.</p></li> <li><p>Run the print server role.</p></li> </ul> <p>The Windows Server 2008 Core edition cannot:</p> <ul> <li><p>Run a SQL Server.</p></li> <li><p>Run an Exchange Server.</p></li> <li><p>Run Internet Explorer.</p></li> <li><p>Run Windows Explorer.</p></li> <li><p>Host a remote desktop session.</p></li> <li><p>Run MMC snap-in consoles locally.</p></li> </ul> </blockquote>
<p>Server Core won't be very useful (to me at least, and I think many others as well) until they get a version of .Net framework on it. Maybe a specialized subset like they have in the Compact Framework on smart phones.</p>
2,379
<pre><code>(function() { //codehere } )(); </code></pre> <p>What is special about this kind of syntax? What does ()(); imply?</p>
<p>The creates an anonymous function, closure and all, and the final () tells it to execute itself.</p> <p>It is basically the same as:</p> <pre><code>function name (){...} name(); </code></pre> <p>So basically there is nothing special about this code, it just a 'shortcut' to creating a method and invoking it without having to name it. </p> <p>This also implies that the function is a one off, or an internal function on an object, and is most useful when you need to the features of a closure.</p>
<p>The stuff in the first set of brackets evaluates to a function. The second set of brackets then execute this function. So if you have something that want to run automagically onload, this how you'd cause it to load and execute.</p>
22,505
<p>I'm getting XML like this:</p> <p><code>&lt;Items&gt; &lt;Row attr1="val"&gt;&lt;/Row&gt; &lt;Row attr1="val2"&gt;&lt;/Row&gt; &lt;/Items&gt;</code></p> <p>This is valid XML, as you know, but another library I'm using is busted and it will only accept XML in this format: </p> <p><code>&lt;Items&gt; &lt;Row attr1="val"/&gt; &lt;Row attr1="val2"/&gt; &lt;/Items&gt; </code></p> <p>I'm already reading the XML into XmlDocuments, manipulating them, and rewriting them using an XmlWriter(), what's the easiest (and most efficient) way for me to "collapse" these empty tags?</p>
<p>Set the <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlelement.isempty.aspx" rel="nofollow noreferrer">IsEmpty</a> property of each XmlElement you want to collapse to true.</p>
<p>If you use System.XML's DOM manipulation objects (XmlElement etc) instead of XmlWriter, you get this for free.</p> <pre><code>XmlElement items = xmlDoc.SelectNodes("items"); XmlElement row = xmlDoc.CreateElement("row"); items[0].appendChild(row); </code></pre> <p>You'll get a "&lt;row/&gt;"</p>
24,168
<p>The full error is - "Value cannot be null. Parameter name: virtualPath". This is occurring in our QA and Training environments (Win 2003 Server &amp; IIS6) but of course defies recreation in a debugger. To make matters worse, despite a reasonable global error handler, no stack trace accompanies the error and nothing is written to the event log. The app is a large fully globalized Asp.Net (VB) web application running under the 2.0 Framework. It uses the usual "App_LocalResources" structure for resx files and to date has performed quite well. There are several places in the app where code like this is used: </p> <pre><code>Dim x As New Compilation.ExpressionBuilderContext(Control.TemplateControl) Dim path As String = x.VirtualPath Dim res As String = HttpContext.GetLocalResourceObject(path, resourceKey).ToString </code></pre> <p>However the Try/Catch block around this code works properly when I force the "path" variable to be nothing. We also use this syntax everywhere for data grid column headers: </p> <pre><code>&lt;asp:TemplateColumn HeaderText="&lt;%$ Resources:resHeader %&gt;" &gt; </code></pre> <p>We also use a considerable amount of Ajax and dynamically load ascx controls into placeholders constantly. If anyone has any insight into this I'd greatly appreciate the help. </p> <p>Thanks, Larry</p>
<p>Follow up - make sure your servers are up to the proper patch level.<br> The root cause of this turned out to be 3 QA VMs that did not have<br> 2.0 .Net Framework SP1 installed.</p>
<p>this might sound silly, but heck i have had this happen to me before.</p> <p>if you copy and pasted your error, i notice it says "virtualPath" (lower case v); whil in your sample code, the property you use has VirtualPath (upper case V). </p> <p>Also, what is the actual exception you are getting? a NullReferenceException?</p>
46,503
<p>In general, what needs to be done to convert a 16 bit Windows program to Win32? I'm sure I'm not the only person to inherit a codebase and be stunned to find 16-bit code lurking in the corners.</p> <p>The code in question is C.</p>
<ol> <li>The meanings of <code>wParam</code> and <code>lParam</code> have changed in many places. I <strong>strongly</strong> encourage you to be paranoid and convert as much as possible to use <a href="http://support.microsoft.com/kb/83456" rel="nofollow noreferrer">message crackers</a>. They will save you no end of headaches. If there is only one piece of advice I could give you, this would be it.</li> <li>As long as you're using message crackers, also enable <code>STRICT</code>. It'll help you catch the Win16 code base using <code>int</code> where it should be using <code>HWND</code>, <code>HANDLE</code>, or something else. Converting these will greatly help with #9 on this list.</li> <li><code>hPrevInstance</code> is useless. Make sure it's not used.</li> <li>Make sure you're using Unicode-friendly calls. That doesn't mean you need to convert everything to <code>TCHAR</code>s, but means you better replace <code>OpenFile</code>, <code>_lopen</code>, and <code>_lcreat</code> with <code>CreateFile</code>, to name the obvious</li> <li><code>LibMain</code> is now <code>DllMain</code>, and the entire library format and export conventions are different</li> <li>Win16 had no VMM. <code>GlobalAlloc</code>, <code>LocalAlloc</code>, <code>GlobalFree</code>, and <code>LocalFree</code> should be replaced with more modern equivalents. When done, clean up calls to <code>LocalLock</code>, <code>LocalUnlock</code> and friends; they're now useless. Not that I can imagine your app doing this, but make sure you don't depend on <code>WM_COMPACTING</code> while you're there.</li> <li>Win16 also had no memory protection. Make sure you're not using <code>SendMessage</code> or <code>PostMessage</code> to send pointers to out-of-process windows. You'll need to switch to a more modern IPC mechanism, such as pipes or memory-mapped files.</li> <li>Win16 also lacked preemptive multitasking. If you wanted a quick answer from another window, it was totally cool to call <code>SendMessage</code> and wait for the message to be processed. That may be a bad idea now. Consider whether <code>PostMessage</code> isn't a better option.</li> <li>Pointer and integer sizes change. Remember to check carefully anywhere you're reading or writing data to disk—especially if they're Win16 structures. You'll need to manually redo them to handle the shorter values. Again, the least painful way to deal with this will be to use message crackers where possible. Otherwise, you'll need to manually hunt down and convert <code>int</code> to <code>DWORD</code> and so on where applicable.</li> <li>Finally, when you've nailed the obvious, consider enabling 64-bit compilation checks. A lot of the issues faced with going from 16 to 32 bits are the same as going from 32 to 64, and Visual C++ is actually pretty smart these days. Not only will you catch some lingering issues; you'll get yourself ready for your eventual Win64 migration, too.</li> </ol> <hr /> <p><strong>EDIT</strong>: As @ChrisN points out, <a href="https://web.archive.org/web/20150702031047/https://msdn.microsoft.com/en-us/library/aa314542(VS.60).aspx" rel="nofollow noreferrer">the official guide for porting Win16 apps to Win32</a> is available archived, and both fleshes out and adds to my points above.</p>
<p>I agree with Alan that trial and error is probably the best way. </p> <p>Here are some good <a href="http://web.mit.edu/dosathena/doc/www/porting-to-NT.html" rel="nofollow noreferrer">tips</a>.</p>
17,737
<p>Is it possible to 3D print a QR code? or to engrave it using a 3D printer? I tried to convert it to individual boxes but that takes too long and is very inaccurate. Is there a better way?</p>
<p>From the excellent Thingiverse link, <a href="https://www.thingiverse.com/thing:4967931" rel="nofollow noreferrer">Customizable QR Keyring or Tag</a> by <a href="https://www.thingiverse.com/outwardb/designs" rel="nofollow noreferrer"><em>OutwardB</em></a> - which was provided in the (now deleted) <a href="https://3dprinting.stackexchange.com/a/18296/4762">link-only answer</a>:</p> <blockquote> <ol> <li><h3>Create the QR code</h3> <ul> <li><p>Go to <a href="https://qrcode-monkey.com" rel="nofollow noreferrer">QRCode Monkey</a></p> </li> <li><p><strong>Only change the Content settings</strong></p> <p>DO NOT change the color, logo or design settings</p> </li> <li><p>Click <strong>Create QR Code</strong></p> </li> <li><p>Click <strong>Download PNG</strong> and wait for the file to download</p> </li> </ul> </li> <li><h3>Convert to SVG</h3> <ul> <li>Go to <a href="https://convertio.co/png-svg/" rel="nofollow noreferrer">PNG to SVG Converter</a> and convert the PNG image you just downloaded to a .SVG file</li> </ul> </li> <li><h3>Customise in OpenSCAD</h3> <p>You will need <a href="https://www.thingiverse.com/download:10312157" rel="nofollow noreferrer"><code>QR_Code_Customizer_V01_2.scad</code></a> from the <a href="https://www.thingiverse.com/thing:4967931/files" rel="nofollow noreferrer">files repository on Thingverse</a></p> <ol> <li><p>Download OpenSCAD from here and install it - <a href="https://openscad.org/downloads.html" rel="nofollow noreferrer">https://openscad.org/downloads.html</a></p> </li> <li><p>Put the downloaded SVG file in the same folder as the .SCAD file from this page</p> </li> <li><p>Double-click the .SCAD file to open it</p> </li> <li><p>Click <strong>Window</strong>, then untick <strong>Hide Customizer</strong></p> <p><em>Optional</em>: Click <strong>Window</strong>, then tick <strong>Hide Editor</strong></p> </li> <li><p>Enter the SVG file name in the basic settings tab (or rename the file to qr-code.svg before opening OpenSCAD)</p> </li> <li><p>Customize the settings. After changing a setting, you may need to click outside the text box to apply the change</p> </li> <li><p>Click <strong>Design</strong> &gt; <strong>Render</strong> and wait for the design to render</p> </li> <li><p>Click <strong>File</strong> &gt; <strong>Export</strong> &gt; <strong>Export to STL</strong></p> </li> <li><p>Save the file</p> </li> </ol> <p><a href="https://i.stack.imgur.com/VyzXZ.gif" rel="nofollow noreferrer" title="QR Customisation - optional"><img src="https://i.stack.imgur.com/VyzXZ.gif" alt="QR Customisation - optional" title="QR Customisation - optional" /></a></p> </li> </ol> <h3>Notes</h3> <ul> <li><strong>Raised</strong> and <strong>Cut-Out</strong> types are for changing filament at layer height</li> <li><strong>Multi-color</strong> and <strong>Code</strong> are to be used together for inlay/multi-color printers</li> <li>You can also set <em>Base Height</em> or <em>Code Height</em> to 0 and export each part on it's own</li> <li>If you want to print a <strong>double sided tag</strong>, you can set <em>Base Height</em> to 0 and export the second side. Then just flip this over in the slicer</li> <li>The text options are a okay for basic text, but if you want to use another program to add some, you can add extra height to the top/bottom of the card under <strong>Extra Size Setting</strong></li> </ul> <h3>Advanced Notes</h3> <ul> <li>There is some logic in the script that stop you from making the size too small if you have Line Size set, you can set Line Size to 0 or half your line size value if you really want to override this.</li> <li>You can change the Customize Design settings before generating the QR Code (on <a href="https://qrcode-monkey.com" rel="nofollow noreferrer">QRCode Monkey</a>), but you'll need to set Line Size to 0 and there are no promises that it'll print well</li> <li>If you want to use a different site to create the QR code, resize the image to 1147x1147 pixels before converting it to an SVG. Or if the QR code in the image doesn't have a border, resize it to 1000x1000 px.</li> <li>If you want to use a different source for the SVG file, there are instructions for working out the size in the code (<a href="https://www.thingiverse.com/download:10312157" rel="nofollow noreferrer"><code>QR_Code_Customizer_V01_2.scad</code></a>) at line 215. You'll need to export it as a STL and measure it outside of OpenSCAD, then enter the values into the script.</li> </ul> </blockquote> <p>The linked to Thingiverse page also has some extra steps for adding an icon:</p> <blockquote> <h3>Add an icon</h3> <p>You can import another SVG file as a logo or use logo fonts.</p> <p>The below example uses an <a href="https://iconmonstr.com/?s=wifi" rel="nofollow noreferrer">wifi SVG file</a> from IconMonstr</p> <ul> <li>Download the wifi SVG file</li> <li>Place it in the same folder as the .SCAD file</li> <li>In the customizer: <ul> <li>Add some extra space to the top or bottom of the card under <strong>Extra Size Settings</strong></li> <li>Go to SVG Logo Settings</li> <li>Tick <strong>enable svg logo</strong></li> <li>Enter the filename under <strong>svg logo name</strong></li> <li>Set the <strong>svg y nudge</strong> position and <strong>svg logo scale</strong></li> </ul> </li> </ul> <p><a href="https://i.stack.imgur.com/A2xCK.png" rel="nofollow noreferrer" title="Adding Wi-Fi logo"><img src="https://i.stack.imgur.com/A2xCK.png" alt="Adding Wi-Fi logo" title="Adding Wi-Fi logo" /></a></p> </blockquote>
<p>From the excellent Thingiverse link, <a href="https://www.thingiverse.com/thing:4967931" rel="nofollow noreferrer">Customizable QR Keyring or Tag</a> by <a href="https://www.thingiverse.com/outwardb/designs" rel="nofollow noreferrer"><em>OutwardB</em></a> - which was provided in the (now deleted) <a href="https://3dprinting.stackexchange.com/a/18296/4762">link-only answer</a>:</p> <blockquote> <ol> <li><h3>Create the QR code</h3> <ul> <li><p>Go to <a href="https://qrcode-monkey.com" rel="nofollow noreferrer">QRCode Monkey</a></p> </li> <li><p><strong>Only change the Content settings</strong></p> <p>DO NOT change the color, logo or design settings</p> </li> <li><p>Click <strong>Create QR Code</strong></p> </li> <li><p>Click <strong>Download PNG</strong> and wait for the file to download</p> </li> </ul> </li> <li><h3>Convert to SVG</h3> <ul> <li>Go to <a href="https://convertio.co/png-svg/" rel="nofollow noreferrer">PNG to SVG Converter</a> and convert the PNG image you just downloaded to a .SVG file</li> </ul> </li> <li><h3>Customise in OpenSCAD</h3> <p>You will need <a href="https://www.thingiverse.com/download:10312157" rel="nofollow noreferrer"><code>QR_Code_Customizer_V01_2.scad</code></a> from the <a href="https://www.thingiverse.com/thing:4967931/files" rel="nofollow noreferrer">files repository on Thingverse</a></p> <ol> <li><p>Download OpenSCAD from here and install it - <a href="https://openscad.org/downloads.html" rel="nofollow noreferrer">https://openscad.org/downloads.html</a></p> </li> <li><p>Put the downloaded SVG file in the same folder as the .SCAD file from this page</p> </li> <li><p>Double-click the .SCAD file to open it</p> </li> <li><p>Click <strong>Window</strong>, then untick <strong>Hide Customizer</strong></p> <p><em>Optional</em>: Click <strong>Window</strong>, then tick <strong>Hide Editor</strong></p> </li> <li><p>Enter the SVG file name in the basic settings tab (or rename the file to qr-code.svg before opening OpenSCAD)</p> </li> <li><p>Customize the settings. After changing a setting, you may need to click outside the text box to apply the change</p> </li> <li><p>Click <strong>Design</strong> &gt; <strong>Render</strong> and wait for the design to render</p> </li> <li><p>Click <strong>File</strong> &gt; <strong>Export</strong> &gt; <strong>Export to STL</strong></p> </li> <li><p>Save the file</p> </li> </ol> <p><a href="https://i.stack.imgur.com/VyzXZ.gif" rel="nofollow noreferrer" title="QR Customisation - optional"><img src="https://i.stack.imgur.com/VyzXZ.gif" alt="QR Customisation - optional" title="QR Customisation - optional" /></a></p> </li> </ol> <h3>Notes</h3> <ul> <li><strong>Raised</strong> and <strong>Cut-Out</strong> types are for changing filament at layer height</li> <li><strong>Multi-color</strong> and <strong>Code</strong> are to be used together for inlay/multi-color printers</li> <li>You can also set <em>Base Height</em> or <em>Code Height</em> to 0 and export each part on it's own</li> <li>If you want to print a <strong>double sided tag</strong>, you can set <em>Base Height</em> to 0 and export the second side. Then just flip this over in the slicer</li> <li>The text options are a okay for basic text, but if you want to use another program to add some, you can add extra height to the top/bottom of the card under <strong>Extra Size Setting</strong></li> </ul> <h3>Advanced Notes</h3> <ul> <li>There is some logic in the script that stop you from making the size too small if you have Line Size set, you can set Line Size to 0 or half your line size value if you really want to override this.</li> <li>You can change the Customize Design settings before generating the QR Code (on <a href="https://qrcode-monkey.com" rel="nofollow noreferrer">QRCode Monkey</a>), but you'll need to set Line Size to 0 and there are no promises that it'll print well</li> <li>If you want to use a different site to create the QR code, resize the image to 1147x1147 pixels before converting it to an SVG. Or if the QR code in the image doesn't have a border, resize it to 1000x1000 px.</li> <li>If you want to use a different source for the SVG file, there are instructions for working out the size in the code (<a href="https://www.thingiverse.com/download:10312157" rel="nofollow noreferrer"><code>QR_Code_Customizer_V01_2.scad</code></a>) at line 215. You'll need to export it as a STL and measure it outside of OpenSCAD, then enter the values into the script.</li> </ul> </blockquote> <p>The linked to Thingiverse page also has some extra steps for adding an icon:</p> <blockquote> <h3>Add an icon</h3> <p>You can import another SVG file as a logo or use logo fonts.</p> <p>The below example uses an <a href="https://iconmonstr.com/?s=wifi" rel="nofollow noreferrer">wifi SVG file</a> from IconMonstr</p> <ul> <li>Download the wifi SVG file</li> <li>Place it in the same folder as the .SCAD file</li> <li>In the customizer: <ul> <li>Add some extra space to the top or bottom of the card under <strong>Extra Size Settings</strong></li> <li>Go to SVG Logo Settings</li> <li>Tick <strong>enable svg logo</strong></li> <li>Enter the filename under <strong>svg logo name</strong></li> <li>Set the <strong>svg y nudge</strong> position and <strong>svg logo scale</strong></li> </ul> </li> </ul> <p><a href="https://i.stack.imgur.com/A2xCK.png" rel="nofollow noreferrer" title="Adding Wi-Fi logo"><img src="https://i.stack.imgur.com/A2xCK.png" alt="Adding Wi-Fi logo" title="Adding Wi-Fi logo" /></a></p> </blockquote>
2,044
<p>I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer. </p> <p>What would this syntax look like?</p> <p>I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?</p> <p>(By now we definitely know that closures not will be included in the next Java release)</p> <p>OR </p> <p><strong>edit: <a href="http://puredanger.com/tech/2009/11/18/closures-after-all/" rel="noreferrer">http://puredanger.com/tech/2009/11/18/closures-after-all/</a> :D</strong></p> <p><strong>edit2: Re-thinking JDK7: <a href="http://blogs.oracle.com/mr/entry/rethinking_jdk7" rel="noreferrer">http://blogs.oracle.com/mr/entry/rethinking_jdk7</a></strong></p> <p><strong>edit3: There’s not a moment to lose!: <a href="http://blogs.oracle.com/mr/entry/quartet" rel="noreferrer">http://blogs.oracle.com/mr/entry/quartet</a></strong></p>
<p>Have a look at <a href="http://www.javac.info/" rel="noreferrer">http://www.javac.info/</a> .</p> <p>It seems like this is how it would look:</p> <pre><code>boolean even = { int x =&gt; x % 2 == 0 }.invoke(15); </code></pre> <p>where the <code>{ int x =&gt; x % 2 == 0 }</code> bit is the closure.</p>
<p>Closures have some serious edge cases. I would say that Closures are a much more significant change than Generics and the later still has a number hairy edge cases. e.g. The Java Collections libraries cannot be written/compiled without warnings.</p>
28,913
<p>We are running our Junit 4 test suite against Weblogic 9 in front of an Oracle 10 database (using Hudson as a continuous integration server) and occasionally we will get an ORA-12519 crash during script teardown. However, the error is very intermittent: </p> <ul> <li>It usually happens for the same Test class </li> <li>It doesn't always happen for the same test cases (sometimes they pass) </li> <li>It doesn't happen for the same number of test cases (anywhere from 3-9) </li> <li>Sometimes it doesn't happen at all, everything passes </li> </ul> <p>While I can't guarantee this doesn't happen locally (when running against the same database, of course), I have run the same suite of class multiple times with no issues.</p> <p>Any ideas?</p>
<p>Don't know if this will be everybody's answer, but after some digging, here's what we came up with.</p> <p>The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was <strong>intermittent</strong></p> <p>After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).</p> <p>The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.</p> <p>So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.</p>
<p>I had the similar issue. It happened every time when I run a pack of database (Spring JDBC) tests with <code>SpringJUnit4ClassRunner</code>, so I resolved the issue putting <code>@DirtiesContext</code> annotation for each test in order to cleanup the application context and release all resources thus each test could run with a new initalization of the application context.</p>
25,133
<p>I am trying to store a large amount of boolean information that is determined at run-time. I was wondering what the best method might be.</p> <p>I have currently been trying to allocate the memory using: </p> <p><code>pStatus = malloc((&lt;number of data points&gt;/8) + 1);</code> </p> <p>thinking that this will give me enough bits to work with. I could then reference each boolean value using the pointer in array notation:</p> <p><code>pStatus[element]</code></p> <p>Unfortunately this does not seem to be working very well. First, I am having difficulty initializing the memory to the integer value <code>0</code>. Can this be done using <code>memset()</code>? Still, I don't think that is impacting why I crash when trying to access <code>pStatus[element]</code>. </p> <p>I am also not entirely convinced that this approach is the best one to be using. What I really want is essentially a giant bitmask that reflects the status of the boolean values. Have I missed something?</p>
<pre><code>pStatus = malloc((&lt;number of data points&gt;/8) + 1); </code></pre> <p>This does allocate enough bytes for your bits. However,</p> <pre><code>pStatus[element] </code></pre> <p>This accesses the element'th <em>byte</em>, not bit. So when element is more than one-eighth of the total number of bits, you're accessing off the end of the array allocated.</p> <p>I would define a few helper functions</p> <pre><code>int get_bit(int element) { uint byte_index = element/8; uint bit_index = element % 8; uint bit_mask = ( 1 &lt;&lt; bit_index); return ((pStatus[byte_index] &amp; bit_mask) != 0); } void set_bit (int element) { uint byte_index = element/8; uint bit_index = element % 8; uint bit_mask = ( 1 &lt;&lt; bit_index); pStatus[byte_index] |= bit_mask); } void clear_bit (int element) { uint byte_index = element/8; uint bit_index = element % 8; uint bit_mask = ( 1 &lt;&lt; bit_index); pStatus[byte_index] &amp;= ~bit_mask; } </code></pre> <p>(error checking on range of element left out for clarity. You could make this macros, too)</p>
<p>You allocation code is correct, see the <code>set_bit()</code> and <code>get_bit()</code> functions given in <a href="https://stackoverflow.com/questions/177054/is-there-a-practical-limit-to-the-size-of-bit-masks#177092">this answer</a> to access the boolean. </p>
36,102
<p>Certainly there's the difference in general syntax, but what other critical distinctions exist? There are <em>some</em> differences, right?</p>
<p>The linked comparisons are very thorough, but as far as the main differences I would note the following:</p> <ul> <li><strike>C# has anonymous methods</strike>VB has these now, too</li> <li><strike>C# has the yield keyword (iterator blocks)</strike>VB11 added this</li> <li>VB supports <a href="http://smartypeeps.blogspot.com/2006/06/late-binding-in-c-and-vbnet.html" rel="noreferrer">implicit late binding</a> (C# has explicit late binding now via the dynamic keyword)</li> <li>VB supports XML literals</li> <li>VB is case insensitive</li> <li>More out-of-the-box code snippets for VB</li> <li><Strike>More out-of-the-box refactoring tools for C#</strike>Visual Studio 2015 now provides the same refactoring tools for both VB and C#.</li> </ul> <p>In general the things MS focuses on for each vary, because the two languages are targeted at very different audiences. <a href="http://blogs.msdn.com/ericlippert/archive/2004/03/02/cargo-cultists-part-three-is-mort-a-cargo-cultist.aspx" rel="noreferrer">This blog post</a> has a good summary of the target audiences. It is probably a good idea to determine which audience you are in, because it will determine what kind of tools you'll get from Microsoft.</p>
<p>When it gets to IL its all just bits. That case insensitivity is just a precompiler pass. But the general consensus is, vb is more verbose. If you can write c# why not save your eyes and hands and write the smaller amount of code to do the same thing.</p>
3,272
<p>I do not have a clear understanding of what causes resin prints to become brittle. Firstly, it appears excessive cold (in the 40s or even 30s, I am in New England) may be a factor. What else can cause brittleness in resin prints? Is there a difference between resin types?</p>
<p>With the information provided my thought is that your layers are underexposed for their thickness. Each layer is just barely bonding to the layer above it. After being pulled on by layers below eventually one of the layers fails. This is especially likely to happen on a thin part of the print any may need more support if it is followed by wider layers. But I would suggest trying to increase your exposure time first.</p> <p>option two: it could be your FEP if that has seen too much use it may be time to replace it.</p> <p><a href="https://ameralabs.com/blog/key-things-calibrating-resin-3d-printer/" rel="nofollow noreferrer">calibrating a resin 3D printer</a></p>
<p><a href="https://3dprinting.stackexchange.com/a/14947/8884">Besides the options of underexposure or bad FEP film</a>, there's also the option of the print being in a bad orientation for printing. Often, the quality gets better if you tilt the model some degrees. You do have to clean up some places, but the stresses from pulling free of the FEP get distributed more evenly and are lower, resulting in generally better prints.</p> <p>Other factors that can impact the print quality is the resin's viscosity: the more viscous, the more likely resin can't flow in enough. Resin's viscosity is antiproportional to the room temperature - the hotter the room, the less viscous the resin.</p>
1,781
<p>In RoR,how to validate a Chinese or a Japanese word for a posting form with utf8 code.</p> <p>In GBK code, it uses [\u4e00-\u9fa5]+ to validate Chinese words. In Php, it uses /^[\x{4e00}-\x{9fa5}]+$/u for utf-8 pages.</p>
<p>Ruby 1.8 has poor support for UTF-8 strings. You need to write the bytes individually in the regular expression, rather then the full code:</p> <pre><code>&gt;&gt; "acentuação".scan(/\xC3\xA7/) =&gt; ["ç"] </code></pre> <p>To match the range you specified the expression will become a bit complicated:</p> <pre><code>/([\x4E-\x9E][\x00-\xFF])|(\x9F[\x00-\xA5])/ # (untested) </code></pre> <p><a href="http://books.google.com.br/books?id=jcUbTcr5XWwC&amp;pg=PA50&amp;lpg=PA50&amp;source=web&amp;ots=fHClxbbxcy&amp;sig=up3TxmEM9C3N1K8hf-nnBQDzPUQ&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=6&amp;ct=result" rel="noreferrer">That will be improved in Ruby 1.9</a>, though.</p> <p><em>Edit:</em> As noted in the comments, the unicode characters \u4E00-\u9FA5 only map to the expression above in the UTF16-BE encoding. The UTF8 encoding is likely different. So you need to analyze the mapping carefully and see if you can come up with a byte-matching expression for Ruby 1.8.</p>
<p>activeSupport has a UTF-8 handler</p> <p><a href="http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Handlers/UTF8Handler.html" rel="nofollow noreferrer">http://api.rubyonrails.org/classes/ActiveSupport/Multibyte/Handlers/UTF8Handler.html</a></p> <hr> <p>otherwise, look in ruby 1.9, encoding method for Regexp objects</p>
32,044
<p>This is a multi-site problem. I have a lot of sites with .htaccess files with multiple line similar to:</p> <pre><code>rewriterule ^(page-one|page-two|page-three)/?$ /index.php?page=$1 [L] </code></pre> <p>This means that both www.domain.com/page-one and www.domain.com/page-one/ will both load www.domain.com/index.php?page=page-one</p> <p>However I'm always told that it is good SEO practice to make sure you use only one URL per page so what I'd like to do make www.domain.com/page-one to redirect to www.domain.com/page-one/ via the .htaccess file. </p> <p>Please note the answer I'm <strong>NOT</strong> looking for is to remove the ?$ from the end of the line as that will just cause www.domain.com/page-one to become a 404 link.</p>
<p>Here's a snippet to force everything to end with a slash</p> <pre><code>rewritecond %{REQUEST_FILENAME} !-f rewritecond %{REQUEST_URI} !(.*)/$ rewriterule ^(.*)$ http://%{HTTP_HOST}/$1/ [L,R=301] </code></pre>
<p><em>Untested</em>, but can't you just do this?</p> <pre><code>RewriteRule ^(.*[^/])$ $1/ RewriteRule ^(page-one|page-two|page-three)?$ /index.php?page=$1 [L] </code></pre>
42,008
<p>I'm building a data warehouse that includes delivery information for restaurants. The data is stored in SQL Server 2005 and is then put into a SQL Server Analysis Services 2005 cube.</p> <p>The Deliveries information consists of the following tables:</p> <p><strong>FactDeliveres</strong></p> <ul> <li>BranchKey</li> <li>DeliveryDateKey</li> <li>ProductKey</li> <li>InvoiceNumber (DD: degenerate dimension)</li> <li>Quantity</li> <li>UnitCosT</li> <li>Linecost</li> </ul> <p><strong>Note:</strong> </p> <ul> <li>The granularity of FactDeliveres is each line on the invoice</li> <li>The Product dimension include supplier information</li> </ul> <p><strong>And the problem:</strong> there is no primary key for the fact table. The primary key should be something that uniquely identifies each delivery plus the ProductKey. But I have no way to uniquely identify a delivery.</p> <p>In the source OLTP database there is a DeliveryID that is unique for every delivery, but that is an internal ID that meaningless to users. The InvoiceNumber is the suppliers' invoices number -- this is typed in manually and so we get duplicates.</p> <p>In the cube, I created a dimension based only on the InvoiceNumber field in FactDeliveres. That does mean that when you group by InvoiceNumber, you might get 2 deliveries combined only because they (mistakenly) have the same InvoiceNumber.</p> <p>I feel that I need to include the DeliveryID (to be called DeliveryKey), but I'm not sure how. </p> <p><strong>So, do I:</strong> </p> <ol> <li>Use that as the underlying key for the InvoiceNumber dimension?</li> <li>Create a DimDelivery that grows every time there is a new delivery? That could mean that some attributes come out of FactDeliveries and go into DimDelivery, like DeliveryDate,Supplier, InvoiceNumber.</li> </ol> <p>After all that, I could just ask you: how do I create a Deliveries cube when I have the following information in my source database</p> <p><strong>DeliveryHeaders</strong></p> <ul> <li>DeliveryID (PK)</li> <li>DeliveryDate</li> <li>SupplierID (FK)</li> <li>InvoiceNumber (typed in manually)</li> </ul> <p><strong>DeliveryDetails</strong></p> <ul> <li>DeliveryID (PK)</li> <li>ProductID (PK)</li> <li>Quantity</li> <li>UnitCosT</li> </ul>
<p>I would have Quantity, UnitCode, InvoiceNumber, DeliveryID all in the fact table. Both InvoiceNumber and DeliveryID are degenerate dimensions, because they will change with every fact (or very few facts). It is possible that you could put them in their own dimension if you have a large number of items on each order. The model below may not be 100% correct if you have multiple deliveries on an invoice, but it will be close. Check out Kimball, he might have an example of a star schema for this business scenario.</p> <pre><code>Fact table: OrderDateID (not in your model, but probably should be, date dimension in a role) DeliveryDateID (date dimension in a role) SupplierID (supplier dimension surrogate key) InvoiceID (invoice dimension surrogate key) ProductID (product dimension surrogate key) Quantity (fact) UnitCost (fact) InvoiceNumber (optional) DeliveryID (optional) </code></pre> <p>with the usual date dimension table and the following dimensions:</p> <pre><code>Supplier Dim: SupplierID (surrogate) SupplierCode and data Invoice Dim: InvoiceID (surrogate) InvoiceNumber (optional) DeliveryID (optional) Product Dim: ProductID (surrogate) ProductCode and Data </code></pre> <p>Always remember, your (star schema) data warehouse is not going to be structured at all like your OLTP data - it's all about the facts and what dimensions describe them.</p>
<p>Fact table PK's are almost always surrogate keys. Each fact is part of several dimensions, so the fact has FK's to the dimensions, but no real keys of it's own.</p> <p>A Delivery Fact (a Line Item) belongs to a Branch, it has a Product, it is part of a larger Delivery, it occurs on a particular Date. Sounds like 4 independent dimensions.</p> <p>The Delivery dimension has it's own PK and it has a dimension attribute of invoice number. Plus, perhaps, other attributes of the delivery as a whole. </p> <p>Each Delivery Line Item Fact is associated with one Delivery and the invoice number for that Delivery. </p>
18,061
<p>In SQL Server how do you query a database to bring back all the tables that have a field of a specific name?</p>
<p>The following query will bring back a unique list of tables where <code>Column_Name</code> is equal to the column you are looking for:</p> <pre><code>SELECT Table_Name FROM INFORMATION_SCHEMA.COLUMNS WHERE Column_Name = 'Desired_Column_Name' GROUP BY Table_Name </code></pre>
<pre><code>SELECT Table_Name FROM Information_Schema.Columns WHERE Column_Name = 'YourFieldName' </code></pre>
2,565
<p>Is it possible to provide WCF with a custom proxy address and custom credentials? </p> <p>I've found this answer on stackoverflow: <a href="https://stackoverflow.com/questions/105499/how-to-set-proxy-with-credentials-to-generated-wcf-client">How to set proxy with credentials to generated WCF client?</a>, but I've got a complication, the service I'm authenticating against uses its own authentication, so I've got to use two sets of credentials (one to get through the proxy, and the other to authenticate against the service)</p> <p>I'm using the technique described in the answers to the other question to provide the service credentials. e.g.</p> <pre><code>client.ClientCredentials.UserName.UserName = username; client.ClientCredentials.UserName.Password = password; </code></pre> <p>I can set the address of the proxy using something like this:</p> <pre><code>(client.Endpoint.Binding as WSHttpBinding).ProxyAddress = ...; </code></pre> <p>How do I set what is effectively two sets of credentials? (NB: The credentials for the proxy and the actual service are different!) Also note that the proxy details are not necessarily the default system proxy details.</p>
<p>If you set the <a href="http://msdn.microsoft.com/en-us/library/system.net.webrequest.defaultwebproxy.aspx" rel="noreferrer">WebRequest.DefaultWebProxy</a> property to a new WebProxy with credentials, WCF will use it for all HTTP requests that it makes. (This will affect all HttpWebRequests used by the application unless explicitly overridden).</p> <pre><code>// get this information from the user / config file / etc. Uri proxyAddress; string userName; string password; // set this before any web requests or WCF calls WebRequest.DefaultWebProxy = new WebProxy(proxyAddress) { Credentials = new NetworkCredential(userName, password), }; </code></pre> <p>My <a href="http://code.logos.com/blog/2010/01/using_http_proxy_servers.html" rel="noreferrer">blog post on proxy servers</a> contains further details.</p>
<p>The client credentials you're setting are fine in order to authenticate to your services.<br> For proxy authentication you need to use HttpTransportSecurity.ProxyCredentials.</p> <p>This link might help you out.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.httptransportsecurity.proxycredentialtype.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.servicemodel.httptransportsecurity.proxycredentialtype.aspx</a></p>
22,639
<p>Is there an equivalant to Environment.NewLine in DotNet for a Tab character?</p>
<p>NewLine is on the Environment class because the new line specification varies between platforms:</p> <p>It's "\r\n" for non-Unix platforms and "\n" for Unix platforms. However tab is always "\t".</p>
<p>Short answer is: no, tab does not change between platforms as newline might, so there is no need for one.</p> <p>Long answer is: technically, yes, you could use the one provided by VB in the Microsoft.VisualBasic.dll. I think it's Microsoft.VisualBasic.Constants.vbTab, but there's no good reason to use it in C# as I said above.</p>
37,662
<p>Any python libs for parsing Bind zone files? Basically something that will aid in adding/removing zones and records. This needs to work even if someone modifies the zone file by hand so overwriting the zone files every time is not a solution. </p>
<p>I was unable to use bicop for classical zone files like these:</p> <pre><code> $TTL 86400 @ IN SOA ns1.first-ns.de. postmaster.robot.first-ns.de. ( 2006040800 ; serial 14400 ; refresh 1800 ; retry 604800 ; expire 86400 ) ; minimum @ IN NS ns1.first-ns.de. </code></pre> <p>I will have a look at <a href="http://www.dnspython.org/" rel="nofollow noreferrer">dnspython</a></p>
<p>See answer above about bicop.</p> <p>As an aside, the Python Package Index at <a href="http://pypi.python.org/pypi" rel="nofollow noreferrer">http://pypi.python.org/pypi</a> is a great place to look for Python packages.</p> <p><strong>EDIT</strong>: The below may still be helpful to someone trying to figure out simple parsing, but bicop is apparently an existing solution.</p> <p>If someone has modified the config by hand, and you don't want to overwrite it, does that imply that you wish to insert/remove lines from an existing config, leaving all comments etc intact? That does prevent parsing then re-outputting the config, but that's a positive as well -- you don't need to fully parse the file to accomplish your goal.</p> <p>To add a record, you might try a simple approach like</p> <pre><code># define zone_you_care_about and line_you_wish_to_insert first, then: for line in bindfile.read(): out.write(line + '\n') if ('zone "%s" in' % zone_you_care_about) in line: out.write(line_you_wish_to_insert) </code></pre> <p>Similar code works for removing a line:</p> <pre><code># define zone_you_care_about and relevant_text_to_remove, then: for line in bindfile.read(): if not relevant_text_to_remove in line: out.write(line + '\n') </code></pre> <p>You may get as far as you need with simple snippets of code like this.</p>
29,308
<p><strong>The situation</strong><br> I have a Git repo and an SVN repo that both hold the same source code but different commit histories. The Git repo has a lot of small well commented submits... while the SVN repo has a few huge commits with comments like "Lots of stuff". Both series of commits follow the same changes made in the code and are roughly equivalent.</p> <p><strong>The desired outcome</strong><br> I would like to switch to using Git-SVN <em>without</em> losing the detailed history from the current Git repo. This should be done by 'grafting' the history from the Git repo onto an SVN branch of the project (branched from the point I really started using Git).</p> <p><strong>Why would you do that? (history)</strong><br> A while ago I started to play with Git. I started by setting up a Git repo in a project I had under SVN control. With a little config, I had both Git and SVN working in parallel on the same source code.</p> <p>This was a great way for me to learn and play with Git, while still having the safety net of SVN. It was a sandbox with real data basically. I didn't have the time to really <em>learn</em> Git but I really wanted to tinker with it. This was actually a pretty good way to learn Git for me.</p> <p>At first, after doing some edits, I would commit to SVN and then to Git... then play with Git knowing my changes were safely in SVN. Soon I was committing more frequently to Git than SVN... Now, SVN commits have fallen to an annoying chore I have to do sometimes.</p> <p>When learning the difference between <code>git revert</code> and <code>svn revert</code> I was <em>VERY</em> glad I had been checking in to the SVN repo. I almost lost a few weeks' work assuming that the two worked the same.</p> <p>I now know the glories of Git-SVN and I am using it happily on several other projects. I fully realized when I started that I might lose my Git repo and have to setup a new one 'properly' using <code>git-svn init</code>... but having played with Git for a while now, I'm sure there is some way of hacking the Git history into SVN.</p>
<p>That could be tough to do what you want. You can import a git repo into svn via something like this: <a href="http://code.google.com/p/support/wiki/ImportingFromGit" rel="nofollow noreferrer">http://code.google.com/p/support/wiki/ImportingFromGit</a>, but I think you will have conflicts. You could just recreate your SVN repo from scratch based on your git repo.</p> <p>For future reference, it probably would've been easier to just use Git as an SVN client:</p> <pre><code>git-svn clone path/to/your/svn/repo git-commit -a -m 'my small change' vi some files to change.txt git-commit -a -m 'another small change' git-svn dcommit # sends your little changes as individual svn commits </code></pre>
<p>From the git svn repository that you are trying to migrate to, do something like the following:</p> <pre><code>git remote add old-repo &lt;path-to-old-repo&gt; git fetch old-repo # to browse and figure out the hashes, if that helps gitk --all &amp; # for each branch you want to graft git rebase --onto &lt;new git svn branch base&gt; &lt;old-repo branch base&gt; &lt;old-repo branch tip&gt; # when done git remote rm old-repo </code></pre> <p>For your information, you should also be able to do the same thing using git format-patch and git am, but git rebase should be more friendly.</p>
14,296
<p>Why EAccessViolation is raised when executing the code below? </p> <pre><code>uses Generics.Collections; ... var list: TList&lt;TNotifyEvent&gt;; ... begin list := TList&lt;TNotifyEvent&gt;.Create(); try list.Add(myNotifyEvent); list.Remove(myNotifyEvent); // EAccessViolation at address... finally FreeAndNil(list); end; end; procedure myNotifyEvent(Sender: TObject); begin OutputDebugString('event'); // nebo cokoliv jineho end; </code></pre>
<p>It looks like a bug.</p> <p>If you compile with debug dcu's (normally don't do that unless you want to loose your sanity!) you see that a call to the comparer went wrong. A (possibly optional) third value of a compare function is not set and causes the access violation.</p> <p>So possibly you can't put method pointers in a generic list.</p> <p>Ok the following works:</p> <pre><code>uses Generics.Defaults; type TForm4 = class(TForm) ... private procedure myNotifyEvent(Sender: TObject); end; TComparer&lt;T&gt; = class (TInterfacedObject, IComparer&lt;T&gt;) public function Compare(const Left, Right: T): Integer; end; implementation uses Generics.Collections; var list: TList&lt;TNotifyEvent&gt;; begin list := TList&lt;TNotifyEvent&gt;.Create(TComparer&lt;TNotifyEvent&gt;.Create); try list.Add(myNotifyEvent); list.Remove(myNotifyEvent); finally FreeAndNil(list); end; end; procedure TForm4.myNotifyEvent(Sender: TObject); begin ShowMessage('event'); end; { TComparer&lt;T&gt; } function TComparer&lt;T&gt;.Compare(const Left, Right: T): Integer; begin Result := 0; end; </code></pre> <p>You have to define your own comparer, with possiby some more intelligence ;-).</p>
<p>the above code is used in TForm1 ...</p> <pre><code>uses Generics.Collections; procedure TForm1.Button1Click(Sender: TObject); var list: TList&lt;TNotifyEvent&gt;; begin list := TList&lt;TNotifyEvent&gt;.Create(); try list.Add(myNotifyEvent); list.Remove(myNotifyEvent); // EAccessViolation at address... finally FreeAndNil(list); end; end; procedure TForm1.myNotifyEvent(Sender: TObject); begin OutputDebugString('event'); // nebo cokoliv jineho end; </code></pre>
36,926
<p>I'm using the following code within the JCProperty class to retrieve data from a DAL: </p> <pre><code>Dim x As JCProperty x = JCPropertyDB.GetProperty(PropertyID) If Not x Is Nothing Then Me.PropertyID = x.PropertyID Me.AddressLine1 = x.AddressLine1 Me.AddressLine2 = x.AddressLine2 Me.AddressLine3 = x.AddressLine3 Me.AddressCity = x.AddressCity Me.AddressCounty = x.AddressCounty Me.AddressPostcode = x.AddressPostcode Me.TelNo = x.TelNo Me.UpdatedOn = x.UpdatedOn Me.CreatedOn = x.CreatedOn Me.Description = x.Description Me.GUID = x.GUID End If </code></pre> <p>This works fine but requires that the DAL object (JCPropertyDB) is aware of the business object (JCProperty) and I effectively create and populate the same object twice (once in the DAL to return to the BL and then again within the BL object to populate itself). </p> <p>I'm missing something here, I know there must be a better way! </p> <p>Effectively I need to assign 'Me = x' which is not allowed. Can someone put me straight?</p>
<p>Not sure if this will answer your question, but the important point is that the domain model is independent of display and independent of storage. This is often denoted as separation of concerns. The idea is to get loose couplings and create a simple system where objects do not have several completely different responsibilities. <br> So what I would do, is to allow the DAL to create business objects directly, but make sure I don't contaminate my business objects with anything related to the DAL. Similarly I don't want to contaminate them with UI-specific things like HTML. In my opinion it's ok that both the business layer, DAL and UI-layer all have dependencies to the domain model, however it's not ok to have dependencies from the domain model and into these other components.<br> To loosen the couplings, using something Spring or any other Dependency injection container together with interfaces and wiring can help you.<br> By recreating the same object in every layer you are violating the DRY principle (Don't repeat yourself) and you are introducing boiler plate code and increasing the chance of introducing an error somewhere.</p>
<p>Check out: <a href="http://www.icemanind.com/layergen.aspx" rel="nofollow noreferrer">http://www.icemanind.com/layergen.aspx</a></p>
23,597
<p>Is there any way to generate Excel/CSV through Javascript? (It should be browser compaatible too)</p>
<p>There is an interesting project on github called <strong>Excel Builder (.js)</strong> that offers a client-side way of downloading Excel <strong>xlsx</strong> files and includes options for formatting the Excel spreadsheet.<br> <a href="https://github.com/stephenliberty/excel-builder.js" rel="noreferrer">https://github.com/stephenliberty/excel-builder.js</a></p> <p>You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful. </p> <p>Another github project with less Excel options but less worries about Excel compatibility issues can be found here: <strong>ExcellentExport.js</strong><br> <a href="https://github.com/jmaister/excellentexport" rel="noreferrer">https://github.com/jmaister/excellentexport</a></p> <p>If you are using AngularJS, there is <strong><a href="https://github.com/asafdav/ng-csv" rel="noreferrer">ng-csv</a></strong>:<br> a "Simple directive that turns arrays and objects into downloadable CSV files".</p>
<p>To answer your question with a working example: </p> <pre><code>&lt;script type="text/javascript"&gt; function DownloadJSON2CSV(objArray) { var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray; var str = ''; for (var i = 0; i &lt; array.length; i++) { var line = new Array(); for (var index in array[i]) { line.push('"' + array[i][index] + '"'); } str += line.join(';'); str += '\r\n'; } window.open( "data:text/csv;charset=utf-8," + encodeURIComponent(str)); } &lt;/script&gt; </code></pre>
43,235
<p>I have a MasterPage, with my Usercontrol inside a div.</p> <p>I can set visible=false to the UserControl and to the containing div, and this works fine. But the Page_Load of the UserControl is always hit.</p> <p>Is this by design, or am I missing how to stop page execution going into the Page_Load method of the UserControl.</p>
<p>svnadmin dump is the recommended way to <a href="http://svnbook.red-bean.com/en/1.1/ch05s03.html#svn-ch-5-sect-3.5" rel="noreferrer">migrating your repositories</a>, but you'll need shell access to do it, otherwise you will have to contact your hosting provider and ask them to do the full repository dump for you. </p>
<p>Sounds like you need a <a href="http://rsvndump.sourceforge.net/" rel="nofollow noreferrer">remote SVN dump command</a>. I haven't used it but it claims to do what you want.</p>
46,261
<p>I really should upgrade to Firefox 3, but I'm very dependent on Firebug working properly.</p> <p>I know there is a version of Firebug that is supposed to work with Firefox 3, but last time I looked, there seemed to be problems with it.</p> <p>So, for those that have made the jump, is Firebug on Firefox 3 ready for prime time?</p>
<p>Yes, I've been using Firebug heavily and it's been rock-steady. What problems were you having in particular? We could test and report the results.</p>
<p>FYI, there's a bug in firebug 1.3.3 on firefox 3.0.9 that causes it not to send an If-modified-since header so it always gets a copy from the server instead of using the cached local copy.</p> <p><a href="http://code.google.com/p/fbug/issues/detail?id=1274&amp;q=etag&amp;colspec=ID%20Type%20Status%20Owner%20Test%20Summary" rel="nofollow noreferrer">http://code.google.com/p/fbug/issues/detail?id=1274&amp;q=etag&amp;colspec=ID%20Type%20Status%20Owner%20Test%20Summary</a></p>
16,681
<p>We're building tools to mine information from the web. We have several pieces, such as </p> <ul> <li>Crawl data from the web</li> <li>Extract information based on templates &amp; business rules</li> <li>Parse results into database</li> <li>Apply normalization &amp; filtering rules</li> <li>Etc, etc.</li> </ul> <p>The problem is troubleshooting issues &amp; having a good "high-level picture" of what's happening at each stage. </p> <p><strong>What techniques have helped you understand and manage complex processes?</strong> </p> <ul> <li>Use workflow tools like Windows Workflow foundation</li> <li>Encapsulate separate functions into command-line tools &amp; use scripting tools to link them together</li> <li>Write a Domain-Specific Language (DSL) to specify what order things should happen at a higher level.</li> </ul> <p>Just curious how you get a handle on a system with many interacting components. We'd like document/understand how the system works at a higher level than tracing through the source code.</p>
<p>The code says what happens at each stage. Using a DSL would be a boon, but possibly not if it comes at the cost of writing your own scripting-language and/or compiler.</p> <p>Higher level documentation should not include details of what happens at each step; it should provide an overview of the steps and how they relate together.</p> <p>Good tips:</p> <ul> <li>Visualize your database schema relations.</li> <li>Use visio or other tools (like the one you mentioned - haven't used it) for process overviews (imho it belongs to the specification of your project).</li> <li>Make sure your code is properly structured / compartmentalized / etc.</li> <li>Make sure you have some sort of project specification (or some other "general" documentation that explains what the system does on an abstract level).</li> </ul> <p>I wouldn't recommend building command-line tools unless you actually have a use for them. No need in maintaining tools you don't use. (That's not the same as saying it can't be useful; but most of what you do sounds more like it belongs in a library rather than executing external processes).</p>
<p>Top down design helps a lot. One mistake I see is making the top down design sacred. Your top level design needs to be reviewed and update just like any other section of code. </p>
39,068
<p>I have to make a newsletter sending utility application which will collect the list of subscriber from our central database and send out the newsletter. I've considered the possibility to be blacklisted due to flooding if I just flush out all emails at once, so I decided to go on a desktop-based softwer which will email those slowly.</p> <p>my question is </p> <ul> <li>what is the max emails per hour that may be addressed to the same email domain (recipient/incoming server)?</li> <li>or what should be delay between 2 e-mails to the same server for it doesn't consider it flooding?</li> </ul> <p>whichever of the above applies more appropriate to the real-world of mail servers configuration... </p> <p>thanks</p>
<p>I make Thread.Sleep(2000) after every 2 mail</p>
<p>It's really going to vary by configuration, so there's not necessarily a one-size-fits-all answer. You might want to check with your ISP - it's probably them or their upstream that you'd need to worry about.</p> <p>Since you're sending a newsletter, could you add multiple recipients via BCC rather than individual messages? That should be less "abusive" to all concerned.</p>
29,131
<p>Do any queries exist that require RIGHT JOIN, or can they always be re-written with LEFT JOIN?</p> <p>And more specifically, how do you re-write this one without the right join (and I guess implicitly without any subqueries or other fanciness):</p> <p><pre><code> SELECT * FROM t1 LEFT JOIN t2 ON t1.k2 = t2.k2 RIGHT JOIN t3 ON t3.k3 = t2.k3 </pre></code></p>
<p>You can always re-write them to get the same result set. However, sometimes the execution plan may be different in significant ways (performance) and sometimes a right join let's you express the query in a way that makes more sense.</p> <p>Let me illustrate the performance difference. Programmers tend to think in terms of an sql statement happening all at once. However, it's useful to keep a mental model that complicated queries happen in a series of steps where tables are typically joined in the order listed. So you may have a query like this:</p> <pre><code>SELECT * /* example: don't care what's returned */ FROM LargeTable L LEFT JOIN MediumTable M ON M.L_ID=L.ID LEFT JOIN SmallTable S ON S.M_ID=M.ID WHERE ... </code></pre> <p>The server will normally start by applying anything it can from the WHERE clause to the first table listed (LargeTable, in this case), to reduce what it needs to load into memory. Then it will join the next table (MediumTable), and then the one after that (SmallTable), and so on. </p> <p>What we want to do is use a strategy that accounts for the expected impact of each joined table on the results. In general you want to keep the result set as small as possible for as long as possible. Apply that principle to the example query above, and we see it's obviously much slower than it needs to be. It starts with the larger sets (tables) and works down. We want to begin with the smaller sets and work up. That means using SmallTable first, and the way to do that is via a RIGHT JOIN.</p> <p>Another key here is that the server usually can't know which rows from SmallTable will be needed until the join is completed. Therefore it only matters if SmallTable is so much smaller than LargeTable that loading the entire SmallTable into memory is cheaper than whatever you would start with from LargeTable (which, being a large table, is probably well-indexed and probably filters on a field or three in the where clause).</p> <p>It's important to also point out that in the vast majority of cases the optimizer will look at this and handle things in the most efficient way possible, and most of the time the optimizer is going to do a better job at this than you could. </p> <p>But the optimizer isn't perfect. Sometimes you need to help it along: especially if one or more of your "tables" is a view (perhaps into a linked server!) or a nested select statement, for example. A nested sub-query is also a good case of where you might want to use a right join for expressive reasons: it lets you move the nested portion of the query around so you can group things better.</p>
<p>I use <code>LEFT JOIN</code>s about 99.999% of the time, but some of my dynamic code generation uses <code>RIGHT JOIN</code>s which mean that the stuff outside the join doesn't need to be reversed.</p> <p>I'd also like to add that the specific example you give I believe produces a cross join, and that is probably not your intention or even a good design.</p> <p>i.e. I think it's effectively the same as:</p> <pre><code>SELECT * FROM t1 CROSS JOIN t3 LEFT JOIN t2 ON t1.k2 = t2.k2 AND t3.k3 = t2.k3 </code></pre> <p>And also, because it's a cross join, there's not a lot the optimizer is going to be able to do.</p>
30,845
<p>I am using <a href="http://www.hibernate.org/" rel="noreferrer">Hibernate</a> in a Java application to access my Database and it works pretty well with MS-SQL and MySQL. But some of the data I have to show on some forms has to come from Text files, and by Text files I mean Human-Readable files, they can be CSV, Tab-Delimited, or even a key, value pair, per line since my data is as simple as this, but my preference of course is XML files.</p> <p>My question is: Can I use hibernate to read those files using HQL, Query , EntityManager and all those resources Hibernate provides me to access files. Which file format should I use and How I configure My persistence.xml file to recognize files as Tables?</p>
<p>Hibernate is written against the JDBC API. So, you need a JDBC driver that works with the file format you are interested in. Obviously, even for read-only access, this isn't going to perform well, but it might still be useful if that's not a high priority. On a Windows system, you can set up ODBC datasources for delimited text files, Excel files, etc. Then you can set up the JdbcOdbcDriver in your Java application to use this data source.</p> <p>For most of the applications I work on, I would not consider this approach; I would use an import/export mechanism to convert from a real database (even if it's an in-process database like Berkeley DB or Derby) to the text files. Yes, it's an extra step, but it could be automated, and the performance isn't likely to be much worse than trying to use the text files directly (it will likely be much better, overall), and it will be more robust and easy to develop.</p>
<p>Like erickson said, your only hope is in finding a JDBC driver for that task. There is maybe <del><a href="https://xlsql.dev.java.net/" rel="nofollow noreferrer">xlsql</a></del> (CSV, XML and Excel driver) which could fit the task. After that, you just have to either find or write the most simple Hibernate Dialect which fits your driver.</p>
5,347
<p>What library should be included to use TransparentBlt?</p> <p>This is VC98 (Visual Studio 6) linking to the Gdi32.lib. (Other GDI functions such as BitBlt link as expected), and the compilers compiles with out error or warning.</p> <p>Even though the Gdi32.lib is included, yet the linker returns this error:</p> <pre> mtcombo.obj : error LNK2001: unresolved external symbol __imp__TransparentBlt@44 C:\Work\Montel\Targ2_12\guitest.exe : fatal error LNK1120: 1 unresolved externals </pre> <p>What am I missing?</p>
<p>AFAIK, you will need the Msimg32.lib</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms532303(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms532303(VS.85).aspx</a></p>
<p>Msimg32.lib</p> <p>FYI you can search the functions on <a href="http://msdn.microsoft.com/library" rel="nofollow noreferrer">http://msdn.microsoft.com/library</a> and at the bottom it will tell you what library you need.</p>
20,869
<p>I'd like to allow users to record videos directly from their webcam. I haven't done much work with PHP but am stuck with it for this project. We currently have a system in place for video uploading and encoding, but nothing to actually access a user's webcam. How would you recommend I proceed?</p>
<p>Webcams aren't available to HTML or JavaScript/DOM in any browsers that I know of, so you're going to end up dependent on some sort of plugin. I'd recommend you start your search with Adobe Flash/Flex, though It's possible that Microsoft Silverlight is able to do the same thing. Flex is a bit more reliable technology and has been around longer, but Microsoft is pouring a ton of money into Silverlight, and I expect it to improve radically over the next few years.</p>
<p>The browser itself cannot access a user's webcam. There are proposals for a new type of input field to support this, but is is not currently available. You'd have to do it through a plug-in.</p>
27,017
<p>I just set up a refurbished <a href="https://www.monoprice.com/product?p_id=29417" rel="nofollow noreferrer">MP Select Mini V2</a> and tried to print the test file included by the manufacturer, <code>cat.gcode</code>, from the included SD card. I printed in PLA (I think; the unlabeled sample included with the printer) at the default extruder temperature, 190&nbsp;°C. The print bed was set to 50&nbsp;°C.</p> <p>It appeared to print the raft fine, and then a couple of layers of the cat. At this point I walked away, and when I came back a few minutes later here's what I found:</p> <p><a href="https://i.stack.imgur.com/UuaCr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UuaCr.jpg" alt="Printer with awful mess"></a></p> <p>The raft is still stuck to the bed, but the layers of cat that were printed fell off the base and onto the floor. Here's what I picked up off the floor, (next to the detached raft):</p> <p><a href="https://i.stack.imgur.com/omh6M.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/omh6M.jpg" alt="Raft and mangled print"></a></p> <p>The raft was stuck on the bed just fine, so I don't think it's an adhesion issue. The bed and the desk the printer is sitting on are both very close to level (things don't slide or roll off). There's no breeze and I'm certain nothing bumped or touched the printer while it was running.</p> <p>This is my first attempt at a print so I obviously have no idea what I'm doing. I'm planning to set up a camera to record the next attempt. What other troubleshooting can I do? What is the likely cause of this problem?</p>
<p>Your trouble lies within the presliced G-code: the temperatures are rather low for PLA and upping both by 10 degrees would be advisable:</p> <ul> <li>200 °C for the Hotend</li> <li>60 °C for the Bed</li> </ul> <p>Atop that, printing a raft for PLA is usually not advisable.</p> <p>Get yourself a slicer (the most common free ones I am comfortable with using are Cura, Slic3r and Slic3r Prusa Edition) and either import a fitting profile and create your own profile, then slice the <code>.stl</code>-model yoruself.</p>
<p>It looks to me as the model did not have enough surface contact with the raft.</p> <hr> <p>This can be caused by to big of a gap between raft and model set in the slicer or because of Underextrusion. The part itself does not look underextruded, at least not a lot, so I would say that the slicer settings were not ideal.</p> <p>I would suggest you slice a part by yourself and test the printer again.</p> <p>From personal experience a skirt or brim works better with PLA and uncomplicated models.</p> <p>For general bugfixing, explanation of slicer settings and anomalies the Simplfy3D hompage is a great resource.</p> <p>Here is an article about <a href="https://www.simplify3d.com/support/articles/rafts-skirts-and-brims/" rel="nofollow noreferrer">Rafts, Skirts and Brims</a> and <a href="https://www.simplify3d.com/support/print-quality-troubleshooting/" rel="nofollow noreferrer">here the general guide page for print quality.</a></p> <hr> <p>Your printing temperature is a bit low but shouldn't be the cause for the problem. Maybe check the specs on the PLA you used. Your bet temperature seems to be fine as the raft did adhere well.</p> <hr>
1,385
<p>I must admit that I am incredibly jealous of those developers who happen to live near active user groups (e.g. the ALT.NET guys in Austin). I often read blog posts and listen to podcasts that reference these in-person meetings and find myself wishing that I could sit in and participate as well. But it just isn't realistic to fly across the country to meet a few guys for a couple hours in a pub to talk about patterns and practices.</p> <p>So I was wondering if there was a similar discussion forum for those who don't happen to live near an active user group. After all, blogs and books only go so far, and for the most part are a one-way avenue of communication. True, you can use comments, e-mails, tweets, and IM to get some interaction, but there is something to be said about face-to-face real-time interaction that will get lost in all of these mediums. </p> <p>I guess what I'm looking for is some sort of video-conferencing deal where people who share an interest in a specific field of software development can get together to talk and interact without having to live right next door to each other. Does anything like this exist?</p>
<p>There's a <a href="http://www.sldnug.net/" rel="nofollow noreferrer">.NET usergroup</a> in SecondLife. Of course this depends how you feel about second life.</p>
<p>There's a <a href="http://www.sldnug.net/" rel="nofollow noreferrer">.NET usergroup</a> in SecondLife. Of course this depends how you feel about second life.</p>
14,249
<p>I currently have a button called Edit and a text box call blah on a ajax updatepanel. is it possible to set the asp.net's textbox Readonly via trigger? </p>
<p>Yes it is possible.</p> <p>Assuming the trigger is the edit button's onclick handler, put the code there...</p>
<p>As long as the button triggers the update panel all you should have to do is set the read only property to true in the button's click event handler.</p>
46,638
<p>I'm trying to debug the MSBuild Customtask, that I have just created, but for some reason it never stops at the breakpoint. I've even tried this:</p> <pre><code> public override bool Execute() { System.Diagnostics.Debugger.Break(); </code></pre> <p>And added a break point on that line... I even eliminated all the other code in the method and that didn't change anything.</p> <p>Is there anything special required to be able to debug the creation of custom tasks for MSBuild ?</p>
<p>It's a bit of a hack, but you could always just put this line of code wherever it is that you want to start debugging:</p> <pre><code>System.Diagnostics.Debugger.Launch(); </code></pre> <p>When you invoke it, the CLR will launch a dialog asking you what debugger you want to attach.</p>
<p>You can set the environment variable <code>MSBUILDDEBUGONSTART=1</code> to make <code>MSBuild.exe</code> prompt to launch a debugger at its application startup.</p> <p>You can then select the Visual Studio instance you're using to develop your task as the debugger, and set a breakpoint in your task's code.</p> <p>This is generally a bit more difficult than modifying your task to call <code>Debugger.Launch()</code>, but it can be used on release builds and without modifying a task, which can be useful.</p> <p>There's one major caveat here: when you build with <code>-m</code>, MSBuild will launch multiple processes, and <em>each of them</em> will prompt to attach a debugger. Try to build with <code>-m:1</code> or build single projects when doing this, so that you don't accidentally spawn dozens of processes that want to be debugged.</p>
46,607
<p>I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that?</p>
<p>Note that venerable <a href="http://www.xmission.com/~nate/glut.html" rel="noreferrer">Nate Robin's GLUT</a> library doesn't support the scrollwheel. But, later implementations of GLUT like <a href="http://freeglut.sourceforge.net/" rel="noreferrer">FreeGLUT</a> do.</p> <p>Using the scroll wheel in FreeGLUT is dead simple. Here is how:</p> <p>Declare a callback function that shall be called whenever the scroll wheel is scrolled. This is the prototype:</p> <pre><code>void mouseWheel(int, int, int, int); </code></pre> <p>Register the callback with the (Free)GLUT function <strong>glutMouseWheelFunc()</strong>.</p> <pre><code>glutMouseWheelFunc(mouseWheel); </code></pre> <p>Define the callback function. The second parameter gives the direction of the scroll. Values of +1 is forward, -1 is backward.</p> <pre><code>void mouseWheel(int button, int dir, int x, int y) { if (dir &gt; 0) { // Zoom in } else { // Zoom out } return; } </code></pre> <p>That's it!</p>
<p>observe case 3 and 4 in the switch statement below in the mouseClick callback</p> <pre><code>glutMouseFunc(mouseClick); </code></pre> <p>... </p> <pre><code>void mouseClick(int btn, int state, int x, int y) { if (state == GLUT_DOWN) { switch(btn) { case GLUT_LEFT_BUTTON: std::cout &lt;&lt; "left click at: (" &lt;&lt; x &lt;&lt; ", " &lt;&lt; y &lt;&lt; ")\n"; break; case GLUT_RIGHT_BUTTON: std::cout &lt;&lt; "right click at: (" &lt;&lt; x &lt;&lt; ", " &lt;&lt; y &lt;&lt; ")\n"; break; case GLUT_MIDDLE_BUTTON: std::cout &lt;&lt; "middle click at: (" &lt;&lt; x &lt;&lt; ", " &lt;&lt; y &lt;&lt; ")\n"; break; case 3: //mouse wheel scrolls std::cout &lt;&lt; "mouse wheel scroll up\n"; break; case 4: std::cout &lt;&lt; "mouse wheel scroll down\n"; break; default: break; } } glutPostRedisplay(); } </code></pre>
3,515
<p>I have a class Agent with a property Id</p> <p>Given a collection of Agents I need to check if any of them have duplicate Ids.</p> <p>I am currently doing this with a hash table but am trying to get Linq-ified, what's a good way of doing this?</p>
<p>Similar to Y Low's approach,</p> <p><strong>Edited:</strong></p> <pre><code> var duplicates = agents.GroupBy(a =&gt; a.ID).Where(a=&gt;a.Count() &gt; 1); foreach (var agent in duplicates) { Console.WriteLine(agent.Key.ToString()); } </code></pre>
<p>this is how i would do it without the need to do group-by in one line:</p> <pre><code> List&lt;Agent&gt; duplicates = new HashSet&lt;Agent&gt;(agents.Where(c =&gt; agents.Count(x =&gt; x.ID == c.ID) &gt; 1)).ToList(); </code></pre>
40,212
<p>For certain programs nothing beats the command line. Unfortunately, I have never seen good documentation or examples on how to write console applications that go beyond "Hello World". I'm interested in making console apps like <a href="http://en.wikipedia.org/wiki/Vim_(text_editor)" rel="nofollow noreferrer">Vim</a> or <a href="http://en.wikipedia.org/wiki/Emacs" rel="nofollow noreferrer">Emacs</a>. Well not exactly like Vim or Emacs but one that takes over the entire command prompt while it is in use and then after you exit it leaves no trace behind. I know that on Unix there is the <a href="http://en.wikipedia.org/wiki/Curses_(programming_library)" rel="nofollow noreferrer">curses library</a> but for Windows? ...</p>
<p><a href="http://pdcurses.sourceforge.net/" rel="nofollow noreferrer">PDCurses</a> works on Win32.</p>
<p>This is the best tool for it I've ever seen!!<br> 1) Create any application using <strong><em>VB6 IDE</em></strong><br> 2) Convert it to <strong><em>Console Application</em></strong>, using <a href="http://nirsoft.net/vb/console_application_visual_basic.html" rel="nofollow"><strong>THIS!</strong></a></p>
6,487
<p>I'm aware of the built in code generation and refactoring one can do with the "Source" and "Refactor" menu items in Eclipse. </p> <p>I also use the Commonclipse plugin to easily make use of the Apache Commons classes that build hashCode, toString, equals methods.</p> <p>What other plugins or tools should I be aware of for generating Java source easily under the Eclipse IDE? </p>
<p><strong>Telosys</strong> ( <a href="https://www.telosys.org/" rel="nofollow noreferrer">https://www.telosys.org/</a> ) is a simple and efficient tool for Java code generation.</p> <p>This code generator is available as an <strong>Eclipse Plugin</strong> (<a href="https://marketplace.eclipse.org/content/telosys-tools" rel="nofollow noreferrer">https://marketplace.eclipse.org/content/telosys-tools</a>) and also as a <strong>Command Line Interface</strong> (<a href="https://doc.telosys.org/telosys-cli" rel="nofollow noreferrer">https://doc.telosys.org/telosys-cli</a>).</p> <p>The model defining all the entities can be created from scratch or from an existing database.</p> <p>The templates are based on <strong>Velocity</strong> (<a href="https://velocity.apache.org/" rel="nofollow noreferrer">https://velocity.apache.org/</a>) and can be downloaded from GitHub. All the templates are customizable and new templates can be created from scratch if necessary. Existing templates can generate code forJPA, Spring MVC, Database documentation, REST API, etc.</p>
<p>I don't know if you're a big UML fan but <a href="http://www.ibm.com/developerworks/rational/library/05/ahmed/" rel="nofollow noreferrer">IBM Rational suite</a> is extremly powerful.</p> <p>I used it to move from UML to generated mock objects but that's only a slight part of what it can do</p>
47,019
<p>How can I write a function that takes an array of integers and returns true if their exists a pair of numbers whose product is odd?</p> <p>What are the properties of odd integers? And of course, how do you write this function in Java? Also, maybe a short explanation of how you went about formulating an algorithm for the actual implementation.</p> <p>Yes, this is a function out of a textbook. No, this is not homework&mdash;I'm just trying to learn, so please no "do your own homework comments."</p>
<p>An odd number is not evenly divisible by two. All you need to know is are there two odd numbers in the set. Just check to see if each number mod 2 is non-zero. If so it is odd. If you find two odd numbers then you can multiply those and get another odd number.</p> <p>Note: an odd number multiplied by an even number is always even.</p>
<p>You can test for evenness (or oddness) by using the modulus.</p> <p>i % 2 = 0 if i is even; test for that and you can find out if a number is even/odd</p>
34,931
<p>I have a Ruby on Rails Website that makes HTTP calls to an external Web Service.</p> <p>About once a day I get a SystemExit (stacktrace below) error email where a call to the service has failed. If I then try the exact same query on my site moments later it works fine. It's been happening since the site went live and I've had no luck tracking down what causes it.</p> <p>Ruby is version 1.8.6 and rails is version 1.2.6.</p> <p>Anyone else have this problem?</p> <p>This is the error and stacktrace.</p> <blockquote> <p>A SystemExit occurred /usr/local/lib/ruby/gems/1.8/gems/rails-1.2.6/lib/fcgi_handler.rb:116:in exit' /usr/local/lib/ruby/gems/1.8/gems/rails-1.2.6/lib/fcgi_handler.rb:116:in exit_now_handler' /usr/local/lib/ruby/gems/1.8/gems/activesupport-1.4.4/lib/active_support/inflector.rb:250:in to_proc' /usr/local/lib/ruby/1.8/net/protocol.rb:133:in call' /usr/local/lib/ruby/1.8/net/protocol.rb:133:in sysread' /usr/local/lib/ruby/1.8/net/protocol.rb:133:in rbuf_fill' /usr/local/lib/ruby/1.8/timeout.rb:56:in timeout' /usr/local/lib/ruby/1.8/timeout.rb:76:in timeout' /usr/local/lib/ruby/1.8/net/protocol.rb:132:in rbuf_fill' /usr/local/lib/ruby/1.8/net/protocol.rb:116:in readuntil' /usr/local/lib/ruby/1.8/net/protocol.rb:126:in readline' /usr/local/lib/ruby/1.8/net/http.rb:2017:in read_status_line' /usr/local/lib/ruby/1.8/net/http.rb:2006:in read_new' /usr/local/lib/ruby/1.8/net/http.rb:1047:in request' /usr/local/lib/ruby/1.8/net/http.rb:945:in request_get' /usr/local/lib/ruby/1.8/net/http.rb:380:in get_response' /usr/local/lib/ruby/1.8/net/http.rb:543:in start' /usr/local/lib/ruby/1.8/net/http.rb:379:in get_response'</p> </blockquote>
<p>Using fcgi with Ruby is known to be very buggy. </p> <p>Practically everybody has moved to <a href="http://mongrel.rubyforge.org/" rel="noreferrer">Mongrel</a> for this reason, and I recommend you do the same.</p>
<p>I would also take a look at <a href="http://modrails.com/" rel="nofollow noreferrer">Passenger</a>. It's a lot easier to get going than the traditional solution of Apache/nginx + Mongrel.</p>
2,294
<p>I'm using the new ASP.Net ListView control to list database items that will be grouped together in sections based on one of their columns like so:</p> <pre><code>region1 store1 store2 store3 region2 store4 region3 store5 store6 </code></pre> <p>Is this possible to do with the ListView's GroupItemTemplate? Every example I have seen uses a static number of items per group, which won't work for me. Am I misunderstanding the purpose of the GroupItem?</p>
<p>I haven't used GroupItemCount, but I have taken this example written up by <a href="http://mattberseth.com/" rel="nofollow noreferrer">Matt Berseth</a> titled <a href="http://mattberseth.com/blog/2008/01/building_a_grouping_grid_with.html" rel="nofollow noreferrer">Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls</a> and have grouped items by a key just like you want.</p> <p>It involves using an outer and inner ListView control. Works great, give it a try.</p>
<p>I tried using GroupItemCount programmatically but it didn't give me the expected results. </p> <p>I followed Otto's suggestion and implemented an outer and inner ListView control. This seems to be the best available solution.</p>
3,375
<p>I have a problem with a little .Net web application which uses the Amazon webservice. With the integrated Visual Studio web server everything works fine. But after deploying it to the IIS on the same computer i get the following error message:</p> <pre><code>Ein Verbindungsversuch ist fehlgeschlagen, da die Gegenstelle nach einer bestimmten Zeitspanne nicht ordnungsgemäß reagiert hat, oder die hergestellte Verbindung war fehlerhaft, da der verbundene Host nicht reagiert hat 192.168.123.254:8080 </code></pre> <p>Which roughly translates to "cant connect to 192.168.123.254:8080"</p> <p>The computer is part of an Active Directory. The AD-Server was installed on a network which uses 192.168.123.254 as a proxy. Now it is not reachable and should not be used.</p> <p><strong>How do I prevent the IIS from using a proxy?</strong></p> <p>I think it has something to do with policy settings for the Internet Explorer. An "old" AD user has this setting, but a newly created user does not. I checked all the group policy settings and nowhere is a proxy defined.</p> <p>The web server is running in the context of the anonymous internet user account on the local computer. Do local users get settings from the AD? If so how can I change that setting, if I cant login as this user?</p> <p>What can I do, where else i could check?</p>
<p>Proxy use can be configured in the web.config. The system.net/defaultProxy element will let you specify whether a proxy is used by default or provide a bypass list.</p> <p>For more info see: <a href="http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx" rel="noreferrer"><a href="http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/kd3cf2ex.aspx</a></a></p>
<p>IIS is a destination. The configuration issue is in whatever is doing the call (acting like a client). If you are using the built-in .Net communication methods you will need to make the adjustment inside of ... Wait for it ... Internet Explorer. </p> <p>Yep! That little bugger has bitten me more times than I care to remember. I used to have to switch the proxy server settings in IE 5 or 6 times a day as I switched between internal and external servers. Newer versions of IE have a much better "don't use proxy server" set of rules.</p> <p>-- Clarification -- As it seems that the user ID used by IIS is using this setting, you'll probably need to search the registry for where the proxy information is stored for each user ID and/or the default.</p>
8,642
<p>The following question answers how to get large memory pages on Windows :<br> "<a href="https://stackoverflow.com/questions/39059/how-do-i-run-my-app-with-large-pages-in-windows">how do i run my app with large pages in windows</a>".</p> <p>The problem I'm trying to solve is how do I configure it on Vista and 2008 Server.</p> <p>Normally you just allow a specific user to lock pages in memory and you are done. However on Vista and 2008 this only works if you are using an Administrator account. It doesn't help if the user is actually part of the Administrators group. All other users always get a 1300 error code stating that some rights are missing.</p> <p>Anyone have a clue as to what else needs to be configured?</p> <p>Thanks, Staffan</p>
<p>Assuming cmd is your SqlCeCommand....</p> <pre><code>using(var dr = cmd.ExecuteReader()) { DataSet ds = new DataSet(); DataTable dt = ds.Tables.Add(); dt.Load(dr); ds.WriteXML(...); } </code></pre>
<p>I would think you could retrieve the data to a DataSet, call WriteXML on it, and then on the other end declare a new DataSet and call ReadXML on it.</p>
10,121
<p>In certain areas in my application I need data from several tables in the database (I have an application, the application has many attributes, each attribute has several definitions, and each definition has a value). I need the data from all these tables for an application. Should I use a view (one that would be rather large) or subqueries for selecting the records? In the case of subqueries is the optimizer able to work efficiently? I'm also interested if caching will work for subqueries.</p>
<p>Views are typically expanded in place into subqueries, unless you explicitly mark the views as persisted by dropping a clustered index on them.</p>
<p>This is an 'It depends' question. A view might help to make the code more maintainable but complex selection predicates might confuse the optimiser.</p> <p>Another option is a stored procedure that returns a record set. If you reuse a subquery several times you may get some mileage from splitting up the query, selecting the subquery into a temporary table and combining the parts in a later step.</p> <p>Without a more specific description of the problem it's hard to really give a meaningful answer.</p>
21,977
<p>This fails:</p> <pre><code>my @a = ("a", "b", "c", "d", "e"); my %h = map { "prefix-$_" =&gt; 1 } @a; </code></pre> <p>with this error:</p> <pre><code>Not enough arguments for map at foo.pl line 4, near "} @a" </code></pre> <p>but this works:</p> <pre><code>my @a = ("a", "b", "c", "d", "e"); my %h = map { "prefix-" . $_ =&gt; 1 } @a; </code></pre> <p>why?</p>
<p>Because Perl is guessing an EXPR (a hash reference, for example) instead of a BLOCK. This should work (note the '+' symbol):</p> <pre><code>my @a = ("a", "b", "c", "d", "e"); my %h = map { +"prefix-$_" =&gt; 1 } @a; </code></pre> <p>See <a href="http://perldoc.perl.org/functions/map.html" rel="noreferrer">http://perldoc.perl.org/functions/map.html</a>.</p>
<p>I think that </p> <pre><code>map { ; "prefix-$_" =&gt; 1 } @a; </code></pre> <p>is more idiomatic, as far as specifying that it is a block of statements and not a hash ref. You're just kicking it off with a null statement. </p>
34,055
<p>I have a database of strings (arbitrary length) which holds more than one million items (potentially more).</p> <p>I need to compare a user-provided string against the whole database and retrieve an identical string if it exists or otherwise return the closest fuzzy match(es) (60% similarity or better). The search time should ideally be under one second.</p> <p>My idea is to use edit distance for comparing each db string to the search string after narrowing down the candidates from the db based on their length.</p> <p>However, as I will need to perform this operation very often, I'm thinking about building an index of the db strings to keep in memory and query the index, not the db directly.</p> <p>Any ideas on how to approach this problem differently or how to build the in-memory index?</p>
<p><a href="http://en.scientificcommons.org/514330" rel="noreferrer">This paper seems to describe exactly what you want.</a></p> <p>Lucene (<a href="http://lucene.apache.org/" rel="noreferrer">http://lucene.apache.org/</a>) also implements Levenshtein edit distance.</p>
<p>Since the amount of data is large, when inserting a record I would compute and store the value of the phonetic algorithm in an indexed column and then constrain (WHERE clause) my select queries within a range on that column. </p>
39,868
<p>I'm having a hard time determining what characters <strong>must</strong> be escaped when using Perl's qr{} construct</p> <p>I'm attempting to create a multi-line precompiled regex for text that contains a myriad of normally escaped characters (#*.>:[]) and also contains another precompiled regex. Additionally I need to match as strictly as possible for testing purposes.</p> <pre><code>my $output = q{# using defaults found in .config * * Options: 1. opt1 &gt; 2. opt2 choice[1-2?]: }; my $sc = qr{(&gt;|\s)}smx; my $re = qr{# using defaults found in .config * * Options: $sc 1. opt1 $sc 2. opt2 choice[1-2?]: }mx; if ( $output =~ $re ) { print "OK!\n"; } else { print "D'oh!\n"; } </code></pre> <p>Error:</p> <pre><code>Quantifier follows nothing in regex; marked by &lt;-- HERE in m/# using defaults found in .config * &lt;-- HERE * Options: (?msx-i:(&gt;|\s)) 1. opt1 (?msx-i:(&gt;|\s)) 2. opt2 choice[1-2?]: / at ./so.pl line 14. </code></pre> <p>Attempting to escape the asterisks results in a failed match (D'oh output). Attempting to escape other pesky chars also results in a failed match. I could continue trying different combos of what to escape, but there's a lot of variations here and am hoping someone could provide some insight.</p>
<p>You have to escape the delimiter for qr//, and you have to escape any regex metacharacters that you want to use as literals. If you want those to be literal *'s, you need to escape them since the * is a regex quantifier.</p> <p>Your problem here is the various regex flags that you've added. The /m doesn't do anything because you don't use the beginning- or end-of-string anchors (^, $). The /s doesn't do anything because you don't use the wildcard . metacharacter. The /x makes all of the whitespace in your regex meaningless, and it turns that line with the # into a regex comment.</p> <p>This is what you want, with regex flags removed and the proper things escaped:</p> <pre><code>my $sc = qr{(&gt;|\s)}; my $re = qr{# using defaults found in \.config \* \* Options: $sc 1\. opt1 $sc 2\. opt2 choice\[1-2\?]: }; </code></pre> <p>Although Damian Conway tells people in <em>Perl Best Practices</em> to always put these options on their regexes, you now see why he's wrong. You should only add them when you want what they do, and you should only add things when you know what they do. :) Here's what you might do if you want to use /x. You have to escape any literal whitespace, you need to denote the line endings somehow, and you have to escape the literal # character. What was readable before is now a mess:</p> <pre> my $sc = qr{(>|\s)}; my $eol = qr{[\r\n]+}; my $re = qr{\# \s+ using \s+ defaults \s+ found \s+ in \s+ \.config $eol \* $eol \* $eol Options: $eol $sc \s+ 1\. \s+ opt1 $eol $sc \s+ 2\. \s+ opt2 $eol choice\[1-2\?]: \s+ }x; if ( $output =~ $re ) { print "OK!\n"; } else { print "D'oh!\n"; } </pre>
<p>Like brian said, you must escape the delimiter and regex metacharacters. Note that when using <code>qr//x</code> (which you are), you must also escape whitespace characters and # (which is a comment marker). You probably don't actually want to use <code>/x</code> here. If you want to be safe, you <strong>can</strong> escape any non-alphanumeric character.</p>
37,133
<p>I want to write a query like this:</p> <pre><code>SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice) FROM Order o </code></pre> <p>But this isn't how the <code>MAX</code> function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows. </p> <p>Does anyone know how to do it my way?</p>
<p>You'd need to make a <code>User-Defined Function</code> if you wanted to have syntax similar to your example, but could you do what you want to do, inline, fairly easily with a <code>CASE</code> statement, as the others have said.</p> <p>The <code>UDF</code> could be something like this:</p> <pre><code>create function dbo.InlineMax(@val1 int, @val2 int) returns int as begin if @val1 &gt; @val2 return @val1 return isnull(@val2,@val1) end </code></pre> <p>... and you would call it like so ...</p> <pre><code>SELECT o.OrderId, dbo.InlineMax(o.NegotiatedPrice, o.SuggestedPrice) FROM Order o </code></pre>
<p>In Presto you could use use</p> <pre><code>SELECT array_max(ARRAY[o.NegotiatedPrice, o.SuggestedPrice]) </code></pre>
15,144
<p>I have an enumeration value marked with the following attribute. The second parameter instructs the compiler to error whenever the value is used. I want this behavior for anyone that implements my library, but I need to use this enumeration value within my library. How do I tell the compiler to ignore the Obsolete error for the couple of uses in my library.</p> <pre><code>public enum Choices { One, Two, [ObsoleteAttribute("don't use me", true)] Three, Four } </code></pre> <hr> <p>Solution (Thanks everyone)</p> <pre><code>public class EnumHack { static EnumHack() { // Safety check if (Choices!= (Choices)Enum.Parse(typeof(Choices), "Three")) throw new Exception("Choices.Three != 3; Who changed my Enum!"); } [Obsolete("Backwards compatible Choices.Three", false)] public const Choices ChoicesThree = (Choices)3; } </code></pre>
<p>Private a separate constant somewhere like this:</p> <pre><code>private const Choices BackwardsCompatibleThree = (Choices) 3; </code></pre> <p>Note that anyone else will be able to do the same thing.</p>
<p>TheSoftwareJedi correctly notes that this won't work with obsolete attribute set to be an error. The following "answer" only works when the obsolete notification is raised as a warning.</p> <hr> <p>From Visual Studio you can do this on a per-project basis:</p> <ol> <li>Go to the Project Properties page for the project you want to be able to suppress the obsolete warning on.</li> <li>Go to the Build tab: Errors and Warnings : Suppress Warnings</li> <li>Enter the warning number, 0612 in this case.</li> </ol> <p>Other projects will continue to get the obsolete warning but this project will not. Note that this will disable <strong>ALL</strong> obsolete warnings.</p>
44,826
<p>I would like to display the up time of the machine my code is running, how can I do that?</p>
<p>Try this link. It uses the <strong>System.Environment.TickCount</strong> property</p> <blockquote> <p>Gets the number of milliseconds elapsed since the system started. - MSDN</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/system.environment.tickcount(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.environment.tickcount(VS.80).aspx</a></p> Note: this method will work for 25 days because TickCount is an Int32.
<p>I suggest you to use the command line : <strong>net statistics workstation</strong> and parse the output. The time that machine is running is after "Statistics since ".</p>
33,214
<p>I am interested in using some kind of a command-line utility for SQL Server similar to Oracle's SQL*Plus. SQL Server seems to have several options: osql, isql, and sqlcmd. However, I am not quite certain which one to use.</p> <p>Do they all essentially do the same thing? Are there any situations where it is preferable to use one over the others?</p>
<p>Use sqlcmd-- it's the most fully featured product.</p> <ul> <li><strong>sqlcmd</strong>: The newest, fanciest command-line interface to SQL Server.</li> <li><strong>isql</strong> : The older, DB-Library (native SQL Server protocol) way of command-line communication with SQL Server.</li> <li><strong>osql</strong> : The older, ODBC-based way of command-line communication with SQL Server.</li> </ul> <p><strong>EDIT:</strong> Times have changed since I replied on this a couple of years ago. Nowadays, you can also use the <a href="http://technet.microsoft.com/en-us/library/cc281720.aspx" rel="noreferrer">invoke-sqlcmd</a> cmdlet in PowerShell. If you're used to PowerShell or plan to do any scripting of any sophistication, use this instead.</p>
<p>There is a free tool "SQLS<em>Plus" (on <a href="http://www.memfix.com" rel="nofollow noreferrer">http://www.memfix.com</a> ) which is exactly like Oracle SQL</em>Plus for SQL Server. Works with all SQL Server versions. </p> <p>Very flexible with data formatting (set lines size, pagesize, etc), variables (var, &amp;, &amp;&amp;), spool, HTML output, etc - lots of added functionality comparing to isql, osql or sqlcmd</p>
43,913
<p>I'm starting to build a community website from the site up and my web framework will be Asp.net and Mysql.</p> <p>I want to start planning some scalability into the infrastructure early because I'm anticipating high traffic when the site goes live.</p> <p><strong>Are there any case studies which you recommend reading where asp.net or mysql has been scaled and which demonstrates good scaling techniques?</strong></p>
<p>I think it could be a challenge to find reference materials for that particular combination. Many .NET shops stick to SQL Server, and fewer use MySQL (at least at scale).</p> <p>In general it would be appropriate to:</p> <ul> <li>Follow general <a href="http://msdn.microsoft.com/en-us/library/ms998530.aspx" rel="nofollow noreferrer">.NET practices for scalability</a>. Weed out what is not appropriate for you.</li> <li>Learn about database performance and implications of various design strategies such as denormalisation (when and why).</li> <li>Consider out-of-process caching like <a href="http://en.wikipedia.org/wiki/Memcached" rel="nofollow noreferrer">memcached</a>.</li> <li>Review books on <a href="http://oreilly.com/catalog/9780596101718/" rel="nofollow noreferrer">MySQL performance</a>. Most of these are focused on UNIX platforms. Windows users may have problems applying some of these practices.</li> <li>Read up on how other people are scaling their sites (<a href="http://oreilly.com/catalog/9780596102357/" rel="nofollow noreferrer">Building Scalable Sites</a> and <a href="http://oreilly.com/catalog/9780596518578/" rel="nofollow noreferrer">The Art of Capacity Planning</a>)</li> <li>Consider how you might optimise your web design to be more scalable. Are you using AJAX? Work out what the impact of excessive polling may be etc.</li> <li>Learn how to measure the performance of your application and database (starting points <a href="http://www.google.com/search?hl=en&amp;q=measuring+asp.net+performance" rel="nofollow noreferrer">ASP.NET</a> and <a href="http://www.google.com/search?hl=en&amp;q=measuring+mysql+performance&amp;btnG=Search" rel="nofollow noreferrer">MySQL</a>).</li> <li>Develop a plan for scaling your architecture (1 server to 2 servers, to multiple servers etc) so that you have some frame of reference for making decisions about building things in your system.</li> </ul>
<p>For mysql scaling, you may find this interesting: <a href="http://www.scribd.com/doc/269855/danga-com-livejournal-backend" rel="nofollow noreferrer">danga livejournal</a> </p>
45,552
<p>I have a <a href="http://en.wikipedia.org/wiki/Red_Hat_Enterprise_Linux" rel="noreferrer">RHEL</a> box that I need to put under a moderate and variable amount of CPU load (50%-75%).</p> <p>What is the best way to go about this? Is there a program that can do this that I am not aware of? I am happy to write some C code to make this happen, I just don't know what system calls will help.</p>
<p>This is exactly what you need (internet archive link): <a href="https://web.archive.org/web/20120512025754/http://weather.ou.edu/%7Eapw/projects/stress/stress-1.0.4.tar.gz" rel="nofollow noreferrer">https://web.archive.org/web/20120512025754/http://weather.ou.edu/~apw/projects/stress/stress-1.0.4.tar.gz</a></p> <p>From the homepage: &quot;stress is a simple workload generator for POSIX systems. It imposes a configurable amount of CPU, memory, I/O, and disk stress on the system. It is written in C, and is free software licensed under the GPL.&quot;</p>
<p>Not sure what your goal is here. I believe glxgears will use 100% CPU. </p> <p>So find any process that you know will max out the CPU to 100%.</p> <p>If you have four CPU cores(0 1 2 3), you could use "taskset" to bind this process to say CPUs 0 and 1. That should load your box 50%. To load it 75% bind the process to 0 1 2 CPUs.</p> <p>Disclaimer: Haven't tested this. Please let us know your results. Even if this works, I'm not sure what you will achieve out of this?</p>
17,129
<p>Note: The "TL smoothers" referred to in the question title are an arrangement of 8 diodes that presumably both provide a voltage drop to address the minimum current output issue of some stepper drivers described in <a href="https://hackaday.com/2016/08/29/how-accurate-is-microstepping-really/" rel="nofollow noreferrer">How Accurate Is Microstepping Really</a>, and provide flyback protection and protection of the driver from currents induced by moving the motor in the unpowered state.</p> <p>Now, on to the question:</p> <p>I put together a simple test part to test Y (or X) axis microstepping accuracy:</p> <p><img src="https://i.stack.imgur.com/siHlD.png" alt="Test part design - OpenSCAD screenshot"></p> <p>Every 1mm in the Z direction, the face steps inward 1/80 mm (corresponding to my printer's [micro]steps per mm setting) in the Y direction and 1 mm in the X direction (to clearly show where the steps happen).</p> <p>Here are the results (two runs, near-identical output):</p> <p><img src="https://i.stack.imgur.com/HyDve.jpg" alt="Photo of test prints lying down"> <img src="https://i.stack.imgur.com/5hJWJ.jpg" alt="Photo of test prints upright"></p> <p>Several of the steps are missing entirely, and it's the middle vertical surface, rather than the side two stepped-vertical surfaces, that shows a step-like texture.</p> <p>Note that layers have been printed counter-clockwise, but the design with steps on both sides is to try to reduce the impact of print orientation so as not to depend on what the slicer decides to do. Print speed was 30 mm/s for outer walls, with outer walls set to be printed first so they're not affected by already-printed inner ones.</p> <p>This looks to me like an indication that microstepping is not working accurately, and seems to agree partly with this article: <a href="https://hackaday.com/2016/08/29/how-accurate-is-microstepping-really/" rel="nofollow noreferrer">https://hackaday.com/2016/08/29/how-accurate-is-microstepping-really/</a></p> <p>Would TL smoothers improve this? My printer is an Ender 3, seemingly the latest revision at the time it was sold (December 2018) based on the bed and other aspects. Some threads I found suggested that this was a problem with older Ender 3s that was fixed in later revisions and that TL smoothers won't help, but it looks to me like it's not fixed.</p> <p>Update: With settings adjusted for 0 jerk and 50 mm/s² acceleration in the outer walls, I got a somewhat improved result:</p> <p><img src="https://i.stack.imgur.com/CtoxR.jpg" alt="New test print (lower) compared to old (upper)"></p> <p>All steps are clearly visible, but at the reduced and more varying speed, artifacts of the extruder motor accuracy (or maybe just bowden latency) are much worse, and at the steps the "overshoot and bounce back" effect is still happening. Is this consistent with a situation where the TL smoothers I asked about could benefit?</p> <p>Update 2: I've further tested with leaving acceleration at default (500 mm/s²) and just disabling "jerk", i.e. "instantaneous" change in speed. The results are at least as good as the above with slow acceleration. What strikes me most is that the "overshoot then bounce back" happens outward from the model on <em>both</em> edges, rather than inward on the righthand side where the (CCW moving) nozzle is turning inward. Could this indicate that there's no microstepping accuracy problem at all, and that the artifact is purely from excess extrusion as the corner is turned?</p> <p>Updated pic (new one below):</p> <p><img src="https://i.stack.imgur.com/jeGq0.jpg" alt="Old test piece above, new with default accel and 0 jerk below"></p>
<p>Is your BL Touch a v3 (likely if you've only just purchased it)? If so, make sure you're using the bugfix version of Marlin 1.1.9, which supposedly fixes the compatibility issues. I say supposedly because there's also a capacitor on the mainboard that can be removed to fix the issue, and once I removed it (and commented out the specific v3 bits in the firmware) the BLTouch performed noticeably better than when relying on the bugfix firmware alone.</p> <p><a href="https://www.youtube.com/channel/UCbgBDBrwsikmtoLqtpc59Bw" rel="nofollow noreferrer">Teaching Tech on YouTube</a> has a few BLtouch Ender 3 videos, covering the changes for configuring the bugfix firmware and the removal of the capacitor.</p>
<p>I've been through the <a href="/q/6959">same sort of issues</a> and eventually found that it was attributed by the cable and connector. Re-check or re-wire the sensor, this helped me out.</p>
1,372
<p>Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri? How would you build it?</p> <p>I'd like to be able to do something like one of the following, but neither are supported (using VB, since it lets you specify type in the Set declaration for the 2nd one):</p> <pre class="lang-vb prettyprint-override"><code>Class MyClass Private _link As Uri 'Option 1: overloaded property Public Property Link1 As Uri Get return _link End Get Set(ByVal value As Uri) _link = value End Set End Property Public Property link1 As String Get return _link.ToString() End Get Set(Byval value As String) _link = new Uri(value) End Set End Property ' Option 2: Overloaded setter Public Property link2 As Uri Get return _link End Get Set(Byval value As Uri) _link = value End Set Set(Byval value As String) _link = new Uri(value) End Set End Class </code></pre> <p>Given that those probably won't be supported any time soon, how else would you handle this? I'm looking for something a little nicer than just providing an additional <code>.SetLink(string value)</code> method, and I'm still on .Net2.0 (though if later versions have a nice feature for this, I'd like to hear about it).</p> <p>I can think of other scenarios where you might want to provide this kind of overload: a class with an SqlConnection member that lets you set either a new connection or a new connection string, for example.</p>
<p>Alternatively, you can of course forego overloading and just name the properties appropriately:</p> <pre><code>Public WriteOnly Property UriString() As String Set(ByVal value As String) m_Uri = new Uri(value) End Set End Property </code></pre> <p>Of course you don't have to make this <code>WriteOnly</code> but it seems appropriate.</p>
<blockquote> <p>Let's say you have a class with a Uri property. Is there any way to get that property to accept both a string value and a Uri?</p> </blockquote> <p>No because this would mean having two getters that vary only in their return type and this isn't allowed in .NET.</p> <p>I would use the <code>Uri</code> method exclusively and perhaps create a convenienec method to set the <code>URI</code> property, given a string. However, since the conversion from <code>String</code> to <code>URI</code> is straightforward, even this might be unnecessary.</p>
19,695
<p>We're having sporadic, random query timeouts on our SQL Server 2005 cluster. I own a few apps that use it, so I'm helping out in the investigation. When watching the % CPU time in regular ol' Perfmon, you can certainly see it pegging out. However, SQL activity monitor only gives cumulative CPU and IO time used by a process, not what it's using right then, or over a specific timeframe. Perhaps I could use the profiler and run a trace, but this cluster is very heavily used and I'm afraid I'd be looking for a needle in a haystack. Am I barking up the wrong tree?</p> <p>Does anyone have some good methods for tracking down expensive queries/processes in this environment?</p>
<p>This will give you the top 50 statements by average CPU time, check here for other scripts: <a href="http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true" rel="nofollow noreferrer">http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true</a></p> <pre><code>SELECT TOP 50 qs.total_worker_time/qs.execution_count as [Avg CPU Time], SUBSTRING(qt.text,qs.statement_start_offset/2, (case when qs.statement_end_offset = -1 then len(convert(nvarchar(max), qt.text)) * 2 else qs.statement_end_offset end -qs.statement_start_offset)/2) as query_text, qt.dbid, dbname=db_name(qt.dbid), qt.objectid FROM sys.dm_exec_query_stats qs cross apply sys.dm_exec_sql_text(qs.sql_handle) as qt ORDER BY [Avg CPU Time] DESC </code></pre>
<p>Profiler may seem like a "needle in a haystack" approach, but it may turn up something useful. Try running it for a couple of minutes while the databases are under typical load, and see if any queries stand out as taking way too much time or hogging resources in some way. While a situation like this could point to some general issue, it could also be related to some specific issue with one or two sites, which mess things up enough in certain circumstances to cause very poor performance across the board.</p>
3,552
<p>We have been using CruiseControl for quite a while with NUnit and NAnt. For a recent project we decided to use the testing framework that comes with Visual Studio, which so far has been adequate.</p> <p>I'm attempting to get the solution running in CruiseControl. I've finally got the build itself to work; however, I have been unable to get any tests to show up in the CruiseControl interface despite adding custom build tasks and components designed to do just that. Does anyone have a definitive link out there to instructions on getting this set up?</p>
<p>Not sure if that helps (i found the ccnet Documentation somewhat unhelpful at times):</p> <p><a href="http://confluence.public.thoughtworks.org/display/CCNET/Using+CruiseControl.NET+with+MSTest" rel="noreferrer">Using CruiseControl.NET with MSTest</a></p>
<p>The CC.Net interface is generated via an XSL transform on your XML files put together as specified in the ccnet.config file for your projects. The XSL is already written for things like FxCop - check your server's CC xsl directory for examples - shouldn't be too hard to write your own to add in the info - just remember to add the XML output from your tests into the main log.</p>
2,373
<p>I need to have one column as the primary key and another to auto increment an order number field. Is this possible?</p> <p>EDIT: I think I'll just use a composite number as the order number. Thanks anyways.</p>
<pre><code>CREATE TABLE [dbo].[Foo]( [FooId] [int] IDENTITY(1,1) NOT NULL, [BarId] [int] IDENTITY(1,1) NOT NULL ) </code></pre> <p>returns</p> <pre><code>Msg 2744, Level 16, State 2, Line 1 Multiple identity columns specified for table 'Foo'. Only one identity column per table is allowed. </code></pre> <p>So, no, you can't have two identity columns. You can of course make the primary key not auto increment (identity).</p> <p>Edit: <a href="http://msdn.microsoft.com/en-us/library/ms174979.aspx" rel="noreferrer">msdn:CREATE TABLE (Transact-SQL)</a> and <a href="http://msdn.microsoft.com/en-us/library/aa258255%28SQL.80%29.aspx" rel="noreferrer">CREATE TABLE (SQL Server 2000)</a>: </p> <blockquote> <p>Only one identity column can be created per table.</p> </blockquote>
<p>A workaround would be to create an INSERT Trigger that increments a counter.</p> <p>So I have a table that has one identity col : applicationstatusid. its also the primary key. I want to auto increment another col: applicationnumber </p> <p>So this is the trigger I write.</p> <pre><code> create trigger [applicationstatus_insert] on [ApplicationStatus] after insert as update [Applicationstatus] set [Applicationstatus].applicationnumber =(applicationstatusid+ 4000000) from [Applicationstatus] inner join inserted on [applicationstatus].applicationstatusid = inserted.applicationstatusid </code></pre>
45,426
<p>I wrote a sample program at <a href="http://codepad.org/ko8vVCDF" rel="noreferrer">http://codepad.org/ko8vVCDF</a> that uses a template function.</p> <p>How do I retrict the template function to only use numbers? (int, double etc.)</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; using namespace std; template &lt;typename T&gt; T sum(vector&lt;T&gt;&amp; a) { T result = 0; int size = a.size(); for(int i = 0; i &lt; size; i++) { result += a[i]; } return result; } int main() { vector&lt;int&gt; int_values; int_values.push_back(2); int_values.push_back(3); cout &lt;&lt; "Integer: " &lt;&lt; sum(int_values) &lt;&lt; endl; vector&lt;double&gt; double_values; double_values.push_back(1.5); double_values.push_back(2.1); cout &lt;&lt; "Double: " &lt;&lt; sum(double_values); return 0; } </code></pre>
<p>The only way to restrict a template is to make it so that it uses something from the types that you want, that other types don't have.</p> <p>So, you construct with an int, use + and +=, call a copy constructor, etc.</p> <p>Any type that has all of these will work with your function -- so, if I create a new type that has these features, your function will work on it -- which is great, isn't it?</p> <p>If you want to restrict it more, use more functions that only are defined for the type you want.</p> <p>Another way to implement this is by creating a traits template -- something like this</p> <pre><code>template&lt;class T&gt; SumTraits { public: const static bool canUseSum = false; } </code></pre> <p>And then specialize it for the classes you want to be ok:</p> <pre><code>template&lt;&gt; class SumTraits&lt;int&gt; { public: const static bool canUseSum = true; }; </code></pre> <p>Then in your code, you can write</p> <pre><code>if (!SumTraits&lt;T&gt;::canUseSum) { // throw something here } </code></pre> <p>edit: as mentioned in the comments, you can use BOOST_STATIC_ASSERT to make it a compile-time check instead of a run-time one</p>
<p>Suppose we want our templated add function can only accepts int and floats, We can do something like below. Can be seen here: <a href="https://godbolt.org/z/qa4z968hP" rel="nofollow noreferrer">https://godbolt.org/z/qa4z968hP</a></p> <pre><code>#include &lt;fmt/format.h&gt; template &lt;typename T&gt; struct restrict_type {}; template&lt;&gt; struct restrict_type&lt;float&gt; {typedef float type;}; template&lt;&gt; struct restrict_type&lt;int&gt; {typedef int type;}; template&lt;typename T&gt; typename restrict_type&lt;T&gt;::type add(T val1, T val2){ return val1 + val2; } int main() { fmt::print(&quot;{}\n&quot;, add(12, 30)); fmt::print(&quot;{}\n&quot;, add(12.5f, 30.9f)); } </code></pre>
17,879
<p>I currently have Apache HTTP Server, but I'm guessing I'll need Tomcat (and then have to configure it in a way that makes it not open to the public), a Java JDK (which I already have, but should probably update), and an IDE (I have Eclipse). But what else should I have or know before starting?</p>
<p>Lets see... you'll need:</p> <ol> <li>A JDK. Preferably the <a href="http://java.sun.com/javase/downloads/index.jsp" rel="nofollow noreferrer">Standard Edition</a>, unless you plan on using GlassFish as a J2EE server. If you do use the standard edition, you need to include the jars from your servlet container/J2EE stack to access J2EE libraries.</li> <li>A Servlet container. <a href="http://tomcat.apache.org/" rel="nofollow noreferrer">Apache Tomcat</a> is a popular one, and Eclipse already has integration support for it. Keep in mind that Tomcat is not a complete J2EE stack... you need something like <a href="http://www.jboss.org/jbossas/" rel="nofollow noreferrer">JBoss Application Server</a> or <a href="http://geronimo.apache.org/" rel="nofollow noreferrer">Apache Geronimo</a> for that.</li> <li>(Semi-Optional) A web server. Apache Web Server <em>surprisingly</em> works well with Apache Tomcat or Apache Geronimo... it's almost like they were made by the same people! Eclipse has built-in support for Tomcat and doesn't appear to require a web server because of it. I could be wrong, though.</li> <li>(Optional) An IDE. If you use <a href="http://www.eclipse.org/" rel="nofollow noreferrer">Eclipse</a>, get the version for Java EE Developers.</li> <li>(Optional) A Database. MySQL and HSQLDB are popular ones for Java, at least for small to medium applications. Keep in mind that you also need to download the JDBC drivers for your database.</li> <li>(Optional) A revision control system. Even on a single-developer project, a revision control system can save your hide if you accidentally remove code or a file that you shouldn't. There are several choices here; <a href="http://subversion.tigris.org/" rel="nofollow noreferrer">Subversion</a> is my personal choice, along with an Eclipse plugin for it, such as <a href="http://subclipse.tigris.org/" rel="nofollow noreferrer">Subclipse</a>.</li> </ol>
<p>I would go for maven.</p> <p>It will give you a quick start in configuring your project (by using archetypes) and it will manage your dependencies.</p> <p>Install it and run the archetype command to create your project.</p> <pre><code>mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-webapp -DarchetypeArtifactId=maven-archetype-webapp </code></pre> <p>After that just use the maven eclipse plugin to configure your eclipse environment for that project (<a href="http://maven.apache.org/plugins/maven-eclipse-plugin/" rel="nofollow noreferrer">http://maven.apache.org/plugins/maven-eclipse-plugin/</a>).</p>
35,617
<p>I have a web application that I need to modify so that it can be rebranded for different customers. I did the same thing with the windows version of the app using resource files and a #define. I have been reading up on resource files for aspx/C# but it seems that they are limited to localization. I'd like to do something like put everything in resource files and then have the web config file act as the #define.</p>
<p>Depending on what you want to rebrand (colors, logo, etc.) you could do this using different CSS files.</p>
<p>I've used Themes to change the 'branding' of a website based on what someone wants. <a href="http://msdn.microsoft.com/en-us/library/ykzx33wh.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ykzx33wh.aspx</a>.</p> <p>You can create numerous themes, put them in the application and then you specify which theme is the default/active in the web.config.</p> <p>Implementing Themes is something you should really do from the beginning but you can certainly retro fit an existing app, but level of effort will differ based on the complexity of the layout and content.</p> <p>I'm not sure how much of the Themes (if any) can be embedded into the assembly/resource though.</p>
43,316
<p>I tried this on J2ME</p> <pre><code>try { Image immutableThumb = Image.createImage( temp, 0, temp.length); } catch (Exception ex) { System.out.println(ex); } </code></pre> <p>I hit this error: <code>java.lang.IllegalArgumentException:</code></p> <p>How do I solve this?</p>
<p>Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]).</p> <p><a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)" rel="nofollow noreferrer">http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)</a></p> <p>(This URL refuses to become a hyperlink for some reason (?))</p>
<p>I just had the same problem with my MIDLET and the problem in my case was the HTTP header that comes along the JPEG image that I read from the socket's InputStream. And I solved it by finding the JPEG SOI marker that is identified by two bytes: <code>FFD8</code> in my byte array. Then when I find the location of the <code>FFD8</code> in my byte array, I trim the starting bytes that represent the HTTP header, and then I could call <code>createImage()</code> without any Exception being thrown... </p> <p>You should check if this is the case with you. Just check is this true <code>(temp[0] == 0xFF &amp;&amp; temp[1] == 0xD8)</code> and if it is not, trim the start of <code>temp</code> so you remove HTTP header or some other junk...</p> <p><strong>P.S.</strong> I presume that you are reading JPEG image, if not, look for the appropriate header in the <code>temp</code> array. </p> <p>Also if this doesn't help, and you are reading JPEG image make sure that the array starts with <code>FFD8</code> and ends with <code>FFD9</code> (which is the EOI marker). And if it doesn't end with the EOI just trim the end like I explained for SOI...</p> <p><strong>P.P.S</strong> And if you find that the data in <code>temp</code> is valid, then your platform cannot decode the JPEG images or the image in <code>temp</code> is to large for JPEG decoder.</p>
34,172
<p>what is the best way to track and lower GDI windows handles . . </p>
<p>Two links worth reading...</p> <p><a href="http://msdn.microsoft.com/en-us/magazine/cc301756.aspx" rel="noreferrer">Resource Leaks: Detecting, Locating, and Repairing Your Leaky GDI Code</a></p> <p><a href="http://www.relisoft.com/win32/GdiLeaks.html" rel="noreferrer">GDI Resource Leaks</a></p>
<p>the easiest way to see the current usage on an end user's machine is to use task manager and look at the column "GDI Handles"</p> <p>When I suspect I have GDI handle leaks I tend to run through my leak scenario once, force a garbage collection, look at task manager, run the action again with gc and check for a difference. If I find one I have used the .Net Profiler (from SciTech) which can show in detail which object causes the leak and why it is not handed back</p>
41,106
<p>Why don't we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we have <a href="http://en.wikipedia.org/wiki/Type_inference" rel="nofollow noreferrer">plenty of languages</a> with full-fledged type inference systems (that work for varying levels of "work").</p> <p><strong>Edit:</strong> By return type polymorphism I mean overloading the function signature only in the return type. For example, C++ and Java only allow overloading in the type of the formal parameters, not in the return type.</p>
<p>If by "return type polymorphism" you mean overloading based on the return value type, I'm not sure about other languages, but for C++ here's the answer (pretty much from the horse's mouth):</p> <p>Function return types don't come into play in overload resolution simply because Stroustrup (I assume with input from other C++ architects) wanted overload resolution to be 'context independent'. See 7.4.1 - "Overloading and Return Type" from the "C++ Programming Language, Third Edition". </p> <blockquote> <p>The reason is to keep resolution for an individual operator or function call context-independent.</p> </blockquote> <p>They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all). Indeed, many functions are called without using the result or the result would be used as part of a larger expression. One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.</p> <p>And, Lord knows, C++ overload resolution is complex enough as it stands...</p>
<p>Because of auto-conversion of types, it is not obvious to know which function to call when return types are close.</p>
30,986
<p>There appear to be a lot of unnecessary frameworks loading into my iPhone app. I didn't link against them in Xcode, and I don't need them.</p> <p>When I run "lsof -p" against them on the iPhone, I see these (and others) that I can't explain:</p> <ul> <li>CoreVideo </li> <li>AddressBookUI</li> <li>JavaScriptCore</li> <li>MobileSync</li> <li>EAP8021X</li> <li>BluetoothManager</li> <li>MusicLibrary</li> <li>CoreAudio</li> <li>MobileMusicPlayer</li> <li>AddressBook</li> <li>CoreTelephony</li> <li>MobileBluetooth</li> <li>Calendar</li> <li>TelephonyUI</li> <li>WebCore / WebKit</li> <li>MediaPlayer</li> <li>VideoToolbox</li> </ul> <p>I wonder whether this is contributing to the slow startup times. My app is very simple. It is basically a Twitter-like posting client. The only multimedia function is to pick an image from the camera or library, and it uses simple NSURL / NSURLConnection functions to post data to a couple of web services.</p> <p>This is a jailbroken 2.1 iPhone with a few apps installed from Cydia. Is this normal?</p>
<p>This is normal, but that doesn't mean it's ideal. It probably only has a small impact on app startup time, but it'll have a slightly greater impact than that on memory usage.</p> <p>If you'd like this to be improved, the best thing to do is to head on over to <a href="http://bugreport.apple.com" rel="nofollow noreferrer">Apple's bug reporter</a> and file a bug about it. Attach a copy of your application (the binary, not the source) and they should be able to track things down from there. I'm sure they'd be interested in reports like this.</p>
<p>Before you go to all of the trouble of trying to stop the OS from loading these frameworks, you should rule out other causes of your slow launch time.</p> <p>First, build a "Hello, World" app and use it as a baseline. A project template app with nothing added should serve well. If that is starting up faster than your own app, then it is something you are doing in your own code.</p>
13,675
<p>I am using ASP.NET membership for the authentication of my web app. This worked great for me. I now have to implement password expiration.</p> <p>If the password has expired the user should be redirected to <code>ChangePassword</code> screen and should not be allowed access to any other part of the application without changing the password.</p> <p>There are many aspx pages. One solution could be to redirect to the <code>ChangePassword</code> screen <code>OnInit</code> of every aspx if the password has expired. Is there any other solutions or recommendations.</p> <p>Thanks, Jai</p>
<p>Further to <a href="https://stackoverflow.com/questions/349286/asp-net-membership-password-expiration/349687#349687">csgero's answer</a>, I found that you don't need to explicitly add an event handler for this event in ASP.Net 2.0 (3.5).</p> <p>You can simply create the following method in <code>global.asax</code> and it gets wired up for you:</p> <pre><code>void Application_PostAuthenticateRequest(object sender, EventArgs e) { if (this.User.Identity.IsAuthenticated) { // get user MembershipUser user = Membership.GetUser(); // has their password expired? if (user != null &amp;&amp; user.LastPasswordChangedDate.Date.AddDays(90) &lt; DateTime.Now.Date &amp;&amp; !Request.Path.EndsWith("/Account/ChangePassword.aspx")) { Server.Transfer("~/ChangePassword.aspx"); } } } </code></pre>
<p>I used the code from above and only slightly modified it to implement in Asp.NET (4.5) MVC5 using the .NET Identity Provider. Just leaving it here for the next guy/gal :) </p> <pre><code>void Application_PostAuthenticateRequest(object sender, EventArgs e) { if (this.User.Identity.IsAuthenticated) { WisewomanDBContext db = new WisewomanDBContext(); // get user var userId = User.Identity.GetUserId(); ApplicationUser user = db.Users.Find(userId); // has their password expired? if (user != null &amp;&amp; user.PasswordExpires &lt;= DateTime.Now.Date &amp;&amp; !Request.Path.EndsWith("/Manage/ChangePassword")) { Response.Redirect("~/Manage/ChangePassword"); } db.Dispose(); } } </code></pre>
45,449
<p>This is probably <a href="http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/x13320.html" rel="noreferrer">a complex solution</a>.</p> <p>I am looking for a simple operator like ">>", but for prepending.</p> <p>I am afraid it does not exist. I'll have to do something like </p> <pre> mv myfile tmp cat myheader tmp > myfile </pre> <p>Anything smarter?</p>
<p>This still uses a temp file, but at least it is on one line:</p> <pre><code>echo "text" | cat - yourfile &gt; /tmp/out &amp;&amp; mv /tmp/out yourfile </code></pre> <p>Credit: <a href="http://www.cyberciti.biz/faq/bash-prepend-text-lines-to-file/" rel="noreferrer">BASH: Prepend A Text / Lines To a File</a></p>
<p>Bah! No one cared to mention about <em>tac</em>.</p> <pre><code>endor@grid ~ $ tac --help Usage: tac [OPTION]... [FILE]... Write each FILE to standard output, last line first. With no FILE, or when FILE is -, read standard input. Mandatory arguments to long options are mandatory for short options too. -b, --before attach the separator before instead of after -r, --regex interpret the separator as a regular expression -s, --separator=STRING use STRING as the separator instead of newline --help display this help and exit --version output version information and exit Report tac bugs to [email protected] GNU coreutils home page: &lt;http://www.gnu.org/software/coreutils/&gt; General help using GNU software: &lt;http://www.gnu.org/gethelp/&gt; Report tac translation bugs to &lt;http://translationproject.org/team/&gt; </code></pre>
7,798
<p>Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:</p> <pre><code>args = [3, 6] range(*args) # call with arguments unpacked from a list </code></pre> <p>This is equivalent to:</p> <pre><code>range(3, 6) </code></pre> <p>Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?</p>
<p>You can use <a href="http://www.php.net/call_user_func_array" rel="noreferrer"><code>call_user_func_array()</code></a> to achieve that:</p> <p><code>call_user_func_array("range", $args);</code> to use your example.</p>
<p>You should use the call_user_func_array</p> <pre><code>call_user_func_array(array(CLASS, METHOD), array(arg1, arg2, ....)) </code></pre> <p><a href="http://www.php.net/call_user_func_array" rel="nofollow noreferrer">http://www.php.net/call_user_func_array</a></p> <p>or use the reflection api <a href="http://www.php.net/oop5.reflection" rel="nofollow noreferrer">http://www.php.net/oop5.reflection</a></p>
37,571
<p>In C++, a function's signature depends partly on whether or not it's const. This means that a class can have two member functions with identical signatures except that one is const and the other is not. If you have a class like this, then the compiler will decide which function to call based on the object you call it on: if it's a const instance of the class, the const version of the function will be called; if the object isn't const, the other version will be called.</p> <p>In what circumstances might you want to take advantage of this feature?</p>
<p>This really only makes sense when the member function returns a pointer or a reference to a data member of your class (or a member of a member, or a member of a member of a member, ... etc.). Generally returning non-const pointers or references to data members is frowned upon, but sometimes it is reasonable, or simply very convenient (e.g. [] operator). In such cases, you provide a const and a non-const versions of the getter. This way the decision on whether or not the object can be modified rests with the function using it, which has a choice of declaring it const or non-const.</p>
<pre><code>#include &lt;iostream&gt; using namespace std; class base { public: void fun() const { cout&lt;&lt;"have fun"; } void fun() { cout&lt;&lt;"non const"; } }; int main() { base b1; b1.fun(); //does not give error return 0; } </code></pre> <p>Here compiler won't give any error, because in case of <code>const</code> functions compiler converts <code>this</code> pointer to <code>const this*</code>. this third argument separates these two functions.</p>
31,266
<p>I'd like to start 3d printing in wax.</p> <p>Is there a reasonably priced 3d printer that is capable of it?</p> <p>Am I right in assuming that all I need is to make my own filament and set extruder temperature correctly, or do I miss something?</p>
<p>Yes, with the proper equipment.</p> <p>Printing wax filament (at 51 seconds): <a href="https://youtu.be/tibkVZB_n9c?t=51s" rel="noreferrer">https://youtu.be/tibkVZB_n9c?t=51s</a></p> <p>There are also options for melting wax, filling a heated reservoir head, and printing with that. I recommend doing this with a cold ambient temperature, so that the wax solidifies quickly. There's no point in just printing a puddle. :)</p>
<p>Just make a silicone mold of any of your prints and pour you wax in the silicone,you silicone putty is pretty cheap so is wax ,no need to break the bank as printers have become less expensive and can do a pretty good job </p>
629
<p>I have a object of type <code>ICollection&lt;string&gt;</code>. What is the best way to convert to <code>string[]</code>. </p> <p>How can this be done in .NET 2?<BR> How can this be done cleaner in later version of C#, perhaps using LINQ in C# 3?</p>
<p>You could use the following snippet to convert it to an ordinary array:</p> <pre><code>string[] array = new string[collection.Count]; collection.CopyTo(array, 0); </code></pre> <p>That should do the job :)</p>
<p>In the (trivial) case of <code>ICollection&lt;String&gt;</code>, use ToArray:</p> <pre><code>String[] GetArray(ICollection&lt;String&gt; mycoll) { return mycoll.ToArray&lt;String&gt;(); } </code></pre> <p>EDIT: with .Net 2.0, you can return the array with an extra <code>List&lt;String&gt;</code>:</p> <pre><code>String[] GetArray(ICollection&lt;String&gt; mycoll) { List&lt;String&gt; result = new List&lt;String&gt;(mycoll); return result.ToArray(); } </code></pre>
42,597
<p>Does anyone have an example of script that can work reliably well across IE/Firefox to detect if the browser is capable of displaying embedded flash content. I say reliably because I know its not possible 100% of the time. </p>
<p><a href="https://github.com/swfobject/swfobject" rel="nofollow noreferrer">SWFObject</a> is very reliable. I have used it without trouble for quite a while.</p>
<p>To create a Flash object standart-compliant (with JavaScript however), I recommend you take a look at</p> <p>Unobtrusive Flash Objects (UFO) </p> <p><a href="http://www.bobbyvandersluis.com/ufo/index.html" rel="nofollow noreferrer">http://www.bobbyvandersluis.com/ufo/index.html</a></p>
19,265
<p>I have a nib that I load the usual way</p> <p><code>[NSBundle loadNibNamed:@"AuthorizationWindow" owner:self];</code></p> <p>and I see the window show on the screen briefly, and using NSLog() I can confirm that -awakeFromNib is called, but I can't figure out why the window does not stay on the screen. I had it working correctly for a bit, but now I'm not sure what I changed that messed it up. Thoughts of where to start looking?</p>
<p>I'd guess your window is being deallocated (or if under GC, collected) right out from under you. There are about a million possible reasons for this (none of which we can diagnose from one line of code), but there mere fact you're using +loadNibNamed:owner: is a warning flag. The reason is that items instantiated in nibs follow the same memory management rules as the rest of Cocoa; if you want them to stick around, you have to retain them (or in GC, keep a reference to them). NSWindowController (and NSViewController too) has some special nib-handling code so that it retains all the top-level objects in its nib when it loads, so that they'll stick around as long as it does*. However, if you don't use that, you have to do all that manually.</p> <p>The real solution is: Don't use +loadNibNamed:owner:. Instead, create an NSWindowController subclass and set up its -init method like so:</p> <pre><code>@implementation AuthorizationWindowController - (id)init { self = [super initWithWindowNibName:@"AuthorizationWindow"]; if (self == nil) return nil; // any other initialization code return self; } </code></pre> <p>*It also has special code to handle bindings-induced retain cycles that would normally cause it to leak, which is quite a bit more difficult to write yourself. Yet one more reason to use NSWindowController.</p>
<p>I would take a closer look at the object you are using to load the nib (<code>self</code>, in the code you provided). Since it is the owner of the window, the window will be released when that object is released.</p>
49,154
<p>I there a PHP based source control 'server' that is compatible with SVN clients?<br /> I'd like to host my SVN on my hosting servers, however the current host will not allow me to start any process or install any software</p>
<p>You could try:</p> <p><a href="http://sourceforge.net/projects/deltaweb" rel="nofollow noreferrer">http://sourceforge.net/projects/deltaweb</a></p>
<p>Not that I know of.</p> <p>You can look at services like <a href="http://cvsdude.com/" rel="nofollow noreferrer">CVSDude.org</a> which provide great SVN hosting that's pretty affordable. They basically specialize in both CVS, and now SVN hosting. </p>
48,177
<p>I need to apply some xml templates to various streams of xml data (and files, on occasion) and there seem to be a large number of xml libraries for java out there -- enough that it's difficult to quickly determine which libraries are still active, how they differ from the other options that are also active, and what criteria should be considered when choosing one.</p> <p>What libraries do you use for manipulating xml in java, and why is it better than the alternatives?</p>
<p>saxon is the xslt and xquery parser -- <a href="http://saxon.sourceforge.net/" rel="noreferrer">http://saxon.sourceforge.net/</a>. this is built by a known xslt expert(who was on the xslt spec committe and who has authored books). there is an open source version and a commercial version.</p> <p>It(xslt piece) gets continuously improved .<br> the other xslt tool in java, is of course, XALAN. </p> <p>xml -- there are so many. notable(well tested over the years) ones<br> 1) jdk xml parser -- dom, sax, stax<br> 2) xerces : from apache<br> 3) XOM -- if DOM doesn't work for you<br> 4) JDOM -- one of the earlier popular open source tool<br> 5) JAXB -- built into the JDK 6 now<br> 6) woodstox -- nice xml processor(read/write) -- <a href="http://woodstox.codehaus.org/" rel="noreferrer">http://woodstox.codehaus.org/</a></p>
<p>I use Xerces for XML parsing (DOM) and validation against XSD.</p> <p>For XSLT processing I used Xalan but it was 3 years ago so many things must have change, in my memory it was easy to use and powerful (I was using input XML file of several Mo)</p>
27,127
<p>I'm working on a Rails web application, and it's currently being used by some 20 users.</p> <p>Some parts of the application are only accessible by some users, so we already have a basic authorization framework in place, which I implemented using the acts_as_authenticated plugin.</p> <p>The users' privileges depend on which department they work in, so for example administration has access to all parts of the application, while accounting only has access to the accounting-related parts, and sales only has access to sales-related parts, etc.</p> <p>On the other hand, users see the links to actions for which they have unsufficient privileges. For example, those in the sales department see a link to the financial records in the main menu, but when they click on it, nothing happens. This is so because AFAIK there's no efficient way to query user privileges using acts_as_authenticated.</p> <p>I want to change this in two ways:</p> <ol> <li><p>I want to introduce more fine-grained authorization. Currently, the authorization is done at the controller level. I want to do this at the action or model level. For example, I want those in the sales department to be able to create and update payments, but not delete them.</p></li> <li><p>I want to be able to query user privileges efficiently, so I can remove unnecessary (and confusing) links from the interface.</p></li> </ol> <p>What do you think is the most elegant way to implement this?</p> <p>Rails-specific answers aren't necessary, I just want to know how this should be implemented in a data-driven application.</p> <p>Finally, here's how it's implemented currently:</p> <pre><code>def authorized? current_user.role.foo? or current_user.role.bar? end </code></pre> <p>And here's my initial idea, which I think is not the best way to solve this:</p> <pre> +------------+------------+---------+ | department | controller | action | +------------+------------+---------+ | accounting | payments | index | | accounting | payments | new | | accounting | payments | create | | accounting | payments | edit | | accounting | payments | update | | accounting | payments | destroy | | sales | payments | new | | sales | payments | create | | sales | payments | edit | | sales | payments | update | +------------+------------+---------+ </pre> <p>or</p> <pre> +------------+----------+-------+--------+------+--------+--------+ | department | model | list | create | read | update | delete | +------------+----------+-------+--------+------+--------+--------+ | accounting | payments | TRUE | TRUE | TRUE | TRUE | TRUE | | sales | payments | FALSE | TRUE | TRUE | TRUE | FALSE | +------------+----------+-------+--------+------+--------+--------+ </pre>
<p>The basic concept of authorization, as I understand it, is a role. Role can express various things:</p> <ol> <li>relation of a user to the system as a whole (eg. to be an admin of the system)</li> <li>relation of a user to some kind of entities (eg. to be a moderator of comments)</li> <li>relation of a user to some particular entity (eg. to be an owner of some resource)</li> <li>some other complex relation (eg. to be a friend of a user that is a owner of some resource)</li> <li>that user has some attribute(s) or it responds to some message in some particular way (eg. to be a teenager)</li> </ol> <p>A really fine grained authorization system should allow you to define role for a user based on any of the above mentioned criteria. Furthermore, it should allow you to set more than one role for a user. (The simplest forms of authorization plugins for Rails usually allow you define just the first kind of roles and set just one role for a user.) </p> <p>The other part of authoriation is a mechanism that decides which part of code to run (or not to run) based on the fact if a user fits into some role (set of roles) or not. To apply this mechanism, we have to find the points where the authorization should take place and select roles for which the code should or should not be run.</p> <p>The way that works for me in Rails is to define roles on the model level and to leave authorization mechanism (setting allowed roles for parts of code that I want to be authorized and asking if current user has the role that is permitted to run the part) entirely for controllers/views.</p> <p>For this I use tweaked rails-authorization-plugin which has all the possibilities I just mentioned built right in (various kinds of roles, many roles for one user, authorization on controller and view level).</p>
<p>you may need to introduce the notion of 'function points' or 'features' into your model as control-points for access; a 'feature' may have an optional 'parent feature' to form a hierarchy. You get to decide what is and isn't a feature, and check for permissions programatically. This should also allow you to check for feature-level access before drawing a menu, so that users never see links to pages they are not allowed to access.</p> <p>a similar situation/solution is described <a href="https://stackoverflow.com/questions/176338/customer-configurable-aspnet-web-site-security-for-fine-grained-control-of-page">here</a></p>
35,307
<p>So I'm generating a random number using Rnd and Randomize to set a seed that looks like this:</p> <pre><code>Randomize lSeed Response.Write Rnd </code></pre> <p>I'm noticing that it's returning the same result for two values in a row for lSeed (e.g. 123, 124) but then on say 125 it will return a new value but 126 will be the same as the on for 125. Why would this be?</p> <p>Edit:</p> <p>I have tried something like this</p> <pre><code>Randomize Randomize lSeed Response.write Rnd </code></pre> <p>And I get the same results I described above.</p>
<p>That's the problem with random numbers...</p> <p><a href="http://web.archive.org/web/20011027002011/http://dilbert.com/comics/dilbert/archive/images/dilbert2001182781025.gif" rel="nofollow noreferrer">http://web.archive.org/web/20011027002011/http://dilbert.com/comics/dilbert/archive/images/dilbert2001182781025.gif</a></p>
<p>You should reseed before getting a random value each time. I'd recommend seeding to a timer.</p>
35,705
<p>Using WMI VB scripting, I would like to create/attach multiple child processes to a parent process, such as the explorer process.</p> <p>When an app is started by clicking on it, it becomes a child process of the explorer process. The same is true for all apps that are loaded when Windows starts up.</p> <p>If you kill the explorer process using the "End Process Tree" context menu option in the task manager, it kills all child processes of the explorer process as well (a quick, brute force way to clean up memory without restarting).</p> <p>I have two scripts - one that kills a bunch of specific processes, and another that restarts those processes.</p> <p>Most of the processes/apps in my scripts are loaded at start-up thus they are children of the explorer process. When I kill the explorer process tree, all these process die, as explained earlier.</p> <p>When I restart these apps using a script, they are no longer children of the explorer process. When I kill the kill the explorer process tree, the apps started by the script do not die.</p> <p>Now, I know I can kill each process individually using a script. But it would be nice to just kill the explorer processes tree in a script without having to specify the individual apps I want to kill.</p> <p>So, if I have one script that can start my apps as children of the explorer process, my other script just has to kill the explorer processes tree.</p> <p>I have a script that does just that. It loops through and kills all the child processes of the explorer process. However it only works on apps that load at start up or are are clicked on.</p> <p>Also, by preventing these apps from loading at start-up, Windows loads MUCH faster. Later, I click on my script icon to load my apps when needed.</p> <p>That's why I want to create a script that can start apps as children of the explorer process.</p> <p>An interesting side note: I have to postpone killing any command/console processes, otherwise the script may kill itself before getting the rest of the processes.</p> <p>Any ideas how this can be done?</p> <p>Below is my code that fails.</p> <pre><code>Option Explicit dim wmi, rootProcessName, rootProcess, objStartup, objConfig, objProcess, strComputer, dropbox, itunes, skype strComputer = "." dropbox="C:\Program Files\Dropbox\Dropbox.exe" itunes="C:\Program Files\iTunes\iTunes.exe" skype="C:\Program Files\Skype\Phone\Skype.exe" Const NORMAL = 32 Set wmi = GetObject("winmgmts:\\" &amp; strComputer &amp; "\root\cimv2") Set objStartup = wmi.Get("Win32_ProcessStartup") Set objConfig = objStartup.SpawnInstance_ objConfig.PriorityClass = NORMAL rootProcessName = "'explorer.exe'" set rootProcess = wmi.ExecQuery("Select * from Win32_Process Where Name = " &amp; rootProcessName ) For Each objProcess in rootProcess objProcess.Create dropbox, null, objConfig objProcess.Create itunes, null, objConfig objProcess.Create skype, null, objConfig Next WScript.Quit </code></pre>
<p>A window's process keeps track of the Process ID of who created it, this is how the relationships are being managed. To get what you want, you either have to change the parent PID stored in the child process, or inject code into the process you want to be the parent and have it create the new child process. Neither of these are really doable.</p> <p>The real solution is to use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms684161.aspx" rel="nofollow">Job Objects</a>, that way you can terminate all the processes which are associated with the job all at the same time. But you would have to migrate out of vbscript.</p>
<p>The use of JobObjects as proposed by @josh poley is standard practice for grouping processes, but does not work when a process is launched as a DCOM service.</p> <p>Launching applications from VBScript has a serious downside when it comes to tracking the processes of things instantiated through CreateObject: Depending on what kind of object it is, the application's process may not become a child of the invoking process. Instead, it will start up under an svchost.exe process.</p> <p>Say we're working in C/C++ and we want to launch Excel from a VB script. In C/C++ we might do the following:</p> <ol> <li>Call CreateJobObject()</li> <li>Create a suspended process that is to invoke the .VBS script</li> <li>Add the created process to the job with AssignProcessToJobObject()</li> <li>Call ResumeThread() to start the suspended process</li> </ol> <p>Given the above, here's roughly what happens:</p> <ol> <li>The created process, P, starts running as a member of job, J.</li> <li>P launches the VBS file with script host, H (cscript or wscript.exe)</li> <li>H runs as a child of P, as expected</li> <li>H executes CreateObject(&quot;Excel.Application&quot;) starting Excel <strong>as a service</strong></li> <li>Hence, Excel becomes a child of a service host process, <strong>not</strong> P</li> <li>This process (<em>svchost.exe -k DcomLaunch</em>) groups DLLs for DCOM execution</li> <li>The scripting complete, H terminates</li> <li>E continues on, but P has lost all trace of it</li> </ol> <p>Line 4 is the culprit. Excel is run as a service, because registry entries indicate that it is a DCOM object. A way around this, is to create a shell object, and run the application through that.</p> <pre><code>dim shell = wscript.createObject(&quot;wscript.shell&quot;) shell.run(&lt;path-to-application&gt;\excel.exe) </code></pre> <p>The downside is that the path to the application must be known.</p>
44,764
<p>Is there a managed API to compile C# applications (to memory or disk)? I assume one exists because SharePoint compiles ASP.NET pages in memory. We want to use it to, at runtime, generate Linq <code>DataContext</code>s and compile those against various projects. </p>
<p>Take a look at the <a href="http://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider.aspx" rel="nofollow noreferrer">Microsoft.CSharp.CSharpCodeProvider</a> class. That page has sample code how to use that class to compile C# sources.</p> <p><strong>Note</strong>: This class cannot be use in partial trust. You need to run with full trust in order to be able to run the C# compiler.</p>
<p>As Franci has pointed out, the CSharpCodeProvider is what you want.</p> <p>While writing my C# book I built "Snippy" which is a quick'n'dirty way of building and running snippets of C# - it's a simple enough project to make it quite easy to see how to use CSharpCodeProvider. The <a href="http://csharpindepth.com/Downloads.aspx" rel="nofollow noreferrer">full source</a> is available - take a look.</p>
28,075
<p>I would like to ask if it is possible to show Generalization relationship in UML for a Domain Model although I understand I can do that in a Class Diagram? I did not see much examples of Domain Model displaying Generalization Relationship except in Class Diagram. If not possible, what is the best way to display that an Entity in a Domain Model is either a Entity A or Entity B or Entity C or Entity D etc ?</p>
<p>Yes, generalization between entities in your domain model is allowed. </p> <p>Basically, the domain model is a class diagram, where classes show the types of entities in your conceptual design, and not concrete programming language classes that you show in your typical class diagram.</p> <p>To better find what you can or can't do, you can read the <a href="http://www.omg.org/technology/documents/formal/uml.htm" rel="nofollow noreferrer">UML 2.x Superstructure specification</a>, but it is quite complex to understand.</p> <p>I generally tend to freely use whatever communicates my design, but if you are constrained to some specific modeling tool that is somewhat strict, you should become familiar with the UML specification.</p>
<p>You need to clarify why you're distinguishing between a domain model and a class diagram. </p> <p>On the one hand, your domain model could simply be a class diagram of everything that could map to your database, and consume it. Hence a generalization relationship could simply depict implementation inheritance or interface inheritance.</p> <p>On the other hand, your domain model could simply express how you expect your classes to work. In which case, it could be any of the standard UML diagrams: class, sequence, collaboration, component, activity, etc.</p> <p>ADD: are you talking about finding different ways to categorize your persistent entities like a tagging system? Or you could make it possible to have a persistent entity have many nodes in a category tree?</p>
19,996
<p>I am new to UserControls, and while developing my own control I found a problem with showing events of my control in the property grid at design time. If I have some events in my control I want to see them in Property grid and if I double-click that I want to have a handler, in the same way Microsoft does for its controls.</p>
<p>They should automatically appear if I'm not mistaken. Make sure you've built your project though, or changes won't propagate to open designers. And make sure it's a <b><code>public</code></b> event too. (Private/protected events rightfully shouldn't show up because they're not accessible.)</p> <p>One thing you can do to make your user's design experience nicer is to do something like the following:</p> <pre><code> [Description("This event is raised when the user presses the enter key while the control has focus."), Category("Key")] public event EventHandler EnterPressed; </code></pre> <p>The "description" bit puts a nice message in the description panel of the property window. The "category" bit puts it in a certain category (the default is Misc. at the end).</p> <p>By the way, you haven't specified a language or environment, so the above may need to be modified if it's not C# in Visual Studio 2005+.</p>
<p>You should be use Delegate at UserControl and raise it at Main page (aspx page) .If this way didn't work,you should be careful when register UserControlID.It need differ with other UserControl.Each UserControl need a ID.</p>
47,675