instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>The web service endpoint usually is defined in an early stage of a project. Since it follows the "contract first" principle, it shouldn't be changed after communicated to client systems.</p>
<p>Therefore, it is vital to label the web service in a good way.</p>
<p>How would you label web services?</p>
<p>e.g.</p>
<pre><code>http://my.domain.com/businessProcess/services/concreteServiceName
</code></pre>
<p>Other ideas?</p>
<p><strong>See this question as a poll... Feel free to vote for the best idea.</strong></p>
|
<p>We decide on names by talking to the developers, business guys, and support guys. We formed a committee called the "interface control committee", and we approach it kind of like you described in the question. We want service names to be descriptive, reflect the processes they support, and fit the needs of the technical and business stakeholders.</p>
<p>When we have ICC meetings, we also talk about schemas and how they should be developed. The business guys are key in this as well since they know what data they want to expose and why.</p>
<p>KA</p>
|
<p>I would include a version number in the URLs. </p>
| 39,215
|
<p>An existing Java site is designed to run under "/" on tomcat and there are many specific references to fixed absolute paths like "/dir/dir/page".</p>
<p>Want to migrate this to Java EE packaging, where the site will need to run under a context-root e.g. "/dir/dir/page" becomes "/my-context-root/dir/dir/page"</p>
<p>Now, the context-root can be easily with ServletRequest.getContextPath(), but that still means a lot of code changes to migrate a large code base. Most of these references are in literal HTML.</p>
<p>I've experimented with using servlet filters to do rewrites on the oubound HTML, and that seems to work fine. But it does introduce some overhead, and I wouldn't see it as a permanent solution. (see <a href="http://github.com/tardate/sources/tree/master%2FEnforceContextRootFilter-1.0-src.zip?raw=true" rel="nofollow noreferrer">EnforceContextRootFilter-1.0-src.zip</a> for the servlet filter approach).</p>
<p>Are there any better approaches to solving this problem? Anything obvious I'm missing? All comments appreciated!</p>
|
<p>Check out a related <a href="https://stackoverflow.com/questions/125359/any-clever-ways-of-handling-the-context-in-a-web-app">question</a></p>
<p>Also consider <a href="http://tuckey.org/urlrewrite/" rel="nofollow noreferrer">URLRewriteFilter</a></p>
<p>Another thing (I keep editing this darn post). If you're using JSP (versus static HTML or something else) you could also create a Tag File to replace the common html tags with links (notably a, img, form). So <a href="/root/path">link</a> can become <t:a href="/root/path">link</t:a>. Then the tag can do the translation for you.</p>
<p>This change can be easily done "en masse", using something like sed.</p>
<pre><code>sed -e 's/<a/<t:a/g' -e 's/<\/a>/<\/t:a>/g' old/x.jsp > new/x.jsp
</code></pre>
<p>Form actions may be a bit trickier than sed, but you get the idea.</p>
|
<p>the apache world used Redirects(mod_rewrite) to do the same.</p>
<p>The Servlet world started using filters</p>
<p>The ruby world (or the RoR) does more of the same stuff and they call it routing.</p>
<p>So, there's no getting around it (Unless you want to use smart regex through out -- which has been tried and it works just fine).</p>
| 17,272
|
<p>We moved our Visual C++ 2003 solution to Visual 2005 and now we have problems deploying to clean XP machines.</p>
<p>Our solution has a DLL project and a command line executable which uses this DLL. Both projects create and embed manifest files.</p>
<p>Our installer also copies the VC8 CRT runtimes from the C:\Programme\Microsoft Visual Studio 8\VC\redist\x86\Microsoft.VC80.CRT\ to the install dir.</p>
<p>When we install on a clean Windows XP, we see the error message "Application has failed to start ... application configuration is incorrect."</p>
<p>Putting the exe in Depends.exe, says:</p>
<pre><code>Error: The Side-by-Side configuration information for "c:\program files\MySoftware\vc8\BENCHMARK.EXE" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).
Error: The Side-by-Side configuration information for "c:\program files\MySoftware\vc8\MYLIB-VC8.DLL" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).
Warning: At least one module has an unresolved import due to a missing export function in a delay-load dependent module.
</code></pre>
<p>Event viewer logs:</p>
<pre><code>Dependent Assembly Microsoft.VC80.CRT could not be found and Last Error was The referenced assembly is not installed on your system.
Resolve Partial Assembly failed for Microsoft.VC80.CRT. Reference error message: The referenced assembly is not installed on your system.
Generate Activation Context failed for C:\Program Files\MySoftware\vc8\Benchmark.exe. Reference error message: The operation completed successfully.
</code></pre>
<p>I've read copying the msvcp80.dll,msvcr80.dll,msvcm80.dll and Microsoft.VC80.CRT.manifest to application folder is sufficient.</p>
<p>What am I doing wrong ?</p>
|
<p>Copying the CRT dlls around is not recommended. As Vinay says you should use the correct merge modules.</p>
<p>You can also use the redist install exe's if merge modules don't work with your installer technology:</p>
<ul>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=32BC1BEE-A3F9-4C13-9C99-220B62A191EE&displaylang=en" rel="noreferrer">VS2005 CRT</a></li>
<li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=200b2fd9-ae1a-4a14-984d-389c36f85647&displaylang=en" rel="noreferrer">VS2005 SP1 CRT</a></li>
</ul>
<p>As a last resort try copying the entire 'Microsoft.VC80.CRT' directory to your programs exe directory (not the contents, the actual directory).</p>
|
<p>Select Visual Studio 2005 Merge modules in the installer.
This can also occur if you have built the exe/dll using visual studio which has service pack installed.</p>
| 33,275
|
<p>Can I do something like this in the markup of an asp.net page, based off the "Define DEBUG constant" setting?</p>
<pre><code>#IF (DEBUG) THEN
<asp:TextBox ID="TextBox1" runat="server">You're in debug mode</asp:TextBox>
#END IF
</code></pre>
|
<pre><code><form runat="server">
<% #if DEBUG %>
<asp:TextBox ID="TextBox1" runat="server">You're in debug mode</asp:TextBox>
<% #else %>
<asp:TextBox ID="TextBox2" runat="server">Mmm... No, I think you're not in debug mode</asp:TextBox>
<% #endif %>
</form>
</code></pre>
<p>Note that you cannot assign the same ID for those text boxes.</p>
<p>Also note that DEBUG is true when it is set so in web.config:</p>
<pre><code><compilation debug="true">
</code></pre>
|
<p>It would be easy enough to roll your own. You might miss some of the cooler non-compiling features of Compilation Constants but you'd definitely have the ability to add markup based on a global parameter of some sort.</p>
| 49,648
|
<p>We have a medium sized .js file that we include in our web framework that I am porting over to SharePoint. However, I'm not sure how to go about this or what the best practice is. This is for a framework solution that will be used by other client projects, so it's best for it to be self contained and deploy-able, rather than requiring manually deploying files to the webserver.</p>
<p>My current thinking to put the JavaScript into an embedded resource and then use the script manager to write out the file. Does this seem reasonable? Or does anyone have any other recommendations?</p>
|
<p>Embeded resource is the best way and you don't need to use the ScriptManager to render it out (as AJAX is not configured OoB on SharePoint), you can just render it as any other client script resource (through the ClientScriptManager).</p>
<p>Best idea is the have an if ContainsScriptManager else UsClientScriptManager style.
That way you get the best of both worlds</p>
|
<p>You could just toss it into a doc library.</p>
<p>If you are packaging your web part into a sharepoint solution, you could include it as a Module (VSEWSS item). Your manifest file would get something like:</p>
<pre><code><TemplateFiles>
<TemplateFile Location="LAYOUTS\somescript.js" />
</TemplateFiles>
</code></pre>
<p>Theres lots of info on how to do this on the web. I've liked the doc library option for images, css, and javascript because I don't have to rebuild and wait for for SP to JIT compile for 30 seconds each time I do a minor tweak to some style or script. I just edit these things in SPDesigner right out of the doc library.</p>
| 11,429
|
<p>In C, what is the difference between using <code>++i</code> and <code>i++</code>, and which should be used in the incrementation block of a <code>for</code> loop?</p>
|
<ul>
<li><p><code>++i</code> will increment the value of <code>i</code>, and then return the incremented value.</p>
<pre><code> i = 1;
j = ++i;
(i is 2, j is 2)
</code></pre></li>
<li><p><code>i++</code> will increment the value of <code>i</code>, but return the original value that <code>i</code> held before being incremented.</p>
<pre><code> i = 1;
j = i++;
(i is 2, j is 1)
</code></pre></li>
</ul>
<p>For a <code>for</code> loop, either works. <code>++i</code> seems more common, perhaps because that is what is used in <a href="https://en.wikipedia.org/wiki/The_C_Programming_Language" rel="noreferrer">K&R</a>.</p>
<p>In any case, follow the guideline "prefer <code>++i</code> over <code>i++</code>" and you won't go wrong.</p>
<p>There's a couple of comments regarding the efficiency of <code>++i</code> and <code>i++</code>. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical.</p>
<p>The efficiency question is interesting... here's my attempt at an answer:
<a href="https://stackoverflow.com/questions/24886/is-there-a-performance-difference-between-i-and-i">Is there a performance difference between i++ and ++i in C?</a></p>
<p>As <a href="https://stackoverflow.com/users/2150/on-freund">@OnFreund</a> notes, it's different for a C++ object, since <code>operator++()</code> is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.</p>
|
<p><em>a=i++</em> means <em>a</em> contains the current <em>i</em> value.</p>
<p><em>a=++i</em> means <em>a</em> contains the incremented <em>i</em> value.</p>
| 4,449
|
<p>I thought I had seen a bug report about this on the jQuery site, but now I cannot find it. I'm trying to resize a dialog in IE6. But when the element is resized, the content and title bar don't resize down. They will resize up if the dialog is made larger, however. The result is that the close button ends up being cut off and the content is clipped if the user resize the dialog to be smaller. </p>
<p>I've tried handling the resizeStop event and manually resizing the content and titlebar, but this can gave me weird results. The sizes and positions of elements in the content area were still off. Also, even though I resize the title bar, the close button still doesn't move back into view. Any ideas? If this is a bug in jQuery-ui, does anyone know a good workaround?</p>
<pre><code><html>
<head>
<title>Example of IE6 resize issue</title>
<link rel="stylesheet" type="text/css" href="http://ui.jquery.com/repository/latest/themes/flora/flora.all.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(
function() {
$(document).ready(function()
{
$("#main-dialog").dialog();
});
});
</script>
</head>
<body>
<div id="main-dialog">
This is just some simple content that will fill the dialog. This example is
sufficient to reproduce the problem in IE6. It does not seem to occur in IE7
or FF. I haven't tried with Opera or Safari.
</div>
</body>
</html>
</code></pre>
|
<p>I was able to come up with a solution. If you add the style <strong>overflow: hidden</strong> to the dialog container div element (which has the css class .ui-dialog-container applied to it), then everything resizes correctly. All I did was add a css rule as follows to the flora theme:</p>
<pre><code>.ui-dialog .ui-dialog-container {
overflow: hidden;
}
</code></pre>
<p>It could also be corrected by executing the following:</p>
<pre><code>if ($.browser.msie && $.browser.version == 6)
{
$(".ui-dialog-container").css({ overflow: 'hidden' });
}
</code></pre>
<p>This corrected the issue I was seeing under IE6 and has not introduced any problems in FireFox.</p>
|
<p>The css may be a factor. Could you change your example so we can see your stylesheet? I've updated the example so that it doesn't depend on having jQuery locally.</p>
<pre><code><html>
<head>
<title>Example of IE6 resize issue</title>
<link rel="stylesheet" type="text/css" href="?.css" />
<script src="http://www.google.com/jsapi"></script>
<script>
google.load("jquery", "1");
google.load("jqueryui", "1");
google.setOnLoadCallback(
function() {
$(document).ready(function()
{
$("#main-dialog").dialog();
});
});
</script>
</head>
<body>
<div id="main-dialog">
This is just some simple content that will fill the dialog. This example is
sufficient to reproduce the problem in IE6. It does not seem to occur in IE7
or FF. I haven't tried with Opera or Safari.
</div>
</body>
</html>
</code></pre>
| 14,398
|
<p>Do you think that project iteration length is related to project team size? If so, how? What other key factors do you use to recognize correct iteration length for different projects?</p>
|
<p>Iteration length is primarily related to the teams ability to communicate and complete a working version of the software. More team members equals more communication channels (<a href="http://en.wikipedia.org/wiki/Brooks%27s_law" rel="nofollow noreferrer">Brooks's Law</a>) which will likely increase your iteration time. </p>
<p>I think that 2 week iterations, whether you deliver to the client or not, are a good goal, as it allows for very good health checks. </p>
<p>Ultimately, the iteration length will depend on the features you wish to implement in the next iteration, and in the early phases your iterations may jump around from 1 week to 1 month as you become comfortable with the team and the technology stack.</p>
|
<p>One of the main drivers for short iterations, is easing integration between modules/features/programmers. Obviously, the bigger your team, the more integration you will have. It's a tradeoff: short iterations mean you're integrating often, which is good - BUT if its a big team you'll be spending a LOT of team on integration overhead, even without new code. Longer iterations obviously mean more integration each time less seldom, and a lot more risky.</p>
<p>If your team is very large, you can try branched integration, i.e. integrating small subteams often, and integrating between the teams less often... BUT then you'll be having inconsistencies between branches, and you lose much of that benefit right there.</p>
<p>Another key factor to consider is complexity - obviously complex, backend systems are riskier integration, simple Web-UI pages are less risky.</p>
<p>(I realize I didnt give you a clear cut answer, there is none. It's always tradeoffs, I hope I give you some food for thought.)</p>
| 13,840
|
<p>I want to build a parser for a C like language. The interesting aspect about it is that I want to build it in such a way that someone who has access to the source can easily modified it to extend the language (a new expression type of instance) with the extensions being runtime configurable (they can be turned on and off).</p>
<p>My current intent is to build a recursive decent parser as an object. Each production will be a method of an object. The method of extension will be to derive classes from this base replacing methods (and production definitions) as needed. I'm still trying to figure out how to mix and match extensions. One idea is to play games with the v-tbl. Objects would be constructed with a v-tbl that is a copy of the base but with methods replaced from derived classes.</p>
<p>Aside from the bit-twiddling nature of the solution the only issues I have with it is</p>
<ul>
<li>a reasonable way to do the v-tbl mixup</li>
<li>what to do when 2 extensions alter the same productions (as most replacements will end up calling the original having one replacement call the other would work but the mechanics of setting this up are the issue)</li>
<li>how to allow the extension of extensions (this might end up looking like a standard MI system, but I've never got how they work)</li>
</ul>
<p>Another solution (a slightly more mundane version of the same same approach) would be to use static member variables to store function-pointers and call them for the same effect.</p>
<p><em>Edit:</em> I have already built a system that lets me build productions from BNF definitions. I can alter it to support whatever I decide on.</p>
|
<p>These are some of the challenges the Perl 6 design effort has faced. You may find it worthwhile looking into some of the solutions they came up with. Or you may find that to be gross overkill.</p>
|
<p>If I recall my university courses correctly, recursive descent parsers have some limitations that might bite you, especially since you're allowing extensions - somebody elses language extension could cause issues.</p>
<p>A proper compiler toolkit - such as the open source <a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a> - might make things easier, and might also provide some different approaches for you.</p>
| 28,778
|
<p>I have this little function</p>
<pre><code>function makewindows(){
child1 = window.open ("about:blank");
child1.document.write("<?php echo htmlspecialchars(json_encode($row2['ARTICLE_DESC']), ENT_QUOTES); ?>");
child1.document.close();
}
</code></pre>
<p>Which whatever I try, simply outputs the php code as the html source, and not the result of the php code. This was previously working fine, and I am not sure what I have changed to result in this behavior.</p>
<p>I have pasted all the code now. An error is generated by a link that calls updateByQuery, preventing makewindows from being parsed correctly..I think. I am not sure what is wrong with updateByQuery however:</p>
<pre><code>function updateByQuery(layer, query) {
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random();
update(layer, url);
}
</code></pre>
|
<p>Have you recently moved this file out of a PHP parsed file (i.e. .phtml/.php) and into a .js file? Note that any PHP you expect to be executed must be parsed by the PHP parser before delivery to the client. If it was originally in a .php file, then it would have been parsed/ executed, and worked fine.</p>
<p>However, .js files are not, by default, parsed by PHP. Perhaps they were, at one point, but your server administrator has recently upgraded something, and lost this behaviour? You may be able to use a local configuration file (in Apache, .htaccess) to re-enable it.</p>
|
<p><strong>Make sure you are running the page from the webserver</strong> like such: <code>http://localhost/yourpage.php</code> and not directly from the file itself like such: <code>file://yourpage.php</code></p>
| 48,067
|
<p>I'd like to take XML in the format below and load each code record into a domain object in my <code>BootStrap.groovy</code>. I want to preserve the formatting of each snippet of code. </p>
<h2>XML</h2>
<pre><code><records>
<code>
<language>Groovy</language>
<snippet>
println "This is Groovy"
println "A very powerful language"
</snippet>
</code>
<code>
<language>Groovy</language>
<snippet>
3.times {
println "hello"
}
</snippet>
</code>
<code>
<language>Perl</language>
<snippet>
@foo = split(",");
</snippet>
</code>
</records>
</code></pre>
<h2>Domain Object</h2>
<pre><code>Code {
String language
String snippet
}
</code></pre>
<h2>BootStrap.groovy</h2>
<pre><code>new Code(language l, snippet: x).save()
</code></pre>
|
<p>roughly something like this:</p>
<pre><code>def CODE_XML = '''
<records>
<code>
<language>Groovy</language>
<snippet>
println "This is Groovy"
println "A very powerful language"
</snippet>
</code>
<code>
<language>Groovy</language>
<snippet>
3.times {
println "hello"
}
</snippet>
</code>
<code>
<language>Perl</language>
<snippet>
@foo = split(",");
</snippet>
</code>
</records>
'''
def records = new XmlParser().parseText(CODE_XML)
records.code.each() { code ->
new Code(language: code.language, snippet: code.snippet).save()
}
</code></pre>
|
<p>If you can specity a DTD or similar and your XML parser obeys it, I think you can specify the contents of the snippet element to be CDATA and always get it as-is.</p>
| 20,831
|
<p>I'm trying to determine the asymptotic run-time of one of my algorithms, which uses exponents, but I'm not sure of how exponents are calculated programmatically.</p>
<p>I'm specifically looking for the pow() algorithm used for double-precision, floating point numbers.</p>
|
<p>I've had a chance to look at fdlibm's implementation. The comments describe the algorithm used:</p>
<pre><code> * n
* Method: Let x = 2 * (1+f)
* 1. Compute and return log2(x) in two pieces:
* log2(x) = w1 + w2,
* where w1 has 53-24 = 29 bit trailing zeros.
* 2. Perform y*log2(x) = n+y' by simulating muti-precision
* arithmetic, where |y'|<=0.5.
* 3. Return x**y = 2**n*exp(y'*log2)
</code></pre>
<p>followed by a listing of all the special cases handled (0, 1, inf, nan).</p>
<p>The most intense sections of the code, after all the special-case handling, involve the <code>log2</code> and <code>2**</code> calculations. And there are no loops in either of those. So, the complexity of floating-point primitives notwithstanding, it looks like a asymptotically constant-time algorithm.</p>
<p>Floating-point experts (of which I'm not one) are welcome to comment. :-)</p>
|
<p>If I were writing a pow function targeting Intel, I would return exp2(log2(x) * y). Intel's microcode for log2 is surely faster than anything I'd be able to code, even if I could remember my first year calculus and grad school numerical analysis.</p>
| 19,937
|
<p>What would be the best method for getting a custom element (that is using J2ME native Graphics) painted on LWUIT elements?</p>
<p>The custom element is an implementation from mapping library, that paints it's content (for example Google map) to Graphics object. How would it be possible to paint the result directly on LWUIT elements (at the moment I am trying to paint it on a Component). </p>
<p>Is the only way to write a wrapper in LWUIT package, that would expose the internal implementation of it?</p>
<p><strong>Edit:</strong></p>
<p><strong><em>John:</em></strong> your solution looks like a lot of engineering :P What I ended up using is following wrapper:</p>
<pre><code>package com.sun.lwuit;
public class ImageWrapper {
private final Image image;
public ImageWrapper(final Image lwuitBuffer) {
this.image = lwuitBuffer;
}
public javax.microedition.lcdui.Graphics getGraphics() {
return image.getGraphics().getGraphics();
}
}
</code></pre>
<p>Now I can get the 'native' Graphics element from LWUIT. Paint on it - effectively painting on LWUIT image. And I can use the image to paint on a component.</p>
<p>And it still looks like a hack :)</p>
<p>But the real problem is 50kB of code overhead, even after obfuscation. But this is a issue for another post :)</p>
<p>/JaanusSiim</p>
|
<p>I do not think any hacking is necessary. You can subclass the LWTUI Component class and then you can pain whatever you want on to the graphic context of the component. You do not get the native lcdui.Graphics object but an object with a same interface that is easy to use.</p>
<p>If you really need to pass a lcdui.Graphics to some underlying library to display its output then I would suggest this:</p>
<p>Somewhere in your component code (do only when the component contents really need to be changed):</p>
<pre><code>private Image buffer = null; // keep this
int[] bufferArray = new int[desiredWidth * desiredHeight];
javax.microedition.lcdui.Image bufferImage =
Image.createEmptyImage(desiredWidth, desiredHeight);
thirPartyComponent.paint(bufferImage.getGraphics());
bufferImage.getRGB(bufferArray,0,1,0,0,desiredWidth, desiredHeight);
bufferImage = null; //no longer needed
buffer = Image.createImage(bufferArray, desiredWidth, desiredHeight);
</code></pre>
<p>In the component paint(g) method:</p>
<pre><code>g.drawImage(0,0, buffer);
</code></pre>
<p>By doing the hack you did you are losing portablity and also sice you are exposing implementation private object you might also break other things.</p>
<p>Hope this helps.</p>
|
<p>Based on the javadoc for LWUIT and J2ME and guessing that the custom J2ME class is a <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Canvas.html" rel="nofollow noreferrer">Canvas</a> it looks like you would have to:</p>
<ul>
<li>Subclass <a href="https://lwuit.dev.java.net/javadocs/com/sun/lwuit/Component.html" rel="nofollow noreferrer">LWUIT's Component class</a> wrapping the custom J2ME component</li>
<li>Override the paint() method of the LWUIT Component</li>
<li>Subclass the <a href="http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Graphics.html" rel="nofollow noreferrer">J2ME Graphics class</a> wrapping the LWUIT Graphics class and pass all the method calls through</li>
<li>Pass in the wrapped J2ME Graphics implementation to the custom J2ME component's paint method</li>
</ul>
<p>That third step is an ugly one. Check on the <a href="https://lwuit.dev.java.net/servlets/SummarizeList?listName=users" rel="nofollow noreferrer">LWUIT mailing list</a> to see if anyone has dome this before. From the published APIs I don't see another way to do it. </p>
<p>Edit: The hack added in the question looks better than my hack for an Image. What I have <em>may</em> be better for a general case, but I don't know either LWUIT or J2ME well enough to really say that. </p>
| 4,332
|
<p>I have been getting clogs and believe that it may be due to a damaged PTFE tube inside my hot end. I have a replacement (it came with my printer), but I can't seem to fit the tube into the nozzle.</p>
<p>I also tried to turn the original PTFE tube around, and I can't get the other end to fit into the nozzle either.</p>
<p>Is there a trick to it?</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>
| 633
|
<p>We have created a web application, using ASP.NET, that allows users to upload documents and attach them to business entities, like customers, contacts and so on. </p>
<p>The application runs on the intranet and all files are uploaded through the web application into a shared folder on the server.</p>
<p>I would like, right from the web page, for the user to <strong>open</strong> the actual file, <strong>edit</strong> it and then <strong>save</strong> the changes back to the original location. This is a <strong>piece of cake</strong> in a Windows environment, I'm just wondering what, if any, is the best way to handle this in a web environment?</p>
<p>The files are usually Word documents, Excel documents and images.</p>
<p><strong>Clarification</strong></p>
<p>We would display all the attachments in a list format. We would like it so that the user would click on an edit link and the file would be opened in the appropriate application, for example, Microsoft Word or Microsoft Excel. I think the file associations in Windows would already handle this. We are just trying to save our user the time to download the original file, make their changes, delete the old file, and the upload the new file.</p>
|
<p>SharePoint does this by exposing FrontPage extensions which Word and Excel know how to deal with.</p>
<p>If you want to look at a commercial product for ASP.NET that allows you to edit images with AJAX (no need for installed software), I work for a company that has one (<a href="http://atalasoft.com" rel="nofollow noreferrer">Atalasoft</a>)</p>
|
<p>I'm trying to do something with using file:// instead of http:// but it's real sporadic based on the browser. Seems to work fine in IE, okay in Firefox, and goes nowhere in Chrome.</p>
<p>Looks like I may just be stuck with downloading, editing, and re-uploading the document.</p>
| 15,115
|
<p>I'm creating a generic class and in one of the methods I need to know the Class of the generic type currently in use. The reason is that one of the method's I call expects this as an argument.</p>
<p>Example:</p>
<pre><code>public class MyGenericClass<T> {
public void doSomething() {
// Snip...
// Call to a 3rd party lib
T bean = (T)someObject.create(T.class);
// Snip...
}
}
</code></pre>
<p>Clearly the example above doesn't work and results in the following error: Illegal class literal for the type parameter T.</p>
<p>My question is: does someone know a good alternative or workaround for this?</p>
|
<p>Still the same problems : Generic informations are erased at runtime, it cannot be recovered. A workaround is to pass the class T in parameter of a static method : </p>
<pre><code>public class MyGenericClass<T> {
private final Class<T> clazz;
public static <U> MyGenericClass<U> createMyGeneric(Class<U> clazz) {
return new MyGenericClass<U>(clazz);
}
protected MyGenericClass(Class<T> clazz) {
this.clazz = clazz;
}
public void doSomething() {
T instance = clazz.newInstance();
}
}
</code></pre>
<p>It's ugly, but it works.</p>
|
<p>public class DatabaseAccessUtil {</p>
<pre><code>EntityManagerFactory entitymanagerfactory;
EntityManager entitymanager;
public DatabaseAccessUtil() {
entitymanagerfactory=Persistence.createEntityManagerFactory("bookmyshow");
entitymanager=entitymanagerfactory.createEntityManager();
}
public void save (T t) {
entitymanager.getTransaction().begin();
entitymanager.persist(t);
entitymanager.getTransaction().commit();
}
public void update(T t) {
entitymanager.getTransaction().begin();
entitymanager.persist(t);
entitymanager.getTransaction().commit();
}
public void delete(T t) {
entitymanager.getTransaction().begin();
entitymanager.remove(t);
entitymanager.getTransaction().commit();
}
public Object retrieve(Query query) {
return query.getSingleResult();
}
//call the method - retrieve(object,requiredclass.class)
public Object retrieve(Object primaryKey,class clazz) throws Exception {
return entitymanager.find(clazz,primaryKey);
}
</code></pre>
<p>}</p>
| 22,075
|
<p>This is a specific version of <a href="https://stackoverflow.com/questions/119540/business-logic-database-or-application-layer">this question</a>.<br/>
I want to check if I am inserting a duplicate row. Should I check it programmatically in my application layer:</p>
<pre><code>if (exists(obj))
{
throw new DuplicateObjectException();
}
HibernateSessionFactory.getSession().save(obj);
</code></pre>
<p>or should I catch the exception thrown by the database layer and triggered when I violate the contraint?</p>
<pre><code>try
{
HibernateSessionFactory.getSession().save(obj);
}
catch(ConstraintViolationException e)
{
throw new DuplicateObjectException();
}
</code></pre>
<p><strong>EDIT:</strong> In other words: though the constraint is there to remain (it's good database design anyway, and I can't be sure my app will be the only one accessing the table) shall I rely on the constraint and handle the exception its violation will raise, or I'd better check anyway?</p>
<p><strong>EDIT2:</strong> Of course I do check+insert within a transaction, locking the table to ensure no other process is writing another record in the meantime</p>
|
<p>First, you <strong>must</strong> have a primary key or unique constraint on the database to enforce this uniqueness properly - no question.</p>
<p>Given that the constraint exists, which way should you code in the application? My preference would be to try the insert and catch the exceptions. Because presumably most inserts will succeed, only a few will fails as duplicates (that's what "exception" implies!): it is inefficient to perform an exists check before every insert, when the database is going to be performing its own constraint checking anyway.</p>
<p>Also, it is theoretically possible for the exists check to be wrong anyway - if someone else manages to commit a record with the same key value in the small interval between your exists check and your insert. Then, if you don't trap the database exception, you will believe the insert succeeded when in fact it didn't.</p>
|
<p>Once hibernate throws an exception from the session you <a href="http://www.hibernate.org/hib_docs/reference/en/html/transactions-demarcation.html" rel="nofollow noreferrer">must discard the session</a> (see section 11.2.3). So, if you need to check for dups and continue using the same session then you have no choice but to check first in the application. </p>
<p>Also there is a possibility with the code in the 1st snippet that another process could insert a record that would cause the duplicate exception to be thrown between the time you check for the duplicate record and the time it actually gets inserted.</p>
| 20,188
|
<p>I am attempting to print the Benchy boat but every attempt so far has been unsuccessful. The print has a sort of slope/blob on the nose of the boat, which emerges after the first 30 layers.</p>
<p><a href="https://i.stack.imgur.com/vx2cM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vx2cM.jpg" alt="defect"></a></p>
<p>Here you can see the front of the boat already arching up:</p>
<p><a href="https://i.stack.imgur.com/q9Z6A.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q9Z6A.jpg" alt="defect 2"></a></p>
<p>I have tried decreasing speed to 40 mm/s but the issue remains.</p>
<p><strong>Printer</strong>: Geetech Prusa I3 Pro B</p>
<p>XY Accelleration: 1000 mm/s<sup>2</sup></p>
<p>XY Jerk: 20 mm/s</p>
<p>Retraction Accelleration: 2000 mm/s<sup>2</sup></p>
<p>Extruder Jerk: 5 mm/s</p>
<p>Printing Speed: 50 mm/s</p>
<p>Travel Speed: 120 mm/s</p>
<p>Layer Height: 0.1 mm</p>
<p>Infill: 60% (Lines)</p>
<p>Material: PLA, 200 °C, 1.75mm filament, retraction enabled.</p>
|
<p>Looks like curling from to much being extruded and no cooling I had the same problem added part cooling and problem was gone </p>
|
<p>The lines along the length of the boat also appear to be wobbling, can you confirm this? Have you used this material before? The layers should look straight and equal.
<a href="https://i.stack.imgur.com/PvV5g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PvV5g.png" alt="enter image description here"></a></p>
<p>I have 2 candidates:
If the lines indeed wobble it may be over extrusion. The excess material pushing the extruded line over the edge. (check the diameter of the filament with a caliper and adjust the extrusion rate if needed)</p>
<p>Or it can be shrinking. 60% infill is quite high. You could try 20 or 30% (less material and more air => less distortion), or adjusting cooling.</p>
<p>Hope it helps, good luck! </p>
| 849
|
<p>Or if any body knows of an alternative control that does?</p>
<p>It would be handy to serve up content to the WebBrowser control that has embedded images & other resources from a database without having a dependency on these resources being hosted on a webserver or to create temporary files on the local file system.</p>
<p>Mhtml supports this but doesn't seem to work in a WebBrowser control when using the DocumentText property?</p>
|
<p>I don't think that what you are trying to achieve is possible using the DocumentText property. MHTML is a document archive format and although it is stored as text with binary data such as images etc. encoded to base64 strings, there does not seem to be any intelligence built into the DocumentText property of the webbrowser control to read this file format. Looking into this property with Reflector you will see that a different mechanism is used to handle this as opposed to the Url property which invokes the "guts" of the webbrowser control via the underlying COM object. </p>
<p>It also doesn't appear that you can accomplish this by writing to the DocumentStream property either.</p>
|
<p>please refer to this answer <a href="https://stackoverflow.com/questions/4737823/c-filenotfoundexception-on-webbrowser/4738244#4738244">c# filenotfoundexception on webbrowser?</a></p>
| 27,113
|
<p>I am working on an ASP.Net application and I want users to be able to take a picture with their local webcam and then upload it to the server.
I can, of course, rely on users doing this manually via their locally installed software, save the image as a file and do a normal file upload. However, what I really want to do is incorporate it all into a UI in the browser.
I know this means accessing local resources so do I need an ActiveX control or Silverlight or is there something I could do in Javascript for example?</p>
<p>This is initially intended for an Intranet app so I can have control of the client's environemnt, including stipulating the browser etc, which means I <i>can</I> use an ActiveX control if I have to. However, it would be nice if I could write this in a generic way so it could be used in an internet app generally (happy to stipulate that it only works on Windows clients but would be good to get it to work in FireFox).</p>
<p>Thanks.</p>
|
<p>The only acceptable and universal way to this for now is Flash/Flex application. Flash player presets literally in every browser in the world and all of them has such capability.</p>
|
<p>This sounds very suspicious to me. You realize the nefarious applications this could be applied to, right? A web page that when a user browses to it, unknownst to them, their webcam snaps a pic of them. ... I don't like it.</p>
| 41,574
|
<p>From googling around it looks like Xcode (3.1 in my case) should be at least trying to give me a sane debug view of STL containers - or at least vectors.</p>
<p>However, whenever I go to look at a vector in the debugger I just see M_impl, with M_start and M_finish members (and a couple of others) - but nothing in-between! (it's a debug build, btw).</p>
<p>Am I missing a setting or something somewhere?</p>
<p>I've also read that there are macros available that can augment the debug viewer even further to inspect more complex containers - but have been unable to find any.</p>
<p>I'd also like to be able to view std::wstrings, without having to drop to the memory viewer. It shows std::string fine. Is there anything I can do to show std::wstring?</p>
<p>I realise this is a bit of a composite question - but it's all really part of the same subject.</p>
|
<p>You can create <a href="https://web.archive.org/web/20090812202145/http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeDebugging/600-Viewing_Variables_and_Memory/variables_and_memory.html" rel="nofollow noreferrer">Data formatters</a> for different variable types so they show up nicer :-).</p>
|
<p>Try using the GDB debugger in Project->Edit Scheme... and consider switching your compiler to LLVM GCC 4.2 in the Project Build Settings (under Build Options -> Compiler for C/C++/Objective-C).</p>
<p>In XCode 4, I found I needed these settings to view things like a std::vector of V3f where V3f is a templated float vector type.</p>
<p>Note that I think you can't use ARC (Automatic Reference Counting) with LLVM GCC 4.2.</p>
| 34,703
|
<p>I am trying to code a flowchart generator for a language using Ruby. </p>
<p>I wanted to know if there were any libraries that I could use to draw various shapes for the various flowchart elements and write out text to those shapes. </p>
<p>I would really prefer not having to write code for drawing basic shapes, if I can help it. </p>
<p>Can someone could point me to some reference documentation with examples of using that library?</p>
|
<p>Write up your flowchart as a directed or undirected graph in <a href="http://www.graphviz.org/About.php" rel="nofollow noreferrer">Graphviz</a>. Graphviz has a language, <a href="http://www.graphviz.org/Documentation.php" rel="nofollow noreferrer">dot</a> that makes it easy to generate graphs. Just generate the dot file, run it through Graphiviz, and you get your image.</p>
<pre><code>graph {
A -- B -- C;
B -- D;
C -- D [constraint=false];
}
</code></pre>
<p>renders as <br>
<a href="http://www.flickr.com/photos/rampion/3130993214/" rel="nofollow noreferrer" title="undirected by rampion, on Flickr"><img src="https://farm4.static.flickr.com/3126/3130993214_af71aa44f6.jpg" width="183" height="255" alt="undirected" /></a></p>
<pre><code>digraph {
A [label="start"];
B [label="eat"];
C [label="drink"];
D [label="be merry"];
A -> B -> C;
C -> D [constraint=false];
B -> D [ arrowhead=none, arrowtail=normal]; // reverse this edge
}
</code></pre>
<p>renders as<br>
<a href="http://www.flickr.com/photos/rampion/3130162313/" rel="nofollow noreferrer" title="directed by rampion, on Flickr"><img src="https://farm4.static.flickr.com/3085/3130162313_51e5b00dc9.jpg" width="212" height="255" alt="directed" /></a></p>
<p>You can control node shapes and much more in Graphviz. </p>
|
<p>I am totally sure, but check out cairo bindings for ruby. Pango for text. I am investigating then currently and came across this page.</p>
| 3,233
|
<p>How do you back up your development machine so that in the event of a catastrophic hardware malfunction, you are up and running in the least amount of time possible?</p>
|
<p>There's an important distinction between backing up your development machine and backing up your work.</p>
<p>For a development machine your best bet is an imaging solution that offers as near a "one-click-restore" process as possible. TimeMachine (Mac) and Windows Home Server (Windows) are both excellent for this purpose. Not only can you have your entire machine restored in 1-2 hours (depending on HDD size), but both run automatically and store deltas so you can have months of backups in relatively little space. There are also numerous "ghosting" packages, though they usually do not offer incremental/delta backups so take more time/space to backup your machine.</p>
<p>Less good are products such as Carbonite/Mozy/JungleDisk/RSync. These products WILL allow you to retrieve your data, but you will still have to reinstall the OS and programs. Some have limited/no histories either.</p>
<p>In terms of backing up your code and data then I would recommend a sourcecode control product like SVN. While a general backup solution will protect your data, it does not offer the labeling/branching/history functionality that SCC packages do. These functions are invaluable for any type of project with a shelf-life.</p>
<p>You can easily run a SVN server on your local machine. If your machine is backed up then your SVN database will be also. This IMO is the best solution for a home developer and is how I keep things.</p>
|
<p>Maybe just a simple hardware hard disk raid would be a good start. This way if one drive fails, you still have the other drive in the raid. If something other than the drives fail you can pop these drives into another system and get your files quickly.</p>
| 4,638
|
<p>Consider this:</p>
<pre><code>var query = from r in this._db.Recipes
where r.RecipesID == recipeID
select new { r.RecipesID, r.RecipesName };
</code></pre>
<p>How would i get individual columns in my <code>query</code> object without using a for-loop?</p>
<p>Basicly: how do I translate <code>DataTable.Rows[0]["ColumnName"]</code> into Linq syntax?</p>
|
<p>It's really unclear what you are looking for, as your two samples are compatible. </p>
<p>As close as I can figure, what you want is:</p>
<pre><code>var rows = query.ToList();
string name = rows[0].RecipesName;
</code></pre>
|
<p>Sorry, misunderstood your question. As others are saying, you can use ToList() to get a List back. An alternative if all you need is the first one, just use:</p>
<pre><code>
query.First().ColumnName
</code></pre>
<p>or if you want to avoid an exception on empty list:</p>
<pre><code>
var obj = query.FirstOrDefault();
if (obj != null)
obj.ColumnName;
</code></pre>
<hr>
<p>Original Answer (so the comment makes sense):</p>
<p>Use <a href="http://blogs.msdn.com/adonet/archive/2007/01/26/querying-datasets-introduction-to-linq-to-dataset.aspx" rel="nofollow noreferrer">Linq to Datasets</a>. Basically would be something like:</p>
<pre><code>
var query = from r in yourTable.AsEnumerable()
select r.Field<string>("ColumnName");
</code></pre>
| 22,689
|
<p>What method do I call to get the name of a class?</p>
|
<pre><code>In [1]: class Test:
...: pass
...:
In [2]: Test.__name__
Out[2]: 'Test'
</code></pre>
|
<p>In [8]: <code>str('2'.__class__)</code><br />
Out[8]: <code>"<type 'str'>"</code><br /></p>
<p>In [9]: <code>str(len.__class__)</code><br />
Out[9]: <code>"<type 'builtin_function_or_method'>"</code><br /></p>
<p>In [10]: <code>str(4.6.__class__)</code><br />
Out[10]: <code>"<type 'float'>"</code><br /></p>
<p>Or, as was pointed out before,<br /></p>
<p>In [11]: <code>4.6.__class__.__name__</code><br />
Out[11]: <code>'float'</code></p>
| 10,105
|
<p>I'm looking for a broad overview of what I need to do and in what order to migrate a W2003 Server to a virtual server environment. Specifically:</p>
<p>How does it work in general?
Do I need to prepare my disks in any way?
What do I install first? The toolkit? Virtual Server?
Can I install linux later?</p>
<p>etc.</p>
<p>Any pointers welcome!</p>
|
<p>Depending on which virtualisation platform you're migrating to there are tools to perform physical to virtual conversions:</p>
<p><a href="http://www.vmware.com/products/converter/" rel="nofollow noreferrer">http://www.vmware.com/products/converter/</a></p>
<p>PlateSpin was the product that we were recommended when we virtualised a chunk of our hosting platform to Virtual Iron.</p>
<p><a href="http://www.platespin.com/products/powerconvert/" rel="nofollow noreferrer">http://www.platespin.com/products/powerconvert/</a></p>
<p>It'll convert physical to Microsoft Virtual Server, Virtual Iron, VMware and Citrix XenServer amongst other capabilities.</p>
<p>In reality we just ran our internal server build process on the virgin VM's which gave us the opportunity to start out with fresh machines and without the configuration 'rot' that happens over time to servers of a particular vintage.</p>
|
<p>Depending on which virtualisation platform you're migrating to there are tools to perform physical to virtual conversions:</p>
<p><a href="http://www.vmware.com/products/converter/" rel="nofollow noreferrer">http://www.vmware.com/products/converter/</a></p>
<p>PlateSpin was the product that we were recommended when we virtualised a chunk of our hosting platform to Virtual Iron.</p>
<p><a href="http://www.platespin.com/products/powerconvert/" rel="nofollow noreferrer">http://www.platespin.com/products/powerconvert/</a></p>
<p>It'll convert physical to Microsoft Virtual Server, Virtual Iron, VMware and Citrix XenServer amongst other capabilities.</p>
<p>In reality we just ran our internal server build process on the virgin VM's which gave us the opportunity to start out with fresh machines and without the configuration 'rot' that happens over time to servers of a particular vintage.</p>
| 31,410
|
<p>How do I write the getDB() function and use it properly?</p>
<p>Here is a code snippet of my App Object:</p>
<pre><code>public class MyApp extends UiApplication {
private static PersistentObject m_oStore;
private static MyBigObjectOfStorage m_oDB;
static {
store = PersistentStore.getPersistentObject(0xa1a569278238dad2L);
}
public static void main(String[] args) {
MyApp theApp = new MyApp();
theApp.enterEventDispatcher();
}
public MyApp() {
pushScreen(new MyMainScreen());
}
// Is this correct? Will it return a copy of m_oDB or a reference of m_oDB?
public MyBigObjectOfStorage getDB() {
return m_oDB; // returns a reference
}
}
</code></pre>
|
<pre><code>public MyBigObjectOfStorage getDB() {
return m_oDB;
}
</code></pre>
<p>As you put it is correct. It will return a <em>copy of the reference</em>, which is kind of in between a copy and a reference.</p>
<p>The actual object instance returned by getDB() is the same object referenced by m_oDB. However, you can't change the reference returned by getDB() to point at a different object and have it actually cause the local private m_oDB to point at the new object. m_oDB will still point at the object it was already.</p>
<p>See <a href="http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html" rel="nofollow noreferrer">http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html</a> for more detail.</p>
<p>Although looking through your code there, you never set m_oDB at all, so getDB() will always return null.</p>
|
<pre><code>public MyBigObjectOfStorage getDB() {
Object o = store.getContents();
if ( o instanceof MyBigObjectOfStorage ) {
return (MyBigObjectOfStorage) o;
} else {
return null;
}
}
</code></pre>
| 27,167
|
<p>Can someone explain what exactly the string "0 but true" means in Perl? As far as I understand, it equals zero in an integer comparison, but evaluates to true when used as a boolean. Is this correct? Is this a normal behavior of the language or is this a special string treated as a special case in the interpreter?</p>
|
<p>It's normal behaviour of the language. Quoting the <a href="https://perldoc.perl.org/perlsyn.html#Truth-and-Falsehood" rel="noreferrer"><code>perlsyn</code></a> manpage:</p>
<blockquote>
<p>The number <code>0</code>, the strings <code>'0'</code> and <code>""</code>, the empty list <code>()</code>, and <code>undef</code>
are all false in a boolean context. All other values are true. Negation
of a true value by <code>!</code> or <code>not</code> returns a special false value.
When evaluated as a string it is treated as <code>""</code>, but as a number, it is
treated as <code>0</code>.</p>
</blockquote>
<p>Because of this, there needs to be a way to return <code>0</code> from a system call that expects to return <code>0</code> as a (successful) return value, and leave a way to signal a failure case by actually returning a false value. <code>"0 but true"</code> serves that purpose.</p>
|
<p>When you want to write a function that returns either an integer value, or <em>false</em> or <b>undef</b> (i.e. for the error case) then you have to watch out for the value zero. Returning it is false and shouldn't indicate the error condition, so returning "0 but true" makes the function return value true while still passing back the value zero when math is done on it.</p>
| 15,784
|
<p>what is a good way to select a random element from a map? C++. It is my understanding that maps don't have random access iterators. The key is a long long and the map is sparsely populated. </p>
|
<pre><code>map<...> MyMap;
iterator item = MyMap.begin();
std::advance( item, random_0_to_n(MyMap.size()) );
</code></pre>
|
<p>Here is the case when <em>all</em> map items must be access in random order.</p>
<ol>
<li>Copy the map to a vector.</li>
<li>Shuffle vector.</li>
</ol>
<p>In pseudo-code (It closely reflects the following C++ implementation):</p>
<pre><code>import random
import time
# populate map by some stuff for testing
m = dict((i*i, i) for i in range(3))
# copy map to vector
v = m.items()
# seed PRNG
# NOTE: this part is present only to reflect C++
r = random.Random(time.clock())
# shuffle vector
random.shuffle(v, r.random)
# print randomized map elements
for e in v:
print "%s:%s" % e,
print
</code></pre>
<p>In C++:</p>
<pre><code>#include <algorithm>
#include <iostream>
#include <map>
#include <vector>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/foreach.hpp>
#include <boost/random.hpp>
int main()
{
using namespace std;
using namespace boost;
using namespace boost::posix_time;
// populate map by some stuff for testing
typedef map<long long, int> Map;
Map m;
for (int i = 0; i < 3; ++i)
m[i * i] = i;
// copy map to vector
#ifndef OPERATE_ON_KEY
typedef vector<pair<Map::key_type, Map::mapped_type> > Vector;
Vector v(m.begin(), m.end());
#else
typedef vector<Map::key_type> Vector;
Vector v;
v.reserve(m.size());
BOOST_FOREACH( Map::value_type p, m )
v.push_back(p.first);
#endif // OPERATE_ON_KEY
// make PRNG
ptime now(microsec_clock::local_time());
ptime midnight(now.date());
time_duration td = now - midnight;
mt19937 gen(td.ticks()); // seed the generator with raw number of ticks
random_number_generator<mt19937,
Vector::iterator::difference_type> rng(gen);
// shuffle vector
// rng(n) must return a uniformly distributed integer in the range [0, n)
random_shuffle(v.begin(), v.end(), rng);
// print randomized map elements
BOOST_FOREACH( Vector::value_type e, v )
#ifndef OPERATE_ON_KEY
cout << e.first << ":" << e.second << " ";
#else
cout << e << " ";
#endif // OPERATE_ON_KEY
cout << endl;
}
</code></pre>
| 19,215
|
<p>The __doPostBack is not working in firefox 3 (have not checked 2). Everything is working great in IE 6&7 and it even works in Chrome??</p>
<p>It's a simple asp:LinkButton with an OnClick event</p>
<pre><code><asp:LinkButton ID="DeleteAllPicturesLinkButton" Enabled="False" OnClientClick="javascript:return confirm('Are you sure you want to delete all pictures? \n This action cannot be undone.');" OnClick="DeletePictureLinkButton_Click" CommandName="DeleteAll" CssClass="button" runat="server">
</code></pre>
<p>The javascript confirm is firing so I know the javascript is working, it's specirically the __doPostBack event. There is a lot more going on on the page, just didn't know if it's work it to post the entire page.</p>
<p>I enable the control on the page load event.</p>
<p>Any ideas?</p>
<hr>
<p>I hope this is the correct way to do this, but I found the answer. I figured I'd put it up here rather then in a stackoverflow "answer"</p>
<p>Seems it had something to do with nesting ajax toolkit UpdatePanel. When I removed the top level panel it was fixed.</p>
<p>Hope this helps if anyone else has the same problem. I still don't know what specifically was causing the problem, but that was the solution for me.</p>
|
<p>Check your User Agent string. This same thing happened to me one time and I realized it was because I was testing out some pages as "googlebot". The JavaScript that is generated depends on knowing what the user agent is.</p>
<p>From <a href="http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1" rel="noreferrer">http://support.mozilla.com/tiki-view_forum_thread.php?locale=tr&comments_parentId=160492&forumId=1</a>:</p>
<blockquote>
<p>To reset your user agent string type about:config into the location bar and press enter. This brings up a list of preferences. Enter general.useragent into the filter box, this should show a few preferences (probably 4 of them). If any have the status user set, right-click on the preference and choose Reset</p>
</blockquote>
|
<p>With or without the OnClientClick event it still doesn't work.</p>
<p>The _doPostBack event is the auto generated javascript that .NET produces.</p>
<pre><code>function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
</code></pre>
<p>*The &95; are underscores, seems to be a problem with the stackoverflow code block format.</p>
| 7,909
|
<p>I'm trying to come up with a way to estimate the number of English words a translation from Japanese will turn into. Japanese has three main scripts -- <a href="http://en.wikipedia.org/wiki/Kanji" rel="nofollow noreferrer">Kanji</a>, <a href="http://en.wikipedia.org/wiki/Hiragana" rel="nofollow noreferrer">Hiragana</a>, and <a href="http://en.wikipedia.org/wiki/Katakana" rel="nofollow noreferrer">Katakana</a> -- and each has a different average character-to-word ratio (Kanji being the lowest, Katakana the highest).</p>
<p><strong>Examples:</strong></p>
<ul>
<li>computer: コンピュータ (Katakana - 6
characters); 計算機 (Kanji: 3
characters)</li>
<li>whale: くじら (Hiragana --
3 characters); 鯨 (Kanji: 1
character)</li>
</ul>
<p>As data, I have a large glossary of Japanese words and their English translations, and a fairly large corpus of matched Japanese source documents and their English translations. I want to come up with a formula that will count numbers of Kanji, Hiragana, and Katakana characters in a source text, and estimate the number of English words this is likely to turn into.</p>
|
<p>Here's what Borland (now Embarcadero) thinks about English to non-English:</p>
<p><a href="http://www.podgoretsky.com/ftp/Docs/Delphi/D5/dg/intapps.html" rel="nofollow noreferrer">Length of English string (in characters)</a></p>
<pre><code>Expected increase
1-5 100%
6-12 80%
13-20 60%
21-30 40%
31-50 20%
over 50 10%
</code></pre>
<p>I think you can sort of apply this (with some modification) for Japanese to non-Japanese. </p>
<p>Another element you might want to consider is the tone of the language. In English, instructions are phrased as an imperative as in "Press OK." But in Japanese language, imperatives are considered rude, and you must phrase instructions in honorific (or keigo) as in "OKボタンを押してください。"</p>
<p>Watch out for three-letter kanji combos. Many of the big words translate into three- or four- letter kanji combo such as 国際化(internationalization: 20 chars), 高可用性(high availability: 17 chars).</p>
|
<p>It seems simple enough - you just need to find out the ratios.</p>
<p>For each script, count the number of script characters and English words in your glossary and work out the ratio.</p>
<p>This can be augmented with the Japanese source documents <strong>assuming</strong> you can both detect which script a Japanese word is in and what the English equivalent phrase is in the translation. Otherwise you'll have to guesstimate the ratios or ignore this as source data,</p>
<p>Then, as you say, count the number of words in each script of your source text, do the multiplies, and you should have a rough estimate.</p>
| 17,506
|
<p>I am selecting rows from a table, but some of the columns are a text type, but they always have numeric data in them. How can I format them as numbers?</p>
<p>e.g. column quantity heading 'Quantity' format 999,999</p>
<p>However, since the column in the table is text, the numeric formatting is ignored.</p>
|
<p>You will need to TO_NUMBER the column in your query.</p>
|
<p>Thanks Steve,</p>
<p>I can now have:</p>
<pre>
column quantity heading 'Quantity' format 999,999
select TO_NUMBER(quantity) as quantity from Sales
</pre>
<p>And I get a right justified report.</p>
| 14,600
|
<p>For example, I could just git pull and then git checkout HEAD-1. But is there a way of seeing the differences before deciding whether to git pull or not?</p>
|
<p>Do a <code>git fetch</code> first to update your remote tracking branch. Then use <code>git log ..origin</code> to see what has changed in the "origin" branch. Then you can do a <code>git pull</code> if you are satisfied with the changes.</p>
|
<p>If you really want to avoid <em>any</em> trace of the remote changes getting into your repo, you can do a local <code>git clone</code>, which will use hardlinks, so will take almost no extra space, and then apply Greg Hewgill’s answer to that. If you are satisfied, you can go back to the original repository and pull from the local clone to avoid going over the network, although you should follow up with a <code>git fetch</code> in the original repository to make sure your remote tracking branches are up to date.</p>
<p>Normally, that isn’t necessary, of course.</p>
| 33,038
|
<p>This is intended to be a more concrete, easily expressable form of my earlier question.</p>
<p>Take a list of words from a dictionary with common letter length.<br>
How to reorder this list tto keep as many letters as possible common between adjacent words? </p>
<p>Example 1:</p>
<pre><code>AGNI, CIVA, DEVA, DEWA, KAMA, RAMA, SIVA, VAYU
reorders to:
AGNI, CIVA, SIVA, DEVA, DEWA, KAMA, RAMA, VAYU
</code></pre>
<p>Example 2:</p>
<pre><code>DEVI, KALI, SHRI, VACH
reorders to:
DEVI, SHRI, KALI, VACH
</code></pre>
<p>The simplest algorithm seems to be: Pick anything, then search for the shortest distance?<br>
However, DEVI->KALI (1 common) is equivalent to DEVI->SHRI (1 common)<br>
Choosing the first match would result in fewer common pairs in the entire list (4 versus 5). </p>
<p>This seems that it should be simpler than full TSP? </p>
|
<p>What you're trying to do, is calculate the shortest hamiltonian path in a complete weighted graph, where each word is a vertex, and the weight of each edge is the number of letters that are differenct between those two words.</p>
<p>For your example, the graph would have edges weighted as so:</p>
<pre>
DEVI KALI SHRI VACH
DEVI X 3 3 4
KALI 3 X 3 3
SHRI 3 3 X 4
VACH 4 3 4 X
</pre>
<p>Then it's just a simple matter of picking your favorite <a href="http://en.wikipedia.org/wiki/Traveling_salesman_problem" rel="nofollow noreferrer">TSP solving algorithm</a>, and you're good to go.</p>
|
<p>This can be done with a recursive approach. Pseudo-code:</p>
<pre><code>Start with one of the words, call it w
FindNext(w, l) // l = list of words without w
Get a list l of the words near to w
If only one word in list
Return that word
Else
For every word w' in l do FindNext(w', l') //l' = l without w'
</code></pre>
<p>You can add some score to count common pairs and to prefer "better" lists.</p>
| 41,392
|
<p>I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data.</p>
<p>Anyone with better ideas?</p>
|
<p>You need to use the <a href="http://maven.apache.org/shared/maven-plugin-testing-harness/" rel="noreferrer">maven-plugin-testing-harness</a>, </p>
<pre>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
</pre>
<p>You derive your unit test classes from <a href="http://maven.apache.org/shared/maven-plugin-testing-harness/apidocs/org/apache/maven/plugin/testing/AbstractMojoTestCase.html" rel="noreferrer">AbstractMojoTestCase</a>. </p>
<p>You need to create a bare bones POM, usually in the <code>src/test/resources</code> folder. </p>
<pre>
<project>
<build>
<plugins>
<plugin>
<groupId>com.mydomain,mytools</groupId>
<artifactId>mytool-maven-plugin</artifactId>
<configuration>
<!-- Insert configuration settings here -->
</configuration>
<executions>
<execution>
<goals>
<goal>mygoal</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
</pre>
<p>Use the AbstractMojoTest.lookupMojo(String,File) (or one of the other variations) to load the Mojo for a specific goal and execute it.</p>
<pre>
final File testPom = new File(PlexusTestCase.getBasedir(), "/target/test-classes/mytools-plugin-config.xml");
Mojo mojo = this.lookupMojo("mygoal", testPom);
// Insert assertions to validate that your plugin was initialised correctly
mojo.execute();
// Insert assertions to validate that your plugin behaved as expected
</pre>
<p>I created my a plugin of my own that you can refer to for clarification <a href="http://ldap-plugin.btmatthews.com" rel="noreferrer">http://ldap-plugin.btmatthews.com</a>,</p>
|
<p>If you'd like to see some real-world examples, the Terracotta Maven plugin (tc-maven-plugin) has some tests with it that you can peruse in the open source forge.</p>
<p>The plugin is at: <a href="http://forge.terracotta.org/releases/projects/tc-maven-plugin/" rel="nofollow noreferrer">http://forge.terracotta.org/releases/projects/tc-maven-plugin/</a></p>
<p>And the source is in svn at: <a href="http://svn.terracotta.org/svn/forge/projects/tc-maven-plugin/trunk/" rel="nofollow noreferrer">http://svn.terracotta.org/svn/forge/projects/tc-maven-plugin/trunk/</a></p>
<p>And in that source you can find some actual Maven plugin tests at: src/test/java/org/terracotta/maven/plugins/tc/</p>
| 13,038
|
<p>I have a text file on my local machine that is generated by a daily Python script run in cron. </p>
<p>I would like to add a bit of code to have that file sent securely to my server over SSH.</p>
|
<p>You can call the <a href="https://en.wikipedia.org/wiki/Secure_copy" rel="noreferrer"><code>scp</code></a> bash command (it copies files over <a href="https://en.wikipedia.org/wiki/Secure_Shell" rel="noreferrer">SSH</a>) with <a href="https://docs.python.org/library/subprocess.html#subprocess.run" rel="noreferrer"><code>subprocess.run</code></a>:</p>
<pre><code>import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])
</code></pre>
<p>If you're creating the file that you want to send in the same Python program, you'll want to call <code>subprocess.run</code> command outside the <code>with</code> block you're using to open the file (or call <code>.close()</code> on the file first if you're not using a <code>with</code> block), so you know it's flushed to disk from Python.</p>
<p>You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).</p>
|
<p>Kind of hacky, but the following should work :)</p>
<pre><code>import os
filePath = "/foo/bar/baz.py"
serverPath = "/blah/boo/boom.py"
os.system("scp "+filePath+" user@myserver.com:"+serverPath)
</code></pre>
| 9,384
|
<p>In our embedded system (using a PowerPC processor), we want to disable the processor cache. What steps do we need to take?</p>
<p>To clarify a bit, the application in question must have as constant a speed of execution as we can make it.
Variability in executing the same code path is not acceptable. This is the reason to turn off the cache.</p>
|
<p>I'm kind of late to the question, and also it's been a while since I did all the low-level processor init code on PPCs, but I seem to remember the cache & MMU being pretty tightly coupled (one had to be enabled to enable the other) and I <em>think</em> in the MMU page tables, you could define the cacheable attribute.</p>
<p>So my point is this: if there's a certain subset of code that must run in deterministic time, maybe you locate that code (via a linker command file) in a region of memory that is defined as non-cacheable in the page tables? That way all the code that can/should benefit from the cache does, and the (hopefully) subset of code that shouldn't, doesn't.</p>
<p>I'd handle it this way anyway, so that later, if you want to enable caching for part of the system, you just need to flip a few bits in the MMU page tables, instead of (re-)writing the init code to set up all the page tables & caching.</p>
|
<p>Perhaps you don't want to globally disable cache, you only want to disable it for a particular address range?</p>
<p>On some processors you can configure TLB (translation lookaside buffer) entries for address ranges such that each range could have caching enabled or disabled. This way you can disable caching for memory mapped I/O, and still leave caching on for the main block of RAM.</p>
<p>The only PowerPC I've done this on was a PowerPC 440EP (from IBM, then AMCC), so I don't know if all PowerPCs work the same way.</p>
| 9,899
|
<p>I'm looking for a reliable, implementation-independent way to clone an entire Document. The Javadocs specifically say that calling cloneNode on a Document is implementation-specific. I've tried passing the Document through a no-op Transformer, but the resulting Node has no owner Document.</p>
<p>I could create a new Document and import the nodes from the old one, but I'm afraid there might be bits of Document metadata that get lost. Same thing with writing the Document to a string and parsing it back in.</p>
<p>Any ideas?</p>
<p>By the way, I'm stuck at Java 1.4.2, for reasons beyond my control.</p>
|
<p>As some of the comments point out, there are problems with serializing and re-parsing a document. In addition to memory usage, performance considerations, and normalization, there's also loss of the prolog (DTD or schema), potential loss of comments (which aren't required to be captured), and loss of what may be significant whitespace. Serialization should be avoided.</p>
<p>If the real goal is to make a copy of an existing DOM Document object, then it should be handled programmatically, in memory. Thanksfully there is a relatively easy way to do this using features available in Java 5 or using external XSLT libraries like Xalan, which is to a a pass-through transformation.</p>
<p>Below is shown the Java 5 solution:</p>
<pre><code>TransformerFactory tfactory = TransformerFactory.newInstance();
Transformer tx = tfactory.newTransformer();
DOMSource source = new DOMSource(doc);
DOMResult result = new DOMResult();
tx.transform(source,result);
return (Document)result.getNode();
</code></pre>
<p>That's basically it. You'll need to handle exceptions and may wish to configure the transformer, but I leave that as an exercise for the reader.</p>
|
<p>Still, how about the quick'n'dirty way: serialize the whole Document into XML string and then parse it back using DOM Parser? </p>
<p>I don't see a reason why the serialized version would lack anything. Mind to provide an example?</p>
<p>Memory consumption would be significant, but, on the other hand, if you're duplicating the whole DOM, it cannot be small anyway...</p>
| 35,260
|
<p>On a PLA print where stringing has occurred, what is the best way to remove it during post processing?</p>
<p>Should I simply cut it with a hobby knife and sand the surface or are the better techniques to use?</p>
|
<p>Use a hobby knife with a chisel blade (straight edge perpendicular to handle, beveled on one side only).</p>
<p>Apply with beveled edge against workpiece. Raise the handle in small increments while stroking over the flaw until it is entirely removed. This provides pretty good control to prevent gouging.</p>
<p>Avoid sanding.</p>
<p>This method also works well for removing "ribs" caused by gaps in painter tape applied to print bed.</p>
|
<p>I pull them off by hand and then a few quick passes with a cigarette lighter works for me.</p>
| 2,107
|
<p>When I delete any file from an asp.net mvc project (project not in svn or any source control provider) it takes upto 60 seconds for the UI to become responsive again. CPU usage jumps to 80/90%.
Has anyone else experienced this and know of any fix or solution?</p>
|
<p>Do you mean deleting a file from Visual Studio solution? If so, the fix is to empty your Windows recycle bin.</p>
|
<p>If you're talking about the running website trying to delete a file, then do your file delete in a separate thread.</p>
<p>If you're talking about deleting a source file, I have had that problem a few years ago. I don't remember what the fix was, but I don't think it's in the latest Visual Studio (which you're probably using if your doing MVC)</p>
| 48,934
|
<p>I'm currently estimating how to best share data between offices at different geographical locations.<br>
My current preference is for using <a href="http://msdn.microsoft.com/en-us/library/ms151198.aspx" rel="nofollow noreferrer">SQL Server Merge Replication</a> and have a main database and handful of subscribers.</p>
<p>The system will also need to allow a few work sites to work disconnected (no or little connectivity on construction sites).</p>
<p>The amount of data is not going to be large, we're talking about sharing data from a custom ERP system between a manufacturing plant, a handful of regional offices and work sites.</p>
<p>The <a href="http://msdn.microsoft.com/en-us/sync/default.aspx" rel="nofollow noreferrer">Sync Framework</a> also looks good and seems to have good support in <em>SQL Server 2008</em>.</p>
<ol>
<li>What other proven system out there should I investigate that can answer these needs?</li>
<li>For those with experience on sharing data in a similar environment, do you have any particular recommendation and tips?</li>
<li>How difficult has it been for you to deal with data conflicts?</li>
</ol>
|
<p>Definitely stick with SQL Server replication, then decide to go down the path of 'build your own replication framework.' I've seen some applications become horrible messes that way.</p>
<p>I've had environments that are setup for snapshot replication in a disconnected model, but the remote sites were read-only. They worked quite well with minimal issues.</p>
<p>I'd also be interested in hearing people's experiences with the sync framework. </p>
<p>You may want to look at what microsoft calls <em><a href="http://msdn.microsoft.com/en-au/library/aa480482.aspx" rel="nofollow noreferrer">smart clients</a></em> which is an architecture microsoft talk about for applications that may have temporary network connectivity.</p>
|
<p>I have already discussed my own experience of SQLServer2005 with #cycnus. My answer is not a real one, just a few arguments to initiate a subject I am very interested in.</p>
<ol>
<li>Our choice for 'not allways connected' sites is to implement web-based merge replication. Data exchanges happen to be even quicker than through VPNs (as we also have a combination of LAN merge replications). I will easily get a speed of 30 to 40 rows per second through web (512 Down/128 Up, shared) while I'll get a 5 rows per second through LAN (overseas, 256 Up/Down, dedicated). Don't ask me why ...</li>
<li>Tips are numerous: subscription should be of the client type (data circulating basically from the suscriber to the publisher before being distributed). Primary Keys should allways be GUID, for many reasons <a href="https://stackoverflow.com/questions/230351/what-should-i-consider-when-selecting-a-data-type-for-my-primary-key#232985">exposed here</a>, but also for replication issues: we are then sure that any newly created record will be able to find its way up to the publisher, as its PK will be unique. Moreover, I recently had a non-convergence issue with one of my replications (bad experience, exposed <a href="https://stackoverflow.com/questions/343224/ms-sql-server-2005-non-convergent-data-after-replication">here</a>) , where I felt very happy not to use natural keys, as the problem occured on the potential "natural key" column.</li>
<li>Data conflicts should then be basically limited to work organisation problems, where (ususally for bad reasons) the same data is modified by different users in different places at the same time. With our "PK is GUID rule", we do not have conflicts out of these specific situations. </li>
<li>One should always have the possibility to modify its database structure, even if replications are running. It is possible to keep on adding fields, indexes, constraints while running merge replication processes. I also find a workaround for adding tables without reinitialising the replication process (exposed <a href="https://stackoverflow.com/questions/220890/how-do-i-add-a-new-replicated-table-to-a-sql-server-2005-db-that-is-in-merge-re#221295">here</a>, still did not understand why I was downvoted on this answer!) </li>
</ol>
| 45,893
|
<p>I'm trying in vain to write a regular expression to match valid ssh connection strings.</p>
<p>I really only need to recognise strings of the format:</p>
<ul>
<li>user@hostname:/some/path</li>
</ul>
<p>but it would be nice to also match an implicit home directory:</p>
<ul>
<li>user@hostname:</li>
</ul>
<p>I've so-far come up with this regex:</p>
<pre><code>/^[:alnum:]+\@\:(\/[:alnum:]+)*$/
</code></pre>
<p>which doesn't work as intended.</p>
<p>Any suggestions welcome before my brain explodes and I start speaking in line noise :)</p>
|
<p>Your supplied regex doesn't have the hostname section. Try:</p>
<pre><code>/^[:alnum:]+\@[:alnum:\.]\:(\/[:alnum:]+)*$/
</code></pre>
<p>or</p>
<pre><code>/^[A-Za-z][A-Za-z0-9_]*\@[A-Za-z][A-Za-z0-9_\.]*\:(\/[A-Za-z][A-Za-z0-9_]*)*$/
</code></pre>
<p>since I don't trust alnum without double brackets.</p>
<p>Also, :alnum: may not give you the required range for your sections. You can have "." characters in your host name and may also need to allow for "_" characters. And it's rare I've seen usernames or hostnames start with a non-alphabetic.</p>
<p>Just as a side note, I try to avoid the enhanced regexes since they don't run on all regex engines (I've been using UNIX for a <strong>long</strong> time). Unfortunately that makes my regexes ungainly (see above) and not overly internationalizable. Apologies for that.</p>
|
<p>Bracket expressions go inside their own brackets. You are matching any one of colon, 'a', 'l', 'm', 'n', or 'u'.</p>
<p>And like Pax said, you missed the hostname. But the bracket expressions are still wrong.</p>
| 46,365
|
<p>I've got a bunch of servers running this Linux app. I'd like for them to be able to generate a GUID with a low probability of collision. I'm sure I could just pull 128 bytes out of /dev/urandom and that would probably be fine, but is there a simple & easy way to generate a GUID that is more equivalent to the Win32 one? Specifically, one that takes into account space (well, MAC address), time, and randomness? I don't want to call off the box for it, I just want something like <a href="http://msdn.microsoft.com/en-us/library/aa713311.aspx" rel="noreferrer">CreateGuid()</a></p>
|
<p>This <a href="http://www.webdav.org/specs/draft-leach-uuids-guids-01.txt" rel="noreferrer">Internet Draft</a> describes one type of UUID in great details and I have used a similar approach with great success when I needed a UUID implementation and could not link to an existing library for architectural reasons.</p>
<p>This <a href="http://en.wikipedia.org/wiki/Universally_Unique_Identifier" rel="noreferrer">article</a> provides a good overview.</p>
|
<p>There is a Boost version available.</p>
<p><a href="http://www.boostpro.com/vault/index.php?action=downloadfile&filename=uuid_v11.zip&directory=&PHPSESSID=69e18b945f686398b963710fd52f143a" rel="nofollow noreferrer">http://www.boostpro.com/vault/index.php?action=downloadfile&filename=uuid_v11.zip&directory=&PHPSESSID=69e18b945f686398b963710fd52f143a</a></p>
| 18,555
|
<p>I'm developing a basic dip-switch user control as a personal learning exercise. Originally I had it set up where you could declare some custom color properties on the user control, and they would be used on elements inside the control.</p>
<p>However, I recenly discovered ToggleButtons, and rebuilt my control to take advantage of them. Since then, my custom color properties (SwitchColor and SwitchBkgndColor) no longer work properly. They are always rendered with the default colors, not the colors I specified when I place them in my Window. Here's some code:</p>
<pre><code> <UserControl x:Class="DipSwitchToggleBtn"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:SwitchesApp"
Width="20" Height="40">
<ToggleButton Name="ToggleBtn" IsThreeState="False">
<ToggleButton.Template>
<ControlTemplate>
<Canvas Name="SwitchBkgnd"
Background="{TemplateBinding app:DipSwitchToggleBtn.SwitchBkgndColor}"
>
<Rectangle Name="SwitchBlock"
Fill="{TemplateBinding app:DipSwitchToggleBtn.SwitchColor}"
Width="16" Height="16"
Canvas.Top="22"
Canvas.Left="2"
/>
</Canvas>
<ControlTemplate.Triggers>
<Trigger Property="ToggleButton.IsChecked" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="SwitchBlock"
Duration="00:00:00.05"
Storyboard.TargetProperty="(Canvas.Top)" To="2" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="SwitchBlock"
Duration="00:00:00.05"
Storyboard.TargetProperty="(Canvas.Top)" To="22" />
</Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</UserControl>
</code></pre>
<p>...and the code behind:</p>
<pre><code>Partial Public Class DipSwitchToggleBtn
Public Property State() As Boolean
Get
Return Me.ToggleBtn.IsChecked
End Get
Set(ByVal value As Boolean)
Me.ToggleBtn.IsChecked = value
End Set
End Property
Public Sub Toggle()
Me.State = Not Me.State
End Sub
#Region " Visual Properties "
Public Shared ReadOnly SwitchColorProperty As DependencyProperty = _
DependencyProperty.Register("SwitchColor", _
GetType(Brush), GetType(DipSwitchToggleBtn), _
New FrameworkPropertyMetadata(Brushes.LightGray))
Public Property SwitchColor() As Brush
Get
Return GetValue(SwitchColorProperty)
End Get
Set(ByVal value As Brush)
SetValue(SwitchColorProperty, value)
End Set
End Property
Public Shared ReadOnly SwitchBkgndColorProperty As DependencyProperty = _
DependencyProperty.Register("SwitchBkgndColor", _
GetType(Brush), GetType(DipSwitchToggleBtn), _
New FrameworkPropertyMetadata(Brushes.Gray))
Public Property SwitchBkgndColor() As Brush
Get
Return GetValue(SwitchBkgndColorProperty)
End Get
Set(ByVal value As Brush)
SetValue(SwitchBkgndColorProperty, value)
End Set
End Property
#End Region
End Class
</code></pre>
<p>The default Gray and LightGray show up in the VS2008 designer and the compiled app, but when I do something like this in my window:</p>
<pre><code><app:DipSwitchToggleBtn x:Name="DipSwitchTest" SwitchColor="#0000FF" SwitchBkgndColor="#000000" />
</code></pre>
<p>The colors I specified for this instance do not get used. Everything compiles without error, but my control is still displayed with the default colors.</p>
<p>I believe there is some new hierarchy at play since I nested my items in the ToggleButton.</p>
<p>Any help would be appreciated. Thank you.</p>
|
<p>In the getters of your color properties you need to convert to brushes</p>
<pre><code>Public Property SwitchBkgndColor() As Brush
Get
Return CType(GetValue(SwitchBkgndColorProperty), Brush)
End Get
Set(ByVal value As Brush)
SetValue(SwitchBkgndColorProperty, value)
End Set
End Property
</code></pre>
<p>It might not make a difference as it probably just auto-converts but give it a try.</p>
|
<p>See the answer from <a href="https://stackoverflow.com/questions/358443/custom-usercontrol-property-used-by-child-element#360700">Custom UserControl Property used by child element</a>. The same concept can be applied for your ToggleButton. Create UserControl with no content just a UserControl.Template override and use TemplateBinding to set your props</p>
| 47,384
|
<p>When Joel Spolsky and Jeff Atwood began the disagreement in their podcast over whether programmers should learn C, regardless of their industry and platform of delivery, it sparkled quite an explosive debate within the developer community that probably still rages amongst certain groups today. I have been reading a number of passages from a number of programmer bloggers with their take on the matter. The arguments from both sides certainly carry weight, both what I did not find is a perspective that is uniquely angled from the standpoint of <strong>developers focused on just the .NET Framework</strong>. Practically all of them were commenting on a general programmer standpoint.</p>
<p>What am I trying to get at? Recall Jeff Atwood's opinion that most of the time developers at such high levels would spend would be on learning the <em>business/domain</em>, on top of whatever is needed to learn the technologies to achieve those domain requirements. In my working experience that is a very accurate description of the work life of many. Now supposing that .NET developers can fork the time for "extra curricular" learning, should <em>that</em> be C?</p>
<p>For the record, I have learnt C back in school myself, and I can absolutely understand and appreciate what the proponents are reasoning for. But, when thinking things through, I personally feel .NET developers should not dive straight into C. Because, the thing I wish more developers would take some time to learn is - <strong>MSIL</strong> and <strong>CLR</strong>.</p>
<p>Maybe I am stuck with the an unusual bunch of colleagues, I don't know, but it seems to me many people do not keep a <em>conscious awareness</em> that their C# or VB code compiles in IL first before JIT comes in and makes it raw machine code. Most do not know IL, and have no interest in how <em>exactly</em> the CLR handles the code they write. Reading Jeffrey Richter's <strong>CLR via C#</strong> was quite a shocker for me in so many areas; glad I read it despite colleagues dismissing it as "too low level". I am no expert in IL but with knowledge of the basics, I found myself following his text easier as I was already familiar with the stack behaviour of IL. I find myself disassembling assemblies to have a look at how the IL turns out when I write certain code.</p>
<p>I learn the CLR and MSIL because I know that is the direct layer <em>below me</em>. The layer that allows me to carry out my own layer of work. C, is actually further down. Closer to our "reality" is the CLR and MSIL. That is why I would recommend others to have a go at those, because I do not see enough folks delving at that layer. Or, is your team already all conversant with MSIL?</p>
|
<p>Of course you should. The greatest way to become overly specialized and single-minded (and, correspondingly, have limited marketable skills) is to only work with a single type of language and eschew all others as "not related to your current task."</p>
<p>Every programmer should have some experience with a modern JIT'd OO language (C#/Java), a lower-level simpler language (C, FORTRAN, etc), a very high level interpreted language (Python, Ruby, etc), and a functional language (Scheme, Lisp, Haskell, etc). Even if you don't use all of them on a day-to-day basis, the broadening of your thought process that such knowledge grants is quite useful.</p>
|
<p>The <strong>CLR</strong> is a <strong>virtual</strong> machine so if that's all you learn, then you only know what's happening at a virtual level.</p>
<p>Learning <strong>C</strong> will teach you more about the <strong>physical</strong> machine as far as memory usage goes, which as you mention is what the CLR uses underneath. Learning how the CLR works isn't going to give you as much insight into, say, garbage collection, as learning C. With C, you <em>really</em> appreciate what's involved in memory management.</p>
<p>Learning <strong>CIL</strong> on the other hand, tells you a bit more about execution in .NET than you would by learning <strong>C</strong>. Still, how <strong>IL</strong> maps to machine language will still be a mystery for the most part so knowing some of the high-level opcodes, like the ones for casting types, isn't that helpful in terms of understanding what's really going on as they're opaque for the most part. Learning <strong>C</strong> and pointers, however, will enlighten you on some of those aspects.</p>
| 15,294
|
<p>I just noticed that Chromium was installed in AppData in both Vista and XP. If Google does that and if other applications does this, than is that becuase there is some form of protection? Should we write installers that does the same thing as Google?</p>
|
<p>Windows still lacks a convention for per-user installation.</p>
<ul>
<li>When an installer asks whether to install for the current user or all users, it really only refers to shortcut placement (Start Menu; Desktop). The actual application files still go in the system-wide <code>%PROGRAMFILES%</code>.</li>
<li>Microsoft's own ClickOnce works around this by creating a completely non-standard <code>%USERPROFILE%\Local Settings\Apps</code> (<code>%USERPROFILE%\AppData\Roaming</code> on Vista / Server 2008) directory, with both program files and configuration data in there.</li>
</ul>
<p>(I'm at a loss why Microsoft couldn't add a per-user Program Files directory in Vista. For example, in OS X, you can create a <code>~/Applications</code>, and the Finder will give it an appropriate icon. Apps like CrossOver and Adobe AIR automatically use that, defaulting to per-user apps. Thus, no permissions issues.)</p>
<p>What you probably <em>should</em> do: if the user is not an admin, install in the user directory; if they do, give them both options.</p>
|
<p>Just so you people know, Google has created an MSI installer for global system installation and management. It's located here:</p>
<p><a href="https://www.google.com/intl/en/chrome/business/browser/" rel="nofollow">https://www.google.com/intl/en/chrome/business/browser/</a></p>
| 6,989
|
<p><em>Note: Originally this question was asked for PostgreSQL, however, the answer applies to almost any database which has a JDBC driver that can detect foreign-key associations.</em> </p>
<hr>
<p>Querying PostgreSQL data dictionary for foreign-keys and relationship between tables is very straightforward, but how can I use that information to generate a graph of the relations between tables?</p>
<p>Any recommendations about tools that can do this?</p>
<p><strong>EDIT:</strong> I know GraphVIZ/DOT <em>can</em> be useful, however, I don't know have any idea regarding how to code an app that would generate the directed graph .DOT file.</p>
|
<p>Dot is part of the <a href="http://www.graphviz.org/" rel="noreferrer">graphviz</a> package, which is a pretty damn cool/useful tool. Of course, you'll need something to generate the dot files for graphviz. I've used <a href="http://schemaspy.sourceforge.net/" rel="noreferrer">SchemaSpy</a> once or twice in the past, and it works pretty well, provided you have the relationships defined in the database.</p>
|
<p><a href="http://en.wikipedia.org/wiki/DOT_language" rel="nofollow noreferrer">Dot</a> is multiplatform and may be useful.</p>
| 22,498
|
<p>I have an xml file where I need to comment out a whole piece of text with Ant.</p>
<p>There's this Ant task</p>
<pre><code><replace file="${src.dir}/Version.as"
token="@revisionPrana" value="${revision}"/>
</code></pre>
<p>that I use to replace words, but in my case I need to replace a whole block like this:</p>
<pre><code><value>
<object class="edumatic.backoffice.view.modules.NavigationModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsNavigationModule.swf"/>
<property name="icon"
value="edumatic/backoffice/view/modules/support/assets/book.png" />
<property name="title" value="Assessments" />
<property name="pluginID" value="EXAM" />
</object>
</value>
<value>
<object class="edumatic.backoffice.view.modules.ContentModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsContentModule.swf" />
<property name="pluginID" value="EXAM" />
</object>
</value>
</code></pre>
<p>Into</p>
<pre><code><!--value>
<object class="edumatic.backoffice.view.modules.NavigationModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsNavigationModule.swf"/>
<property name="icon"
value="edumatic/backoffice/view/modules/support/assets/book.png" />
<property name="title" value="Assessments" />
<property name="pluginID" value="EXAM" />
</object>
</value>
<value>
<object class="edumatic.backoffice.view.modules.ContentModuleInfo">
<property name="url"
value="edumatic/backoffice/view/modules/support/ExamsContentModule.swf" />
<property name="pluginID" value="EXAM" />
</object>
</value-->
</code></pre>
<p>So, basically I need to comment out a whole block of XML. Can I do this with a replace task (putting the whole block in the attribute token and value doesn't really work)? Or is there a quick way to read in the xml with ant and delete some nodes and save the xml again?</p>
<p>Searching for and replace it by isn't an option because there are multiple value children and not all of them need to be commented out.</p>
<p>Adding a attribute like isn't an option either because the xml is being parsed by an IOC container (Prana). Maybe prana will ignore the id="1" but it still iss messy, and I don't like messy on the long term.</p>
|
<p>If you can identify what is to be replaced through a regular expression, I recommend using the optional task <strong>replaceregexp</strong>. Here's the doc: <a href="http://ant.apache.org/manual/Tasks/replaceregexp.html" rel="nofollow noreferrer">http://ant.apache.org/manual/Tasks/replaceregexp.html</a>
You can call it twice, one for the start tag and other for the end tag.</p>
<p>The regexp for replacing your <em></em> can be a bit cumbersome, since you say you do not want to replace all <em></em> tags, but I think this is the easiest way. </p>
<p>Another option would be to create a custom ant task to do what you want.</p>
|
<p>If it is an XML file, then you could also call an XSLT transform</p>
| 28,417
|
<p>I have a war file that I have to deploy as root on glassfish. Deploying the application with "/" as its context root happens successfully. But when I try to run that application by <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a>, it throws a 503 saying the requested service() is not currently available. The log file server.log has an error saying "javax.servlet.ServletException: Site tree is not in the root web application's servlet context". I dont have the source code of this application. Is it a configuration issue that I can try to solve?</p>
|
<p>Deploying to "/" is correct for placing a webapp in the root context. The other way to depoy to the root is setting your webapp as the "default-web-module" in your "virtual-server" entry. The 503 error is a problem with your servlet. Assuming glassfish v2, you need to turn up your logging levels in your glassfish domain.xml. Look for the tag "module-log-levels" and set the "root", "server", and "web-container" elements to "ALL".</p>
|
<p>I can't guarantee this, but try undeploying, then renaming the ROOT folder and then deploying again.</p>
| 10,626
|
<p>Is there a way to <em>always</em> have LF line endings in Visual Studio? I can never seem to find it!</p>
|
<p>There'a an add-in for Visual Studio 2008 that converts the end of line format when a file is saved. You can download it here: <a href="http://grebulon.com/software/stripem.php" rel="noreferrer">http://grebulon.com/software/stripem.php</a></p>
|
<p>There's a plugin to VS called Strip'Em where you can choose which kind of new line type you want to auto convert all the line endings to when saving.</p>
<p>(You can choose between LF, CRLF, CR.)</p>
| 6,702
|
<p>I've seen quite a few developer job postings recently that include a sentence that reads more or less like this: "Must have experience with N-Tier architecture", or "Must be able to develop N-Tier apps".</p>
<p>This leads me to ask, what is N-Tier architecture? How does one gain experience with it?</p>
|
<p><a href="http://en.wikipedia.org/wiki/Multitier_architecture" rel="noreferrer">Wikipedia</a>:</p>
<blockquote>
<p>In software engineering, multi-tier
architecture (often referred to as
n-tier architecture) is a
client-server architecture in which,
the presentation, the application
processing and the data management are
logically separate processes. For
example, an application that uses
middleware to service data requests
between a user and a database employs
multi-tier architecture. The most
widespread use of "multi-tier
architecture" refers to three-tier
architecture.</p>
</blockquote>
<p>It's debatable what counts as "tiers," but in my opinion it needs to at least cross the process boundary. Or else it's called layers. But, it does not need to be in physically different machines. Although I don't recommend it, you <em>can</em> host logical tier and database on the same box.</p>
<p><img src="https://upload.wikimedia.org/wikipedia/en/6/66/Overview_of_a_three-tier_application.png" alt="alt text"></p>
<p><strong>Edit</strong>: One implication is that presentation tier and the logic tier (sometimes called Business Logic Layer) needs to cross machine boundaries "across the wire" sometimes over unreliable, slow, and/or insecure network. This is very different from simple Desktop application where the data lives on the same machine as files or Web Application where you can hit the database directly.</p>
<p>For n-tier programming, you need to package up the data in some sort of transportable form called "dataset" and fly them over the wire. .NET's <a href="http://msdn.microsoft.com/en-us/library/system.data.dataset.aspx" rel="noreferrer">DataSet</a> class or Web Services protocol like <a href="http://www.w3.org/TR/soap/" rel="noreferrer">SOAP</a> are few of such attempts to fly objects over the wire.</p>
|
<p>A tier is a group of computers having similar functionality and serving the same need. Tiers exist for security and scalability reasons. A typical modern web application is a 3-tiered one (and is also called "thin client"):</p>
<p><strong>Tier 1</strong> (Client tier). Code, running in your browser and in the browsers of all users of the system (millions of computers). Minimum to no business or application logic, just GUI logic.</p>
<p><strong>Tier 2</strong> (Application tier). Back-end code representing application and business logic running on the server (thousands of computers). All heavy lifting happens here.</p>
<p><strong>Tier 3</strong> (Persistence tier). Relational database nodes connected in a master/slave manner (tens of computers).</p>
<p>N-tier means that there can be additional groups of computers such as caches, proxies or other intermediaries.</p>
<p>3-tier architecture wasn't always the case. Twenty years a ago a 2-tier design (Client tier + Persistence tier, aka "thick client") was ubiquitous.</p>
<p><em>Important: the notion of "tiers" and "layers" is often conflated. Tiers are groups of devices that are always physically separated (by network or a process boundary) while "layer" is a purely software term.</em></p>
| 40,234
|
<p>I have some HTML that looks like this:</p>
<pre><code><ul class="faq">
<li class="open">
<a class="question" href="">This is my question?</a>
<p>Of course you can, it will be awesome. </p>
</li>
</ul>
</code></pre>
<p>Using CSS I'm setting the <code>p</code> tag to <code>display:none;</code>. I want to use jQuery to display or hide the <code>p</code> tag when the <code>anchor</code> is clicked, but I'm having some troubles with the sibling selector. </p>
<p>Just trying to get the selector working, I tried:</p>
<pre><code>$("a.question").click(function () {
$(this + " ~ p").css("background-color", "red");
});
</code></pre>
<p>to test it out. Seemingly, the sibling selector can't really be used like that, and as I'm completely new to jQuery I don't know the appropriate means to make that happen. </p>
|
<p>Try using: </p>
<pre><code>$(this).siblings('p').css()
</code></pre>
|
<blockquote>
<p>I want to use jQuery to display or hide the 'p' tag when the anchor is clicked</p>
</blockquote>
<p>Since you mentioned that you'd like to toggle the 'p' tag when the anchor is clicked, I'd do:</p>
<pre><code> $("a.question").click(function (event) {
$(this).siblings('p').show(); //toggle the p tags that are siblings to the clicked element
event.preventDefault(); //stop the browser from following the link
});
</code></pre>
| 30,853
|
<p>What web site structure(s)/architecture(s) would the community swear by, with a narrowing down in the direction towards more of a small facebook style project?</p>
<p>I understand the question to be rather broad/subjective; but being relatively new to the area of web development, I find just looking at and learning from examples of working projects most times extremely helpful, and that at other times just blows my mind and changes how I construct future assignments.</p>
<p>With the latter paragraph in mind, does the community have any suggestions on places to look/articles to read?</p>
|
<p>I guess it depends on the technology you select. For web projects in general I've always employed (Web-)MVC for the past two years or so. The advantage being a clear seperation of frontend and backend in order to create a managable code base.</p>
<p>But that's as vague as a recommendation could be. :)</p>
<p>Aside from using a framework to build your site from scratch, you might also want to look into using what's already out there (in terms of open source). I'd recommend any kind of "community software" that's semi-established, well documented, not too often in the news because of security issues and offers API to extend its base. That could indeed jump start you on your facebook-esque site. ;)</p>
|
<p>Possibly a bit heavy for your immediate needs, but have you seen the <a href="http://oreilly.com/catalog/9780596000356/" rel="nofollow noreferrer">Polar bear</a>*? Well worth a browse in the library to see if it's what you require.</p>
<p>*<a href="http://oreilly.com/catalog/9780596000356/" rel="nofollow noreferrer">Information Architecture for the World Wide Web, Second Edition</a></p>
| 6,833
|
<p>Recently, my Ender 3D Pro has been unable to print any large models successfully with PLA as the filament starts to expand inside the Teflon tube, causing a clog after about an hour of printing. I am starting to suspect that the problem is heat creep.</p>
<ul>
<li>This occurs with the two brands of PLA filament that I use (3D Fila and Voolt 3D).</li>
<li>The hotend that I am using is the one that comes with the printer, I don't know what it is made out of.</li>
</ul>
<p>I have tried many things to patch this problem:</p>
<ul>
<li>Try to unclog it with the needle</li>
<li>Replace nozzle (three times)</li>
<li>Check if the Teflon tube is touching the nozzle</li>
<li>Increase temperature from 200 to 220 °C</li>
<li>Increase temperature from 200 to 215 °C</li>
</ul>
<p>If the problem is indeed heat creep, I have plans to control the heat sink temperature with a Peltier and an extra thermometer. Any other ideas are appreciated.</p>
|
<p>Since you mentioned "Check if the Teflon tube is touching the nozzle", it sounds like you've disassembled the tube from the couplings and put it back together. This is error-prone and in my experience the main/only likely cause of clogging in Creality hotends. Heat creep is unlikely unless you're operating in a very high ambient temperature or have a failing/failed fan.</p>
<p>The tube can't just be "touching" the nozzle. It needs to be compressed against it. There are various ways to do this, but what usually worked best for me (before I moved to a different setup) was to back the coupler out of the heat sink by at least 1-2 full turns, press the tube all the way in against the nozzle, then tighten the coupler back down to compress the end of the tube against the nozzle mating surface.</p>
<p>The end of the tube also needs to be clean cut, straight, and undamaged. If it's charred, bent, gnarled, whatever, cut it straight with a razor blade while holding it in a jig to make sure the cut is perpendicular. You can find several such jigs (PTFE tube cutting tools) on Thingiverse or make your own or buy one. I like to also take the razor blade and chamfer the outside of the tube end ever so slightly before inserting it. I do this by hand, but I've seen videos of it being done with a jig that looks something like a pencil sharpener, which would probably be the best way.</p>
|
<p>This sounds like heat creep may be the problem. For preventing heat creep to occur you should do the opposite, print at lower temperature, tweak retraction length and increase cooling of the cold end.</p>
<p>A Peltier element is not very effective cooler, use a bigger fan, or a fan with a higher flow rate. Note that the Peltier element required a large cooling body and a fan as well, so this adds a lot of weight to and limits space of the hotend. You should not go there, it has been tried before.</p>
| 2,075
|
<p>I'm using the ssOption control (Sheridan 3d Option control) in VB6.</p>
<p>In Windows 98 the text area background color is the same color as the background color around the Option Circle, and that color is the default form color. So the Option button appears to be transparent. </p>
<p>There is no Background color property and on Windows XP the background color of the text area is a different color from the background color around the Option circle. </p>
<p>Any ideas as to why this would happen? The control's wrapper is in Threed32.ocx and I have the same version of it in the Windows\system32 directory on both the Win98 and WinXP systems.</p>
<ol>
<li>Why might it behave differently on 98 vs XP?</li>
<li>Any ideas on a fix?</li>
</ol>
|
<p>SSOption sets it background to the Windows Button Face on Windows XP. This the same background you get when you make a new form. You will need to use a frame or another type of enclosure that has a background of button face if you want to use it on a multi-colored form. Otherwise use VB6's Option button. </p>
<p>The advantages of the SSOption is the ability to display it's text in a 3D raised or inset format. This really only works well using the default button face color which is why it is hard coded into the control. It also has better formatting of the text when the option button is to the right of the text.</p>
<p>If you can't use a enclosing frame or panel then you have a tedious alternative. You can make an VB6 option with no text. If you are using the 3D font. Then you can use two labels to achieve the same effect. Make the bottom white (or top depending on raised vs inset) and offset by one pixel or 15 twips.</p>
<p>You can use the ZoomIn tool if you installed VB6 as part of the Visual Studio 6 package to make sure it is right.</p>
<p>If you are using it for the Alignment. Then you can fiddle with the width of the VB6 native option control until it looks right or make the option with no text and use a label.</p>
|
<p>Threed32.ocx is ancient - it was designed for VB4. I would replace it with the built-in VB6 option control.</p>
| 41,377
|
<p>Does anyone know if silverlight plugs into chrome, or when they plan to support it?</p>
|
<p>This guy have had partial success with silverlight in chrome, but it does not seem to be supported:</p>
<p><a href="http://wildermuth.com/2008/09/02/Silverlight_2_and_Google_Chrome" rel="nofollow noreferrer">http://wildermuth.com/2008/09/02/Silverlight_2_and_Google_Chrome</a></p>
<p>From The Microsoft Silverlight Team in the <a href="http://silverlight.net/forums/t/24044.aspx" rel="nofollow noreferrer">silverlight forum</a>:</p>
<blockquote>
<p>Hello, currently we don't have plans
to support Chrome. We will support it
in the future if it gains enough
market share. Please understand, each
browser implements the plug-in model
differently, so it'll be a lot of
effort to officially support a browser
100%... By the way, IE 8 also runs
each tab in its own process. If a tab
crashes, other tabs will still work
fine.</p>
</blockquote>
<p><strong>UPDATE:</strong></p>
<p>Jon Galloway has just posted instructions on how to get silverlight successfully running on Chrome here:</p>
<p><a href="http://weblogs.asp.net/jgalloway/archive/2008/09/17/running-silverlight-2-on-google-chrome-using-the-chrome-dev-channel.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/jgalloway/archive/2008/09/17/silverlight-on-chrome.aspx</a></p>
|
<p>Silverlight already works with web-kit, and since Google's Chrome is based on web-kit, it shouldn't be too much effort to get it working.</p>
<p>Indeed, <a href="http://bits.samiq.net/2008/09/silverlight-and-flash-running-on-google.html" rel="nofollow noreferrer">this</a> gentleman seems to have had some success.</p>
<p>Based on this, I would suspect that Silverlight will be fully supported by Chrome by the time it goes gold. </p>
| 7,322
|
<p>In Python, you can do this:</p>
<pre><code>import webbrowser
webbrowser.open_new("http://example.com/")
</code></pre>
<p>It will open the passed in url in the default browser</p>
<p>Is there a ruby equivalent?</p>
|
<h2>Cross-platform solution:</h2>
<p>First, install the <a href="http://www.copiousfreetime.org/projects/launchy/" rel="noreferrer">Launchy</a> gem:</p>
<pre><code>$ gem install launchy
</code></pre>
<p>Then, you can run this:</p>
<pre><code>require 'launchy'
Launchy.open("http://stackoverflow.com")
</code></pre>
|
<p>If it's windows and it's IE, try this: <a href="http://rubyonwindows.blogspot.com/search/label/watir" rel="nofollow noreferrer">http://rubyonwindows.blogspot.com/search/label/watir</a> also check out Selenium ruby: <a href="http://selenium.rubyforge.org/getting-started.html" rel="nofollow noreferrer">http://selenium.rubyforge.org/getting-started.html</a></p>
<p>HTH </p>
| 18,424
|
<p>So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that?</p>
<p>My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException.</p>
<p>So, what I want to do is effectively this:</p>
<pre><code>public class MyClassMock extends MyClass {
public MyClassMock() {
try {
super(0);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Mocked methods
}
</code></pre>
<p>But Java complains that super isn't the first statement.</p>
<p>My workaround:</p>
<pre><code>public class MyClassMock extends MyClass {
public static MyClassMock construct() {
try {
return new MyClassMock();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public MyClassMock() throws Exception {
super(0);
}
// Mocked methods
}
</code></pre>
<p>Is this the best workaround? Why doesn't Java let me do the former?</p>
<hr>
<p>My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways.</p>
<p>I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.</p>
|
<p>Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases.</p>
<p>In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do <em>unsafe</em> things if one knows how to deal with them.</p>
<p>In C# .NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this:</p>
<pre><code>public ClassName(...) : base(...)
</code></pre>
<p>in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.</p>
|
<p>One way to get around it is by calling a private static function. The try-catch can then be placed in the function body.</p>
<pre><code>public class Test {
public Test() {
this(Test.getObjectThatMightThrowException());
}
public Test(Object o) {
//...
}
private static final Object getObjectThatMightThrowException() {
try {
return new ObjectThatMightThrowAnException();
} catch(RuntimeException rtx) {
throw new RuntimeException("It threw an exception!!!", rtx);
}
}
}
</code></pre>
| 2,728
|
<p>Is it necessary to pay $99 before I can watch the video to submit an iPhone application to the App Store, or it is available free of cost anywhere?</p>
|
<p>You can join the developer program and watch the video without paying. It's on Video → App Store and Distribution after you've logged in:</p>
<ul>
<li><a href="https://developer.apple.com/videos/app-store-and-distribution/" rel="nofollow noreferrer">https://developer.apple.com/videos/app-store-and-distribution/</a></li>
</ul>
<p>You may also read:</p>
<ul>
<li><a href="https://developer.apple.com/ios/submit/" rel="nofollow noreferrer">https://developer.apple.com/ios/submit/</a></li>
</ul>
<p>What you can't do without putting down your $99 is get your application on an iPhone or iPod touch (and that includes your own).</p>
|
<p>$99 is for registration for the developer where you can debug your iphone application on your mobile when you are developing as we had done tone of iphone application though business account and that is more than $99 but it will help you more once you register with $99 - thanks</p>
| 39,705
|
<p>The system I work on here was written before .net 2.0 and didn't have the benefit of generics. It was eventually updated to 2.0, but none of the code was refactored due to time constraints. There are a number of places where the code uses ArraysLists etc. that store things as objects. </p>
<p>From performance perspective, how important change the code to using generics? I know from a perfomance perspective, boxing and unboxing etc., it is inefficient, but how much of a performance gain will there really be from changing it? Are generics something to use on a go forward basis, or it there enough of a performance change that a conscience effort should be made to update old code?</p>
|
<p>Technically the performance of generics is, as you say, better. However, unless performance is hugely important AND you've already optimised in other areas you're likely to get MUCH better improvements by spending your time elsewhere.</p>
<p>I would suggest: </p>
<ul>
<li>use generics going forward.</li>
<li>if you have solid unit tests then refactor to generics as you touch code</li>
<li>spend other time doing refactorings/measurement that will significantly improve performance (database calls, changing data structures, etc) rather than a few milliseconds here and there.</li>
</ul>
<p>Of course there's reasons other than performance to change to generics: </p>
<ul>
<li>less error prone, since you have compile-time checking of types</li>
<li>more readable, you don't need to cast all over the place and it's obvious what type is stored in a collection</li>
<li>if you're using generics going forward, then it's cleaner to use them everywhere</li>
</ul>
|
<p>The biggest gains, you will find in Maintenance phases. Generics are much easier to deal with and update, without having to deal with conversion and casting issues. If this is code that you continually visit, then by all means take the effort. If this is code that hasn't been touched in years, I wouldn't really bother.</p>
| 12,047
|
<p>I need advice on how to handle relatively large set of flags in my SQL2k8 table.</p>
<p>Two question, bear with me please :)</p>
<p>Let's say I have 20 flags I'd like to store for one record.</p>
<p>For example:</p>
<p>CanRead = 0x1
CanWrite = 0x2
CanModify = 0x4
...
and so on to the final flag 2^20</p>
<p>Now, if i set the following combination of one record: Permissions = CanRead | CanWrite</p>
<p>I can easily check whether that record has required permission by doing WHERE (Permissions & CanRead) = CanRead</p>
<p>That works.</p>
<p>But, I would also like to retrieve all records that can either write OR modify.</p>
<p>If I issue WHERE (Permissions & ( CanWrite | CanModify )) = (CanWrite | CanModify) i obviously won't get my record that has permissions set to CanRead | CanWrite</p>
<p>In other words, how can I find records that match ANY of the flags in my mask that i'm sending to the procedure?</p>
<p>Second question, how performant is in in SQL 2008? Would it actually be better to create 20 bit fields?</p>
<p>Thanks for your help</p>
|
<p><strong>Don't to that.</strong> It's like saving a CSV string into a memo field and defeating the purpose of a database.</p>
<p>Use a boolean (bit) value for every flag. In this specific sample you're finding everything that can read and can write or modify:</p>
<pre><code>WHERE CanRead AND (CanWrite OR CanModify)
</code></pre>
<p>Simple pure SQL with no clever hacks. The extra 7 bit's you're wasting for every flag aren't worth the headache.</p>
|
<p>Nope, that won't work.</p>
<p>I'm sending just one mask to the procedure</p>
<p>Something like @filter which in C# i fill with @filter = CanModify | CanWrite</p>
<p>So, the procedure gets the OR-ed value as a filter.</p>
<p>Oh and by the way, it is NOT a permission model, I'm using that just as an example.</p>
<p>I really have around 20 unique flags that my object can have.</p>
| 19,172
|
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p>
<p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
|
<p>Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:</p>
<pre><code>from uuid import getnode as get_mac
mac = get_mac()
</code></pre>
<p>The return value is the mac address as 48 bit integer.</p>
|
<p>For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.</p>
<pre><code>struct ifreq ifr;
uint8_t macaddr[6];
if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) < 0)
return -1;
strcpy(ifr.ifr_name, "eth0");
if (ioctl(s, SIOCGIFHWADDR, (void *)&ifr) == 0) {
if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) {
memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6);
return 0;
... etc ...
</code></pre>
<p>You've tagged the question "python". I don't know of an existing Python module to get this information. You could use <A HREF="http://pypi.python.org/pypi/ctypes/1.0.2" rel="nofollow noreferrer">ctypes</A> to call the ioctl directly.</p>
| 19,251
|
<pre><code>public class Address
{
public string ZipCode {get; set;}
}
public class Customer
{
public Address Address {get; set;}
}
</code></pre>
<p>how can I access eitther "ZipCode" or "Address.ZipCode" with reflection? For example: </p>
<pre><code>Typeof(Customer).GetProperty("ZipCode")?
</code></pre>
|
<p>You'd need something like:</p>
<pre><code>PropertyInfo addressProperty = typeof(Customer).GetProperty("Address");
ProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty("ZipCode");
object address = addressProperty.GetValue(customer, null);
object zipCode = zipCodeProperty.GetValue(address, null);
</code></pre>
<p>Basically if you want to take a string "Address.ZipCode" and navigate down it, you need to split it by "." and then call GetProperty on the appropriate type at every step to get the property itself, then PropertyInfo.GetValue to get the next value in the chain. Something like this:</p>
<pre><code>public static object FollowPropertyPath(object value, string path)
{
Type currentType = value.GetType();
foreach (string propertyName in path.Split('.'))
{
PropertyInfo property = currentType.GetProperty(propertyName);
value = property.GetValue(value, null);
currentType = property.PropertyType;
}
return value;
}
</code></pre>
<p>Call it like this:</p>
<pre><code>object zipCode = FollowPropertyPath(customer, "Address.ZipCode");
</code></pre>
<p>Note that this works on the compile-time types of the properties. If you want it to cope with the execution time type (e.g. if customer.Address didn't have a ZipCode property, but the actual type returned by Address did) then change <code>property.PropertyType</code> to <code>property.GetType()</code>.</p>
<p>Also note that this doesn't have any error handling etc :)</p>
|
<p>adabyron,</p>
<p>I created a version of your code for when you only need to grab the types, and if you don't have an actual object instance.</p>
<pre><code> public static Type FollowPropertyPath<T>(string path)
{
if (path == null) throw new ArgumentNullException("path");
Type currentType = typeof(T);
foreach (string propertyName in path.Split('.'))
{
int brackStart = propertyName.IndexOf("[");
var property = currentType.GetProperty(brackStart > 0 ? propertyName.Substring(0, brackStart) : propertyName);
if (property == null)
return null;
currentType = property.PropertyType;
if (brackStart > 0)
{
foreach (Type iType in currentType.GetInterfaces())
{
if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof (IDictionary<,>))
{
currentType = iType.GetGenericArguments()[1];
break;
}
if (iType.IsGenericType && iType.GetGenericTypeDefinition() == typeof (ICollection<>))
{
currentType = iType.GetGenericArguments()[0];
break;
}
}
}
}
return currentType;
}
</code></pre>
| 47,819
|
<p>I have written an ASP.NET composite control which includes some Javascript which communicates with a web service.</p>
<p>I have packaged the classes for the control and the service into a DLL to make it nice and easy for people to use it in other projects.</p>
<p>The problem I'm having is that as well as referencing the DLL in their project, the consumer of my control must also include a .ASMX file for the web service. Whilst it isn't a complicated file (just a one-liner which refers to the class in the DLL), I would like to avoid having it if I can.</p>
<p>Is there any way to avoid having to have the .ASMX file?</p>
<ul>
<li>Can I register the service with the web server in Application_Start?</li>
<li>Can I make a web.config change to reference it somehow?</li>
</ul>
<p>All suggestions gratefully received!</p>
<p><strong>UPDATE:</strong> The article linked to in John Sheehan's response (below) does work - but not if you want to call the web service using AJAX. Does anybody know of an AJAX friendly version?</p>
|
<p>Try something like this. I don't know if it will work though. I got this idea from ELMAH, which creates a handler for a page that doesn't physically exist and then serves it up from the assembly.</p>
<pre><code><configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*WebService.asmx" type="MyHandler.WebServiceHandler, MyHandler" />
</httpHandlers>
</system.web>
</configuration>
</code></pre>
<p>EDIT: I was close, see this article (in VB though): <a href="http://www.codeproject.com/KB/aspnet/wsinaclasslibrary.aspx" rel="noreferrer">http://www.codeproject.com/KB/aspnet/wsinaclasslibrary.aspx</a></p>
|
<p>Short answer is no. The ASMX is the entry point for any web service. There are alternatives if you use WCF, but that's not entirely the same thing.</p>
| 42,007
|
<p>We are migrating our works repository so I want to do a cull of all the unreferenced files that exist in the source tree before moving it into the nice fresh (empty) repository.</p>
<p>So far I have gone through by hand and found all the unreferenced files that I know about but I want to find out if I have caught them all. One way would be to manually move the project file by file to a new folder and see what sticks when compiling. That will take all week, so I need an automated tool.</p>
<p>What do people suggest?</p>
<p>Clarifications:<br>
1) It is C++.<br>
2) The files are mixed. I am looking for files that have been superseded by others but have left to rot in the repository - for instance file_iter.h is not referenced by any other file in the program but remains in the repository just in case someone wants to compile a version from 1996! Now we are moving to a fresh repository we can safely junk all the files that are no longer used.<br>
3) Lint only finds unused includes - not unused files (I have the 7.5 manual in front of me).</p>
|
<p>You've tagged this post with <strong>c++</strong>, so I'm assuming that's the language in question. If that's the only thing that's in the repository then it shouldn't be too hard to grep all files in the repository for each filename to give you a good starting point. If the repository contains other files (metadata, support files, resources, etc) then you're probably going to need to do it manually.</p>
|
<p>A static source code analysis tool like lint might do the job. They will tell you if a piece of code will never be called.</p>
| 7,465
|
<p>I am seeting up Apache server with TortoiseSVN for local source code repository. Currently on trial purpose I am setting only two users.
Is it possible for administrator to set up some thing so that file get compulsory locked once its checkout (copy to working directory) by some one.</p>
<p>Abhijit Dhopate</p>
|
<p>The main reason you might want to do this on subversion is for binary files (i.e. images, etc.) that are difficult or impossible to 'merge'. In those cases, each user can request a lock on a file. There is also a svn property (needs-lock) that can be applied to files that makes them read-only on checkout, and read-write when you lock, so that you remember to request the lock before editing.</p>
<p>See <a href="http://svnbook.red-bean.com/en/1.5/svn.advanced.locking.html" rel="nofollow noreferrer">the chapter on locking</a> in the svn book.</p>
|
<p>Wouldn't that defeat one of the purposes of a concurrent versioning system like SubVersion? Generally, you'll check out a block of files, but the server doesn't know whether anyone is editing those files. Why not allow another user access to those files and deal with the results if a conflict emerges?</p>
| 12,915
|
<p>If I have 2 query sources how do I find ones that are in one that are not in the other?</p>
<p>example of join to find items in both:</p>
<pre><code>var results = from item1 in qs1.Items
join item2 in qs2 on item1.field1 equals item2.field2
select item1;
</code></pre>
<p>So what would the linq code be to return the items in qs1 that are not in qs2?</p>
|
<p>Darren Kopp's <a href="https://stackoverflow.com/questions/50702/linq-how-do-you-do-a-query-for-items-in-one-query-source-that-are-not-in-anothe/50724#50724">answer</a>:</p>
<pre><code>var excluded = items1.Except(items2);
</code></pre>
<p>is the best solution from a performance perspective.</p>
<p><em>(NB: This true for at least regular LINQ, perhaps LINQ to SQL changes things as per <a href="http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx" rel="nofollow noreferrer">Marco Russo's blog post</a>. However, I'd imagine that in the "worst case" Darren Kopp's method will return at least the speed of Russo's method even in a LINQ to SQL environment).</em></p>
<p>As a quick example try this in <a href="http://www.linqpad.net/" rel="nofollow noreferrer">LINQPad</a>:</p>
<pre><code>void Main()
{
Random rand = new Random();
int n = 100000;
var randomSeq = Enumerable.Repeat(0, n).Select(i => rand.Next());
var randomFilter = Enumerable.Repeat(0, n).Select(i => rand.Next());
/* Method 1: Bramha Ghosh's/Marco Russo's method */
(from el1 in randomSeq where !(from el2 in randomFilter select el2).Contains(el1) select el1).Dump("Result");
/* Method 2: Darren Kopp's method */
randomSeq.Except(randomFilter).Dump("Result");
}
</code></pre>
<p>Try commenting one of the two methods out at a time and try out the performance for different values of n.</p>
<p>My experience (on my Core 2 Duo Laptop) seems to suggest:</p>
<pre><code>n = 100. Method 1 takes about 0.05 seconds, Method 2 takes about 0.05 seconds
n = 1,000. Method 1 takes about 0.6 seconds, Method 2 takes about 0.4 seconds
n = 10,000. Method 1 takes about 2.5 seconds, Method 2 takes about 0.425 seconds
n = 100,000. Method 1 takes about 20 seconds, Method 2 takes about 0.45 seconds
n = 1,000,000. Method 1 takes about 3 minutes 25 seconds, Method 2 takes about 1.3 seconds
</code></pre>
<p><em>Method 2 (Darren Kopp's answer) is clearly faster.</em></p>
<p>The speed decrease for Method 2 for larger n is most likely due to the creation of the random data (feel free to put in a DateTime diff to confirm this) whereas Method 1 clearly has algorithmic complexity issues (and just by looking you can see it is at least O(N^2) as for each number in the first collection it is comparing against the entire second collection).</p>
<p><strong>Conclusion:</strong> Use Darren Kopp's answer of LINQ's 'Except' method</p>
|
<p>Here's a more simple version of the same thing, you don't need to nest the query:</p>
<pre><code>List<string> items1 = new List<string>();
items1.Add("cake");
items1.Add("cookie");
items1.Add("pizza");
List<string> items2 = new List<string>();
items2.Add("pasta");
items2.Add("pizza");
var results = from item in items1
where items2.Contains(item)
select item;
foreach (var item in results)
Console.WriteLine(item); //Prints 'pizza'
</code></pre>
| 7,346
|
<p>What is the best way to randomize an array of strings with .NET? My array contains about 500 strings and I'd like to create a new <code>Array</code> with the same strings but in a random order.</p>
<p>Please include a C# example in your answer.</p>
|
<p>If you're on .NET 3.5, you can use the following IEnumerable coolness:</p>
<pre><code>Random rnd=new Random();
string[] MyRandomArray = MyArray.OrderBy(x => rnd.Next()).ToArray();
</code></pre>
<p>Edit: and here's the corresponding VB.NET code:</p>
<pre><code>Dim rnd As New System.Random
Dim MyRandomArray = MyArray.OrderBy(Function() rnd.Next()).ToArray()
</code></pre>
<p>Second edit, in response to remarks that System.Random "isn't threadsafe" and "only suitable for toy apps" due to returning a time-based sequence: as used in my example, Random() is perfectly thread-safe, unless you're allowing the routine in which you randomize the array to be re-entered, in which case you'll need something like <code>lock (MyRandomArray)</code> anyway in order not to corrupt your data, which will protect <code>rnd</code> as well.</p>
<p>Also, it should be well-understood that System.Random as a source of entropy isn't very strong. As noted in the <a href="http://msdn.microsoft.com/en-us/library/system.random.aspx" rel="noreferrer">MSDN documentation</a>, you should use something derived from <code>System.Security.Cryptography.RandomNumberGenerator</code> if you're doing anything security-related. For example:</p>
<pre><code>using System.Security.Cryptography;
</code></pre>
<p>...</p>
<pre><code>RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
string[] MyRandomArray = MyArray.OrderBy(x => GetNextInt32(rnd)).ToArray();
</code></pre>
<p>...</p>
<pre><code>static int GetNextInt32(RNGCryptoServiceProvider rnd)
{
byte[] randomInt = new byte[4];
rnd.GetBytes(randomInt);
return Convert.ToInt32(randomInt[0]);
}
</code></pre>
|
<p>Here's a simple way using OLINQ:</p>
<pre><code>// Input array
List<String> lst = new List<string>();
for (int i = 0; i < 500; i += 1) lst.Add(i.ToString());
// Output array
List<String> lstRandom = new List<string>();
// Randomize
Random rnd = new Random();
lstRandom.AddRange(from s in lst orderby rnd.Next(100) select s);
</code></pre>
| 13,413
|
<p>Looking at this loop that copies one c-string to another:</p>
<pre><code>void strcpyr(char *s, char *t)
{
while(*s++=*t++)// Why does this work?
;
}
</code></pre>
<p>Why do we not check for the '\0' character in the while loop, like this?</p>
<pre><code>while((*s++=*r++)!='\0')..
</code></pre>
<p>How does the first loop terminate?</p>
|
<p>The statement *s++=*t++ not only assigns the next character from t to s but also returns the current value of *t as the result of the expression. The while loop terminates on any false value, including '\0'.</p>
<p>Think of it this way. If you did:</p>
<pre><code>char c = *s++ = *t++;
</code></pre>
<p>in addition to copying a char from *t to *s and incrementing both, it would also set c to the current value of *t.</p>
|
<p>I think you mean to write this:</p>
<pre><code>void strcpyr(char *s, char *t) {
while (*s++ = *t++);
}
</code></pre>
<p>The loop terminates when the value pointed to by "t" is zero. For C (and C++) loops and conditionals, any integer that is non-zero is true.</p>
| 30,687
|
<p>Is there a Generics Friendly way of using Collection.EMPTY_LIST in my Java Program.</p>
<p>I know I could just declare one myself, but I'm just curious to know if there's a way in the JDK to do this.</p>
<p>Something like <code>users = Collections<User>.EMPTY_LIST;</code></p>
|
<p>By doing the following:</p>
<pre><code>List<User> users = Collections.emptyList();
</code></pre>
<p>The type of the returned list from <code>Collections.emptyList();</code> will be <em>inferred</em> as a <code>String</code> due to the left-hand-side of the assignment. However, if you prefer to not have this inference, you can define it explicitly by doing the following:</p>
<pre><code>List<User> users = Collections.<User>emptyList();
</code></pre>
<p>In this particular instance, this may appear as redundant to most people (in fact, I've seen very little code out in the wild that makes use of explicit type arguments), however for a method with the signature: <code>void doStuff(List<String> users)</code> it would be perfectly clean for one to invoke <code>doStuff()</code> with an explicit type argument as follows:</p>
<pre><code>doStuff(Collections.<String>emptyList());
</code></pre>
|
<pre><code>List<User> users = Collections.emptyList();
</code></pre>
| 20,434
|
<p>I have inherited a project that has class libraries written in VB.NET, some of these have ".settings" files and the others have a ".dll.config" file to store connection strings. What is the difference between these 2 methods?</p>
<p>EDIT: In what scenarios would I prefer one over the other?</p>
|
<p>They're basically the same thing - or strongly related, anyway. A settings file gives you strongly-typed access to entries in an app.config file, and keeps them in sync. When you compile, the app.config file is copied to the bin folder with the name of your assembly.</p>
<p>Note that, if you modify the .config file by hand, you can lose changes if the settings file overwrites them. In VS2008 it will prompt you, so you can choose to sync them.</p>
|
<p>I think that .settings is application wide, while the .dll.config files are specific to the assembly they are named for.</p>
| 39,308
|
<p>I'm using a <code>DateTime</code> in C# to display times. What date portion does everyone use when constructing a time?</p>
<p>E.g. the following is not valid because there is no zero-th month or zero-th day:</p>
<pre><code>// 4:37:58 PM
DateTime time = new DateTime(0, 0, 0, 16, 47, 58);
</code></pre>
<p>Do I use COM's zero date?</p>
<pre><code>// 4:37:58 PM
DateTime time = new DateTime(1899, 12, 30, 16, 47, 58);
</code></pre>
<p>Or perhaps SQL Server's?</p>
<pre><code>//4:37:58 PM
DateTime time = new DateTime(1900, 1, 1, 16, 47, 58);
</code></pre>
<p>I realize it's arbitrary, since I'll be ignoring the date portions in code, but it would still be nice to be able to use:</p>
<pre><code>DateTime duration = time2 - time1;
</code></pre>
<hr>
<h1>Answer</h1>
<p>I think I like <strong>MinValue</strong></p>
<pre><code> DateTime time = DateTime.MinValue.Date.Add(new TimeSpan(16, 47, 58));
</code></pre>
<hr>
<p><strong>Note:</strong> I can't use a <code>TimeSpan</code>, because that doesn't store times of the day. And the reason I know that is because there's no way to display its contents as a time.</p>
<p>Which is to say that <code>TimeSpan</code> records a <em>span of time</em>, not a <em>time of day</em>, e.g.:</p>
<pre><code>TimeSpan t = new TimeSpan(16, 47, 58);
t.ToString();
</code></pre>
<p>returns a span of time in the format <em>hours</em>:<em>minutes</em>:<em>seconds</em>, e.g.:</p>
<pre><code>16:47:58
</code></pre>
<p>rather than a time:</p>
<pre><code>4:47:58 PM (United States)
04:47:58 nm (South Africa)
4:47:58.MD (Albania)
16:47:58 (Algeria)
04:47:58 م (Bahrain)
PM 4:47:58 (Singapore)
下午 04:47:58 (Taiwan)
04:47:58 PM (Belize)
4:47:58 p.m. (New Zealand)
4:47:58 μμ (Greece)
16.47.58 (Italy)
오후 4:47:58 (Korea)
04:47:58 ب.ظ (Iran)
ਸ਼ਾਮ 04:47:58 (India)
04:47:58 p.m. (Argentina)
etc
</code></pre>
<p>In other words, there is a difference between a timespan, and a time. And also realize that <code>TimeSpan</code> doesn't provide a mechanism to convert a span of time into a time of day - and there is a reason for that.</p>
|
<p>what about DateTime.MinValue?</p>
|
<p>Use a TimeSpan, and make it UTC if you have TimeZone issues.</p>
| 48,705
|
<p>I'd like to be able to hook into a 3rd party application to see what SQL Statements are being executed. Specifically, it is a VB6 application running on SQL Server 2005.</p>
<p>For example, when the application fills out a grid, I'd like to be able to see exactly what query produced that data.</p>
|
<p>If you have the appropriate rights (sysadmin or ALTER TRACE permission) on the DB you could watch using SQL Profiler.</p>
|
<p>Reviewing it on the server as other answers indicate is most likely the best way to go. However, if that's not available, you can also turn on <a href="http://technet.microsoft.com/en-us/library/ms403323(SQL.90).aspx" rel="nofollow noreferrer">ODBC logging</a> which may be helpful.</p>
| 13,633
|
<p>I have an application written in flash (actually it is written in Haxe and run under SHWX but it doesn't matter here). I have a pretty complex task that consumes a lot of CPU power and sometimes executes for more that 15 seconds. If that happens, I've got an error saying 'A script has executed for longer than the default timeout period of 15 seconds.' and everything crashes.</p>
<p>I know I can use continuations to stop this from happening but is there a way to extend that 'default timeout period'? It's a developer tool, responsivnes doesn't really matter.</p>
|
<p>Another way is to link a <a href="http://swfmill.org/" rel="nofollow noreferrer">swfmill</a>-based swf via -swf-lib switch and set this ScriptLimits tag there, haxe will re-use it then.</p>
|
<p>I suggest breaking your function into smaller chunks and spreading them over multiple frames. This way you can display an progress animation and the Flash application won't become unresponsive. So for example if you have to loop over 1000 items, you do 100 in one frame, then another hundred in the next frame, etc, until you have processed them all. I wouldn't recommend hacking your swf.</p>
| 11,673
|
<p>I am trying to use page methods in my asp.net page. I have enable page methods set to true on the script manager, the webmethod attribute defined on the method, the function is public static string, I know the function works because when I run it from my code behind it generates the expected result, but when I call it via page method in my result function the result is always alerted as undefined. If I use fiddler it doesn't even look like there is additional traffic or a new request created. I'm running the site on port 82 if that makes a difference. I'm at a loss here. Can someone give me some pointers?</p>
|
<p>In your PagesMethods call, remove the parentheses from the callback and error functions:</p>
<pre><code>PageMethods.getAdCodeInfo(value, onSuccess, onError)
</code></pre>
<p><code>onSuccess</code> and <code>onError</code> are basically variables that point to the functions. So you don't need parentheses for variable names.</p>
|
<p>OK, stupid me. Here is some code. </p>
<pre><code> function getName()
{
var ddlAdCodes=$get('<%=ddlAdCodes.ClientID %>');
var value=ddlAdCodes.options[ddlAdCodes.selectedIndex].value;
//alert(value);
PageMethods.getAdCodeInfo(value,onSuccess(),onError());
}
function onSuccess(result)
{
alert(result);
}
function onError(error)
{
alert("error "+error);
}
</code></pre>
| 27,564
|
<p>What is best way to allow user to pick date from a mobile device from usability prospective?</p>
|
<p>I'd detest any form of drop-down, select-list when using a mobile app.</p>
<p>Unfortunately, three separate boxes (for day, month and year) would be equally painful on a MIDP-profile device.</p>
<p>I'd almost suggest using one text box, and do a <code>DateTime.TryParse(String, out DateTime)</code> to get the result. That allows them to type in any number of formats.. and the bulk of the time it'll work okay.</p>
<p>Also, if you gave them a hint on the form as to the correct formatting (e.g. 12 Mar 2009) then it'd probably be the format they use.</p>
|
<p>Are you building WAP page in asp.net? You have a DatePicker control in the mobile toolset. On devices that supports it this will render as a regular date picker (as in regular asp.net) while on more limited devices it will render as a series of selectors where you first select the year, then the month and finally the date. Unless you have a good reason to do otherwise you should use this I think.</p>
| 40,456
|
<p>I am able to create and execute a DTS package that copies tables from a remote Oracle database to a local SQL server, but want to setup the connection to the Oracle database as a linked server.</p>
<p>The DTS package currently uses the <em>Microsoft OLE DB Provider for Oracle</em> with the following properties:</p>
<ul>
<li>Data Source: <code>SERVER=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=acc)));uid=*UserName*;pwd=*UserPassword*;</code></li>
<li>Password: <em>UserPassword</em></li>
<li>User ID: <em>UserName</em></li>
<li>Allow saving password: true</li>
</ul>
<p>How do I go about setting a linked server to an Oracle database using the data source defined above?</p>
|
<p>I was able to setup a linked server to a remote Oracle database, which ended up being a multi-step process:</p>
<ol>
<li>Install Oracle ODBC drivers on SQL Server.</li>
<li>Create System DSN to Oracle database on SQL Server.</li>
<li>Create linked server on SQL server using System DSN.</li>
</ol>
<p><strong>Step 1: Install Oracle ODBC drivers on server</strong></p>
<p>a. Download the necessary <a href="http://www.oracle.com/technology/software/tech/oci/instantclient/htdocs/winsoft.html" rel="nofollow noreferrer">Oracle Instant Client</a> packages: Basic, ODBC, and SQL*Plus (optional)</p>
<p>b. Unzip the packages to a local directory on the SQL server, typically <code>C:\Oracle</code>. This should result in a [directory] like <code>C:\Oracle\instantclient_10_2</code>, which will be the value of [directory] referenced in the rest of this answer.</p>
<p>c. Create a text file named <strong><code>tnsnames.ora</code></strong> within the instant client [directory] that contains the following:</p>
<pre><code>OracleTnsName =
(
DESCRIPTION=
(
ADDRESS = (PROTOCOL=TCP)(HOST=10.1.3.42)(PORT=1521)
)
(
CONNECT_DATA = (SERVICE_NAME=acc)
)
)
</code></pre>
<p>Note: Actual <code>HOST</code>, <code>PORT</code>, and <code>SERVICE_NAME</code> will vary based on Oracle server you are establishing a connection to. This information can often be found using the Oracle network client tools under the <em>listeners</em>.</p>
<p>The <code>OracleTnsName</code> can be any name you want to assign to the Oracle data source, and will be used when setting up the system DSN. You can also use the syntax above to define multiple TNS names in the same <a href="http://www.orafaq.com/wiki/Tnsnames.ora" rel="nofollow noreferrer">tnsnames.ora</a> file if desired.</p>
<p>d. Add the [directory] to the system <strong><code>PATH</code></strong> environment variable.</p>
<p>e. Create a new system environment variable named <strong><code>TNS_Admin</code></strong> that has a value of [directory]</p>
<p>f. Execute the <strong><code>[directory]\odbc_install.exe</code></strong> utility to install the Oracle ODBC drivers.</p>
<p>g. It is recommended that you reboot the SQL server, but may not be necessary. Also, you may want to grant security permissions to this directory for the SQL server and SQL agent user identities.</p>
<p><strong>Step 2: Create a System DNS that uses the Oracle ODBC driver</strong></p>
<p>a. Open the <em>ODBC Data Source Administrator</em> tool. [ Administrative Tools --> Data Sources (ODBC) ]</p>
<p>b. Select the System DSN tab and then select the Add button.</p>
<p>c. In the drivers list, select <em>Oracle in instantclient {version}</em>. (e.g. 'Oracle in instantclient 10_2') and then select Finish button.</p>
<p>d. Specify the following:</p>
<ul>
<li><code>Data Source Name</code>: {System DSN Name}</li>
<li><code>Description</code>: {leave blank/empty}</li>
<li><code>TNS Service Name</code>: should have the <code>OracleTnsName</code> you defined in the <strong><code>tnsnames.ora</code></strong> file listed, select it as the value.</li>
<li><em>User ID</em>: {Oracle user name}</li>
</ul>
<p>e. Select Test Connection button. You should be prompted to provide the {Oracle user password}. If all goes well the test will succeed.</p>
<p><strong>Step 3: Create linked server in SQL to the Oracle database</strong></p>
<p>Open a query window in SQL server and execute the following:</p>
<pre><code>EXEC sp_addlinkedserver
@server = '{Linked Server Name}'
,@srvproduct = '{System DSN Name}'
,@provider = 'MSDASQL'
,@datasrc = '{System DSN Name}'
EXEC sp_addlinkedsrvlogin
@rmtsrvname = '{Linked Server Name}'
,@useself = 'False'
,@locallogin = NULL
,@rmtuser = '{Oracle User Name}'
,@rmtpassword = '{Oracle User Password}'
</code></pre>
<p>Note: The <code>{Linked Server Name}</code> can be anything you want to use when referencing the Oracle server, but the <code>{System DNS Name}</code> <strong>must</strong> match the name of the system DSN you created previously.</p>
<p>The <code>{Oracle User Name}</code> should be the same as the User ID used by the system DSN, and the <code>{Oracle User Password}</code> should be the same as you used to successfully test the ODBC connection. See <a href="http://support.microsoft.com/kb/280106" rel="nofollow noreferrer">KB 280106</a> for information on troubleshooting Oracle linked server issues.</p>
<p><strong>Querying the Oracle linked server</strong></p>
<p>You may use <a href="http://msdn.microsoft.com/en-us/library/ms188427.aspx" rel="nofollow noreferrer">OPENQUERY</a> to execute pass-through queries on the Oracle linked server, but be aware that for very large recordsets you may receive a <code>ORA-01652</code> error message if you specify a <code>ORDER BY</code> clause in the pass-through query. Moving the <code>ORDER BY</code> clause from the pass-through query to the outer select statement solved this issue for me.</p>
|
<p>I had the same problem. I was on the phone with Microsoft for hours, and they did not have a solution. None of those "connection timeout" settings helped me. </p>
<p>To resolve it, I created a DTS job that runs a proc which only updates the time on one row, in one column, every two minutes. Then I setup a replication between SQL Server and Oracle, scheduled to replicate that single cell change, from SQL to Oracle, every 3 minutes. It keeps the connection alive!</p>
| 39,595
|
<p>I'm looking for a good TraceListener for .Net that supports rolling over the log file based on size limits. </p>
<p><strong>Constraints</strong></p>
<ul>
<li>Uses .Net built in Trace logging</li>
<li>Independent class or binary that's not part of some gigantic library</li>
<li>Allows rolling over a log file based on size</li>
</ul>
|
<p>You could use <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.logging.filelogtracelistener.aspx" rel="noreferrer">Microsoft.VisualBasic.Logging.FileLogTraceListener</a>, which comes built-in with the .NET Framework. Don't let the VisualBasic in the namespace scare you, you'll just have to reference the microsoft.visualbasic.dll assembly and it should work fine with C#.</p>
|
<p>Consider <a href="http://msdn.microsoft.com/en-us/library/ff664700%28PandP.50%29.aspx" rel="nofollow">Enterprise Library Logging Application Block</a></p>
<p>Make sure to install only the Logging block, since EntLib installer checks all blocks by default.</p>
| 18,944
|
<p>I would like to either prevent or handle a <code>StackOverflowException</code> that I am getting from a call to the <code>XslCompiledTransform.Transform</code> method within an <code>Xsl Editor</code> I am writing. The problem seems to be that the user can write an <code>Xsl script</code> that is infinitely recursive, and it just blows up on the call to the <code>Transform</code> method. (That is, the problem is not just the typical programmatic error, which is usually the cause of such an exception.)</p>
<p>Is there a way to detect and/or limit how many recursions are allowed? Or any other ideas to keep this code from just blowing up on me?</p>
|
<p>From Microsoft:</p>
<blockquote>
<p>Starting with the .NET Framework
version 2.0, a StackOverflowException
object cannot be caught by a try-catch
block and the corresponding process is
terminated by default. Consequently,
users are advised to write their code
to detect and prevent a stack
overflow. For example, if your
application depends on recursion, use
a counter or a state condition to
terminate the recursive loop.</p>
</blockquote>
<p>I'm assuming the exception is happening within an internal .NET method, and not in your code.</p>
<p>You can do a couple things.</p>
<ul>
<li>Write code that checks the xsl for infinite recursion and notifies the user prior to applying a transform (Ugh).</li>
<li>Load the XslTransform code into a separate process (Hacky, but less work).</li>
</ul>
<p>You can use the Process class to load the assembly that will apply the transform into a separate process, and alert the user of the failure if it dies, without killing your main app.</p>
<p>EDIT: I just tested, here is how to do it:</p>
<p>MainProcess:</p>
<pre><code>// This is just an example, obviously you'll want to pass args to this.
Process p1 = new Process();
p1.StartInfo.FileName = "ApplyTransform.exe";
p1.StartInfo.UseShellExecute = false;
p1.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p1.Start();
p1.WaitForExit();
if (p1.ExitCode == 1)
Console.WriteLine("StackOverflow was thrown");
</code></pre>
<p>ApplyTransform Process:</p>
<pre><code>class Program
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
throw new StackOverflowException();
}
// We trap this, we can't save the process,
// but we can prevent the "ILLEGAL OPERATION" window
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.IsTerminating)
{
Environment.Exit(1);
}
}
}
</code></pre>
|
<p>You can read up this property every few calls, <code>Environment.StackTrace</code> , and if the stacktrace exceded a specific threshold that you preset, you can return the function.</p>
<p>You should also try to replace some recursive functions with loops.</p>
| 25,345
|
<p>The university I work at uses Oracle for the database system. We currently have programs we run at night to download what we need into some local Access tables for our testing needs. Access is getting to small for this now and we need something bigger. Also, the nightly jobs require constant maintance to keep working (because of network issues, table changes, bad code :) ) and I would like to eliminate them to free us up for more important things.</p>
<p>I am most familiar with MySQL so I setup a test MySQL server. What is the best way to automate copying the needed tables from Oracle to MySQL?</p>
<p>Edit: I accepted the answer. I don't like the answer but it seems to be correct based on further research and the lack of other answers provided. Thanks to all for pondering my question and answering it.</p>
|
<p>I don't think there is really anything that is going to do this. If you could setup a local Oracle database, then most likely you could as oracle has various means of keeping two databases "in sync", provided they are both Oracle.</p>
<p>If you must use mysql, then likely you are going to just have to write something to sync the data, this is of course always going to run in the same problems you currently have with the access "database".</p>
<p>You could setup something with HSODBC and triggers, but</p>
<ol>
<li>I've found HSODBC to be very memory hungry</li>
<li>This is only going to add more load to your DB, which you say is already heavily loaded during the day.</li>
</ol>
<p>If the main thing you are doing is wanting a local Test copy of your oracle database, you would be best to setup syncing with a local version of oracle, as far as I can tell from the licenses, oracle is free for development copies ( I have seen some posts to the contrary, but if you find that is the case, you could always use something like Oracle XE)</p>
|
<p>Could you just copy the Oracle tables and then set them up as linked tables in MS Access? This way the front-end stays the same plus you keep everything in Oracle (less moving parts than exporting and importing).</p>
| 4,117
|
<p>The Oracle community has a several support sites (<a href="http://www.11ghelp.com/map/sitemap-110.html" rel="nofollow noreferrer">here</a> and <a href="http://www.oracleabc.com/oracledocs/11gErrors/" rel="nofollow noreferrer">here</a>) that have lists of errors. The first site even has suggestions for how to fix them.</p>
<p>Does anyone know of an equivalent list for Microsoft COM, preferably with Office Interop issues?</p>
|
<p>No, every component is permitted to define its own. The only restrictions are that error values must have the high bit set, and the bits in the middle are <em>supposed</em> to identify the component. </p>
<p><a href="http://en.wikipedia.org/wiki/HRESULT" rel="nofollow noreferrer">Wikipedia</a> has an article showing how the bits of the error code are divided up.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/library/aa705941(VS.85).aspx" rel="nofollow noreferrer">Here</a> is ms's general com ex list; pretty short but its something. When I was working with OWC, I typically found them scattered on different sites or in separate blog entries. (Yay Google) </p>
| 38,982
|
<p>I'm using C# on Framework 3.5. I'm looking to quickly group a Generic List<> by two properties. For the sake of this example lets say I have a List of an Order type with properties of CustomerId, ProductId, and ProductCount. How would I get the sum of ProductCounts grouped by CustomerId and ProductId using a lambda expression?</p>
|
<pre><code>var sums = Orders.GroupBy(x => new { x.CustomerID, x.ProductID })
.Select(group => group.Sum(x => x.ProductCount));
</code></pre>
|
<p>var New1 = EmpList.GroupBy(z => z.Age).OrderBy(Employee => Employee.Key);</p>
<p>dataGridView1.DataSource = New1;</p>
| 47,471
|
<p>When I create a TFS report of a query with the Excel integration features (we are using Excel 2003), Excel resets formatting of all cells after clicking the "Refresh" button in the TFS Toolbar.</p>
<p>Our team likes to print this report and drag it into our weekly meeting as it accurately lists all our open tasks. Bad formatting is a pain, though: Vertical alignment set to "bottom" and no borders on cells makes it nearly impossible to know when one Task/Bug starts and the other ends...</p>
|
<p>I ended up doing this:</p>
<ul>
<li><code>tfpt.exe</code> (<a href="http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx" rel="nofollow noreferrer">Team Foundation Power Tools</a>) </li>
<li>query for xml: <code>tfpt query /format:xml</code> (add your query name here etc.)</li>
<li>convert that to a html table with XSL</li>
<li>write a simple batch script to do above steps</li>
<li>(Profit!!!)</li>
</ul>
<p>This is the XSL script I used (will need tweeking if you use other fields):</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:spss="http://xml.spss.com/spss/oms"
exclude-result-prefixes="spss">
<xsl:template match="/">
<html>
<head>
<title>All active Work Items</title>
</head>
<body>
<table border="1" frame="border" rules="all">
<tr><th>ID</th><th>Area Path</th><th>Assigned To</th><th>Title</th><th>Description</th></tr>
<xsl:for-each select=".//WorkItem">
<tr>
<td><xsl:value-of select="./Field[@RefName='System.Id']/@Value"/></td>
<td><xsl:value-of select="./Field[@RefName='System.AreaPath']/@Value"/></td>
<td><xsl:value-of select="./Field[@RefName='System.AssignedTo']/@Value"/></td>
<td><xsl:value-of select="./Field[@RefName='System.Title']/@Value"/></td>
<td><xsl:value-of select="./Field[@RefName='System.Description']/@Value"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
<p>My guess is that since Microsoft is playing up this feature in the VS 2010 CTP, it's not currently supported.</p>
<p>Your best bet may be to create a sheet with all of the appropriate formatting and then cut and paste from the <em>live</em> excel sheet into the formatted sheet.</p>
| 35,904
|
<p>I am building a web application which uses an externally built class to handle much of the work and rules for the site. Most pages will require access to this class to get the information it needs to display. In the past I would put such a class in a session variable, so it's easily accessible when required and not need to be continually re-instantiated. </p>
<p>First Question, is this a bad idea to stuff this class into a session variable (it's not very big)?</p>
<p>Second question, if it's not a bad idea to store the sites app layer class in a session, then is there a way I can write a centralized method to use to grab or store the class into the session? I don't want to use a bunch of repeated code page after page getting the class, checking its there, creating if it's not, etc.</p>
|
<p>Before deciding on where to store your class, you have to answer two questions:</p>
<ol>
<li>How long this class should live?</li>
<li>In what scope should it be visible?</li>
</ol>
<p>Examples that answer both questions: request, user session, application.</p>
<p>If this class is stateless (no data and only logic), then it can probably live during the
whole life of application. If this is just data unique to each user (that should not be reloaded on each request), then you can put it directly into session and skip following paragraphs.</p>
<p>Now, after you decided on life length, you have several solutions. The best solution for lifestyle management is an IoC container. The simpler solution is just to abstract storage and use a static facade, like Current.MyClass, where MyClass instance is stored in request, session or application depending on what storage was provided to Current.</p>
<p>You should not implement singleton in the specified class, however, since it should not itself decide how many instances you need and it limits your ability to replace is with another class with same interface if required.</p>
|
<p>Without knowing any frameworks you use, it does not seem smart idea to put a class into the session store - it will be copied once per user - unless it has data that is unique to that user.</p>
<p>The best advice I can give would be to have a singleton class (you can google it - it is a design pattern) and then just have a function in that class that will return the class you need, or create it if it doesn't yet exist.</p>
| 43,627
|
<p>I have a class that defines the names of various session attributes, e.g.</p>
<pre><code>class Constants {
public static final String ATTR_CURRENT_USER = "current.user";
}
</code></pre>
<p>I would like to use these constants within a JSP to test for the presence of these attributes, something like:</p>
<pre><code><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="com.example.Constants" %>
<c:if test="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}">
<%-- Do somthing --%>
</c:if>
</code></pre>
<p>But I can't seem to get the sytax correct. Also, to avoid repeating the rather lengthy tests above in multiple places, I'd like to assign the result to a local (page-scoped) variable, and refer to that instead. I believe I can do this with <code><c:set></code>, but again I'm struggling to find the correct syntax.</p>
<p><strong>UPDATE:</strong> Further to the suggestion below, I tried:</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
</code></pre>
<p>which didn't work. So instead, I tried substituting the literal value of the constant. I also added the constant to the content of the page, so I could verify the constant's value when the page is being rendered</p>
<pre><code><c:set var="nullUser" scope="session"
value="${sessionScope['current.user'] eq null}" />
<%= "Constant value: " + WebHelper.ATTR_CURRENT_PARTNER %>
</code></pre>
<p>This worked fine and it printed the expected value "current.user" on the page. I'm at a loss to explain why using the String literal works, but a reference to the constant doesn't, when the two appear to have the same value. Help.....</p>
|
<p>It's not working in your example because the <code>ATTR_CURRENT_USER</code> constant is not visible to the JSTL tags, which expect properties to be exposed by getter functions. I haven't tried it, but the cleanest way to expose your constants appears to be the <a href="http://jakarta.apache.org/taglibs/sandbox/doc/unstandard-doc/index.html#useConstants" rel="nofollow noreferrer" title="Unstandard tag library from Apache">unstandard tag library</a>.</p>
<p>ETA: Old link I gave didn't work. New links can be found in this answer: <a href="https://stackoverflow.com/questions/127328/java-constants-in-jsp">Java constants in JSP</a></p>
<p>Code snippets to clarify the behavior you're seeing:
Sample class:</p>
<pre><code>package com.example;
public class Constants
{
// attribute, visible to the scriptlet
public static final String ATTR_CURRENT_USER = "current.user";
// getter function;
// name modified to make it clear, later on,
// that I am calling this function
// and not accessing the constant
public String getATTR_CURRENT_USER_FUNC()
{
return ATTR_CURRENT_USER;
}
}
</code></pre>
<p>Snippet of the JSP page, showing sample usage: </p>
<pre><code><%-- Set up the current user --%>
<%
session.setAttribute("current.user", "Me");
%>
<%-- scriptlets --%>
<%@ page import="com.example.Constants" %>
<h1>Using scriptlets</h1>
<h3>Constants.ATTR_CURRENT_USER</h3>
<%=Constants.ATTR_CURRENT_USER%> <br />
<h3>Session[Constants.ATTR_CURRENT_USER]</h3>
<%=session.getAttribute(Constants.ATTR_CURRENT_USER)%>
<%-- JSTL --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="cons" class="com.example.Constants" scope="session"/>
<h1>Using JSTL</h1>
<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>
<c:out value="${cons.ATTR_CURRENT_USER_FUNC}"/>
<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER_FUNC]}"/>
<h3>Constants.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[Constants.ATTR_CURRENT_USER]}"/>
<%--
Commented out, because otherwise will error:
The class 'com.example.Constants' does not have the property 'ATTR_CURRENT_USER'.
<h3>cons.ATTR_CURRENT_USER</h3>
<c:out value="${sessionScope[cons.ATTR_CURRENT_USER]}"/>
--%>
<hr />
</code></pre>
<p>This outputs: </p>
<h1>Using scriptlets</h1>
<h3>Constants.ATTR_CURRENT_USER</h3>
<p>current.user <br /></p>
<h3>Session[Constants.ATTR_CURRENT_USER]</h3>
<p>Me</p>
<hr />
<h1>Using JSTL</h1>
<h3>Constants.getATTR_CURRENT_USER_FUNC()</h3>
<p>current.user</p>
<h3>Session[Constants.getATTR_CURRENT_USER_FUNC()]</h3>
<p>Me</p>
<h3>Constants.ATTR_CURRENT_USER</h3>
<p><br /><hr /></p>
|
<p>First, your syntax had an extra "]" which was causing an error. </p>
<p>To fix that, and to set a variable you would do this:</p>
<pre><code><c:set var="nullUser"
scope="session"
value="${sessionScope[Constants.ATTR_CURRENT_USER] eq null}" />
<c:if test="${nullUser}">
<h2>First Test</h2>
</c:if>
<c:if test="${nullUser}">
<h2>Another Test</h2>
</c:if>
</code></pre>
| 14,867
|
<p>I'm considering using Flash but I'm pretty addicted to autocomplete and Step-at-a-time debugging.</p>
|
<p>By using Eclipse with the ActionScript plugin you get full code hinting in the same format that you do with intellisense. </p>
<p>Or you can use <a href="http://www.flashdevelop.org/community/" rel="nofollow noreferrer">FlashDevelop</a> that has both intellisense and can <a href="http://www.flashdevelop.org/community/viewtopic.php?p=6105" rel="nofollow noreferrer">debug (trace) your code</a>.</p>
|
<p>If you mean ActionScript I once heard that <a href="http://www.primalscript.com/" rel="nofollow noreferrer">PrimalScript</a> will do Intellisense. Never tested it though. As for debugging, MAYBE, <a href="http://www.primalscope.com/" rel="nofollow noreferrer">PrimalScope</a> will have that too. I'd recommend you try before you buy, though. (They both have trials.)</p>
| 7,168
|
<p>I've got a situation where I have a DLL I'm creating that uses another third party DLL, but I would prefer to be able to build the third party DLL into my DLL instead of having to keep them both together if possible.</p>
<p>This with is C# and .NET 3.5.</p>
<p>The way I would like to do this is by storing the third party DLL as an embedded resource which I then place in the appropriate place during execution of the first DLL.</p>
<p>The way I originally planned to do this is by writing code to put the third party DLL in the location specified by <code>System.Reflection.Assembly.GetExecutingAssembly().Location.ToString()</code>
minus the last <code>/nameOfMyAssembly.dll</code>. I can successfully save the third party <code>.DLL</code> in this location (which ends up being </p>
<blockquote>
<p>C:\Documents and Settings\myUserName\Local Settings\Application
Data\assembly\dl3\KXPPAX6Y.ZCY\A1MZ1499.1TR\e0115d44\91bb86eb_fe18c901 </p>
</blockquote>
<p>), but when I get to the part of my code requiring this DLL, it can't find it.</p>
<p>Does anybody have any idea as to what I need to be doing differently?</p>
|
<p>Once you've embedded the third-party assembly as a resource, add code to subscribe to the <a href="http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve.aspx" rel="noreferrer"><code>AppDomain.AssemblyResolve</code></a> event of the current domain during application start-up. This event fires whenever the Fusion sub-system of the CLR fails to locate an assembly according to the probing (policies) in effect. In the event handler for <code>AppDomain.AssemblyResolve</code>, load the resource using <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx" rel="noreferrer"><code>Assembly.GetManifestResourceStream</code></a> and feed its content as a byte array into the corresponding <a href="http://msdn.microsoft.com/en-us/library/h538bck7.aspx" rel="noreferrer"><code>Assembly.Load</code></a> overload. Below is how one such implementation could look like in C#:</p>
<pre><code>AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var resName = args.Name + ".dll";
var thisAssembly = Assembly.GetExecutingAssembly();
using (var input = thisAssembly.GetManifestResourceStream(resName))
{
return input != null
? Assembly.Load(StreamToBytes(input))
: null;
}
};
</code></pre>
<p>where <code>StreamToBytes</code> could be defined as:</p>
<pre><code>static byte[] StreamToBytes(Stream input)
{
var capacity = input.CanSeek ? (int) input.Length : 0;
using (var output = new MemoryStream(capacity))
{
int readLength;
var buffer = new byte[4096];
do
{
readLength = input.Read(buffer, 0, buffer.Length);
output.Write(buffer, 0, readLength);
}
while (readLength != 0);
return output.ToArray();
}
}
</code></pre>
<p>Finally, as a few have already mentioned, <a href="http://research.microsoft.com/~mbarnett/ILMerge.aspx" rel="noreferrer">ILMerge</a> may be another option to consider, albeit somewhat more involved. </p>
|
<p>Instead of writing the assembly to disk you can try to do Assembly.Load(byte[] rawAssembly) where you create rawAssembly from the embedded resource.</p>
| 12,226
|
<p>Is it legal to add support for a 3rd party file format in my application by reverse engineer a unencrypted binary file format from another application, and reading the contents?</p>
|
<p>Depends on your location.
In the EU it is specifically permitted (article 6 EU software convention) to "reverse engineer file formats for the purpose of interoperability"</p>
<p>In general it's hard to prevent someone reading a file format, there have been examples where you are prohibeted from writing a file because the format contains patented technology (if software patents are allowed in your country). This was the case with GIF for a number of years.</p>
|
<p>If you have to violate the terms of an EULA to do so, it is illegal. Although most states have laws expressly permitting reverse engineering, it is my understanding that that is not an 'inalienable right', but one you can waive contractually. (In other words, permitting reverse engineering does not prevent you from agreeing not to anyway.) Some jurisdictions go further, however, and explicitly state that reverse engineering is always permitted, even if a contract states otherwise.</p>
<p>If you live in the US, the DMCA generally prohibits reverse engineering if you have to circumvent a "copy protection technology" to do so, but it makes specific exception for cirucumventing it for the purpose of making something compatiable with the format.</p>
<p>Otherwise, it is <em>probably</em> legal. Regardless of the answer here, though, consult a lawyer.</p>
| 14,743
|
<p>I am working on creating an immutable class.<br>
I have marked all the properties as read-only. </p>
<p>I have a list of items in the class.<br>
Although if the property is read-only the list can be modified. </p>
<p>Exposing the IEnumerable of the list makes it immutable.<br>
I wanted to know what is the basic rules one has to follow to make a class immutable ? </p>
|
<p>I think you're on the right track -</p>
<ul>
<li>all information injected into the class should be supplied in the constructor</li>
<li>all properties should be getters only</li>
<li>if a collection (or Array) is passed into the constructor, it should be copied to keep the caller from modifying it later</li>
<li>if you're going to return your collection, either return a copy or a read-only version (for example, using <a href="http://msdn.microsoft.com/en-us/library/system.collections.arraylist.readonly.aspx" rel="noreferrer">ArrayList.ReadOnly</a> or similar - you can combine this with the previous point and <em>store</em> a read-only copy to be returned when callers access it), return an enumerator, or use some other method/property that allows read-only access into the collection</li>
<li>keep in mind that you still may have the appearance of a mutable class if any of your members are mutable - if this is the case, you should copy away whatever state you will want to retain and avoid returning entire mutable objects, unless you copy them before giving them back to the caller - another option is to return only immutable "sections" of the mutable object - thanks to @Brian Rasmussen for encouraging me to expand this point</li>
</ul>
|
<p>Using <a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.readonlycollection-1?view=netframework-4.8" rel="nofollow noreferrer">ReadOnlyCollection</a> will restrict client from modifying it.</p>
| 45,896
|
<blockquote>
<p><strong>Possible duplicate</strong><br>
<a href="https://stackoverflow.com/questions/197182/windows-forms-application-like-google-chrome-with-multiple-processes">Windows Forms application like Google Chrome with multiple processes</a><br>
<a href="https://stackoverflow.com/questions/628744/chrome-ie8-multi-process-design-is-it-possible-in-net">Chrome / IE8 multi-process design, is it possible in .NET?</a><br>
<a href="https://stackoverflow.com/questions/5664071/sample-for-multi-process-c-sharp-app-like-google-chrome">Sample for Multi-process C# app like Google Chrome</a></p>
</blockquote>
<p>Both IE8 and Google Chrome browser have <a href="http://www.hanselman.com/blog/MicrosoftIE8AndGoogleChromeProcessesAreTheNewThreads.aspx" rel="nofollow noreferrer">separate processes for each tab that is opened</a>.</p>
<p>For example, you launch IE8 and open Yahoo and Google in their own tabs, you end up with 3 processes running on your system:</p>
<ul>
<li>IE8 itself process [master process]
<ul>
<li>Google tab process </li>
<li>Yahoo tab process</li>
</ul></li>
</ul>
<p>I'm toying with the idea of a similar thing in C#/WinForms.</p>
<p>Take a simple example: I have a master process that shows a Form, and I have a Button in a child process. How can we render the Button from the other process onto my Form?</p>
|
<p>That doesn't sound like such a good idea. The winforms common controls are for the most part not thread-safe, and giving each control it's own process seems icky.</p>
<p>If you want to try this, perhaps give each <em>form</em> it's own process, or even just it's own thread. Or perhaps if you have a tab control then just give each tab its own thread.</p>
<p><strong>Update</strong><br>
.Net provides something called an AppDomain that you can use. It's more than a thread, but less than a process. If you have a from with multiple tab pages, you could create a custom control that holds the contents for each tab page and put each custom control in it's own assembly. Then those assemblies can be dynamically loaded into their own AppDomains. From there you should be able to create an instance of the control you want. However, there are certain rules about talking across appdomains, so I don't know that you'd be able to just add that control to a tab page on your form.</p>
|
<p>The reason that chrome gives each tab its own process is sandboxing. If one tab behaves errantly it is less likely to take down the whole browser. Is there a similar need in your app? </p>
<p>Also, note that browser tabs don't need to share information. What's on a tab is on a tab and no other tab needs to care about it. Is your winforms app similarly divided?</p>
| 24,631
|
<p>Each of these variables has an integer value. But this syntax is not valid for some reason:</p>
<pre><code><xsl:when test="$nextAnswerListItemPos < $nextQuestionStemPos" >
</code></pre>
|
<p>You have to use <code>&lt;</code> instead of <code><</code> and <code>&gt;</code> instead of <code>></code>, because those are reserved characters.</p>
|
<p>Also, in XSLT 2.0, you can use the operators "gt" (greater than), "lt" (less than), and "eq" (equal). Using these instead of the entities makes your code a bit cleaner.</p>
| 41,062
|
<p>Open source implementation will be preferred.</p>
|
<p>Obviously, it isn't an easy task, PDF formatting is much richer than HTML's one (plus you must extract images and link them, etc.).<br>
Simple text extraction is much simpler (although not trivial...).<br>
I see in the sidebar of your question a similar question: <a href="https://stackoverflow.com/questions/276434/converting-pdf-to-html-with-python" title="Converting PDF to HTML with Python">Converting PDF to HTML with Python</a> which points to a library (poppler, which is apparently written in C++, perhaps can be accessed with JNI/JNA) and to a related question which offers even more answers.</p>
|
<p>Only ones I know of have to be paid for.</p>
<p><a href="http://bfo.co.uk/" rel="nofollow noreferrer">BFO</a><br>
<a href="http://www.jpedal.org/" rel="nofollow noreferrer">JPedal</a></p>
| 46,815
|
<p>I've been using IntelliJ IDEA at the day job for Java development for a few weeks now. I'm really impressed with it and I'm looking to extend it for other programming languages that I tinker with, starting with Python. I found this plug-in, <a href="https://pythonid.dev.java.net/" rel="nofollow noreferrer">pythonid</a>. I figured I would look for some input on the Stack before proceeding. First, has anyone given pythonid a try and and have any feedback about it (the site for it is a bit weak)? And second, sre there any other Python plug-ins for IntelliJ IDEA that might be better?</p>
|
<p>I've tried Pythonid before and found it very limited. There's a <a href="http://plugins.intellij.net/plugin/?id=631" rel="nofollow noreferrer">new Python plugin</a> from JetBrains, the people that make IDEA, which looks pretty nice, though it's <a href="http://www.jetbrains.net/confluence/display/PYH/Release+Notes" rel="nofollow noreferrer">still very unfinished</a>.</p>
|
<p>I've tried Pythonid before and found it very limited. There's a <a href="http://plugins.intellij.net/plugin/?id=631" rel="nofollow noreferrer">new Python plugin</a> from JetBrains, the people that make IDEA, which looks pretty nice, though it's <a href="http://www.jetbrains.net/confluence/display/PYH/Release+Notes" rel="nofollow noreferrer">still very unfinished</a>.</p>
| 49,326
|
<p>I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to <code>padding</code> and <code>position:relative</code>, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.</p>
<p>The main section of css that seems to be causing the problem is:</p>
<pre class="lang-css prettyprint-override"><code>#settings{
float:left;
}
#right_content{
margin-top:20px;
margin-left:440px;
width:400px;
}
</code></pre>
<p>This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.</p>
<p>The site is available at: <a href="http://frickinsweet.com/tools/Theme.mvc.aspx" rel="nofollow noreferrer">http://frickinsweet.com/tools/Theme.mvc.aspx</a> to see the source code.</p>
|
<p>I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF. </p>
|
<p>Sorry I should have mentioned that as well. I tried floating that content right and additionally tried floating it left and setting the position with the thinking that both divs would start out at left:0 where setting the margin of the right would move it over.</p>
<p>Thanks</p>
| 7,300
|
<p>I am seeing strange behaviour with the flash.media.Sound class in Flex 3.</p>
<pre><code>var sound:Sound = new Sound();
try{
sound.load(new URLRequest("directory/file.mp3"))
} catch(e:IOError){
...
}
</code></pre>
<p>However this isn't helping. I'm getting a stream error, and it actually sees to be in the Sound constructor.</p>
<blockquote>
<p>Error #2044: Unhandled IOErrorEvent:.
text=Error #2032: Stream Error. at... ]</p>
</blockquote>
<p>I saw one example in the Flex docs where they add an event listener for IOErrorEvent, SURELY I don't have to do this, and can simply use try-catch? Can I set a null event listener?</p>
|
<p><a href="http://livedocs.adobe.com/flex/3/langref/flash/errors/IOError.html" rel="noreferrer">IOError</a> = target file cannot be found (or for some other reason cannot be read). Check your file's path.</p>
<p>Edit: I just realized this may not be your problem, you're just trying to catch the IO error? If so, you can do this:</p>
<pre>var sound:Sound = new Sound();
sound.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
sound.load(new URLRequest("directory/file.mp3"));
function ioErrorHandler(event:IOErrorEvent):void {
trace("IO error occurred");
}
</pre>
|
<p>You will need to add a listener since the URLRequest is not instantaneous. It will be <strong>very</strong> fast if you're loading from disk, but you will still need the Event-listener.
There's a good example of how to set this up (Complete with IOErrorEvent handling) in the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/media/Sound.html#load()" rel="nofollow noreferrer">livedocs</a>.</p>
| 10,645
|
<p>This is a follow-up to my <a href="https://stackoverflow.com/questions/372695/is-there-a-standard-c-function-object-for-taking-apart-a-stdpair">question from yesterday</a>. I have Scott Meyers' warning about write-only code on my mind. I like the idea in principle of using standard algorithms to access the keys or values of a std::map, but the syntax required is a little baroque IMHO. Let's say I want to dump all the keys of a map to a vector. Given following declarations,</p>
<pre><code>typedef std::map<int, int> MyMap;
MyMap m;
std::vector<int> v;
</code></pre>
<p>which code is more maintainable (i.e., potentially less confusing)?</p>
<p>Option #1:</p>
<pre><code>std::transform(m.begin(),
m.end(),
std::back_inserter(v),
std::tr1::bind(&MyMap::value_type::first, _1));
</code></pre>
<p>Option #2:</p>
<pre><code>for (MyMap::iterator i = m.begin(); i != m.end(); ++i)
{
v.push_back(i->first);
}
</code></pre>
<p>Option 1 is more standard library-ish but I have to mentally decompose it to understand what's going on. Option 2 seems easier to read at the expense of a possible small runtime penalty. I'm not hurting for CPU time so I'm leaning toward option 2. Does you guys agree? Is there a third option I should consider?</p>
<p>P.S. Over the course of writing this question I concluded that the best way (for my project) to read the keys of a std::map is to store them off in a side container and iterate over that. The maintainability question still stands though.</p>
|
<p>Clarity always beats clever. Do what you can read later.</p>
<p>You're not alone in thinking that the standard code is a little obtuse. The next C++ standard will introduce <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions" rel="noreferrer">lambda functions</a> so you can write more legible code with the standard algorithms.</p>
|
<p>Go with option #1, see Scott Meyers, <a href="https://rads.stackoverflow.com/amzn/click/com/0201749629" rel="nofollow noreferrer" rel="nofollow noreferrer">Effective STL</a> Item #43, page 181.</p>
| 49,233
|
<p>I'm trying to learn C. As a C# developer, my IDE is Visual Studio. I've heard this is a good environment for C/C++ development. However, it seems no matter what little thing I try to do, intuition fails me. Can someone give good resources for how to either:</p>
<ul>
<li>learn the ins and out of C in Visual Studio</li>
<li>recommend a better C IDE + compiler</li>
</ul>
<hr>
<p><strong>Edit:</strong> See also: <a href="https://stackoverflow.com/questions/951516/a-good-c-ide">https://stackoverflow.com/questions/951516/a-good-c-ide</a></p>
|
<p>well you can use visual studio just fine take a look at here man
<a href="http://www.daniweb.com/forums/thread16256.html" rel="noreferrer">http://www.daniweb.com/forums/thread16256.html</a></p>
<p>Go to View Menu select Solution Explorer or CTRL+ ALT +L</p>
<p>Then Select The project that your are developing and right click on that.</p>
<p>Then select the Properties from the submenu.</p>
<p>Then select the Configuration properties from the Tree structure. under that select C/C++ then select Advanced. Now in the right side pane change the property</p>
<p>Compile As from Compile as C++ Code (/TP) to Compile as C Code (/TC)</p>
<p>Finally change your file extensions to .c</p>
<h1>Now you configured you Visual Studio to compile C programs</h1>
<p><strong>And you can use NetBeans too it could even be more user friendly than Visual Studio download it you wont regret i promise</strong></p>
|
<p>Visual Studio or Express do consider .c files as C code, but the compiler will keep giving warnings, and irritating suggestions which you do not require, in the debugger. Gives an indication that Visual C++, as the name suggests is optimized for C++ development for the Windows Operating system, which was originally written in plain pure C.</p>
| 4,823
|
<p>I tried this in mysql:</p>
<pre><code>mysql> alter table region drop column country_id;
</code></pre>
<p>And got this:</p>
<pre><code>ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to
'./product/region' (errno: 150)
</code></pre>
<p>Any ideas? Foreign key stuff?</p>
|
<p>You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.</p>
<p>But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:</p>
<blockquote>
<p>SHOW CREATE TABLE region;</p>
</blockquote>
<p>This should show you the name of the index, something like this:</p>
<blockquote>
<p>CONSTRAINT <code>region_ibfk_1</code> FOREIGN
KEY (<code>country_id</code>) REFERENCES
<code>country</code> (<code>id</code>) ON DELETE NO
ACTION ON UPDATE NO ACTION</p>
</blockquote>
<p>Now simply issue an:</p>
<blockquote>
<p>alter table region drop foreign key
<code>region_ibfk_1</code>;</p>
</blockquote>
<p>And finally an:</p>
<blockquote>
<p>alter table region drop column
country_id;</p>
</blockquote>
<p>And you are good to go!</p>
|
<p>averageRatings= FOREACH groupedRatings <strong>GENERATE group AS</strong> movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;</p>
<p>If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.</p>
| 19,378
|
<p>My basic question is, in .NET, how do I clone WebControls?</p>
<p>I would like to build a custom tag, which can produce multiple copies of its children.
Ultimately I intend to build a tag similar to in JSP/Struts.</p>
<p>But the first hurdle I have is the ability to duplicate/clone the contents of a control.</p>
<p>Consider this rather contrived example;</p>
<pre><code><custom:duplicate count="2">
<div>
<p>Some html</p>
<asp:TextBox id="tb1" runat="server" />
</div>
</custom:duplicate>
</code></pre>
<p>The HTML markup which is output would be something like,</p>
<pre><code><div>
<p>Some html</p>
<input type="text" id="tb1" />
</div>
<div>
<p>Some html</p>
<input type="text" id="tb1" />
</div>
</code></pre>
<p><em>Note: I know i have the id duplicated, I can come up with a solution to that later!</em></p>
<p>So what we would have is my custom control with 3 children (I think) - a literal control, a TextBox control, and another literal control.</p>
<p>In this example I have said 'count=2' so what the control should do is output/render its children twice.</p>
<p>What I would hope to do is write some "OnInit" code which does something like:</p>
<pre><code>List<WebControl> clones;
for(int i=1; i<count; i++)
{
foreach(WebControl c in Controls)
{
WebControl clone = c.Clone();
clones.Add(clone);
}
}
Controls.AddRange(clones);
</code></pre>
<p>However, as far as I can tell, WebControls do not implement ICloneable, so its not possible to clone them in this way.</p>
<p>Any ideas how I can clone WebControls?</p>
|
<p>What's wrong with using a Repeater and binding a dud data source. It'll duplicate the templated controls and handle the ID creation and all.</p>
|
<p>The way to do this in ASP.NET is using templates. There are samples in MSDN for this, just look for templated controls / ITemplate.</p>
| 19,514
|
<p>I need to scramble the names and logins of all the users in a UAT database we have. (because of the data protection act)</p>
<p>However, there is a catch.</p>
<p>The testers still need to be able to login using the hashed login names</p>
<p>so if a user login is "Jesse.J.James" then the hash should be something like</p>
<p>Ypois.X.Qasdf</p>
<p>i.e. approximately the same length, with the dots in the same place</p>
<p>so MD5, sha1 etc would not be suitable as they would create very long strings and also add their own special characters such as + and = which are not allowed by the validation regex.</p>
<p>So I'm looking for some suggestions as to how to achieve this</p>
<p>I guess I need to rollmy own hashing algorith</p>
<p>anyone done anything similar?</p>
<p>I am using c# but I guess that is not so important to the algorithm</p>
<p>thanks alot</p>
<p><strong>ADDED -</strong> </p>
<p>Thanks for all the answers. I think I am responsible for the confusion by using the word "Hash" when that is not what needed to be done</p>
|
<p>You do not need to hash the data. You should just randomize it so it has no relation to the original data.</p>
<p>For example, update all the login names, and replace each letter with another random letter.</p>
|
<p>Why not use a test data generator for the data that could identify an individual?</p>
<p><a href="https://stackoverflow.com/questions/16317/creating-test-data-in-a-database#16336">Creating test data in a database</a></p>
| 20,842
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.