instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>If not, is <a href="http://en.wikipedia.org/wiki/Smoke_test#Smoke_testing_in_software_development" rel="nofollow noreferrer">smoke testing</a> still used?</p>
<p>It's sort of a Venn Diagram. Some Automated tests are Smoke tests, and some smoke tests are Automated (inasfar as they are ran by a computer program). A Smoke test is a take off (if I recall correctly) on the term "Where there's smoke, there's usually fire." It's a set of preliminary tests that the program must pass to be considered for 'real' (viz. fire) testing.</p> <p>A smoke test can be manual insomuch as a tester has a list of steps he follows, but these aren't automated with a computer program.</p> <p>Smoke testing is still used -- in places I've worked, it's usually automated.</p>
<p>My understanding of "smoke testing" is different than the wikipedia article. I understand smoke testing to be the developer opening the app and testing the basic functionality to verify that the app looks right &amp; is doing the basics. So I always thought it was a manual process, not an automated one.</p>
28,539
<p>I have 2 tables (A and B) with the same primary keys. I want to select all row that are in A and not in B. The following works:</p> <pre><code>select * from A where not exists (select * from B where A.pk=B.pk); </code></pre> <p>however it seems quite bad (~2 sec on only 100k rows in A and 3-10k less in B)</p> <p>Is there a better way to run this? Perhaps as a left join?</p> <pre><code>select * from A left join B on A.x=B.y where B.y is null; </code></pre> <p>On my data this seems to run slightly faster (~10%) but what about in general?</p>
<p>I think your last statement is the best way. You can also try</p> <pre><code>SELECT A.* from A left join B on A.x = B.y where B.y is null </code></pre>
<p>This helped me a lot. <code>Joins</code> are always faster than Sub Queries to give results:</p> <pre><code>SELECT tbl1.id FROM tbl1 t1 LEFT OUTER JOIN tbl2 t2 ON t1.id = t2.id WHERE t1.id&gt;=100 AND t2.id IS NULL ; </code></pre>
46,106
<p>What are the correct version numbers for C#? What came out when? Why can't I find any answers about <strong><em>C# 3.5</em></strong>?</p> <p>This question is primarily to aid those who are searching for an answer using an incorrect version number, e.g. <strong><em>C# 3.5</em></strong>. The hope is that anyone failing to find an answer with the wrong version number will find <em>this</em> question and then search again with the right version number.</p>
<h1>C# language version history:</h1> <p>These are the <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-version-history" rel="noreferrer">versions of C#</a> known about at the time of this writing:</p> <ul> <li><strong>C# 1.0</strong> released with .NET 1.0 and VS2002 (January 2002)</li> <li><strong>C# 1.2</strong> (bizarrely enough); released with .NET 1.1 and VS2003 (April 2003). First version to call <code>Dispose</code> on <code>IEnumerator</code>s which implemented <code>IDisposable</code>. A few other small features.</li> <li><strong>C# 2.0</strong> released with .NET 2.0 and VS2005 (November 2005). Major new features: generics, anonymous methods, nullable types, and iterator blocks</li> <li><strong>C# 3.0</strong> released with .NET 3.5 and VS2008 (November 2007). Major new features: lambda expressions, extension methods, expression trees, anonymous types, implicit typing (<code>var</code>), and query expressions</li> <li><strong>C# 4.0</strong> released with .NET 4 and VS2010 (April 2010). Major new features: late binding (<code>dynamic</code>), delegate and interface generic variance, more <a href="https://en.wikipedia.org/wiki/Component_Object_Model" rel="noreferrer">COM</a> support, named arguments, tuple data type and optional parameters</li> <li><strong>C# 5.0</strong> released with .NET 4.5 and VS2012 (August 2012). <a href="https://devblogs.microsoft.com/csharpfaq/visual-studio-11-beta-is-here/" rel="noreferrer">Major features</a>: async programming, and caller info attributes. Breaking change: <a href="https://ericlippert.com/2009/11/16/closing-over-the-loop-variable-considered-harmful-part-two/" rel="noreferrer">loop variable closure</a>.</li> <li><strong>C# 6.0</strong> released with .NET 4.6 and VS2015 (July 2015). Implemented by <a href="https://github.com/dotnet/roslyn" rel="noreferrer">Roslyn</a>. <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-6" rel="noreferrer">Features</a>: initializers for automatically implemented properties, using directives to import static members, exception filters, element initializers, <code>await</code> in <code>catch</code> and <code>finally</code>, extension <code>Add</code> methods in collection initializers.</li> <li><strong>C# 7.0</strong> released with .NET 4.7 and VS2017 (March 2017). Major <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7" rel="noreferrer">new features</a>: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#tuples" rel="noreferrer">tuples</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#ref-locals-and-returns" rel="noreferrer">ref locals and ref return</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#pattern-matching" rel="noreferrer">pattern matching</a> (including pattern-based switch statements), <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#out-variables" rel="noreferrer">inline <code>out</code> parameter declarations</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#local-functions" rel="noreferrer">local functions</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#numeric-literal-syntax-improvements" rel="noreferrer">binary literals, digit separators</a>, and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-7#generalized-async-return-types" rel="noreferrer">arbitrary async returns</a>.</li> <li><strong>C# 7.1</strong> released with VS2017 v15.3 (August 2017). New features: <a href="https://github.com/dotnet/csharplang/issues/97" rel="noreferrer">async main</a>, <a href="https://github.com/dotnet/csharplang/issues/415" rel="noreferrer">tuple member name inference</a>, <a href="https://github.com/dotnet/csharplang/issues/102" rel="noreferrer">default expression</a>, and <a href="https://github.com/dotnet/csharplang/issues/154" rel="noreferrer">pattern matching with generics</a>.</li> <li><strong>C# 7.2</strong> released with VS2017 v15.5 (November 2017). New features: <a href="https://github.com/dotnet/csharplang/issues/37" rel="noreferrer">private protected access modifier</a>, <a href="https://github.com/dotnet/csharplang/issues/666" rel="noreferrer">Span&lt;T&gt;, aka interior pointer, aka stackonly struct</a>, and <a href="https://github.com/dotnet/csharplang/milestone/6" rel="noreferrer">everything else</a>.</li> <li><strong>C# 7.3</strong> released with VS2017 v15.7 (May 2018). New features: <a href="https://devblogs.microsoft.com/premier-developer/dissecting-new-generics-constraints-in-c-7-3/" rel="noreferrer">enum, delegate and <code>unmanaged</code> generic type constraints</a>. <code>ref</code> reassignment. Unsafe improvements: <code>stackalloc</code> initialization, unpinned indexed <code>fixed</code> buffers, custom <code>fixed</code> statements. Improved overloading resolution. Expression variables in initializers and queries. <code>==</code> and <code>!=</code> defined for tuples. Auto-properties' backing fields can now be targeted by attributes.</li> <li><strong>C# 8.0</strong> released with .NET Core 3.0 and VS2019 v16.3 (September 2019). Major <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8" rel="noreferrer">new features</a>: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references" rel="noreferrer">nullable reference-types</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams" rel="noreferrer">asynchronous streams</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges" rel="noreferrer">indices and ranges</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#readonly-members" rel="noreferrer">readonly members</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations" rel="noreferrer">using declarations</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods" rel="noreferrer">default interface methods</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions" rel="noreferrer">static local functions</a>, and <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#enhancement-of-interpolated-verbatim-strings" rel="noreferrer">enhancement of interpolated verbatim strings</a>.</li> <li><strong>C# 9.0</strong> released with <a href="https://devblogs.microsoft.com/dotnet/announcing-net-5-0/" rel="noreferrer">.NET 5.0</a> and VS2019 v16.8 (November 2020). Major <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9" rel="noreferrer">new features</a>: <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#init-only-setters" rel="noreferrer">init-only properties</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#record-types" rel="noreferrer">records</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/with-expression" rel="noreferrer">with-expressions</a>, data classes, positional records, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#top-level-statements" rel="noreferrer">top-level programs</a>, <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements" rel="noreferrer">improved pattern matching</a> (simple type patterns, relational patterns, logical patterns), improved target typing (target-type <code>new</code> expressions, target typed <code>??</code> and <code>?</code>), and covariant returns. Minor features: relax ordering of <code>ref</code> and <code>partial</code> modifiers, parameter null checking, lambda discard parameters, native <code>int</code>s, attributes on local functions, function pointers, static lambdas, extension <code>GetEnumerator</code>, module initializers, and extending partial.</li> <li><strong>C# 10.0</strong> released with .NET 6.0 (November 2021). Major <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-10" rel="noreferrer">new features</a>: record structs, struct parameterless constructors, interpolated string handlers, global <code>using</code> directives, file-scoped namespace declarations, extended property patterns, const interpolated strings, mixed assignment and declaration in deconstruction, async method builders (via attributes) for individual methods, the <code>CallerArgumentExpression</code> attribute for parameters, enhanced <code>#line</code> pragmas.</li> <li><strong>C# 11.0</strong> will be released with .NET 7.0 (Date to be annonced, already testable). Major <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-11" rel="noreferrer">new features</a>: file-scoped types, generic math support, auto-default structs, pattern match <code>Span&lt;char&gt;</code> on a constant string, extended nameof scope, numeric <code>IntPtr</code>, UTF-8 string literals, required members, <code>ref</code> fields and <code>scoped ref</code>, raw string literals, improved method group conversion to delegate, warning wave 7, generic attributes, newlines in string interpolation expressions, list patterns</li> </ul> <h2>In response to the OP's question:</h2> <blockquote> <p>What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?</p> </blockquote> <p>There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (<a href="https://msdn.microsoft.com/en-us/library/bb822049.aspx" rel="noreferrer">this MSDN page</a> used to refer to it that way, for example), but the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.environment.version" rel="noreferrer"><code>Environment.Version</code></a> property still reports 4.0.xxx.</p> <p>As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: <a href="https://github.com/dotnet/csharplang/blob/master/Language-Version-History.md" rel="noreferrer">Features Added in C# Language Versions</a>. There is also <a href="https://github.com/dotnet/roslyn/blob/master/docs/Language%20Feature%20Status.md" rel="noreferrer">a page that tracks upcoming and recently implemented language features</a>.</p>
<h2>Preview: C# 11.0 .NET Core 7.0 Visual Studio 2022 Update 1</h2> <p><a href="https://devblogs.microsoft.com/dotnet/early-peek-at-csharp-11-features/" rel="nofollow noreferrer"><strong><code>READ MORE</code></strong></a></p> <ul> <li>Allow newlines in the “holes” of interpolated strings</li> <li>List patterns</li> <li>Parameter null-checking</li> <li>Interaction with Nullable Reference Types</li> <li>Generic attributes</li> <li>field keyword</li> <li>Static abstracts in interfaces</li> <li>Declarations under or patterns</li> <li>Records and initialization</li> <li>Discriminated unions</li> <li>Params Span of T</li> <li>Statements as expressions</li> <li>Expression trees</li> <li>Type system extensions</li> </ul>
30,756
<p>In my environment here I use Java to serialize the result set to XML. It happens basically like this:</p> <pre><code>//foreach column of each row xmlHandler.startElement(uri, lname, "column", attributes); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lname, "column"); </code></pre> <p>The XML looks like this in Firefox:</p> <pre><code>&lt;row num="69004"&gt; &lt;column num="1"&gt;10069&lt;/column&gt; &lt;column num="2"&gt;sd&amp;#26;&lt;/column&gt; &lt;column num="3"&gt;FCVolume &lt;/column&gt; &lt;/row&gt; </code></pre> <p>But when I parse the XML I get the a</p> <blockquote> <p>org.xml.sax.SAXParseException: Character reference "<strong>&amp;#26</strong>" is an invalid XML character.</p> </blockquote> <p>My question now is: Which charactes do I have to replace or how do I have to encode my characters, that they will be valid XML?</p>
<p>I found an interesting list in the <a href="http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets" rel="noreferrer">Xml Spec</a>: According to that List its discouraged to use the Character #26 (Hex: <em>#x1A</em>).</p> <blockquote> <p>The characters defined in the following ranges are also discouraged. They are either control characters or permanently undefined Unicode characters</p> </blockquote> <p>See the <a href="http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets" rel="noreferrer">complete ranges</a>.</p> <p>This code replaces all non-valid Xml Utf8 from a String:</p> <pre><code>public String stripNonValidXMLCharacters(String in) { StringBuffer out = new StringBuffer(); // Used to hold the output. char current; // Used to reference the current character. if (in == null || ("".equals(in))) return ""; // vacancy test. for (int i = 0; i &lt; in.length(); i++) { current = in.charAt(i); if ((current == 0x9) || (current == 0xA) || (current == 0xD) || ((current &gt;= 0x20) &amp;&amp; (current &lt;= 0xD7FF)) || ((current &gt;= 0xE000) &amp;&amp; (current &lt;= 0xFFFD)) || ((current &gt;= 0x10000) &amp;&amp; (current &lt;= 0x10FFFF))) out.append(current); } return out.toString(); } </code></pre> <p>its taken from <a href="http://cse-mjmcl.cse.bris.ac.uk/blog/2007/02/14/1171465494443.html" rel="noreferrer">Invalid XML Characters: when valid UTF8 does not mean valid XML</a></p> <p>But with that I had the still UTF-8 compatility issue:</p> <pre><code>org.xml.sax.SAXParseException: Invalid byte 1 of 1-byte UTF-8 sequence </code></pre> <p>After reading <a href="http://www.velocityreviews.com/forums/t166758-returning-xml-as-utf8-from-a-servlet.html" rel="noreferrer">XML - returning XML as UTF-8 from a servlet</a> I just tried out what happens if I set the Contenttype like this:</p> <pre><code>response.setContentType("text/xml;charset=utf-8"); </code></pre> <p>And it worked ....</p>
<p>Which version of JRE are you running? <a href="http://www.saxproject.org/faq.html" rel="nofollow noreferrer">Sax Project</a> says: </p> <blockquote> <p>J2SE 1.4 bundles an old version of SAX2. How do I make SAX2 r2 or later available?</p> </blockquote>
18,959
<p>I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.</p> <p>Here are some trivial examples where they functionally do the same thing if either were found within another function:</p> <p><strong>Lambda function</strong></p> <pre><code>&gt;&gt;&gt; a = lambda x : 1 + x &gt;&gt;&gt; a(5) 6 </code></pre> <p><strong>Nested function</strong></p> <pre><code>&gt;&gt;&gt; def b(x): return 1 + x &gt;&gt;&gt; b(5) 6 </code></pre> <p>Are there advantages to using one over the other? (Performance? Readability? Limitations? Consistency? etc.)</p> <p>Does it even matter? If it doesn't then does that violate the Pythonic principle:</p> <blockquote> <p><a href="https://www.python.org/dev/peps/pep-0020/" rel="noreferrer">There should be one-- and preferably only one --obvious way to do it.</a>.</p> </blockquote>
<p>If you need to assign the <code>lambda</code> to a name, use a <code>def</code> instead. <code>def</code>s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.</p> <p><code>lambda</code>s can be used for <em>use once, throw away</em> functions which won't have a name.</p> <p>However, this use case is very rare. You rarely need to pass around unnamed function objects.</p> <p>The builtins <code>map()</code> and <code>filter()</code> need function objects, but <strong>list comprehensions</strong> and <strong>generator expressions</strong> are generally more readable than those functions and can cover all use cases, without the need of lambdas. </p> <p>For the cases you really need a small function object, you should use the <code>operator</code> module functions, like <code>operator.add</code> instead of <code>lambda x, y: x + y</code></p> <p>If you still need some <code>lambda</code> not covered, you might consider writing a <code>def</code>, just to be more readable. If the function is more complex than the ones at <code>operator</code> module, a <code>def</code> is probably better. </p> <p>So, real world good <code>lambda</code> use cases are very rare.</p>
<p>lambda is useful for generating new functions:</p> <pre><code>&gt;&gt;&gt; def somefunc(x): return lambda y: x+y &gt;&gt;&gt; f = somefunc(10) &gt;&gt;&gt; f(2) 12 &gt;&gt;&gt; f(4) 14 </code></pre>
16,297
<p>I am looking for an open-source project involving c++ GUI(s) working with a database. I have not done it before, and am looking for a way to get my feet wet. Which can I work on?</p>
<p>How about this one <a href="http://sourceforge.net/projects/sqlitebrowser/" rel="nofollow noreferrer">http://sourceforge.net/projects/sqlitebrowser/</a>:</p> <blockquote> <p>SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface.</p> </blockquote>
<p>Sourceforge has a help wanted page: <a href="http://sourceforge.net/people/" rel="nofollow noreferrer">http://sourceforge.net/people/</a></p> <p>browse the postings to see if a project is in your expertise or find one that sound interesting...</p> <p>And let me be the first to say thank you for being willing to contribute your time and knowlede to the open source movement.</p>
10,264
<p><strong>EDIT:</strong> See <a href="https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#221252">my working code</a> in the answers below.</p> <hr> <p><strong>In brief:</strong> I have a JSP file which calls a method in a Java Bean. This method creates a PDF file and in theory, returns it to the JSP so that the user can download it. However, upon loading the PDF, Adobe Reader gives the error: <em>File does not begin with '%PDF-'</em>.</p> <p><strong>In detail:</strong> So far, the JSP successfully calls the method, the PDF is created and then the JSP appears to give the user the finished PDF file. However, as soon as Adobe Reader tries to open the PDF file, it gives an error: <em>File does not begin with '%PDF-'</em>. Just for good measure, I have the method create the PDF on my Desktop so that I can check it; when I open it normally within Windows is appears fine. So why is the output from the JSP different?</p> <p>To create the PDF, I'm using <a href="http://xmlgraphics.apache.org/fop" rel="nofollow noreferrer">Apache FOP</a>. I'm following one of their most basic examples, with the exception of passing the resulting PDF to a JSP instead of simply saving it to the local machine. I have been following their <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html#basics" rel="nofollow noreferrer">basic usage pattern</a> and <a href="http://svn.apache.org/viewvc/xmlgraphics/fop/trunk/examples/embedding/java/embedding/ExampleFO2PDF.java?view=markup" rel="nofollow noreferrer">this example code</a>.</p> <p>Here's my JSP file:</p> <pre><code>&lt;%@ taglib uri="utilTLD" prefix="util" %&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt; &lt;%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %&gt; &lt;%@ page language="java" session="false" %&gt; &lt;%@ page contentType="application/pdf" %&gt; &lt;%-- Construct and initialise the PrintReportsBean --%&gt; &lt;jsp:useBean id="printReportsBean" scope="request" class="some.package.printreports.PrintReportsBean" /&gt; &lt;jsp:setProperty name="printReportsBean" property="*"/&gt; &lt;c:set scope="page" var="xml" value="${printReportsBean.download}"/&gt; </code></pre> <p>Here's my Java Bean method:</p> <pre><code>//earlier in the class... private static FopFactory fopFactory = FopFactory.newInstance(); public File getDownload() throws UtilException { OutputStream out = null; File pdf = new File("C:\\documents and settings\\me\\Desktop\\HelloWorld.pdf"); File fo = new File("C:\\somedirectory", "HelloWorld.fo"); try { FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); out = new FileOutputStream(pdf); out = new BufferedOutputStream(out); Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); //identity transformer Source src = new StreamSource(fo); Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); return pdf; } catch (Exception e) { throw new UtilException("Could not get download. Msg = "+e.getMessage()); } finally { try { out.close(); } catch (IOException io) { throw new UtilException("Could not close OutputStream. Msg = "+io.getMessage()); } } } </code></pre> <p>I realise that this is a very specific problem, but any help would be much appreciated!</p>
<p>The way I have implemented this type of feature in the past is to make a servlet write the contents of the PDF file out to the response as a stream. I don't have the source code with me any longer (and it's been at least a year since I did any servlet/jsp work), but here is what you might want to try:</p> <p>In a servlet, get a handle on the response's output stream. Change the mime type of the response to "application/pdf", and have the servlet do the file handling you have in your example. Only, instead of returning the File object, have the servlet write the file to the output stream. See examples of file i/o and just replace any outfile.write(...) lines with responseStream.write(...) and you should be set to go. Once you flush and close the output stream, and do the return, if I remember correctly, the browser should be able to pick up the pdf from the response.</p>
<p>I agree with <a href="https://stackoverflow.com/questions/218909/returning-a-pdf-file-from-a-java-bean-to-a-jsp#218942">matt b</a>, maybe its the spaces between JSP tags. Try putting the directive</p> <pre><code>&lt;%@ page trimDirectiveWhitespaces="true" %&gt; </code></pre>
26,942
<p>I am trying to connect to simple webparts in my sharepoint team site, i need one of the webparts to filter its information based on what it recieves from another webpart</p> <p>I am using the query string filter webpart and the a list view webpart but no matter how i connect them always i am getting this error </p> <p>"Web Part Error: This page has exceeded its data fetch limit for connected Web Parts. Try disconnecting one or more Web Parts to correct the problem."</p> <p>What should I do and what am I doing wrong</p> <p><strong>update:</strong> i can connect to web parts on some other pgae, but getting this error on the DispForm.aspx page of a certain item , is webpart connections not allowed there ??!!</p>
<p>There is an issue with creating QueryString filter webparts in sharepoint, when you're not using the Web UI (I'm making an assumption that you aren't).</p> <p>This fella here has a post about it and how he hacked around the issue.</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/0328f1b2-20cd-427f-887a-e2925bd695e3/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/0328f1b2-20cd-427f-887a-e2925bd695e3/</a></p> <p>Another option is not using the QueryString filter web part at all, and just passing querystrings to a regular web part.</p> <p><a href="http://mo.notono.us/2008/04/moss-filter-views-through-url-query.html" rel="nofollow noreferrer">http://mo.notono.us/2008/04/moss-filter-views-through-url-query.html</a></p>
<p>The page 'DispForm.aspx' usually is a form of a SharePoint list and different rules apply to list-form pages than on pages that do not belong to a Sharepoint list (and the differences are hardly documented). I solved the problem by workarounds; you could use not a ListViewWebPart, but a DataViewWebPart (<a href="http://itfootprint.wordpress.com/2007/05/23/using-query-string-and-data-view-webpart/" rel="nofollow noreferrer">Using Query String and Data view WebPart</a>), or you could avoid the QueryStringFilterWebPart by using URL parameters that the ListViewWebPart understands (<a href="http://acsir-englian.spaces.live.com/blog/cns!6BA7474731AF29F8!456.trak" rel="nofollow noreferrer">ListViewWebPart Filter Param</a>).</p>
26,429
<p>I'm designing a web site navigation hierarchy. It's a tree of nodes. Nodes represent web pages.</p> <p>Some nodes on the tree are special. I need a name for them.</p> <p>There are multiple such nodes. Each is the "root" of a sub-tree with pages that have a distinct logo, style sheet, or layout. Think of different departments.</p> <p><a href="http://img518.imageshack.us/img518/153/subtreesfe1.gif" rel="nofollow noreferrer">site map with color-coded sub-trees http://img518.imageshack.us/img518/153/subtreesfe1.gif</a></p> <p>What should I name this type of node?</p>
<p>How about Root (node with children, but no parent), Node (node with children and parent) and Leaf (node with no children and parent)?</p> <p>You can then distinguish by name and position within the tree structure (E.g. DepartmentRoot, DepartmentNode, DepartmentLeaf) if need be..</p> <h2>Update Following Comment from OP</h2> <p>Looking at your question, you said that &quot;some&quot; are special, and in your diagram, you have different nodes looking differently at different levels. The nodes may be different in their design, you can build a tree structure many ways. For example, a single abstract class that <em>can</em> have child nodes, if no children, its a leaf, if no parent, its a root but this can change in its lifetime. Or, a fixed class structure in which leafs are a specific class type that <em>cannot</em> have children added to them in any way.</p> <p>IF your design does not need you to distinguish nodes differently depending on their position (relative to the root) it suggests that you have an abstract class used for them all.</p> <p>In which case, it raises the question, <strong>how is it different?</strong></p> <p>If it is simply the same as the standard node everywhere else, but with a bit of styling, how about <em>StyledNode</em>? Do you even need it to be seperate (no style == no big deal, it doesn't render).</p> <p>Since I don't know the mechanics of how the tree is architected, there could possibly be several factors to consider when naming.</p>
<p>How about <em>PageTemplate</em> to embody the fact that its children have their own layout, CSS etc?</p>
11,231
<p>The ReSharper reformat code feature is very handy and flexible, particularly with the new code layout templating flexibility JetBrains have added in version 3.0.</p> <p>Is there a standard set of code style settings for ReSharper which match the rules enforced by <a href="http://code.msdn.microsoft.com/sourceanalysis" rel="noreferrer">Microsoft StyleCop</a>, so that StyleCop compliance can be as easy as running the ReSharper "reformat code" feature?</p>
<p>Try the ReSharper StyleCop plugin at: <a href="http://www.codeplex.com/StyleCopForReSharper" rel="noreferrer">http://www.codeplex.com/StyleCopForReSharper</a></p>
<p>I am looking for the same things.</p> <p>Here is a Custom Type member layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Patterns xmlns="urn:shemas-jetbrains-com:member-reordering-patterns"&gt; &lt;!--Do not reorder COM interfaces and structs marked by StructLayout attribute--&gt; &lt;Pattern&gt; &lt;Match&gt; &lt;Or Weight="100"&gt; &lt;And&gt; &lt;Kind Is="interface"/&gt; &lt;HasAttribute CLRName="System.Runtime.InteropServices.InterfaceTypeAttribute"/&gt; &lt;/And&gt; &lt;HasAttribute CLRName="System.Runtime.InteropServices.StructLayoutAttribute"/&gt; &lt;/Or&gt; &lt;/Match&gt; &lt;/Pattern&gt; &lt;!--Special formatting of NUnit test fixture--&gt; &lt;Pattern RemoveAllRegions="true"&gt; &lt;Match&gt; &lt;And Weight="100"&gt; &lt;Kind Is="class"/&gt; &lt;HasAttribute CLRName="NUnit.Framework.TestFixtureAttribute" Inherit="true"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;!--Setup/Teardow--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And&gt; &lt;Kind Is="method"/&gt; &lt;Or&gt; &lt;HasAttribute CLRName="NUnit.Framework.SetUpAttribute" Inherit="true"/&gt; &lt;HasAttribute CLRName="NUnit.Framework.TearDownAttribute" Inherit="true"/&gt; &lt;HasAttribute CLRName="NUnit.Framework.FixtureSetUpAttribute" Inherit="true"/&gt; &lt;HasAttribute CLRName="NUnit.Framework.FixtureTearDownAttribute" Inherit="true"/&gt; &lt;/Or&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Group Region="Setup/Teardown"/&gt; &lt;/Entry&gt; &lt;!--All other members--&gt; &lt;Entry/&gt; &lt;!--Test methods--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And Weight="100"&gt; &lt;Kind Is="method"/&gt; &lt;HasAttribute CLRName="NUnit.Framework.TestAttribute" Inherit="false"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;/Entry&gt; &lt;/Pattern&gt; &lt;!--Default pattern--&gt; &lt;Pattern&gt; &lt;!--public delegate--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And Weight="100"&gt; &lt;Access Is="public"/&gt; &lt;Kind Is="delegate"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group Region="Delegates"/&gt; &lt;/Entry&gt; &lt;!--public enum--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And Weight="100"&gt; &lt;Access Is="public"/&gt; &lt;Kind Is="enum"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;Name Region="${Name} enum"/&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!--fields and constants--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;Or&gt; &lt;Kind Is="constant"/&gt; &lt;Kind Is="field"/&gt; &lt;/Or&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Kind Order="constant field"/&gt; &lt;Readonly/&gt; &lt;Static/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group Region="Fields"/&gt; &lt;/Entry&gt; &lt;!-- Events--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;Kind Is="event"/&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group Region="Events"/&gt; &lt;/Entry&gt; &lt;!--Constructors. Place static one first--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;Kind Is="constructor"/&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Static/&gt; &lt;/Sort&gt; &lt;Group Region="Constructors"/&gt; &lt;/Entry&gt; &lt;!--properties, indexers--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;Or&gt; &lt;Kind Is="property"/&gt; &lt;Kind Is="indexer"/&gt; &lt;/Or&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group Region="Properties"/&gt; &lt;/Entry&gt; &lt;!--interface implementations--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And Weight="100"&gt; &lt;Kind Is="member"/&gt; &lt;ImplementsInterface/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;ImplementsInterface Immediate="true"/&gt; &lt;Kind Order="property"/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;ImplementsInterface Immediate="true" Region="${ImplementsInterface} Members"/&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!-- public Methods --&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And&gt; &lt;Kind Is="method"/&gt; &lt;Access Is="public"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Static/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!-- internal Methods --&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And&gt; &lt;Kind Is="method"/&gt; &lt;Access Is="internal"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Static/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!--protected internal Methods --&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And&gt; &lt;Kind Is="method"/&gt; &lt;Access Is="protected-internal"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Static/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!-- protected Methods --&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And&gt; &lt;Kind Is="method"/&gt; &lt;Access Is="protected"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Static/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!-- private Methods --&gt; &lt;Entry&gt; &lt;Match&gt; &lt;And&gt; &lt;Kind Is="method"/&gt; &lt;Access Is="private"/&gt; &lt;/And&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Static/&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;!--all other members--&gt; &lt;Entry/&gt; &lt;!--nested types--&gt; &lt;Entry&gt; &lt;Match&gt; &lt;Kind Is="type"/&gt; &lt;/Match&gt; &lt;Sort&gt; &lt;Name/&gt; &lt;/Sort&gt; &lt;Group&gt; &lt;Name Region="Nested type: ${Name}"/&gt; &lt;/Group&gt; &lt;/Entry&gt; &lt;/Pattern&gt; &lt;/Patterns&gt; &lt;!-- I. Overall I.1 Each pattern can have &lt;Match&gt;....&lt;/Match&gt; element. For the given type declaration, the pattern with the match, evaluated to 'true' with the largest weight, will be used I.2 Each pattern consists of the sequence of &lt;Entry&gt;...&lt;/Entry&gt; elements. Type member declarations are distributed between entries I.3 If pattern has RemoveAllRegions="true" attribute, then all regions will be cleared prior to reordering. Otherwise, only auto-generated regions will be cleared I.4 The contents of each entry is sorted by given keys (First key is primary, next key is secondary, etc). Then the declarations are grouped and en-regioned by given property II. Available match operands Each operand may have Weight="..." attribute. This weight will be added to the match weight if the operand is evaluated to 'true'.The default weight is 1 II.1 Boolean functions: II.1.1 &lt;And&gt;....&lt;/And&gt; II.1.2 &lt;Or&gt;....&lt;/Or&gt; II.1.3 &lt;Not&gt;....&lt;/Not&gt; II.2 Operands II.2.1 &lt;Kind Is="..."/&gt;. Kinds are: class, struct, interface, enum, delegate, type, constructor, destructor, property, indexer, method, operator, field, constant, event, member II.2.2 &lt;Name Is="..." [IgnoreCase="true/false"] /&gt;. The 'Is' attribute contains regular expression II.2.3 &lt;HasAttribute CLRName="..." [Inherit="true/false"] /&gt;. The 'CLRName' attribute contains regular expression II.2.4 &lt;Access Is="..."/&gt;. The 'Is' values are: public, protected, internal, protected internal, private II.2.5 &lt;Static/&gt; II.2.6 &lt;Abstract/&gt; II.2.7 &lt;Virtual/&gt; II.2.8 &lt;Override/&gt; II.2.9 &lt;Sealed/&gt; II.2.10 &lt;Readonly/&gt; II.2.11 &lt;ImplementsInterface CLRName="..."/&gt;. The 'CLRName' attribute contains regular expression II.2.12 &lt;HandlesEvent /&gt; --&gt; </code></pre> <p>based on this one, that did not do the trick for me but who deserves the credit: <a href="http://www.clydesdalesoftware.net/blogs/jluif/CommentView,guid,1875594b-0d23-401f-8e22-f1cbf87beefe.aspx" rel="nofollow noreferrer">http://www.clydesdalesoftware.net/blogs/jluif/CommentView,guid,1875594b-0d23-401f-8e22-f1cbf87beefe.aspx</a></p> <p>This is a header snippet that complies to stylecop:</p> <pre><code>// &lt;copyright file="$FileName$" company="$Company$"&gt; // Copyright (c) 2008 All Right Reserved // &lt;/copyright&gt; // &lt;author&gt;$author$&lt;/author&gt; // &lt;email&gt;$email$&lt;/email&gt; // &lt;date&gt;$date$&lt;/date&gt; // &lt;summary&gt;$summary$&lt;/summary&gt; </code></pre> <p>Still not quite there but it is a start.</p> <p>Since this answer the Custom type member layout has been put in the StyleCop for resharper plugin. See <a href="http://1succeeded0failed0skipped.com/blogs/howardvanrooijen/archive/2008/12/07/stylecop-for-resharper-v0-0-14220-released.aspx" rel="nofollow noreferrer">here</a></p>
8,229
<p>I am writing a search application specifically for music playlists.</p> <p>The genre and file format differs from playlist to playlist, and sometimes within the playlist there are differences too. There is also a concept of "synonymous" tags (e.g. urban would cover both hiphop and r&amp;b, but not the other way around).</p> <p>Below is a list of search terms and my expected results.</p> <p>gospel: should return all playlists with at least one gospel song. playlists with all gospel songs would be shown first. urban: should return all r&amp;b and hiphop. again playlists with all urban tracks would come first. hiphop: should return all hiphop but not r&amp;b. flac: should return all playlists that contain flac files. starting with the ones that are pure flac. hiphop flac: should return hiphop flacs first, followed by other hiphop audio hiphop AND flac: should return hiphop flacs only hiphop audio: should return hiphop flacs, hiphop mp3s, etc</p> <p>As I'm just starting this project, I'm thinking of the best way to index all this. Would a fulltext search thing like Lucene be of any use here? Note I don't have any text describing these playlists, but I could generate some.</p> <p>I'm thinking of organising all these terms as "tags" and storing them in the db many-to-many.</p> <p>table: playlist ( pk(id), desc ) table: tag ( pk(id), desc ) table: playlist_has_tag ( pk(link_id, tag_id) )</p> <p>To solve the urban == hiphop || rnb thing, I would maybe add a tag_synonyms table:</p> <p>table: tag_synonyms ( pk(tag_id, synonym_tag_id) )</p> <p>Then I'd have two records to indicate that urban encompasses hiphop and rnb: urban's tag id, hiphop's tag id urban's tag id, rnb's tag id</p> <p>I'm feeling though that the query could be come quite convoluted using this approach.</p> <p>Could CouchDB be of use here? I'm currently using PostgreSQL. Is there some software out there that will make this kind of thing easy?</p> <p>I would like to be able to drill down and support complex search terms in the future like:</p> <p>(hiphop OR house) AND filetype:mp3 AND artwork:no</p> <p>And also incorporate things like duration, etc.</p>
<p>If you try to think too hard on how to structure your data for searching, there is a good chance you will miss an important search that you could have really used in your app. </p> <p>Alternatively (and this is from experience) you end up re-inventing all sorts of indexing techniques. </p> <p>I have some experience with lucene (there is java and .net version, there was a C port but I am not sure how alive it is these days) - and it can do amazing things with data that is stored in any structure.</p> <p>I like the look of couch db, just depends how much you want to experiment with something new and powerful, or go for something which is (currently) fairly battle hardened: lucene. </p>
<p>I don't see how database software would play a role in your solution.</p> <p>If I were to be the one implementing this, I would first ensure all related data is captured in a normalized way. This would include things like category, artwork, lyrics, etc. </p> <p>The main advantage of this is your idea of 'complex' searches actually become quite simple.</p>
22,452
<p>I want to pass an integer value to a form in .Net so that it can load the right data. I'm using this so that when I double click on a record in a list, a form opens with the data from that record loaded so it can be edited. What is the best way to do this? Should I create a property and set it before calling the Show() method, or should I overload the constructor or something and send the value in as an initialisation value that way?</p> <p>Note - this doesn't need to work with sending more than one value in to the form - only one value will be needed.</p> <p>It shouldn't really matter but this is in C++ .Net.</p>
<p>I'd suggest something else.</p> <p>create a static method (to the form you want to open) - pass the parameter to the static method. </p> <p>leave it up to the static method to new up the form, load the data and call the Show method.</p> <p>this way the calling form doesn't have to mess with the form to much (ctor, setting the value, calling show) - you keep this logic away and encapsulated in the form - which means you can also re-use it without copying the code.</p>
<p>Make it obligatory in the constructor. It wouldn't make sense to have one of these forms anyway if you don't have something to edit.</p>
40,337
<p>In coding a traditional MVC application, what is the best practice for coding server-side form validations? Does the code belong in the controller, or the model layer? And why?</p>
<p>From Wikipedia:</p> <blockquote> <p><a href="http://en.wikipedia.org/wiki/Model_View_Controller" rel="nofollow noreferrer">Model-view-controller</a> (MVC) is an architectural pattern used in software engineering. Successful use of the pattern isolates business logic from user interface considerations, resulting in an application where it is easier to modify either the visual appearance of the application or the underlying business rules without affecting the other. In MVC, the model represents the information (the data) of the application and the business rules used to manipulate the data; the view corresponds to elements of the user interface such as text, checkbox items, and so forth; and the controller manages details involving the communication to the model of user actions such as keystrokes and mouse movements.</p> </blockquote> <p>Thus, model - it holds the application and the business rules.</p>
<p>My experience with MVC thus far consists of entirely rails.</p> <p>Rails does it's validation 100% in the Model.<br> For the most part this works very well. I'd say 9 out of 10 times it's all you need.</p> <p>There are some areas however where what you're submitting from a form doesn't match up with your model properly. There may be some additional filtering/rearranging or so on.</p> <p>The best way to solve these situations I've found is to create faux-model objects, which basically act like Model objects but map 1-to-1 with the form data. These faux-model objects don't actually save anything, they're just a bucket for the data with validations attached.<br> An example of such a thing (in rails) is <a href="http://www.realityforge.org/articles/2005/12/02/validations-for-non-activerecord-model-objects" rel="nofollow noreferrer">ActiveForm</a></p> <p>Once the data gets into those (and is valid) it's usually a pretty simple step to transfer it directly across to your actual models.</p>
4,530
<p>This code is from <em>Prototype.js</em>. I've looked at probably 20 different tutorials, and I can't figure out why this is not working. The response I get is null.</p> <pre><code>new Ajax.Request(/path/to / xml / file.xml, { method: "get", contentType: "application/xml", onSuccess: function(transport) { alert(transport.responseXML); } }); </code></pre> <p>If I change the <code>responseXML</code> to <code>responseText</code>, then it alerts to me the XML file as a string. This is not a PHP page serving up XML, but an actual XML file, so I know it is not the response headers.</p>
<p>If transport.responseXML is null but you have a value for transport.responseText then I believe it's because it's not a valid XML file.</p> <p><strong>Edit:</strong> I just noticed that in our code here whenever we request an XML file we set the content type to 'text/xml'. I have no idea if that makes a difference or not.</p>
<p>Just want to share my afternoon working on the issue with a NULL result for <strong>responseXML</strong> responses. My results were exactly as described in the question: responseText was filled with the XML file, responseXML was NULL. As i was totally sure my file is in valid XML format, the error must be somewhere different.</p> <p>As mentioned in the <strong>Prototype v1.7</strong> documentation, i set the content type to <strong>"application/xml"</strong>. The response sent was constantly "text/html", no matter what. </p> <p>To make it short, the problem i ran into was, that my XML file had the ending <strong>".gpx"</strong> as it's a de facto standard for GPS coordinates. The mime-types collection of my local XAMPP Apache installation only foresees the endings "xml" and "xsl". After adding "gpx" and restarting the server the program ran smoothly as it's supposed to be.</p> <p>In my case, there are three solutions:</p> <p>1) edit the "mime.types" file of Apache. Using an XAMPP installation, you might find it under "C:\xampp\apache\conf\mime.types". Search for the "application/xml" record and change as follows:</p> <pre><code>application/xml xml xsl gpx </code></pre> <p>Don't forget to restart the server!</p> <p>2) add the mime type in a <strong>.htaccess</strong> of the appropriate folder. Open or create a .htaccess file and add following line:</p> <pre><code>AddType application/xml xml xsl gpx </code></pre> <p>3) during upload process, change file type to "xml" instead of whatever you have</p> <p>Hope i safe some time to one of you guys.</p>
7,824
<p>I have a problem in my project with the .designer which as everyone know is autogenerated and I ahvent changed at all. One day I was working fine, I did a back up and next day boom! the project suddenly stops working and sends a message that the designer cant procees a code line... and due to this I get more errores (2 in my case), I even had a back up from the day it was working and is useless too, I get the same error, I tryed in my laptop and the same problem comes. How can I delete the &quot;FitTrack&quot;? The incredible part is that while I was trying on the laptop the errors on the desktop were gone in front of my eyes, one and one second later the other one (but still have the warning from the designer and cant see the form), I closed and open it again and again I have the errors...</p> <p>The error is:</p> <pre><code>Warning 1 The designer cannot process the code at line 27: Me.CrystalReportViewer1.ReportSource = Me.CrystalReport11 The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. C:\Documents and Settings\Alan Cardero\Desktop\Reportes Liquidacion\Reportes Liquidacion\Reportes Liquidacion\Form1.Designer.vb 28 0 </code></pre>
<p>I would back up the designer.cs file associated with it (like copy it to the desktop), then edit the designer.cs file and remove the offending lines (keeping track of what they do) and then I'd try to redo those lines via the design mode of that form.</p>
<p>I do an easy way; Right Click on the report then choose Run Custom Tool.</p> <p>Automatically it fixes all problems and working for me, i solve 52 crystal ReportViewer errors.</p>
11,113
<p>I'm have written an msi file that offers a choice of "per-user" or "for all" installation in the UI phase, and now find that the installer fails on Vista:</p> <ul> <li>if I just reuse the installer that works for XP, Vista will trigger a UAC prompt even for the "per-user" installation, making that installation pointless</li> <li>if I turn off UAC in bit 3 of PID_WORDCOUNT, Vista won't invoke UAC at all anymore, so even if the user would have permission to install into the machine registry (say), the privilege raising doesn't happen, so the installation fails.</li> </ul> <p>So: how can I prevent installer from invoking UAC when it isn't really needed? Alternatively, how can I programmatically request UAC even if bit 3 is set?</p>
<p>Unfortunately, the Windows Installer does not provide a way to create a single package that can install per-machine and per-user but only prompt for UAC on the per-machine case. The issue is that the bit that can suppress the UAC prompt is stored in the SummaryInformation stream and is not modifiable while the package is executing.</p>
<p>I turned off UAC by setting the bit 3 of PID_WORDCOUNT in my MSI package. I can able to install it for "ALLUSERS" and "PER-USER", and also write in for HKLM in both the modes on VISTA machines. Is it mandatory for you to get UAC popup for privileged user during installation?</p>
31,508
<p>I know you can do a trick of putting an HTML element on top of a Silverlight app, but that will not work full screen. Is there anyway to show an html page inside a Silverlight application?</p>
<p>The answer is, you can't. At least right now you can't - in the future it might be added but that's certainly not going to occur for a number of years (2.0 RTW was released today).</p> <p>However, this link may be of some interest:</p> <p><a href="http://blogs.msdn.com/delay/archive/2007/09/10/bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/delay/archive/2007/09/10/bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy.aspx</a></p> <p>It basically parses some "HTML text" and displays it as it can in a text block. Works for simple stuff, but may not be as complex as you need.</p>
<p>The answer is, you can't. At least right now you can't - in the future it might be added but that's certainly not going to occur for a number of years (2.0 RTW was released today).</p> <p>However, this link may be of some interest:</p> <p><a href="http://blogs.msdn.com/delay/archive/2007/09/10/bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/delay/archive/2007/09/10/bringing-a-bit-of-html-to-silverlight-htmltextblock-makes-rich-text-display-easy.aspx</a></p> <p>It basically parses some "HTML text" and displays it as it can in a text block. Works for simple stuff, but may not be as complex as you need.</p>
24,741
<p>I'm trying to select a column from a single table (no joins) and I need the count of the number of rows, ideally before I begin retrieving the rows. I have come to two approaches that provide the information I need.</p> <p><strong>Approach 1:</strong></p> <pre><code>SELECT COUNT( my_table.my_col ) AS row_count FROM my_table WHERE my_table.foo = 'bar' </code></pre> <p>Then</p> <pre><code>SELECT my_table.my_col FROM my_table WHERE my_table.foo = 'bar' </code></pre> <p>Or <strong>Approach 2</strong></p> <pre><code>SELECT my_table.my_col, ( SELECT COUNT ( my_table.my_col ) FROM my_table WHERE my_table.foo = 'bar' ) AS row_count FROM my_table WHERE my_table.foo = 'bar' </code></pre> <p>I am doing this because my SQL driver (SQL Native Client 9.0) does not allow me to use SQLRowCount on a SELECT statement but I need to know the number of rows in my result in order to allocate an array before assigning information to it. The use of a dynamically allocated container is, unfortunately, not an option in this area of my program.</p> <p>I am concerned that the following scenario might occur:</p> <ul> <li>SELECT for count occurs</li> <li>Another instruction occurs, adding or removing a row</li> <li>SELECT for data occurs and suddenly the array is the wrong size.<br> -In the worse case, this will attempt to write data beyond the arrays limits and crash my program.</li> </ul> <p>Does Approach 2 prohibit this issue?</p> <p>Also, Will one of the two approaches be faster? If so, which?</p> <p>Finally, is there a better approach that I should consider (perhaps a way to instruct the driver to return the number of rows in a SELECT result using SQLRowCount?)</p> <p>For those that asked, I am using Native C++ with the aforementioned SQL driver (provided by Microsoft.)</p>
<p>There are only two ways to be 100% certain that the <code>COUNT(*)</code> and the actual query will give consistent results:</p> <ul> <li>Combined the <code>COUNT(*)</code> with the query, as in your Approach 2. I recommend the form you show in your example, not the correlated subquery form shown in the comment from kogus.</li> <li>Use two queries, as in your Approach 1, after starting a transaction in <code>SNAPSHOT</code> or <code>SERIALIZABLE</code> isolation level. </li> </ul> <p>Using one of those isolation levels is important because any other isolation level allows new rows created by other clients to become visible in your current transaction. Read the MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/ms173763.aspx" rel="noreferrer"><code>SET TRANSACTION ISOLATION</code></a> for more details.</p>
<p>Why don't you put your results into a vector? That way you don't have to know the size before hand.</p>
30,202
<p>If I create a test suite for a development project, should those classes be kept under version control with the rest of the project code?</p>
<p>Yes, there is no reason not to put them in source control. What if the tests change? What if the interfaces change, necessitating that the tests change?</p>
<p>Yes they should. People checking out the latest release should be able to unit test the code on their machine. This will help to identify missing dependencies and can also provide them with unofficial documentation on how the code works.</p>
14,041
<p>Running into a problem where on certain servers we get an error that the directory name is invalid when using Path.GetTempFileName. Further investigation shows that it is trying to write a file to c:\Documents and Setting\computername\aspnet\local settings\temp (found by using Path.GetTempPath). This folder exists so I'm assuming this must be a permissions issue with respect to the asp.net account. </p> <p>I've been told by some that Path.GetTempFileName should be pointing to C:\Windows\Microsoft.NET\Framework\v2.0.50727\temporaryasp.net files.</p> <p>I've also been told that this problem may be due to the order in which IIS and .NET where installed on the server. I've done the typical 'aspnet_regiis -i' and checked security on the folders etc. At this point I'm stuck.</p> <p>Can anyone shed some light on this?</p> <p>**Update:**Turns out that providing 'IUSR_ComputerName' access to the folder does the trick. Is that the correct procedure? I don't seem to recall doing that in the past, and obviously, want to follow best practices to maintain security. This is, after all, part of a file upload process.</p>
<p>This is probably a combination of impersonation and a mismatch of different authentication methods occurring.</p> <p>There are many pieces; I'll try to go over them one by one.</p> <p><strong>Impersonation</strong> is a technique to "temporarily" switch the user account under which a thread is running. Essentially, the thread briefly gains the same rights and access -- no more, no less -- as the account that is being impersonated. As soon as the thread is done creating the web page, it "reverts" back to the original account and gets ready for the next call. This technique is used to access resources that only the user logged into your web site has access to. Hold onto the concept for a minute.</p> <p>Now, by default ASP.NET runs a web site under a local account called <strong>ASPNET</strong>. Again, by default, only the ASPNET account and members of the Administrators group can write to that folder. Your temporary folder is under that account's purview. This is the second piece of the puzzle.</p> <p>Impersonation doesn't happen on its own. It needs to be turn on intentionally in your web.config.</p> <pre><code>&lt;identity impersonate="true" /&gt; </code></pre> <p>If the setting is missing or set to false, your code will execute pure and simply under the ASPNET account mentioned above. Given your error message, I'm positive that you have impersonation=true. There is nothing wrong with that! Impersonation has advantages and disadvantages that go beyond this discussion.</p> <p>There is one question left: when you use impersonation, <em>which account gets impersonated</em>?</p> <p>Unless you specify the account in the web.config (<a href="http://msdn.microsoft.com/en-us/library/72wdk8cc.aspx" rel="noreferrer">full syntax of the identity element here</a>), the account impersonated is the one that the IIS handed over to ASP.NET. And that depends on how the user has authenticated (or not) into the site. That is your third and final piece.</p> <p>The IUSR_ComputerName account is a low-rights account created by IIS. By default, this account is the account under which a web call runs <strong>if the user could not be authenticated</strong>. That is, the user comes in as an "anonymous".</p> <p>In summary, this is what is happening to you:</p> <p>Your user is trying to access the web site, and IIS could not authenticate the person for some reason. Because Anonymous access is ON, (or you would not see IUSRComputerName accessing the temp folder), IIS allows the user in anyway, but as a generic user. Your ASP.NET code runs and impersonates this generic IUSR___ComputerName "guest" account; only now the code doesn't have access to the things that the ASPNET account had access to, including its own temporary folder.</p> <p>Granting IUSR_ComputerName WRITE access to the folder makes your symptoms go away.</p> <p>But that just the symptoms. You need to review <strong>why is the person coming as "Anonymous/Guest"?</strong></p> <p>There are two likely scenarios:</p> <p>a) You intended to use IIS for authentication, but the authentication settings in IIS for some of your servers are wrong.</p> <p>In that case, you need to disable Anonymous access on those servers so that the usual authentication mechanisms take place. Note that you might still need to grant to your users access to that temporary folder, or use another folder instead, one to which your users already have access.</p> <p>I have worked with this scenario many times, and quite frankly it gives you less headaches to forgo the Temp folder; create a dedicated folder in the server, set the proper permissions, and set its location in web.config. </p> <p>b) You didn't want to authenticate people anyway, or you wanted to use ASP.NET Forms Authentication (which uses IIS's Anonymous access to bypass checks in IIS and lets ASP.NET handle the authentication directly)</p> <p>This case is a bit more complicated.</p> <p>You should go to IIS and disable all forms of authentication other than "Anonymous Access". Note that you can't do that in the developer's box, because the debugger needs Integrated Authentication to be enabled. So your debugging box will behave a bit different than the real server; just be aware of that.</p> <p>Then, you need to decide whether you should turn impersonation OFF, or conversely, to specify the account to impersonate in the web.config. Do the first if your web server doesn't need outside resources (like a database). Do the latter if your web site does need to run under an account that has access to a database (or some other outside resource).</p> <p>You have two more alternatives to specify the account to impersonate. One, you could go to IIS and change the "anonymous" account to be one with access to the resource instead of the one IIS manages for you. The second alternative is to stash the account and password encrypted in the registry. That step is a bit complicated and also goes beyond the scope of this discussion.</p> <p>Good luck!</p>
<p>You can use <strong>Path.GetTempPath()</strong> to find out which directory to which it's trying to write.</p>
7,916
<p>I want to discover at run-time ONLY the static Methods of a class, how can I do this? Or, how to differentiate between static and non-static methods.</p>
<p>Use <code>Modifier.isStatic(method.getModifiers())</code>.</p> <pre><code>/** * Returns the public static methods of a class or interface, * including those declared in super classes and interfaces. */ public static List&lt;Method&gt; getStaticMethods(Class&lt;?&gt; clazz) { List&lt;Method&gt; methods = new ArrayList&lt;Method&gt;(); for (Method method : clazz.getMethods()) { if (Modifier.isStatic(method.getModifiers())) { methods.add(method); } } return Collections.unmodifiableList(methods); } </code></pre> <p>Note: This method is actually dangerous from a security standpoint. Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (see section 6 of the Java secure coding guidelines).</p> <p>Disclaimer: Not tested or even compiled.</p> <p>Note <code>Modifier</code> should be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.</p>
<p>To flesh out the previous (correct) answer, here is a full code snippet which does what you want (exceptions ignored):</p> <pre><code>public Method[] getStatics(Class&lt;?&gt; c) { Method[] all = c.getDeclaredMethods() List&lt;Method&gt; back = new ArrayList&lt;Method&gt;(); for (Method m : all) { if (Modifier.isStatic(m.getModifiers())) { back.add(m); } } return back.toArray(new Method[back.size()]); } </code></pre>
36,600
<p>Once again a very beginner-ish question, but here I go:</p> <p>I would like to use a servlet or similar to copy an uploaded file (from an html file select) to a permanent location. This is all I need to do with the file. I am currently going with using the Apache Commons FileUpload and IO libraries. Is there no easier or more elegant solution?</p>
<p>The Apache commons FileUpload is probably the best way if you are using pure JSP and servlets. If you use a framework like struts2 you will have some more options since they have file upload components built in and are very easy to use. </p>
<p>The Servlet API has no way to extract the file from the POST (PUT?) data. </p> <p>Just like Vincent said, Apache commons FileUpload is the best free way to do this.</p> <p>You might also consider using a signed applet if you don't want to use the Apache libs.</p>
27,101
<p>Lets say you need to attach some JavaScript functionality to an ASP.NET User Control of which there might be multiple instances on any given page. Because JavaScript has shared global state, what techniques can you use to keep the client state and behavior for each instance of a control separate?</p>
<p>Well, the main thing you can do is make sure your JavaScript functions are abstract enough that they are not coupled to specific instances of HTML controls - have them accept parameters that allow you to pass various instances of objects in. </p> <p>The JavaScript that does whatever magic you need to be done should only exist once in your page regardless of how many instances of a user control you have on a given page, thus your functions need to be ignorant of that fact.</p> <p>Without more information about what you are trying to do, there is little more I can offer in the way of help; it would depend on your circumstance.</p> <hr> <p>EDIT: One way I have dealt with particular aspects of this problem is to create a static property on the user control (thus it is the same variable across multiple instances) that tracks the client-side IDs of the various user control elements (the user control adds the client IDs to this list in the <strong><em>control's</em></strong> OnLoad event); then, in the <strong><em>page's</em></strong> OnPreRender event (IIRC), render those out in a JavaScript variable that my code knows to look for on the client and operate on. I don't know if that makes sense, but it might help someone...</p>
<pre><code>function &lt;%=this.ClientID %&gt;_myButton_onclick() { DoSomething(); } </code></pre> <p>and</p> <pre><code>&lt;button id="myButton" onclick="&lt;%=this.ClientID %&gt;_myButton_onclick()"&gt; </code></pre> <p>Notice in this case the control is a regular HTML control.</p>
43,064
<p>Is <a href="http://bouncycastle.org/java.html" rel="nofollow noreferrer">Bouncy Castle API</a> Thread Safe ? Especially,</p> <pre><code>org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher org.bouncycastle.crypto.paddings.PKCS7Padding org.bouncycastle.crypto.engines.AESFastEngine org.bouncycastle.crypto.modes.CBCBlockCipher </code></pre> <p>I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.</p> <p>Please let me know if you have come across such situations using Bouncy Castle.</p>
<p>It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe. Some terminology -</p> <pre><code>E(X) = Enctrypt message X D(X) = Dectrypt X. (Note that D(E(X)) = X) IV = Initialization vector. A random sequence to bootstrap the CBC algorithm CBC = Cipher block chaining. </code></pre> <p>A really simple CBC implementation can look like: P1, P2, P3 = Plain text messages</p> <pre><code>1. Generate an IV, just random bits. 2. Calculate E( P1 xor IV) call this C1 3. Calculate E( P2 xor C1) call this C2 4. Calculate E( P3 xor C2) call this C3. </code></pre> <p>As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order). </p> <p>So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe. </p> <p>You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. </p>
<p>The J2ME version is not thread safe.</p>
7,208
<p>I have a network C++ program in Windows that I'd like to test for network disconnects at various times. What are my options?</p> <p>Currently I am:</p> <ol> <li>Actually disconnecting the network wire from the back of my computer</li> <li>using ipconfig /release</li> <li>Using the <a href="http://www.nirsoft.net/utils/cports.html" rel="nofollow noreferrer">cports</a> program to close out the socket completely</li> </ol> <p>None of these methods though are ideal for me, and I'd like to emulate network problems more easily. </p> <p>I would like for sometimes connects to fail, sometimes socket reads to fail, and sometimes socket writes to fail. It would be great if there was some utility I could use to emulate these types of problems.</p> <p>It would also be nice to be able to build some automated unit tests while this emulated bad network is up.</p>
<p>You might want to abstract the network layer, and then you can have unit tests that inject interesting failure events at appropriate points.</p>
<p>You can subclass whatever library class you are using to manage your sockets (presumably CAsyncSocket or CSocket if you are using MFC), override the methods whose failure you want to test, and insert appropriate test code in your overrides.</p>
8,677
<p>How would I write a Perl CGI script that receives a file via a HTTP post and saves that to the file system?</p>
<p>Just a note: however you will write it, <strong>don't</strong> save it in a place accessible from your web-server.</p> <p>And now to the point: below is a script which I was using for some time for photo-uploading. It might need some tweaking, but should show you the way.</p> <p>As the image isnt uploaded to web-accesible directory, we then have separate process checking it, resizing, putting a watermark and placing it where it can be accessed.</p> <pre><code> #!/usr/bin/perl -wT use strict; use CGI; use CGI::Carp qw ( fatalsToBrowser ); use File::Basename; $CGI::POST_MAX = 1024 * 5000; my $safe_filename_characters = "a-zA-Z0-9_.-"; my $upload_dir = "/home/www/upload"; my $query = new CGI; my $filename = $query-&gt;param("photo"); my $email_address = $query-&gt;param("email_address"); if ( !$filename ) { print $query-&gt;header ( ); print "There was a problem uploading your photo (try a smaller file)."; exit; } my ( $name, $path, $extension ) = fileparse ( $filename, '\..*' ); $filename = $name . $extension; $filename =~ tr/ /_/; $filename =~ s/[^$safe_filename_characters]//g; if ( $filename =~ /^([$safe_filename_characters]+)$/ ) { $filename = $1; } else { die "Filename contains invalid characters"; } my $upload_filehandle = $query-&gt;upload("photo"); open ( UPLOADFILE, "&gt;$upload_dir/$filename" ) or die "$!"; binmode UPLOADFILE; while ( &lt;$upload_filehandle&gt; ) { print UPLOADFILE; } close UPLOADFILE; print $query-&gt;header ( ); print &lt;&lt;END_HTML; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Thanks!&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;Thanks for uploading your photo!&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; END_HTML </code></pre>
<p>I'd start by using <a href="http://search.cpan.org/dist/CGI" rel="nofollow noreferrer">CGI</a> and reading <a href="http://search.cpan.org/perldoc/CGI#CREATING_A_FILE_UPLOAD_FIELD" rel="nofollow noreferrer">CREATING A FILE UPLOAD FIELD</a>, and using <a href="http://perldoc.perl.org/functions/open.html" rel="nofollow noreferrer">open</a> to create a file and <a href="http://perldoc.perl.org/functions/print.html" rel="nofollow noreferrer">print</a> to write to it. (and then <a href="http://perldoc.perl.org/functions/close.html" rel="nofollow noreferrer">close</a> to close it).</p>
19,670
<p>I've switched over to a Mac recently and, although things have been going quite well, the very different text-editing behaviours across applications is driving me insane.</p> <p><kbd>Home</kbd>, <kbd>End</kbd>, <kbd>Page Up</kbd>, <kbd>Page Down</kbd>, <kbd>Apple-arrow</kbd>, <kbd>Ctrl-arrow</kbd>, <kbd>alt-arrow</kbd> etc. quite often do different things depending on the application.</p> <p>Is there a way to standardise this behaviour?</p>
<p>There are standards, but they are not based around what you're used to from windows. It drove me mad until I got over myself and decided to learn what the actual standards were. Since then I've been sold.</p> <p>The ones I use:</p> <ul> <li><kbd>Command</kbd>-<kbd>Left</kbd>/<kbd>Right</kbd> - Jump to start/end of line <ul> <li>Can also do this with <kbd>ctrl</kbd>-<kbd>a</kbd>/<kbd>e</kbd> which is great if you're used to ssh</li> </ul></li> <li><p><kbd>Command</kbd>-<kbd>Up</kbd>/<kbd>Down</kbd> - Jump to top/bottom of text field or document</p></li> <li><p><kbd>Option</kbd>-<kbd>Left</kbd>/<kbd>Right</kbd> - Jump to start/end of word or previous/next word</p></li> </ul> <p>These basically replace <kbd>home</kbd>/<kbd>end</kbd>/<kbd>pgup</kbd>/<kbd>pgdown</kbd>, and <kbd>ctrl</kbd>-<kbd>left</kbd>/<kbd>right</kbd> from the windows world.</p> <p>I find this to be a massive win due to the fact I have a macbook pro and almost no laptops have proper <kbd>home</kbd>/<kbd>end</kbd>/<kbd>pgup</kbd>/<kbd>pgdown</kbd> keys - not needing them in OSX is a godsend</p> <p><a href="http://www.hcs.harvard.edu/~jrus/Site/System%20Bindings.html" rel="nofollow noreferrer">Here's a big list of the rest of them</a></p>
<p>And what's funny (and frustrating!) is that the Microsoft <strong>OS X</strong> apps (e.g. Entourage) use the <strong>Windows</strong> standards.</p> <p>I develop on WinXP during the day but have an iMac at home, so it's confusing enough trying to switch modes between work and home. But then I have to remember if I'm writing an e-mail in Entourage, I need to revert back to Windows mode.</p> <p>I can't think of any good reason why MS wouldn't follow the OS X keyboard standards...</p>
5,413
<p>So, I can create an input button with an image using</p> <pre><code>&lt;INPUT type=&quot;image&quot; src=&quot;/images/Btn.PNG&quot; value=&quot;&quot;&gt; </code></pre> <p>But, I can't get the same behavior using CSS. For instance, I've tried</p> <pre><code>&lt;INPUT type=&quot;image&quot; class=&quot;myButton&quot; value=&quot;&quot;&gt; </code></pre> <p>where &quot;myButton&quot; is defined in the CSS file as</p> <pre><code>.myButton { background:url(/images/Btn.PNG) no-repeat; cursor:pointer; width: 200px; height: 100px; border: none; } </code></pre> <p>If that's all I wanted to do, I could use the original style, but I want to change the button's appearance on hover (using a <code>myButton:hover</code> class). I know the links are good, because I've been able to load them for a background image for other parts of the page (just as a check). I found examples on the web of how to do it using JavaScript, but I'm looking for a CSS solution.</p> <p>I'm using Firefox 3.0.3 if that makes a difference.</p>
<p>If you're wanting to style the button using CSS, make it a type="submit" button instead of type="image". type="image" expects a SRC, which you can't set in CSS.</p> <p>Note that Safari won't let you style any button in the manner you're looking for. If you need Safari support, you'll need to place an image and have an onclick function that submits the form.</p>
<p>Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.</p>
23,768
<p>I have a script for OS X 10.5 that focuses the Search box in the Help menu of any application. I have it on a key combination and, much like Spotlight, I want it to toggle when I run the script. So, I want to detect if the search box is already focused for typing, and if so, type Esc instead of clicking the Help menu.</p> <p>Here is the script as it stands now:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 click helpMenuItem end tell end tell </code></pre> <p>And I'm thinking of something like this:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 set searchBox to menu item 1 of menu of helpMenuItem if (searchBox's focused) = true then key code 53 -- type esc else click helpMenuItem end if end tell end tell </code></pre> <p>... but I get this error:</p> <blockquote> <p>Can’t get focused of {menu item 1 of menu "Help" of menu bar item "Help" of menu bar 1 of application process "Script Editor" of application "System Events"}.</p> </blockquote> <p>So is there a way I can get my script to detect whether the search box is already focused?</p> <hr> <p>I solved my problem by <a href="https://stackoverflow.com/questions/69391/">working around it</a>. I still don't know how to check if a menu item is selected though, so I will leave this topic open.</p>
<p>Using /Developer/Applications/Utilities/Accessibility Tools/Accessibility Inspector.app you can use the built-in accessibility system to look at properties of the UI element under the mouse. Take special note of the cmd-F7 action to lock focus on an element and the Refresh button. Sadly the element and property names don't directly match those in the script suite, but you can look at the dictionary for System Events or usually guess the right terminology.</p> <p>Using this you can determine two things. First, the <code>focused</code> property isn't on the <code>menu item</code>, but rather there is a <code>text field</code> within the <code>menu item</code> that is focused. Second, the menu item has a <code>selected</code> property.</p> <p>With this, I came up with:</p> <pre><code>tell application "System Events" tell (first process whose frontmost is true) set helpMenuItem to menu bar item "Help" of menu bar 1 -- Use reference form to avoid building intermediate object specifiers, which Accessibility apparently isn't good at resolving after the fact. set searchBox to a reference to menu item 1 of menu of helpMenuItem set searchField to a reference to text field 1 of searchBox if searchField's focused is true then key code 53 -- type esc else click helpMenuItem end if end tell end tell </code></pre> <p>Though this still doesn't work. The key event isn't firing as far as I can tell, so something may still be hinky with the <code>focused</code> property on the text field.</p> <p>Anyway, your <code>click</code> again solution seems much easier.</p>
<p>This worked for me to toggle between two menu items, based on which one is selected, using the &quot;selected&quot; property:</p> <pre><code>tell application &quot;System Preferences&quot; reveal anchor &quot;keyboardTab&quot; of pane &quot;com.apple.preference.keyboard&quot; end tell tell application &quot;System Events&quot; to tell process &quot;System Preferences&quot; tell pop up button 2 of tab group 1 of window 1 click delay 0.2 set appControl to menu item &quot;App Controls&quot; of menu 1 set fKeys to menu item &quot;F1, F2, etc. Keys&quot; of menu 1 if selected of appControl is true then click fKeys else click appControl end if end tell end tell </code></pre>
9,448
<p>I find way too many projects to get involved in, way to many languages to play with (and way too many cool features within those languages), and way too many books to read...</p> <p>How do you guys stay focused and actually get anything done, rather than leaving a trail of partially complete "experiments?"</p>
<p>Seems like there are two types of developers: Tinkerers and Entrepreneurs. </p> <p>Tinkerers want to know how every little thing works. Once they get the hang of something, they're distracted by everything they don't know. The tech world is brutal for a Tinkerer because there's so much to learn and each new year creates more. Tinkerers are proud of their knowledge.</p> <p>Entrepreneurs want to know enough to build something really great. They think in terms of features and end-user experiences. You never hear them argue about Python over .NET over Java over C because they just don't care. They're more interested in the result of a language versus the language itself. Entrepreneurs are proud of their user-base.</p> <p>Sounds like you're struggling with your Tinkerer tendencies. I've got the same problem and have found only one thing that helps - find an Entrepreneur developer that you thoroughly respect. When you put the two together, it's unbeatable. The Tinkerer plumbs the depth of every technical nuance. They keep the Entrepreneur technically honest. In turn, the Entrepreneur creates focus and opportunity for the Tinkerer. When they catch you browsing the Scala site (assuming you're not a Scala developer), they reveal a new challenge in your existing project. Not only that, they're much better at understanding what non-Tinkerers want.</p>
<p>1) I leave a utterly MASIVE trail of unfinished stuff, all side projects of course.<br /> 2) When I need motivation to work I open my wallet... That usually does it for me.</p>
20,860
<p>I cannot get my extruder to work on my Creality Ender-4 printer. I have heated the nozzle but the extruder does not move.</p> <p>I tested the motor and cable on another system and they work just fine.</p> <p>Could it be the board or what could it be?</p>
<p>Most filaments you can leave in the extruder indefinitely without any ill effects.</p> <p>There are some filaments that need to be stored away from moisture, particularly Nylon, because they absorb moisture from the air and don't print well if they contain a lot of absorbed moisture. However, this isn't an inherent issue with having the filaments in the extruder (if you had some setup that protected the filament from moisture while in the extruder, that would be fine as well - but in most cases it is more practical to store such filament in an airtight box). </p> <p>Most commodity filaments (ABS/PLA/PETG) don't suffer from this as much (PLA supposedly also absorbs moisture but I haven't noticed this to be a problem, perhaps it depends on the conditions of the room in which your printer is kept) so they're fine to leave in the extruder.</p>
<p>If you "planing" to leave the filament there for months, then it would be a good idea to store it away, but for most filaments it is not a big deal to be stay loaded... provided that the humidity is not high (e.g. a shower or kitchen next to it would be not so good). </p> <p>My experiences with "moistured" filament is that they get brittle, but only breaks when I don't print something. And it is a pain in the a** to get out the last part of the filament that broke right at the entrance... so store it away is always a good idea, if you are not too lazy ;) </p>
929
<p>Castle Active Record? Plain NHibernate? Subsonic? Entity? Something like Nettiers?</p> <p>I'd like to use one, but I don't know enough to decide. Nhibernate seems over kill and complex, but widely used. Subsonic seems neat and easy. But is it stable? I have CodeSmith, and I was pointed to Nettiers, which seems neat as well, but complex too. How do others evaluate and decide what to use? Do you make small simple projects with each to see the features? Eeeny, Meenie, Miney, Moe? </p>
<p>I like NHibernate. It's actually not that complicated, it's surprisingly flexible and it doesn't pollute your object model with attributes and other funky stuff that shouldn't be there.</p> <p>I find that the active record pattern doesn't fit that well into a statically typed language like C# as much as the domain pattern does, as it can make mocking more complicated.</p>
<p>Since the question is "how do I pick" and not "what should I pick"...:</p> <p>I'd pick the one that seems easiest to use first. Then I'd research a bit on google to see if it seems stable. Then I'd stress-test it myself, with some multithreaded goodness and a domain structure that has different types of relations and inheritance.</p> <p>You can also get inspired by <a href="http://polepos.sourceforge.net/" rel="nofollow noreferrer">http://polepos.sourceforge.net/</a> it's a database performance benchmark but mostly for the java frameworks. If you're up for it you can adapt the source code to .net, it's not horribly complex.</p> <p>That said, my current favourites are ActiveRecord and LINQ.</p>
32,849
<p>Flex uses by default UTF-8. I have not fount a way to specify a different encoding/charset on the actionscript WebService class.</p>
<p>Ummm, look here:</p> <p><a href="http://www.adobe.com/devnet/flex/articles/struts_06.html" rel="nofollow noreferrer">http://www.adobe.com/devnet/flex/articles/struts_06.html</a></p> <p>I think that sample implies that declaring your mxml file as iso-8859-1 might do the trick, but I really don't think so.</p> <p>I might be wrong but as far as I know the Flash player only handles UTF-8 encoding. I've searched for a link to an official page saying so, but couldn't find it.</p> <p>If that's the case you either:</p> <p>a) update the webservice to handle UTF-8 encoding</p> <p>b) if that's not possible, proxy your call to your own webservice that accepts UTF-8 and then call the actual one.</p> <p>You might want to give a go to the old system.useCodepage=true trick BUT that didn't use to work when the user was on Linux or Mac, USE WITH CARE!</p>
<p>There is also a way to specify an encoding to the flex compiler but that does not seem to work. Right now the only solution I have found is to re-encode the incomming requests on the server side. I am surprised this limitation is not written black on white in the flex reference documentation.</p>
10,243
<p>What is the best way to replace all '&amp;lt' with <code>&amp;lt;</code> in a given database column? Basically perform <code>s/&amp;lt[^;]/&amp;lt;/gi</code></p> <p>Notes:</p> <ul> <li>must work in <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server#SQL_Server_2005" rel="noreferrer">MS SQL Server</a> 2000</li> <li>Must be repeatable (and not end up with <code>&amp;lt;;;;;;;;;;</code>)</li> </ul>
<p>Some hacking required but we can do this with <strong>LIKE</strong>, <strong>PATINDEX</strong>, <strong>LEFT</strong> AND <strong>RIGHT</strong> and good old string concatenation.</p> <pre><code>create table test ( id int identity(1, 1) not null, val varchar(25) not null ) insert into test values ('&amp;lt; &lt;- ok, &amp;lt &lt;- nok') while 1 = 1 begin update test set val = left(val, patindex('%&amp;lt[^;]%', val) - 1) + '&amp;lt;' + right(val, len(val) - patindex('%&amp;lt[^;]%', val) - 2) from test where val like '%&amp;lt[^;]%' IF @@ROWCOUNT = 0 BREAK end select * from test </code></pre> <p>Better is that this is SQL Server version agnostic and should work just fine.</p>
<p>If MSSQL's regex flavor supports negative lookahead, that would be The Right Way to approach this.</p> <pre><code>s/&amp;lt(?!;)/&amp;lt;/gi </code></pre> <p>will catch all instances of <strong>&amp;lt</strong> which are not followed by a <strong>;</strong> (even if they're followed by nothing, which <strong>[^;]</strong> would miss) and does not capture the following non-<strong>;</strong> character as part of the match, eliminating the issue mentioned in the comments on the original question of that character being lost in the replacement.</p> <p>Unfortunately, I don't use MSSQL, so I have no idea whether it supports negative lookahead or not...</p>
18,201
<p>Suppose I have a base class B, and a derived class D. I wish to have a method foo() within my base class that returns a new object of whatever type the instance is. So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation resides solely in the base class B.</p> <p>Is this possible?</p>
<p>Don't. Make the "foo" method abstract.</p> <pre><code>abstract class B { public abstract B foo(); } </code></pre> <p>Or receive an abstract factory through the base class constructor:</p> <pre><code>abstract class B { private final BFactory factory; protected B(BFactory factory) { this.factory = factory; } public B foo() { return factory.create(); } } interface BFactory { B create(); } </code></pre> <p>Add covariant return types and generics to taste.</p>
<p>@Rik</p> <p>Well, the real problem is that I have a abstract base class Thing. And Thing has a method called getNextThing() which returns a new instance of Thing.</p> <p>Then, I have a number of subclasses like BigThing, LittleThing, SomethingThing, and I don't want to keep rewriting the getNextThing() method for each of them. It seems wasteful, since they all do the same... thing.</p> <p>Am I incorrect in my approach?</p>
20,147
<p>When you create a procedure (or a function) in Oracle PL/SQL, you cannot specify the maximum length of the varchar2 arguments, only the datatype. For example</p> <pre><code>create or replace procedure testproc(arg1 in varchar2) is begin null; end; </code></pre> <p>Do you know the maximum length of a string that you can pass as the arg1 argument to this procedure in Oracle ?</p>
<p>In PL/SQL procedure it may be up to 32KB</p> <p>Futher information here: <a href="http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804" rel="noreferrer">http://it.toolbox.com/blogs/oracle-guide/learn-oracle-sql-and-plsql-datatypes-strings-10804</a></p>
<p>In PL/SQL the maximum size of <code>VARCHAR2</code> datatype is <strong>32767 bytes</strong> since 10gR2 (and probably earlier but I just checked the documentation upto that release).</p> <p>The documentation references:</p> <ul> <li>Oracle 12cR1: <a href="http://docs.oracle.com/cd/E16655_01/appdev.121/e17622/datatypes.htm#LNPLS99943" rel="nofollow">PL/SQL Language Reference 12c Release 1</a></li> <li>Oracle 11gR2: <a href="http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/datatypes.htm#LNPLS99943" rel="nofollow">PL/SQL Language Reference 11g Release 2</a></li> <li>Oracle 10gR2: <a href="http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/datatypes.htm#sthref732" rel="nofollow">PL/SQL User's Guide and Reference 10g Release 2</a></li> </ul>
22,551
<p>I have a site on my webhotel I would like to run some scheduled tasks on. What methods of achieving this would you recommend?</p> <p>What I’ve thought out so far is having a script included in the top of every page and then let this script check whether it’s time to run this job or not.</p> <p>This is just a quick example of what I was thinking about:</p> <pre><code>if ($alreadyDone == 0 &amp;&amp; time() &gt; $timeToRunMaintainance) { runTask(); $timeToRunMaintainance = time() + $interval; } </code></pre> <p>Anything else I should take into consideration or is there a better method than this?</p>
<p>That's what cronjobs are made for. <code>man crontab</code> assuming you are running a linux server. If you don't have shell access or no way to setup cronjobs, there are free services that setup cronjobs on external servers and ping one of your URLs.</p>
<p>Command line PHP + cron would be the way I would go. It's simple and should fit the bill. It is usually installed with PHP as a matter of course.</p>
14,624
<p>If I am setting up a site how would I go about ensuring that the person who gives me a credit card number (for instance) is the person who is authorized to use it? Maybe more generally how would I go about reducing the opportunity for fraud and stolen ID usage whether it be for a purchase or system access. </p> <p>I don't work in this field (online purchases) but I would think that authentication of a user has to be a very hard/tricky endeavor. </p>
<p>I would say just stick with the industry standard methods.</p> <p>Someone is assumed to have posession of the card if they can supply information which verifies with the card payment gateway. As part of that, for example is the <a href="http://www.advansys.com/default.asp/p=87" rel="nofollow noreferrer">Mastercard/VISA 3D auth</a> scheme which adds a passphrase to online payments.</p> <p>You could try and go further than this <a href="http://en.wikipedia.org/wiki/Two-factor_authentication" rel="nofollow noreferrer">2-factor authentication</a> with fraud prevention, but the credit card companies have more of a vested interest in it so just follow their lead.</p>
<p>Another common method is the <a href="http://en.wikipedia.org/wiki/Address_Verification_System" rel="nofollow noreferrer">address verification system</a>, used by lots of online vendors. </p>
47,729
<p>This is the way I read file:</p> <pre><code> public static string readFile(string path) { StringBuilder stringFromFile = new StringBuilder(); StreamReader SR; string S; SR = File.OpenText(path); S = SR.ReadLine(); while (S != null) { stringFromFile.Append(SR.ReadLine()); } SR.Close(); return stringFromFile.ToString(); } </code></pre> <p>The problem is it so long (the .txt file is about 2.5 megs). Took over 5 minutes. Is there a better way?</p> <p><strong>Solution taken</strong></p> <pre><code> public static string readFile(string path) { return File.ReadAllText(path); } </code></pre> <p>Took less than 1 second... :)</p>
<p>Leaving aside the horrible variable names and the lack of a using statement (you won't close the file if there are any exceptions) that should be okay, and <em>certainly</em> shouldn't take 5 minutes to read 2.5 megs.</p> <p>Where does the file live? Is it on a flaky network share?</p> <p>By the way, the only difference between what you're doing and using File.ReadAllText is that you're losing line breaks. Is this deliberate? How long does ReadAllText take?</p>
<p>To read a text file fastest you can use something like this</p> <pre><code>public static string ReadFileAndFetchStringInSingleLine(string file) { StringBuilder sb; try { sb = new StringBuilder(); using (FileStream fs = File.Open(file, FileMode.Open)) { using (BufferedStream bs = new BufferedStream(fs)) { using (StreamReader sr = new StreamReader(bs)) { string str; while ((str = sr.ReadLine()) != null) { sb.Append(str); } } } } return sb.ToString(); } catch (Exception ex) { return ""; } } </code></pre> <p>Hope this will help you. and for more info, please visit to the following link- <a href="http://cc.davelozinski.com/c-sharp/fastest-way-to-read-text-files" rel="nofollow">Fastest Way to Read Text Files</a></p>
26,065
<p>Because windows is case-insensitive and because SVN is case-sensitive and because VS2005 tends to rename files giving them the lower-case form which messes my repositories' history, I've tried to add the pre-commit hook script from <a href="http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py" rel="nofollow noreferrer">http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/case-insensitive.py</a>. Sure enough, the script uses classes from python's libsvn ("from svn import repos, fs") which I fail to find compiled for Windows. Is there an alternative? To libsvn or to the hook script?</p>
<p>The Tigris.org's pre-complied python bindings for libsvn are a separate download. The latest as of Oct 27 could be found <a href="http://subversion.tigris.org/files/documents/15/44104/svn-win32-1.5.4_py25.zip" rel="nofollow noreferrer">here</a>.</p> <p>There are other binary SVN distributions listed <a href="http://subversion.tigris.org/getting.html#windows" rel="nofollow noreferrer">here</a>, and they probably have different policy for bundling the python bindings.</p>
<p>There are two alternative Python bindings for libsvn:</p> <ul> <li><a href="http://pysvn.tigris.org/" rel="nofollow noreferrer">pysvn</a>.</li> <li><a href="https://launchpad.net/subvertpy" rel="nofollow noreferrer">subvertpy</a>. </li> </ul> <p>Subvertpy is quite new and is written by the author of <a href="http://bazaar-vcs.org/BzrForeignBranches/Subversion" rel="nofollow noreferrer">bzr-svn</a>: the transparent <a href="http://subversion.apache.org/" rel="nofollow noreferrer">svn</a> inter-operation bridge for <a href="http://bazaar-vcs.org/" rel="nofollow noreferrer">bzr</a>.</p> <p>For a while, bzr-svn used the upstream <a href="http://www.swig.org/" rel="nofollow noreferrer">SWIG</a> Python bindings, and the author contributed a lot of bug fixes. It helped move the upstream python support for "horribly broken" to "painfully aggravating and unpythonic". So after wasting too many hours of his life to SWIG, the author decided to make his own bindings.</p>
29,457
<p>I have looked at NHibernate and EntitySpaces and they both seem to work differently.</p> <p>In EntitySpaces, you define the database tables and table relationships and the classes are generated for you.</p> <p>In NHibernate, you define the classes and the table relationships are generated for you. This is what I am looking for.</p> <p>Are there any other ASP.NET ORMs that generate tables from classes like NHibernate? Any recommendations?</p>
<p>Linq to SQL can create the database table structures and relationships from the classes, with the <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.createdatabase.aspx" rel="nofollow noreferrer">dataContext.CreateDatabase()</a> method.</p>
<p>I had fairly good success working with Genome ORM. It does many jobs for you. You can first design your domain model and then generate the DB scripts out of that. Beside this Genome generates DTOs for you. It is pretty good at that and saves a lot of time of developers.</p> <p><a href="http://www.genom-e.com" rel="nofollow noreferrer">http://www.genom-e.com</a></p>
49,333
<p>I am using OpenOffice.org for most of my not so very frequent Office Suite needs and most of the time it is more than adequate replacement for it's commercial alternative.</p> <p>Where it falls short though is the scripting API. I am yet to find the documentation that would make sense of the API in a way that would let me concentrate on my task at hand instead of wandering how to select a piece of text in an opened document.</p> <p>So - is there a good documentation for getting programmers like me, who do not exactly live and breathe the UNO object model, quickly started and explain in few pages or less, how to find stuff that I need in the OO.o API</p>
<p>If you're specifically talking about working with text documents, that section of the OO.org Dev Guide really is the way to go:</p> <p><a href="http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Text/Working_with_Text_Documents" rel="noreferrer">http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Text/Working_with_Text_Documents</a></p> <p>Note that the document navigation is on the right side, and kind of small. There's similar entry points for Spreadsheets:</p> <p><a href="http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Working_With_Spreadsheet_Documents" rel="noreferrer">http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Spreadsheets/Working_With_Spreadsheet_Documents</a></p> <p>And for drawing documents:</p> <p><a href="http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Drawings/Working_with_Drawing_Documents" rel="noreferrer">http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Drawings/Working_with_Drawing_Documents</a></p> <p>I think this is the kind of general "cheatsheet" reference you're looking for and I don't think there's any better source for it.</p>
<p>I would start with the <a href="http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/OpenOffice.org_Developers_Guide" rel="nofollow noreferrer">OpenOffice.org Developer's Guide</a></p>
32,667
<p>I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'.</p> <ul> <li>What is it?</li> <li>What does it do for me?</li> <li>Why should I use it?</li> <li>When should I use it (also when not)?</li> <li>What are some common pitfalls and misconceptions</li> </ul>
<p>Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:</p> <ul> <li>Running the tests becomes automate-able and repeatable</li> <li>You can test at a much more granular level than point-and-click testing via a GUI</li> </ul> <p>Note that if your test code writes to a file, opens a database connection or does something over the network, it's more appropriately categorized as an integration test. Integration tests are a good thing, but should not be confused with unit tests. Unit test code should be short, sweet and quick to execute.</p> <p>Another way to look at unit testing is that you write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages:</p> <ul> <li>You don't write speculative "I might need this in the future" code -- just enough to make the tests pass</li> <li>The code you've written is always covered by tests</li> <li>By writing the test first, you're forced into thinking about how you want to call the code, which usually improves the design of the code in the long run.</li> </ul> <p>If you're not doing unit testing now, I recommend you get started on it. Get a good book, practically any xUnit-book will do because the concepts are very much transferable between them. </p> <p>Sometimes writing unit tests can be painful. When it gets that way, try to find someone to help you, and resist the temptation to "just write the damn code". Unit testing is a lot like washing the dishes. It's not always pleasant, but it keeps your metaphorical kitchen clean, and you really want it to be clean. :)</p> <hr> <p>Edit: One misconception comes to mind, although I'm not sure if it's so common. I've heard a project manager say that unit tests made the team write all the code twice. If it looks and feels that way, well, you're doing it wrong. Not only does writing the tests usually speed up development, but it also gives you a convenient "now I'm done" indicator that you wouldn't have otherwise.</p>
<p>Unit-testing and TDD in general enables you to have shorter feedback cycles about the software you are writing. Instead of having a large test phase at the very end of the implementation, you incrementally test everything you write. This increases code quality very much, as you immediately see, where you might have bugs.</p>
2,377
<p>I've been trying to print anything for the past few days. Every time I go to print something the printer stops pushing plastic out and usually the motor makes a knocking sound.</p> <p>My original thought was that my E-steps were off (because they were) but I solved that and I still have a problem. Then I noticed that I was struggling with getting the PLA filament to feed into the nozzle. I assumed it was a clogged nozzle and possibly heat creep (because I was a dummy and used my old, bowden retraction settings on my new, direct extruder). I cleared out the clog and I'm able to feed plastic through after disengaging the idler arm. Though, I do struggle getting the filament into the nozzle. Maybe it's due to the Hemera's tight tolerances or due to a misalignment in the hot end, I'm not sure yet. Once I do get the plastic in, it quickly and easily pushes through and spits out of the nozzle so I think that my nozzle isn't clogged. I did do a cold pull the other day. </p> <p>But I've noticed that my extruder is making a knocking sound, as if someone was gently rapping on my chamber door. I also see that the gears move one step back and forth. It looks to me that the motor is stuck or frozen. I'm pretty sure that it's not skipping steps. The sound happens at varying heights and not just the first layer. The first time I noticed it, it was printing the cabin of Benchy. Z > 1 mm when I finally decided to ask this question. The sound is kind of loud, but that's most likely the resonance in the machine than a symptom, stating it nonetheless. </p> <h2>My setup:</h2> <ul> <li><strong>Printer:</strong> Creality CR-10S </li> <li><strong>Extruder:</strong> E3D Hemera </li> <li><strong>Nozzle temp:</strong> 205-220&nbsp;°C</li> <li><strong>Retraction:</strong> Initially 5&nbsp;mm at 40&nbsp;mm/s, then 0.3&nbsp;mm, then most recently none </li> <li><strong>Motor Vref:</strong> just north of 800&nbsp;mA. (I've read somewhere that the Hemera motor wants 800&nbsp;to 1000&nbsp;mA) </li> </ul> <p>I'm just not sure what could be wrong here. I feel like I checked all the steps and I'm just missing something. </p>
<p>A knocking or clicking sound does not imply you <strong>have a problem</strong>, it implies that you <strong>could have a problem</strong>; it can be the characteristic of the extruder. </p> <hr> <p><em>My own designed 2.85&nbsp;mm filament, 1:4 speed reducing <a href="https://www.thingiverse.com/thing:2897762" rel="nofollow noreferrer">belt driven extruders</a> make clicking sounds while extruding (independent of the layer height), I have verified that no steps are lost and the printer extrudes exactly the requested amount of filament (2.85&nbsp;mm filament requires a lot more pressure for the same nozzle size, the noise is coming from inside of the metal Bulldog housing, not the stepper adjacent, it is not stepper nor filament skipping noise).</em> </p> <hr> <p>A clicking sound in combination with gears losing position as you describe (or filament skipping back) does mean that the pressure in the nozzle is too big for the extruder to push it through. If the gears loose position, this means that the stepper is not powerful enough to push it through, this means that more current or a more powerful stepper is required (the latter option is due to the design of the extruder not possible). If the filament skips back while the gears are in place the tension/grip to the filament needs to be increased. </p> <p>In troubleshooting this problem it is best to increase the current to the stepper close to the upper side of the specifications of the stepper and see if the knocking sounds disappear. This should not be a problem for such a priced and tested extruder system, i.e. considering the reputation and quality of E3D this extruder must work out of the box unless you have received damaged components.</p>
<p>I had a bad connection at my motor that was causing the problem. I soldered direct to the motor and no more problems.</p>
1,559
<p>Ok, I know this is a strange question, but there is a "standard" (fan-wise at least) Unicode support for the Klingon alphabet, and since code can be written in Unicode with no problem, that means it is possible to write Kode with Klingon tokens( vars, function names, etc...).</p> <p>For the record I've written C++ in Japanese and it works, so K++ in Klingon should work too. But I don't know of any text editor with support for Klingon. Any suggestions?</p>
<p>Not likely, especially when you consider rule 9 of the <a href="http://www.aumha.org/a/klingon.php" rel="nofollow noreferrer">KLINGON GUIDE To Writing Perfect Code</a></p> <blockquote> <p>“Indentation?! I will show you how to indent when I indent your skull!”</p> </blockquote> <p>and number 7 does not bode well for any editor:</p> <blockquote> <p>“Klingon function calls do not have ‘parameters.’ They have ‘arguments’ . . . and they ALWAYS WIN THEM!”</p> </blockquote> <p><code>[</code>Seriously, this is an interesting <a href="http://www.oocities.org/harry_robinson_testing/klingon.htm" rel="nofollow noreferrer">Unicode editor problem</a><code>]</code></p> <p><img src="https://i.stack.imgur.com/OT01m.gif" alt="alt text"></p> <p>After all, ITunes has a license agreement in Klingon!</p> <p><img src="https://i.stack.imgur.com/K5DER.png" alt="ITune license"></p> <p>And you need the right keyboard, off course \o/</p> <p><img src="https://i.stack.imgur.com/fxkWH.jpg" alt="Keyboard Klingon i.telegraph.co.uk/multimedia/archive/01239/kling_1239147c.jpg"></p> <p>Now... may be you can try to "Google it" ;-)</p> <p><img src="https://i.stack.imgur.com/WzxkA.jpg" alt="KlingonGoogle"></p>
<p><a href="http://ttp://code.google.com/p/googleappengine/issues/detail?id=2134" rel="nofollow noreferrer">important</a> obviously support: Klingon</p> <blockquote> <p>(to no use rejected by unicode 2000 in favor of comets,snowmen,4 scissors and so) Comment 1 by gra...@gmail.com, Sep 22, 2009 How can we use app engine without Klingon support? :( Comment 2 , Today (27 minutes ago) recover the Klingon fonts from imagefile will work towards users, very sceptical it's ok engineering. signs have different sizes. we could agree serve Klingon with dynamic images. Comment 3 , Today (18 minutes ago)</p> </blockquote> <p>knowledgebase <a href="http://std.dkuug.dk/jtc1/sc2/wg2/docs/n1643/n1643.htm" rel="nofollow noreferrer">http://std.dkuug.dk/jtc1/sc2/wg2/docs/n1643/n1643.htm</a> <a href="http://wazu.jp/gallery/Test_Klingon.html" rel="nofollow noreferrer">http://wazu.jp/gallery/Test_Klingon.html</a> <a href="http://www.evertype.com/standards/csur/klingon.html" rel="nofollow noreferrer">http://www.evertype.com/standards/csur/klingon.html</a></p>
39,142
<p>I have just started using QPixmapCache and I was wondering, since there is not much documentation, about how to adjust the size based on the system the application is running on.</p> <p>Some users might have lots of free memory while others have very little. I have no idea what the best setting would be. </p> <p>What would be the best way to detect the system (free) RAM and adjust the cache size to fit?</p> <p><a href="http://doc.trolltech.com/4.4/qpixmapcache.html#setCacheLimit" rel="nofollow noreferrer">http://doc.trolltech.com/4.4/qpixmapcache.html#setCacheLimit</a></p>
<p>To detect free RAM in Windows, you can use the <a href="http://msdn.microsoft.com/en-us/library/aa366586.aspx" rel="nofollow noreferrer">GlobalMemoryStatus</a> function.</p> <p>I'm not sure if this will help you size the pixmap cache; perhaps you will need to do some performance measurements and create a lookup table.</p>
<p>Note that QPixmap is window-system specific. This means that QPixmap likely corresponds to graphics card memory more than the general RAM. Just like any other cache, the size of it should "as much as it needs to be, but not more".</p> <p>The best way to tune the cache is to profile your application running on a typical machine (of the target users). See if the cache starts to trash old pixmaps and get cache misses.</p>
47,409
<p>Waiting for a heatbed to get up to 85˚C for a relatively small part got me wondering why beds aren't hardware/G-code configurable for what area is heated? I'm sure it would be an increase in parts costs and electronics, but it seems that being able to just heat an area a little larger than the part(s) being built would save in time and energy use.</p>
<p>I've wondered that myself a while ago and fact is that such beds or silicone heating pads do <a href="http://www.formbot3d.com/dual-zone-heated-build-plate-and-digital-controller-for-t-rex-2_p0015.html" rel="nofollow noreferrer">exist</a>. Usually these are quite large (and expensive) and usually referred to as "dual zone heat beds/pads".</p> <p>As far as energy consumption; less area to heat is faster heat up times (depending on the control) and less energy consumed. For small prints this may be beneficial. The price of such beds are very high, so to break even you would have to print a lot. An alternative to buying would be to <a href="https://reprap.org/wiki/Etched_heatbed_construction" rel="nofollow noreferrer">etch your own bed</a>.</p>
<p>it is probably too late for the party but i thought about grid heated bed recently. about controlling which zone to turn on and off, i think we can treat the grid as Led matrix, the matrix led signal can be used to drive mosfets to power the heat pads.</p>
953
<p>Does anyone know of a decent UML standards guide?</p> <p>My company currently relies on UML 2.0 (rightly or wrongly) to do the majority (read <em>all</em>) of their design work. I have been asked to come up with a draft 'best practice' guide to help other developers develop better models. The main problem I face is that Im slightly biased against UML... I feel that: if a diagram takes more than 5 mins to draw then its too complicated! Im looking for advice predominantly on what sort of standards I should be looking at. Also Im looking for an external source of information that can be used to balence out my irrational loathing of UML-heavy design and act as a 'sanitizer' for my suggestions.</p> <p>Most of all Im looking to write a useful document rather than one that will sit moulding away in some obscure network directory.</p> <p>Any ideas?</p>
<p><a href="https://rads.stackoverflow.com/amzn/click/com/0321193687" rel="noreferrer" rel="nofollow noreferrer">UML Distilled</a> by Martin Fowler</p>
<p>I know you probably want an easy to read book for this but from what you are describing I would suggest going with the specs found on <a href="http://www.uml.org/" rel="nofollow noreferrer">OMG</a> itself. They are a bit much to read but would be as complete as you could hope for. They also have lonks to articles and tutorials that may be helpful.</p> <p>As far as books go I have found that <a href="https://rads.stackoverflow.com/amzn/click/com/0321269675" rel="nofollow noreferrer" rel="nofollow noreferrer">Using UML</a> is quite good since it tackles the software development process as well as the UML tools and methods.</p>
30,316
<p>I have a simple function in which an array is declared with size depending on the parameter which is int.</p> <pre><code> void f(int n){ char a[n]; }; int main() { return 0; } </code></pre> <p>This piece of code compiles fine on <a href="http://en.wikipedia.org/wiki/G%2B%2B" rel="noreferrer">GNU C++</a>, but not on MSVC 2005.</p> <p>I get the following compilation errors:</p> <pre><code> .\main.cpp(4) : error C2057: expected constant expression .\main.cpp(4) : error C2466: cannot allocate an array of constant size 0 .\main.cpp(4) : error C2133: 'a' : unknown size </code></pre> <p>What can I do to correct this?</p> <p>(I'm interested in making this work with MSVC,without using new/delete)</p>
<p>What you have found it one of the Gnu compiler's extensions to the C++ language. In this case, Visual C++ is completely correct. Arrays in C++ must be defined with a size that is a compile-time constant expression.</p> <p>There was a feature added to C in the 1999 update to that language called variable length arrays, where this is legal. If you can find a C compiler that supports C99, which is not easy. But this feature is not part of standard C++, not is it going to be added in the next update to the C++ standard.</p> <p>There are two solutions in C++. The first is to use a std::vector, the second is just to use operator <code>new []</code>:</p> <pre><code>char *a = new char [n]; </code></pre> <p>While I was writing my answer, another one posted a suggestion to use _alloca. I would strongly recommend against that. You would just be exchanging one non-standard, non-portable method for another one just as compiler-specific.</p>
<p>Typically in C (excepting C99 compilers as others have pointed out) and C++, if you want to allocate memory on the stack, the size of what you want to allocate has to be known at compile time. Local variables are allocated on the stack, so an array whose length depends on a function parameter at run time violates this rule. Klein is correct to point out that using the 'new' operator is one way to solve this problem:</p> <pre> <code> char *a = new char [n]; </pre> <p></code></p> <p>'a' is still a local variable allocated on the stack, but instead of being the whole array (which has variable length), it's just a pointer to an array (which is always the same size, and thus known at compile time). The array is allocated on the heap, which typically plays the stack's counterpart -- the stack is for things with a size known at compile time, and the heap is for things with a size not known at a compile time.</p>
40,224
<p>I have an XML document with un-namespaced elements, and I want to use XSLT to add namespaces to them. Most elements will be in namespace A; a few will be in namespace B. How do I do this?</p>
<p>With foo.xml</p> <pre><code>&lt;foo x="1"&gt; &lt;bar y="2"&gt; &lt;baz z="3"/&gt; &lt;/bar&gt; &lt;a-special-element n="8"/&gt; &lt;/foo&gt; </code></pre> <p>and foo.xsl</p> <pre><code> &lt;xsl:template match="*"&gt; &lt;xsl:element name="{local-name()}" namespace="A" &gt; &lt;xsl:copy-of select="attribute::*"/&gt; &lt;xsl:apply-templates /&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template match="a-special-element"&gt; &lt;B:a-special-element xmlns:B="B"&gt; &lt;xsl:apply-templates match="children()"/&gt; &lt;/B:a-special-element&gt; &lt;/xsl:template&gt; &lt;/xsl:transform&gt; </code></pre> <p>I get</p> <pre><code>&lt;foo xmlns="A" x="1"&gt; &lt;bar y="2"&gt; &lt;baz z="3"/&gt; &lt;/bar&gt; &lt;B:a-special-element xmlns:B="B"/&gt; &lt;/foo&gt; </code></pre> <p>Is that what you’re looking for?</p>
<p>Here's what I have so far:</p> <pre><code>&lt;xsl:template match="*"&gt; &lt;xsl:element name="{local-name()}" namespace="A" &gt; &lt;xsl:apply-templates /&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template match="a-special-element"&gt; &lt;B:a-special-element xmlns:B="B"&gt; &lt;xsl:apply-templates /&gt; &lt;/B:a-special-element&gt; &lt;/xsl:template&gt; </code></pre> <p>This almost works; the problem is that it's not copying attributes. From what I've read thusfar, xsl:element doesn't have a way to copy all of the attributes from the element as-is (use-attribute-sets doesn't appear to cut it). </p>
17,452
<p>I'm using selenium to run some functional tests on the UI for our current application. </p> <p>I want to ensure that strings from the resource files in the Web project are being displayed at the correct time and place.</p> <p>Simple (I thought) all I have to do is reference the assembly of the web application and assert that the text selenium is reading from the UI matches the test in the approriate resource file.</p> <p>The problem is the ASP.Net does some precomilation processing on the resource files and compiles them into an assembly called App_GlobalResources, which isn't created by the normal build process so the functional tests fail because that can't find the App_GlobalResources assembly to look the string up from.</p> <p>So, any suggestions? Do I need to abandon the App_GlobalResources approach and do something manual that I have control over? </p> <p>Do you understand the problem or do I need to provide more info?</p>
<p>Concatenation is (significantly) faster according to my machine. But stylistically, I'm willing to pay the price of substitution if performance is not critical. Well, and if I need formatting, there's no need to even ask the question... there's no option but to use interpolation/templating.</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; def so_q_sub(n): ... return "%s%s/%d" % (DOMAIN, QUESTIONS, n) ... &gt;&gt;&gt; so_q_sub(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; def so_q_cat(n): ... return DOMAIN + QUESTIONS + '/' + str(n) ... &gt;&gt;&gt; so_q_cat(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; t1 = timeit.Timer('so_q_sub(1000)','from __main__ import so_q_sub') &gt;&gt;&gt; t2 = timeit.Timer('so_q_cat(1000)','from __main__ import so_q_cat') &gt;&gt;&gt; t1.timeit(number=10000000) 12.166618871951641 &gt;&gt;&gt; t2.timeit(number=10000000) 5.7813972166853773 &gt;&gt;&gt; t1.timeit(number=1) 1.103492206766532e-05 &gt;&gt;&gt; t2.timeit(number=1) 8.5206360154188587e-06 &gt;&gt;&gt; def so_q_tmp(n): ... return "{d}{q}/{n}".format(d=DOMAIN,q=QUESTIONS,n=n) ... &gt;&gt;&gt; so_q_tmp(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; t3= timeit.Timer('so_q_tmp(1000)','from __main__ import so_q_tmp') &gt;&gt;&gt; t3.timeit(number=10000000) 14.564135316080637 &gt;&gt;&gt; def so_q_join(n): ... return ''.join([DOMAIN,QUESTIONS,'/',str(n)]) ... &gt;&gt;&gt; so_q_join(1000) 'http://stackoverflow.com/questions/1000' &gt;&gt;&gt; t4= timeit.Timer('so_q_join(1000)','from __main__ import so_q_join') &gt;&gt;&gt; t4.timeit(number=10000000) 9.4431309007150048 </code></pre>
<p>Actually the correct thing to do, in this case (building paths) is to use <code>os.path.join</code>. Not string concatenation or interpolation</p>
49,280
<p>I have a site where I use CustomErrors in the web.config to specify a custom error page, and that's working just fine. The custom 404 page is also specified in the IIS configuration (because if it's not, I don't get my custom 404 page).</p> <p>But I have some logic that kicks in if a user gets a 404 that looks at their requested URL and make a navigation suggestion, if appropriate. This logic relies on the aspxerrorpath value. On my development PC, the aspxerrorpath is correctly appended to the URL, like so: <em><a href="http://localhost:3092/FileNotFound.aspx?aspxerrorpath=/badpage.aspx" rel="noreferrer">http://localhost:3092/FileNotFound.aspx?aspxerrorpath=/badpage.aspx</a></em>, but on my test site, there's no aspxerrorpath appended to the URL, so all of my custom logic is bypassed and my suggestions don't work. I'm not sure if this is an IIS config issue or something else. The web server is Windows Server 2008 with IIS 7.</p> <p>Any thoughts?</p> <p>Many Thanks.</p>
<p>The aspxerrorpath parameter is passed if the error was caught by .NET (and the error page specified in web.config is used). This happens if you're using the development web server, or if IIS is configured not to check that the file exists.</p> <p>If IIS checks that the file exists, then the custom error configured in IIS is used, and the requested URL is included in the querystring as something like</p> <p><code>http://example.com/FileNotFound.aspx?404;http://example.com/badpage.aspx</code></p>
<p>You may have to add the below to web.config</p> <pre><code>&lt;customErrors mode=&quot;On&quot;&gt; &lt;error statusCode=&quot;404&quot; redirect=&quot;~/error404.aspx&quot; /&gt; &lt;/customErrors&gt; </code></pre> <p>For more information check : <a href="https://web.archive.org/web/20200221100823/http://geekswithblogs.net:80/shahed/archive/2007/10/23/116278.aspx" rel="nofollow noreferrer">Link</a></p> <p>Update: We can utilize the IIS7 functionality for displaying custom 404 error pages using HTTPModules as described in <a href="http://professionalaspnet.com/archive/2008/02/13/Enforcing-a-Custom-404-Page-in-ASP.NET.aspx" rel="nofollow noreferrer">http://professionalaspnet.com/archive/2008/02/13/Enforcing-a-Custom-404-Page-in-ASP.NET.aspx</a></p>
33,499
<p>I'm attempting to learn basic Win32 programming and running into a frustrating problem. I wish to convert a variable (Call it NumClicks) and display it as the application name (as part of a string). From what I've seen, going from int + some block of text to a char* is problematic, because converting it to the requisite end data type(LPCWSTR) is more difficult than a straight casting.</p> <p>Any ideas or links? </p>
<p>use <a href="http://msdn.microsoft.com/en-us/library/ms647550(VS.85).aspx" rel="nofollow noreferrer">wsprintf</a><br> It allows you to compose a string the same way printf allows you to print a line of text.</p>
<p>rather than use wsprintf i would use sprinf(buf, "%S", "plain old string");</p>
40,322
<p><code>Monitor.Pulse/All</code> and <code>Monitor.Wait</code> are useful methods, but I'm getting complaints that when using them in large quantities (I have a DSL designer that spits them out by the dozen), the resulting code becomes unreadable. What do you think?</p>
<p>If it's sprinkled all over code that you actually have to read, that could be a problem. Why does it come up so often in the first place? Could the functionality actually be encapsulated somewhere else?</p> <p>Fundamentally there's nothing wrong with Wait/Pulse - but like everything else in life, if it's used inappropriately it will become a problem. Whether or not your use is inappropriate is hard to tell without seeing the code :(</p>
<p>Sounds like something that should be coded by injection as an aspect. However, my knowledge of the support of AOP in C# is negligible, so I can't offer any more than that.</p>
46,971
<p>Was wondering if anyone knows, or has pointers to good documentation that discusses, the low-level implementation details of Cocoa's 'performSelectorOnMainThread:' method.</p> <p>My best guess, and one I think is probably pretty close, is that it uses mach ports or an abstraction on top of them to provide intra-thread communication, passing selector information along as part of the mach message.</p> <p>Right? Wrong? Thanks!</p> <p><strong>Update 09:39AMPST</strong></p> <p>Thank you Evan DiBiase and Mecki for the answers, but to clarify: I understand what happens in the run loop, but what I'm looking for an answer to is; "<em>where</em> is the method getting queued? <em>how</em> is the selector information getting passed into the queue?" Looking for more than Apple's doc info: I've read 'em</p> <p><strong>Update 14:21PST</strong></p> <p>Chris Hanson brings up a good point in a comment: my objective here is not to learn the underlying mechanisms in order to take advantage of them in my own code. Rather, I'm just interested in a better conceptual understanding of the process of signaling another thread to execute code. As I said, my own research leads me to believe that it's takes advantage of mach messaging for IPC to pass selector information between threads, but I'm specifically looking for <strong>concrete</strong> information on what is happening, so I can be sure I'm understanding things <em>correctly</em>. Thanks! </p> <p><strong>Update 03/06/09</strong></p> <p>I've opened a bounty on this question because I'd really like to see it answered, but if you are trying to collect please make sure you read <strong>everything</strong>, including all currently posed answers, comments to both these answers and to my original question, and the update text I posted above. I'm look for the <strong>lowest-level detail</strong> of the mechanism used by <code>performSelectorOnMainThread:</code> and the like, and as I mentioned earlier, I suspect it has something to do with Mach ports but I'd really like to know for sure. The bounty will not be awarded unless I can <strong>confirm</strong> the answer given is correct. Thanks everyone!</p>
<p>Yes, it does use Mach ports. What happens is this:</p> <ol> <li>A block of data encapsulating the perform info (the target object, the selector, the optional object argument to the selector, etc.) is enqueued in the thread's run loop info. This is done using <code>@synchronized</code>, which ultimately uses <code>pthread_mutex_lock</code>.</li> <li>CFRunLoopSourceSignal is called to signal that the source is ready to fire.</li> <li>CFRunLoopWakeUp is called to let the main thread's run loop know it's time to wake up. This is done using mach_msg.</li> </ol> <p>From the Apple docs:</p> <blockquote> <p>Version 1 sources are managed by the run loop and kernel. These sources use Mach ports to signal when the sources are ready to fire. A source is automatically signaled by the kernel when a message arrives on the source’s Mach port. The contents of the message are given to the source to process when the source is fired. The run loop sources for CFMachPort and CFMessagePort are currently implemented as version 1 sources.</p> </blockquote> <p>I'm looking at a stack trace right now, and this is what it shows:</p> <pre><code>0 mach_msg 1 CFRunLoopWakeUp 2 -[NSThread _nq:] 3 -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] 4 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] </code></pre> <p>Set a breakpoint on mach_msg and you'll be able to confirm it.</p>
<p>As Mecki said, a more general mechanism that could be used to implement <code>-performSelectorOn…</code> is <code>NSTimer</code>.</p> <p><code>NSTimer</code> is toll-free bridged to <code>CFRunLoopTimer</code>. An implementation of <code>CFRunLoopTimer</code> – although not necessarily the one actually used for normal processes in OS X – can be found in CFLite (open-source subset of CoreFoundation; package CF-476.14 in the <a href="http://www.opensource.apple.com/darwinsource/10.5.4/" rel="nofollow noreferrer">Darwin 9.4 source code</a>. (CF-476.15, corresponding to OS X 10.5.5, is not yet available.)</p>
18,003
<p>I have a Crystal Report which is viewed via a CrystalReportViewer control on an .aspx page (using VS2008). </p> <p>The report has two data-driven FieldObjects (which can contain a variable number of chars) which I would like to display on the same line beside each other. </p> <p>Problem is when the text in the first FieldObject is too long it overlaps the text in the second FieldObject. </p> <p>I have tried setting the 'CanGrow=True' and 'MaxNumberOfLines=1' on the first FieldObject to 'push' the second FieldObject further to the right, but this didn't work. </p> <p><strong>How do I get the second FieldObject to always display immediately after the first FieldObject regardless of the length of the text in the first?</strong> </p> <p>Cheers in advance of any knowledge you can drop.</p>
<p>you can add a text object to the report. And while editing the text of the text object, drag the field you want to show from the object explorer into the text box. Then hit space, then drag the second field in to the same text box. Your two fields will always be one space a part. You could, of course, add more spaces or any other text you want.</p>
<p>Or you can create a function which returns field1 + " " + field2 and add the function to the report.</p>
5,407
<p>I have been getting an error in <strong>VB .Net</strong> </p> <blockquote> <p>object reference not set to an instance of object.</p> </blockquote> <p>Can you tell me what are the causes of this error ?</p>
<p>sef, If the problem is with Database return results, I presume it is in this scenario:</p> <pre><code> dsData = getSQLData(conn,sql, blah,blah....) dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here </code></pre> <p>To fix that:</p> <pre><code> dsData = getSQLData(conn,sql, blah,blah....) If dsData.Tables.Count = 0 Then Exit Sub dt = dsData.Tables(0) 'Perhaps the obj ref not set is occurring here </code></pre> <p><strong>edit</strong>: added code formatting tags ...</p>
<p>Well, Error is explaining itself. Since You haven't provided any code sample, we can only say somewhere in your code, you are using a Null object for some task. I got same Error for below code sample.</p> <pre><code>Dim cmd As IDbCommand cmd.Parameters.Clear() </code></pre> <p>As You can see I am going to Clear a Null Object. For that, I'm getting Error </p> <blockquote> <p>"object reference not set to an instance of an object"</p> </blockquote> <p>Check your code for such code in your code. Since you haven't given code example we can't highlight the code :)</p>
15,916
<p>I'm working with DotNetNuke's scheduler to schedule tasks and I'm looking to get the physical file path of a email template that I created. The problem is that HttpContext is NULL because the scheduled task is on a different thread and there is not http request. How would you go about getting the file's physical path?</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.mappath.aspx" rel="noreferrer">System.Web.Hosting.HostingEnvironment.MapPath</a> is what you're looking for. Whenever you're using the Server or HttpContext.Current objects, check first to see if <a href="http://msdn.microsoft.com/en-us/library/system.web.hosting.hostingenvironment.aspx" rel="noreferrer">HostingEnvironment</a> has what you need.</p>
<p>Since this process is really out-of-band in relation to the web site, maybe you can just put the path in a config file. </p> <p>May not be the best idea, but it is an alternative.</p>
13,455
<p>How do you delete all the cookies for the current domain using JavaScript?</p>
<pre><code>function deleteAllCookies() { var cookies = document.cookie.split(";"); for (var i = 0; i &lt; cookies.length; i++) { var cookie = cookies[i]; var eqPos = cookie.indexOf("="); var name = eqPos &gt; -1 ? cookie.substr(0, eqPos) : cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } } </code></pre> <p>Note that this code has two limitations:</p> <ul> <li>It will not delete cookies with <code>HttpOnly</code> flag set, as the <code>HttpOnly</code> flag disables Javascript's access to the cookie.</li> <li>It will not delete cookies that have been set with a <code>Path</code> value. (This is despite the fact that those cookies will appear in <code>document.cookie</code>, but you can't delete it without specifying the same <code>Path</code> value with which it was set.)</li> </ul>
<p>I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the "path" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the "path", the path won't match and it won't expire. The <code>document.cookie</code> value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.</p> <p>If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append <code>"; path=/;"</code> to the cookie value. Then it will expire from any page.</p>
21,627
<p>I have a Git repository I store random things in. Mostly random scripts, text files, websites I've designed and so on.</p> <p>There are some large binary files I have deleted over time (generally 1-5MB), which are sitting around increasing the size of the repository, which I don't need in the revision history.</p> <p>Basically I want to be able to do..</p> <pre><code>me@host:~$ [magic command or script] aad29819a908cc1c05c3b1102862746ba29bafc0 : example/blah.psd : 3.8MB : 130 days old 6e73ca29c379b71b4ff8c6b6a5df9c7f0f1f5627 : another/big.file : 1.12MB : 214 days old </code></pre> <p>..then be able to go though each result, checking if it's no longer required then removing it (probably using <code>filter-branch</code>)</p>
<p>This is an adaptation of <a href="https://stackoverflow.com/questions/223678/git-which-commit-has-this-blob#223890">the <code>git-find-blob</code> script I posted previously</a>:</p> <pre class="lang-perl prettyprint-override"><code>#!/usr/bin/perl use 5.008; use strict; use Memoize; sub usage { die "usage: git-large-blob &lt;size[b|k|m]&gt; [&lt;git-log arguments ...&gt;]\n" } @ARGV or usage(); my ( $max_size, $unit ) = ( shift =~ /^(\d+)([bkm]?)\z/ ) ? ( $1, $2 ) : usage(); my $exp = 10 * ( $unit eq 'b' ? 0 : $unit eq 'k' ? 1 : 2 ); my $cutoff = $max_size * 2**$exp; sub walk_tree { my ( $tree, @path ) = @_; my @subtree; my @r; { open my $ls_tree, '-|', git =&gt; 'ls-tree' =&gt; -l =&gt; $tree or die "Couldn't open pipe to git-ls-tree: $!\n"; while ( &lt;$ls_tree&gt; ) { my ( $type, $sha1, $size, $name ) = /\A[0-7]{6} (\S+) (\S+) +(\S+)\t(.*)/; if ( $type eq 'tree' ) { push @subtree, [ $sha1, $name ]; } elsif ( $type eq 'blob' and $size &gt;= $cutoff ) { push @r, [ $size, @path, $name ]; } } } push @r, walk_tree( $_-&gt;[0], @path, $_-&gt;[1] ) for @subtree; return @r; } memoize 'walk_tree'; open my $log, '-|', git =&gt; log =&gt; @ARGV, '--pretty=format:%T %h %cr' or die "Couldn't open pipe to git-log: $!\n"; my %seen; while ( &lt;$log&gt; ) { chomp; my ( $tree, $commit, $age ) = split " ", $_, 3; my $is_header_printed; for ( walk_tree( $tree ) ) { my ( $size, @path ) = @$_; my $path = join '/', @path; next if $seen{ $path }++; print "$commit $age\n" if not $is_header_printed++; print "\t$size\t$path\n"; } } </code></pre>
<p>A little late to the party, but <a href="https://github.com/cyaninc/git-fat" rel="nofollow">git-fat</a> has this functionality built in.</p> <p>Just install it with pip and run <code>git fat -a find 100000</code> where the number at the end is in Bytes.</p>
38,183
<p>I've got a minidump file from a crash in one of our apps. It's a 32-bit native app, and it was running on 64-bit Windows.</p> <p>If I load the minidump file into WinDbg, WinDbg won't load the symbols for the system DLLs. I've got my symbol paths configured correctly:</p> <pre><code>_NT_SYMBOL_PATH=SRV*C:\WebSymbols*http://msdl.microsoft.com/download/symbols </code></pre> <p>...because WinDbg correctly loads symbols for minidumps created on 32-bit Windows. It just won't load symbols for DLLs in the SysWOW64 directory.</p> <p>I've tried 32-bit WinDbg (from Debugging Tools 6.9) on 32-bit Windows 2003, and 64-bit WinDbg (also from Debugging Tools 6.9) on 64-bit Windows 2008. Both fail to load the symbols. This is from the 32-bit WinDbg:</p> <pre>0:014> !sym noisy noisy mode - symbol prompts on 0:014> .reload .................................................................................... Loading unloaded module list .. SYMSRV: C:\WebSymbols\ntdll.dll\48E714D0170000\ntdll.dll not found SYMSRV: http://msdl.microsoft.com/download/symbols/ntdll.dll/48E714D0170000/ntdll.dll not found DBGENG: C:\Windows\SysWOW64\ntdll.dll - Couldn't map image from disk. Unable to load image C:\Windows\SysWOW64\ntdll.dll, Win32 error 0n2 DBGENG: ntdll.dll - Partial symbol image load missing image info DBGHELP: Module is not fully loaded into memory. DBGHELP: Searching for symbols using debugger-provided data. SYMSRV: C:\WebSymbols\wntdll.pdb\6686D0C5D0554E14953396093DA218A92\wntdll.pdb not found SYMSRV: http://msdl.microsoft.com/download/symbols/wntdll.pdb/6686D0C5D0554E14953396093DA218A92/wntdll.pdb not found DBGHELP: wntdll.pdb - file not found *** WARNING: Unable to verify timestamp for ntdll.dll *** ERROR: Module load completed but symbols could not be loaded for ntdll.dll DBGHELP: ntdll - no symbols loaded SYMSRV: C:\WebSymbols\kernel32.dll\48E7156Cf0000\kernel32.dll not found SYMSRV: http://msdl.microsoft.com/download/symbols/kernel32.dll/48E7156Cf0000/kernel32.dll not found DBGENG: C:\Windows\SysWOW64\kernel32.dll - Couldn't map image from disk. Unable to load image C:\Windows\SysWOW64\kernel32.dll, Win32 error 0n2 DBGENG: kernel32.dll - Partial symbol image load missing image info DBGHELP: Module is not fully loaded into memory. DBGHELP: Searching for symbols using debugger-provided data. SYMSRV: C:\WebSymbols\wkernel32.pdb\B0C3B36CC7EF4F3E9C168E186A5A6FEB2\wkernel32.pdb not found SYMSRV: http://msdl.microsoft.com/download/symbols/wkernel32.pdb/B0C3B36CC7EF4F3E9C168E186A5A6FEB2/wkernel32.pdb not found DBGHELP: wkernel32.pdb - file not found *** WARNING: Unable to verify timestamp for kernel32.dll *** ERROR: Module load completed but symbols could not be loaded for kernel32.dll DBGHELP: kernel32 - no symbols loaded SYMSRV: C:\WebSymbols\KERNELBASE.dll\48E7156D5a000\KERNELBASE.dll not found SYMSRV: http://msdl.microsoft.com/download/symbols/KERNELBASE.dll/48E7156D5a000/KERNELBASE.dll not found DBGENG: C:\Windows\SysWOW64\KERNELBASE.dll - Couldn't map image from disk. DBGENG: KERNELBASE.dll - Partial symbol image load missing image info DBGHELP: Module is not fully loaded into memory. DBGHELP: Searching for symbols using debugger-provided data. SYMSRV: C:\WebSymbols\wkernelbase.pdb\A8683F0C515F469B833E3FA562E0DB251\wkernelbase.pdb not found SYMSRV: http://msdl.microsoft.com/download/symbols/wkernelbase.pdb/A8683F0C515F469B833E3FA562E0DB251/wkernelbase.pdb not found DBGHELP: wkernelbase.pdb - file not found *** WARNING: Unable to verify timestamp for KERNELBASE.dll *** ERROR: Module load completed but symbols could not be loaded for KERNELBASE.dll DBGHELP: KERNELBASE - no symbols loaded</pre> <p>Any ideas? Are the symbols just not available on Microsoft's symbol server?</p>
<p>Are you debugging on a 32-bit or 64-bit system, and with the 32 or 64-bit version of WinDBG? You typically have to debug on the same architecture package you took the dump from:</p> <p><a href="http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx" rel="noreferrer"><a href="http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx" rel="noreferrer">http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx</a></a></p> <blockquote> <p>"The 32-bit version of Debugging Tools for Windows is the best choice, unless you are debugging an application on a 64-bit processor. In that case, you should use a 64-bit package."</p> </blockquote> <p>Also, take a look at this article where he is debugging a 32-bit app running on a 64-bit platform:</p> <p><a href="http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx" rel="noreferrer"><a href="http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx" rel="noreferrer">http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx</a></a></p>
<p>Consider the workaround mentionned here where syswo64\ntdll.dll is copied to Syswow64\ntdll32.dll</p> <p><a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98781&amp;wa=wsignin1.0" rel="nofollow noreferrer">https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98781&amp;wa=wsignin1.0</a></p> <p>Works for me.</p>
33,271
<p>I'm doing some experiments with Microsoft Dynamics CRM. You interact with it through web services and I have added a Web Reference to my project. The web service interface is very rich, and the generated "Reference.cs" is some 90k loc. </p> <p>I'm using the web reference in a console application. I often change something, recompile and run. Compilation is fast, but newing up the web service reference is very slow, taking some 15-20 seconds: <code> CrmService service = new CrmService(); </code> Profiling reveals that all time is spent in the SoapHttpClientProtocol constructor.</p> <p>The culprit is apparently the fact that the XML serialization code (not included in the 90k loc mentioned above) is generated at run time, before being JIT'ed. This happens during the constructor call. The wait is rather frustrating when playing around and trying things out.</p> <p>I've tried various combinations of sgen.exe, ngen and XGenPlus (which takes several hours and generates 500MB of additional code) but to no avail. I've considered implementing a Windows service that have few CrmService instances ready to dish out when needed but that seems excessive.</p> <p>Any ideas?</p>
<p>The following is ripped from <a href="http://communities.vmware.com/thread/47063" rel="noreferrer">this</a> thread on the VMWare forums:</p> <p>Hi folks,</p> <p>We've found that sgen.exe does work. It'just that there is a couple of additional steps beyond pre-generating the serializer dll's that we missed in this thread. Here is the detailed instruction</p> <h2>PROBLEM</h2> <p>When using the VIM 2.0 SDK from .NET requires long time to instantiate the VimService class. (The VimService class is the proxy class generated by running 'wsdl.exe vim.wsdl vimService.wsdl')</p> <p>In other words, the following line of code:</p> <pre><code>_service = new VimService(); </code></pre> <p>Could take about 50 seconds to execute.</p> <h2>CAUSE</h2> <p>Apparently, the .NET <code>XmlSerializer</code> uses the <code>System.Xml.Serialization.*</code> attributes annotating the proxy classes to generate serialization code in run time. When the proxy classes are many and large, as is the code in VimService.cs, the generation of the serialization code can take a long time.</p> <h2>SOLUTION</h2> <p>This is a known problem with how the Microsoft .NET serializer works.</p> <p>Here are some references that MSDN provides about solving this problem:</p> <p><a href="http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/bk3w6240.aspx</a> <a href="http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx" rel="noreferrer">http://msdn2.microsoft.com/en-us/library/system.xml.serialization.xmlserializerassemblyattribute.aspx</a></p> <p>Unfortunately, none of the above references describe the complete solution to the problem. Instead they focus on how to pre-generate the XML serialization code.</p> <p>The complete fix involves the following steps:</p> <ol> <li><p>Create an assembly (a DLL) with the pre-generated XML serializer code</p></li> <li><p>Remove all references to System.Xml.Serialization.* attributes from the proxy code (i.e. from the VimService.cs file)</p></li> <li><p>Annotate the main proxy class with the XmlSerializerAssemblyAttribute to point it to where the XML serializer assembly is.</p></li> </ol> <p>Skipping step 2 leads to only 20% improvement in the instantiation time for the <code>VimService</code> class. Skipping either step 1 or 3 leads to incorrect code. With all three steps 98% improvement is achieved.</p> <p>Here are step-by-step instructions:</p> <p>Before you begin, makes sure you are using .NET verison 2.0 tools. This solution will not work with version 1.1 of .NET because the sgen tool and the <code>XmlSerializationAssemblyAttribute</code> are only available in version 2.0 of .NET</p> <ol> <li><p>Generate the VimService.cs file from the WSDL, using wsdl.exe:</p> <p><code>wsdl.exe vim.wsdl vimService.wsdl</code></p> <p>This will output the VimService.cs file in the current directory</p></li> <li><p>Compile VimService.cs into a library</p> <p><code>csc /t:library /out:VimService.dll VimService.cs</code></p></li> <li><p>Use the sgen tool to pre-generate and compile the XML serializers:</p> <p><code>sgen /p VimService.dll</code></p> <p>This will output the VimService.XmlSerializers.dll in the current directory</p></li> <li><p>Go back to the VimService.cs file and remove all <code>System.Xml.Serialization.*</code> attributes. Because the code code is large, the best way to achieve that is by using some regular expression substitution tool. Be careful as you do this because not all attributes appear on a line by themselves. Some are in-lined as part of a method declaration.</p> <p>If you find this step difficult, here is a simplified way of doing it:</p> <p>Assuming you are writing C#, do a global replace on the following string:</p> <p><code>[System.Xml.Serialization.XmlIncludeAttribute</code></p> <p>and replace it with:</p> <p><code>// [System.Xml.Serialization.XmlIncludeAttribute</code></p> <p>This will get rid of the <code>Xml.Serialization</code> attributes that are the biggest culprits for the slowdown by commenting them out. If you are using some other .NET language, just modify the replaced string to be prefix-commented according to the syntax of that language. This simplified approach will get you most of the speedup that you can get. Removing the rest of the Xml.Serialization attributes only achieves an extra 0.2 sec speedup.</p></li> <li><p>Add the following attribute to the VimService class in VimService.cs:</p> <p><code>[System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")]</code></p> <p>You should end up with something like this:</p> <p><code>// ... Some code here ... [System.Xml.Serialization.XmlSerializerAssemblyAttribute(AssemblyName = "VimService.XmlSerializers")] public partial class VimService : System.Web.Services.Protocols.SoapHttpClientProtocol { // ... More code here</code></p></li> <li><p>Regenerate VimSerice.dll library by</p> <p><code>csc /t:library /out:VimService.dll VimService.cs</code></p></li> <li><p>Now, from your application, you can add a reference to VimSerice.dll library.</p></li> <li><p>Run your application and verify that VimService object instanciation time is reduced.</p></li> </ol> <h2>ADDITIONAL NOTES</h2> <p>The sgen tool is a bit of a black box and its behavior varies depending on what you have in your Machine.config file. For example, by default it is supposed to ouptut optimized non-debug code, but that is not always the case. To get some visibility into the tool, use the /k flag in step 3, which will cause it to keep all its temporary generated files, including the source files and command line option files it generated.</p> <p>Even after the above fix the time it takes to instantiate the VimService class for the first time is not instantaneous (1.5 sec). Based on empirical observation, it appears that the majority of the remaining time is due to processing the <code>SoapDocumentMethodAttribute</code> attributes. At this point it is unclear how this time can be reduced. The pre-generated XmlSerializer assembly does not account for the SOAP-related attributes, so these attributes need to remain in the code. The good news is that only the first instantiation of the VimService class for that app takes long. So if the extra 1.5 seconds are a problem, one could try to do a dummy instantiation of this class at the beginning of the application as a means to improve user experience of login time. </p>
<p>I came across this thread when trying to find out why my initial <code>SoapHttpClientProtocol</code> calls were taking so long. </p> <p>I found that setting the Proxy to null/Empty stopped the Proxy AutoDetect from occurring - This was taking up to 7 seconds on the initial call:</p> <pre><code>this.Proxy = GlobalProxySelection.GetEmptyWebProxy(); </code></pre>
20,740
<p>I have a Queue object that I need to ensure is thread-safe. Would it be better to use a lock object like this:</p> <pre><code>lock(myLockObject) { //do stuff with the queue } </code></pre> <p>Or is it recommended to use Queue.Synchronized like this:</p> <pre><code>Queue.Synchronized(myQueue).whatever_i_want_to_do(); </code></pre> <p>From reading the MSDN docs it says I should use Queue.Synchronized to make it thread-safe, but then it gives an example using a lock object. From the MSDN article:</p> <blockquote> <p>To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.</p> <p>Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.</p> </blockquote> <p>If calling Synchronized() doesn't ensure thread-safety what's the point of it? Am I missing something here?</p>
<p>Personally I always prefer locking. It means that <em>you</em> get to decide the granularity. If you just rely on the Synchronized wrapper, each individual operation is synchronized but if you ever need to do more than one thing (e.g. iterating over the whole collection) you need to lock anyway. In the interests of simplicity, I prefer to just have one thing to remember - lock appropriately!</p> <p>EDIT: As noted in comments, if you <em>can</em> use higher level abstractions, that's great. And if you <em>do</em> use locking, be careful with it - document what you expect to be locked where, and acquire/release locks for as short a period as possible (more for correctness than performance). Avoid calling into unknown code while holding a lock, avoid nested locks etc.</p> <p>In .NET 4 there's a <em>lot</em> more support for higher-level abstractions (including lock-free code). Either way, I still wouldn't recommend using the synchronized wrappers.</p>
<p>It seems clear to me that using a lock(...) {...} lock is the right answer.</p> <blockquote> <p><strong>To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.</strong></p> </blockquote> <p>If other threads access the queue without using .Synchronized(), then you'll be up a creek - unless all your queue access is locked up.</p>
43,975
<p>I have two tables Organisation and Employee having one to many relation i.e one organisation can have multiple employees. Now I want to select all information of a particular organisation plus first name of all employees for this organisation. What’s the best way to do it? Can I get all of this in single record set or I will have to get multiple rows based on no. of employees? Here is a bit graphical demonstration of what I want:</p> <pre><code>Org_ID Org_Address Org_OtherDetails Employess 1 132A B Road List of details Emp1, Emp2, Emp3..... </code></pre>
<p>The original question was database specific, but perhaps this is a good place to include a more generic answer. It's a common question. The concept that you are describing is often referred to as 'Group Concatenation'. There's no standard solution in SQL-92 or SQL-99. So you'll need a vendor-specific solution.</p> <ul> <li><strong>MySQL</strong> - Use the built-in GROUP_CONCAT function. In your example you would want something like this:</li> </ul> <pre>select o.ID, o.Address, o.OtherDetails, GROUP_CONCAT( concat(e.firstname, ' ', e.lastname) ) as Employees from employees e inner join organization o on o.org_id=e.org_id group by o.org_id </pre> <ul> <li><strong>PostgreSQL</strong> - PostgreSQL 9.0 is equally simple now that string_agg(expression, delimiter) is built-in. Here it is with 'comma-space' between elements:</li> </ul> <pre>select o.ID, o.Address, o.OtherDetails, STRING_AGG( (e.firstname || ' ' || e.lastname), ', ' ) as Employees from employees e inner join organization o on o.org_id=e.org_id group by o.org_id </pre> <p>PostgreSQL before 9.0 allows you to define your own aggregate functions with CREATE AGGREGATE. Slightly more work than MySQL, but much more flexible. See this <a href="https://stackoverflow.com/questions/43870/how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query">other post</a> for more details. (Of course PostgreSQL 9.0 and later have this option as well.)</p> <ul> <li><p><strong>Oracle</strong> - same idea using <strong>LISTAGG</strong>.</p> </li> <li><p><strong>MS SQL Server</strong> - same idea using <strong>STRING_AGG</strong></p> </li> <li><p><strong>Fallback solution</strong> - in other database technologies or in very very old versions of the technologies listed above you don't have these group concatenation functions. In that case create a stored procedure that takes the org_id as its input and outputs the concatenated employee names. Then use this stored procedure in your query. Some of the other responses here include some details about how to write stored procedures like these.</p> </li> </ul> <pre>select o.ID, o.Address, o.OtherDetails, MY_CUSTOM_GROUP_CONCAT_PROCEDURE( o.ID ) as Employees from organization o </pre>
<p>If you use Oracle you can create a PL/SQL function you can use in your query that accepts an organization_id as input, and returns the first name of all employees belonging to that org as a string. For example:-</p> <pre><code>select o.org_id, o.org_address, o.org_otherdetails, org_employees( o.org_id ) as org_employees from organization o </code></pre>
12,786
<p>Can anyone recommend any Ad Management components for .NET? I have a customer who would like to sell his own advertising through his own site. This rules out using packaged ad providers such as Google Ads.</p> <p>I've googled several packages, but I'd like to see if anyone has any first hand experience with a particular package.</p> <p>Or should I just roll my own ad management system?</p> <p>Thanks!</p>
<p>If there is going to be any size or complexity to the ad system, I wouldn't roll your own. Focus on your core competencies and outsource the rest, because ad people can be crazy and it's nearly impossible to implement all the features they would want. Frequency capping, geotargeting, failover reporting, inventory management, just to name a few.</p> <p>Check out Atlas Solutions, formerly Accipiter (now bought by Microsoft), which provides hosted ad serving solutions. Of course, that will come with a price, but what doesn't?</p>
<p>If there is going to be any size or complexity to the ad system, I wouldn't roll your own. Focus on your core competencies and outsource the rest, because ad people can be crazy and it's nearly impossible to implement all the features they would want. Frequency capping, geotargeting, failover reporting, inventory management, just to name a few.</p> <p>Check out Atlas Solutions, formerly Accipiter (now bought by Microsoft), which provides hosted ad serving solutions. Of course, that will come with a price, but what doesn't?</p>
28,057
<p>You're stepping through C/C++ code and have just called a Win32 API that has failed (typically by returning some unhelpful generic error code, like 0). Your code doesn't make a subsequent GetLastError() call whose return value you could inspect for further error information.</p> <p>How can you get the error value without recompiling and reproducing the failure? Entering "GetLastError()" in the Watch window doesn't work ("syntax error").</p>
<p>As mentioned a couple times, the <code>@err</code> pseudo-register will show the last error value, and <code>@err,hr</code> will show the error as a string (if it can). </p> <p>According to Andy Pennell, a member of the Visual Studio team, starting with VS 7 (Visual Studio .NET 2002), using the '@' character to indicate pseudo-registers is deprecated - they prefer to use '$' (as in <code>$err,hr</code>). Both $ and @ are supported for the time being.</p> <p>You can also use the $err pseudo-register in a conditional breakpoint; so you can break on a line of code only if the last error is non-zero. This can be a <strong>very</strong> handy trick.</p> <p>Some other pseudo registers that you may find handy (from John Robbins' outstanding book, <a href="https://rads.stackoverflow.com/amzn/click/com/0735615365" rel="noreferrer" rel="nofollow noreferrer">"Debugging Applications for Microsoft .NET and Microsoft Windows"</a>):</p> <ul> <li><code>$tib</code> - shows the thread information block</li> <li><code>$clk</code> - shows a clock count (useful for timing functions). To more easily use this, place a <code>$clk</code> watch then an additional <code>$clk=0</code> watch. The second watch will clear the pseudo register after the display of the current value, so the next step or step over you do gives you the time for that action only. Note that this is a rough timing that includes a fair bit of debugger overhead, but it can still be very useful.</li> </ul>
<p>"edit and continue" add the code so you can see the error (just don't create a new global variable to store it). It works really well if you can quickly put a call to a pre-existing function that executes this kind of error handling code.</p> <p>As a bonus, you can leave the new code there for the future too.</p> <p>If you can't do this, then QBziZ is right "ERR,hr" does it.</p>
19,337
<p>Should I use a hand-written schema for my projected developed in a high-level language (such as Python, Ruby) or should I let my ORM solution auto-generate it? Eventually I will need to migrate without destroying all the data. It's okay to be tied to a specific RDBMS but it would be nice if features such as constraints and procedures could be supported somehow.</p>
<p>I never go with ORM-generated schema.</p> <p>I find that the ways in which the ORM wants to generate the schema are often at total odds with how I want my database to be structured. Also, and I know this is trivial, the nomenclature scheme is usually poor.</p> <p>Database structure has its own constraints, that I find that usually the ORM autogeneration tools don't consider fully. And if you're going to be wanting to run reports on your database later (and you will), then having good database structure and design is very important.</p>
<p>Let your ORM solution generate it, but don't just blindly use it; read through it and sanity-check it.</p>
15,449
<p>I've got an MDI application written in Delphi 2006 which runs XP with the default theme. </p> <p>Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window? </p> <p>I've tried setting the <code>BorderStyle</code> of the <code>MDIChildren</code> to <code>bsSizeToolWin</code> but they are still rendered as normal Forms.</p>
<p>All your need - overload procedure CreateWindowHandle, like this:</p> <pre><code>unit CHILDWIN; interface uses Windows, Classes, Graphics, Forms, Controls, StdCtrls; type TMDIChild = class(TForm) private { Private declarations } public { Public declarations } procedure CreateWindowHandle(const Params: TCreateParams); override; end; implementation {$R *.dfm} procedure TMDIChild.CreateWindowHandle(const Params: TCreateParams); begin inherited CreateWindowHandle(Params); SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); end; end. </code></pre>
<p>I don't think there is; in my experience, MDI in Delphi is very strictly limited and controlled by its implementation in the VCL (and perhaps also by the Windows API?). For example, don't try hiding an MDI child (you'll get an exception if you try, and you'll have to jump through a couple of API hoops to work around that), or changing the way an MDI child's main menu is merged with the host form's.</p> <p>Given these limitations, perhaps you should reconsider why you'd like to have special title bars in the first place? I guess there are also good reasons why this MDI stuff is standardized --- your users might appreciate it :)</p> <p>(PS: nice to see a Delphi question around here!)</p>
3,022
<p>I've been trying to display text using a Quartz context, but no matter what I've tried I simply haven't had luck getting the text to display (I'm able to display all sorts of other Quartz objects though). Anybody knows what I might be doing wrong?</p> <p>example:</p> <pre><code>-(void)drawRect:(CGRect)rect { // Drawing code CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSelectFont(context, "Arial", 24, kCGEncodingFontSpecific); CGContextSetTextPosition(context,80,80); CGContextShowText(context, "hello", 6); //not even this works CGContextShowTextAtPoint(context, 1,1, "hello", 6); } </code></pre>
<p>Here is a fragment of code that I'm using.</p> <pre><code>UIColor *mainTextColor = [UIColor whiteColor]; [mainTextColor set]; drawTextLjust(@"Sample Text", 8, 50, 185, 18, 16); </code></pre> <p>And:</p> <pre><code>static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right, int maxFontSize, int minFontSize) { CGPoint point = CGPointMake(left, y); UIFont *font = [UIFont systemFontOfSize:maxFontSize]; [text drawAtPoint:point forWidth:right - left withFont:font minFontSize:minFontSize actualFontSize:NULL lineBreakMode:UILineBreakModeTailTruncation baselineAdjustment:UIBaselineAdjustmentAlignBaselines]; } </code></pre>
<p>OK, I got it. First off, change your encoding mode to kCGEncodingMacRoman. Secondly, insert this line underneath it:</p> <pre><code>CGContextSetTextMatrix(canvas, CGAffineTransformMake(1, 0, 0, -1, 0, 0)); </code></pre> <p>This sets the conversion matrix for text so that it is drawn correctly. If you don't put that line in, your text will be upside down and back to front. No idea why this wasn't the default. Finally, make sure you've set the right fill colour. It's an easy mistake to make if you forget to change from the backdrop colour to the text colour and end up with white-on-white text.</p>
17,300
<p>What I am looking for is a way to call a method after another method has been invoked but before it is entered. Example:</p> <pre><code>public class Test { public void Tracer ( ... ) { } public int SomeFunction( string str ) { return 0; } public void TestFun() { SomeFunction( "" ); } } </code></pre> <p>In the example above I would like to have Tracer() called after SomeFunction() has been invoked by TestFun() but before SomeFunction() is entered. I'd also like to get reflection data on SomeFunction().</p> <hr> <p>I found something interesting in everyone's answers. The <strong>best answer to the question</strong> is to use Castle's DynamicProxy; however, this is not that I'm going to use to solve my problem because it requires adding a library to my project. I have only a few methods that I need to "trace" so I've chosen to go with a modified "core" methodology mixed with the way Dynamic Proxy is implemented. I explain this in my answer to my own question below.</p> <p>Just as a note I'm going to be looking into AOP and the ContextBoundObject class for some other applications.</p>
<p>You can use a dynamic proxy (<a href="http://www.castleproject.org/dynamicproxy/index.html" rel="nofollow noreferrer">Castle's DynamicProxy</a> for example) to intercept the call, run whatever code you wish, and then either invoke your method or not, depending on your needs.</p>
<p>You would have to use some form of AOP framework like <a href="http://www.springframework.net/doc-latest/reference/html/aop-quickstart.html" rel="nofollow noreferrer">SpringFramework.NET</a> to do that.</p>
23,376
<p>Google results on this one are a bit thin, but suggest that it is not easily possible.</p> <p>My specific problem is that I need to renumber the IDs in two tables that are related to each other such that table B has an "table_a_id" column in it. I can't renumber table A first because then its children in B point to the old IDs. I can't renumber table B first because then they would point to the new IDs before they were created. Now repeat for three or four tables.</p> <p>I don't really want to have to fiddle around with individual relationships when I could just "start transaction; disable ref integrity; sort IDs out; re-enable ref integrity; commit transaction". Mysql and MSSQL both provide this functionality IIRC so I would be surprised if Postgres didn't.</p> <p>Thanks!</p>
<p>There are two things you can do (these are complementary, not alternatives):</p> <ul> <li>Create your foreign key constraints as DEFERRABLE. Then, call "SET CONSTRAINTS DEFERRED;", which will cause foreign key constraints not to be checked until the end of the transaction. Note that the default if you don't specify anything is NOT DEFERRABLE (annoyingly).</li> <li>Call "ALTER TABLE mytable DISABLE TRIGGER ALL;", which prevents any triggers executing while you load data, then "ALTER TABLE mytable ENABLE TRIGGER ALL;" when you're done to re-enable them.</li> </ul>
<p>I think that an easear solution would be to create "temporary" columns associating where you want them to be.</p> <p>update the values with the foreign keys to the new columns</p> <p>drop the inicial columns</p> <p>rename to the new "temporary" columns to the same names then the inicial ones.</p>
16,921
<p>So I have a function that looks something like this:</p> <pre><code>float function(){ float x = SomeValue; return x / SomeOtherValue; } </code></pre> <p>At some point, this function overflows and returns a really large negative value. To try and track down exactly where this was happening, I added a cout statement so that the function looked like this:</p> <pre><code>float function(){ float x = SomeValue; cout &lt;&lt; x; return x / SomeOtherValue; } </code></pre> <p>and it worked! Of course, I solved the problem altogether by using a double. But I'm curious as to why the function worked properly when I couted it. Is this typical, or could there be a bug somewhere else that I'm missing?</p> <p>(If it's any help, the value stored in the float is just an integer value, and not a particularly big one. I just put it in a float to avoid casting.)</p>
<p>Welcome to the wonderful world of floating point. The answer you get will likely depend on the floating point model you compiled the code with. </p> <p>This happens because of the difference between the IEEE spec and the hardware the code is running on. Your CPU likely has 80 bit floating point registers that get use to hold the 32-bit float value. This means that there is far more precision while the value stays in a register than when it is forced to a memory address (also known as 'homing' the register).</p> <p>When you passed the value to cout the compiler had to write the floating point to memory, and this results in a lost of precision and interesting behaviour WRT overflow cases.</p> <p>See the MSDN documentation on VC++ <a href="http://msdn.microsoft.com/en-us/library/e7s85ffb(VS.80).aspx" rel="noreferrer">floating point switches</a>. You could try compiling with /fp:strict and seeing what happens.</p>
<p>I dont think the cout has any effect on the variable, the problem would have to be somewhere else.</p>
7,151
<p>Hello is there a way to prevent bend on print with M3D printer? </p> <p><a href="https://i.stack.imgur.com/j2IRe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j2IRe.jpg" alt="enter image description here"></a></p>
<p>You can to print a brim, a thin layer on the bottom connected to the model. This will help hold it in place. Since it is thin (one or two layers) it will not warp itself.</p> <p>The brim is not the same thing as a raft. A raft is under the model. The brim is on the same layer as the models bottom layer but outside the model. It looks something like this:</p> <p><a href="https://i.stack.imgur.com/0PvWl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0PvWl.png" alt="brim"></a></p> <p>I assume that you use a heated bed if you have one?</p> <p>Also, it is imperative that you get a good first layer. Calibrate your machine carefully.</p>
<p>Try using an adhesive before you print. This could be <a href="http://airwolf3d.com/shop/wolfbite-prevents-3d-printed-parts-from-warping" rel="nofollow noreferrer">http://airwolf3d.com/shop/wolfbite-prevents-3d-printed-parts-from-warping</a> ... What is the temperature of the room you are printing in like?</p>
469
<p>Is there an Open Source Free Graph Control for Windows Forms .NET 2.0?</p>
<p>I have been using <a href="http://zedgraph.org/wiki/index.php?title=Main_Page" rel="nofollow noreferrer">ZedGraph</a> for a while. You can generate various types of graphs that look very professional. </p>
<p>I would recommend <a href="http://www.nplot.com/" rel="nofollow noreferrer">nPlot</a></p>
26,630
<p>Is there a better, more elegant (and/or possibly faster) way than</p> <pre><code>boolean isNumber = false; try{ Double.valueOf(myNumber); isNumber = true; } catch (NumberFormatException e) { } </code></pre> <p>...?</p> <hr> <p><strong>Edit</strong>: Since I can't pick two answers I'm going with the regex one because a) it's elegant and b) saying "Jon Skeet solved the problem" is a tautology because Jon Skeet himself is the solution to all problems.</p>
<p>I don't believe there's anything built into Java to do it faster and still reliably, assuming that later on you'll want to actually parse it with Double.valueOf (or similar).</p> <p>I'd use Double.parseDouble instead of Double.valueOf to avoid creating a Double unnecessarily, <em>and</em> you can also get rid of blatantly silly numbers quicker than the exception will by checking for digits, e/E, - and . beforehand. So, something like:</p> <pre><code>public boolean isDouble(String value) { boolean seenDot = false; boolean seenExp = false; boolean justSeenExp = false; boolean seenDigit = false; for (int i=0; i &lt; value.length(); i++) { char c = value.charAt(i); if (c &gt;= '0' &amp;&amp; c &lt;= '9') { seenDigit = true; continue; } if ((c == '-' || c=='+') &amp;&amp; (i == 0 || justSeenExp)) { continue; } if (c == '.' &amp;&amp; !seenDot) { seenDot = true; continue; } justSeenExp = false; if ((c == 'e' || c == 'E') &amp;&amp; !seenExp) { seenExp = true; justSeenExp = true; continue; } return false; } if (!seenDigit) { return false; } try { Double.parseDouble(value); return true; } catch (NumberFormatException e) { return false; } } </code></pre> <p>Note that despite taking a couple of tries, this <em>still</em> doesn't cover "NaN" or hex values. Whether you want those to pass or not depends on context.</p> <p>In my experience regular expressions are slower than the hard-coded check above.</p>
<p>If you want something that's blisteringly fast, and you have a very clear idea of what formats you want to accept, you can build a state machine <a href="http://en.wikipedia.org/wiki/Deterministic_finite-state_machine" rel="nofollow noreferrer">DFA</a> by hand. This is essentially how regexes work under the hood anyway, but you can avoid the regex compilation step this way, and it may well be faster than a generic regex compiler.</p>
46,912
<p>I have a database in single user mode and I am trying to drop it so I can re-run the creation scripts on it, but I'm being locked out from it.</p> <ol> <li>How do I figure out who has the lock on it?</li> <li>How do I disable that lock?</li> </ol>
<p>run sp_who, find the spid with the database name you require, kill the spid.</p>
<p>From SQL Server Management Studio:</p> <ol> <li>open the object explorer</li> <li>expand the database server</li> <li>expand "Management"</li> <li>double-click on "Activity Monitor"</li> <li>locate the process using the desired database</li> <li>right-click on process</li> <li>click "Kill Process"</li> </ol>
12,868
<p>Has anybody got any real world stories build mobile web sites with NetBiscuits?</p> <p>Someone told me it was the next big thing in mobile development (<a href="http://www.netbiscuits.com/home" rel="nofollow noreferrer">http://www.netbiscuits.com/home</a>) and it looks pretty good from their site. Just wondered if anybody (besides them) has actually used it.</p>
<p>In addition to what @JohnIdol says correctly, I've found that you need to setup a number VS environment variables. I don't have the name of the batch file in front of me, but you can modify or 'I think' use it. It is in VS program files tree somewhere. Also, as I remember you don't want to be in a standard shell but a .NET setup shell for some paths and such. I'll add details later when I'm at a Windows PC with VS.</p> <p>EDIT: The batch file mentioned is a shortcut in ProgFiles menu. Here is the details of its properties. </p> <pre><code>%comspec% /k ""C:\Program Files\Microsoft Visual Studio 8\VC\vcvarsall.bat""x86" </code></pre> <p>Here is my batch file, using MSBuild to call the solution.</p> <pre><code>@echo off :: setup VS2005 command line build environment set VSINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8 set VCINSTALLDIR=C:\Program Files\Microsoft Visual Studio 8\VC set FrameworkDir=C:\WINDOWS\Microsoft.NET\Framework set FrameworkVersion=v2.0.50727 set FrameworkSDKDir=C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0 set DevEnvDir=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE set PATH=C:\Program Files\Microsoft Visual Studio 8\Common7\IDE;C:\Program Files\Microsoft Visual Studio 8\VC\BIN;C:\Program Files\Microsoft Visual Studio 8\Com mon7\Tools;C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\bin;C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\bin;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin;C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\VCPackages;%PATH% set INCLUDE=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\INCLUDE;C:\Program Files\Microsoft Visual Studio 8\VC\INCLUDE;C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\include;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\include;%INCLUDE% set LIB=C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC\LIB;C:\Program Files\Microsoft Visual Studio 8\VC \PlatformSDK\lib;C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\lib;%LIB% set LIBPATH=C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727;C:\Program Files\Microsoft Visual Studio 8\VC\ATLMFC\LIB echo %0 %* echo %0 %* &gt;&gt; %MrB-LOG% cd if not ""=="%~dp1" pushd %~dp1 cd if exist %~nx1 ( echo VS2005 build of '%~nx1'. echo VS2005 build of '%~nx1'. &gt;&gt; %MrB-LOG% set MrB-BUILDLOG=%MrB-BASE%\%MrB-WORK%.%MrB-NICEDATE%.%MrB-NICETIME%.build-errors.log msbuild.exe %~nx1 /t:Rebuild /p:Configuration=Release &gt; %MrB-BUILDLOG% findstr /r /c:"[1-9][0-9]* Error(s)" %MrB-BUILDLOG% if not errorlevel 1 ( echo ERROR: sending notification email for build errors in '%~nx1'. echo ERROR: sending notification email for build errors in '%~nx1'. &gt;&gt; %MrB-LOG% call mrb-email "Mr Build isn't happy about build errors in '%~nx1'" %MrB-BUILDLOG% ) else ( findstr /r /c:"[1-9][0-9]* Warning(s)" %MrB-BUILDLOG% if not errorlevel 1 ( echo ERROR: sending notification email for build warnings in '%~nx1'. echo ERROR: sending notification email for build warnings in '%~nx1'. &gt;&gt; %MrB-LOG% call mrb-email "Mr Build isn't happy about build warnings in '%~nx1'" %MrB-BUILDLOG% ) else ( echo Successful build of '%~nx1'. echo Successful build of '%~nx1'. &gt;&gt; %MrB-LOG% ) ) ) else ( echo ERROR '%1' doesn't exist. echo ERROR '%1' doesn't exist. &gt;&gt; %MrB-LOG% ) popd </code></pre>
<p>You can start msbuild from the command line. msbuild understands .sln (solution) files. You can specify the .sln file and the build configuration (debug, release etc.) from the command line.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms164311.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms164311.aspx</a> <br> Here is the documentation on what you can do with msbuild. MSBuild.exe is installed with the .net framework, not with visual studio. You can find it in c:\windows\microsoft.net\framework\v3.5 (or v2.0.50727)</p> <p>I searched a bit and found that you can also do a command line build with visual studio using devenv.exe /build, more info here:<br> <a href="http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/xee0c8y7(VS.80).aspx</a></p>
35,481
<p>I'm trying to register an atl service using</p> <p>ExeName.exe /service</p> <p>as described here: <a href="http://msdn.microsoft.com/en-us/library/74y2334x(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/74y2334x(VS.80).aspx</a></p> <p>After doing so though, it's not appearing in my services control panel (the one that I get to by typing Services in the start box on vista).</p> <p>I've tried to dig through the atl code to see where it handles the /service switch, but can't find it, although I can find code to handle /RegServer and /UnregServer</p> <p>This used to work, I've somehow managed to register this service before. But, now I've moved its location and can't get it registered again. When I run ExeName.exe /service, it does start up as a Local Server if I do a /RegServer first, but I want it installed as a service.</p> <p>Am I missing something, and do you know where the handling of the /service switch is done?</p>
<p>Running with the CAtlServiceModule::Install method out of the box, you must use the correct capitals on each argument - "/Service", "/UnregServer", etc. </p>
<p>Shot in the dark: Are you running on Vista? If so make sure you are running with full admin privleges. Otherwise it's possible you're registering this app via virtualization. </p>
33,796
<p>I have a project that has a makefile with broken dependencies. Is there any best known way to generate a list of dependencies for the project that I can use in the makefile, other than examining each source file by hand or with a hand written perl script?</p>
<p><a href="https://make.mad-scientist.net/papers/advanced-auto-dependency-generation/#combine" rel="noreferrer">GNU make</a>'s documentation provides a good solution.</p> <p>Absolutely. <code>g++ -MM &lt;your file&gt;</code> will generate a GMake compatible list of dependencies. I use something like this:</p> <pre><code># Add .d to Make's recognized suffixes. SUFFIXES += .d #We don't need to clean up when we're making these targets NODEPS:=clean tags svn #Find all the C++ files in the src/ directory SOURCES:=$(shell find src/ -name "*.cpp") #These are the dependency files, which make will clean up after it creates them DEPFILES:=$(patsubst %.cpp,%.d,$(SOURCES)) #Don't create dependencies when we're cleaning, for instance ifeq (0, $(words $(findstring $(MAKECMDGOALS), $(NODEPS)))) #Chances are, these files don't exist. GMake will create them and #clean up automatically afterwards -include $(DEPFILES) endif #This is the rule for creating the dependency files src/%.d: src/%.cpp $(CXX) $(CXXFLAGS) -MM -MT '$(patsubst src/%.cpp,obj/%.o,$&lt;)' $&lt; -MF $@ #This rule does the compilation obj/%.o: src/%.cpp src/%.d src/%.h @$(MKDIR) $(dir $@) $(CXX) $(CXXFLAGS) -o $@ -c $&lt; </code></pre> <p><strong>Note:</strong> <code>$(CXX)</code>/<code>gcc</code> command must be <a href="https://stackoverflow.com/questions/14109724/makefile-missing-separator">preceded with a hard tab</a></p> <p>What this will do is automatically generate the dependencies for each file that has changed, and compile them according to whatever rule you have in place. This allows me to just dump new files into the <code>src/</code> directory, and have them compiled automatically, dependencies and all.</p>
<p>The Digital Mars C/C++ compiler comes with a <a href="http://www.digitalmars.com/ctg/makedep.html" rel="nofollow noreferrer">makedep</a> tool.</p>
40,458
<p>I know I can edit each individual DTS package and save it as a Visual Basic script, but with hundreds of packages on the server, that will take forever. How can I script them all at once? I'd like to be able to create one file per package so that I can check them into source control, search them to see which one references a specific table, or compare the packages on our development server to the packages on our production server.</p>
<p>I ended up digging through the SQL 2000 documentation (Building SQL Server Applications / DTS Programming / Programming DTS Applications / DTS Object Model) and creating a VBS script to read the packages and write XML files. It's not complete, and it could be improved in several ways, but it's a big start:</p> <p>GetPackages.vbs</p> <pre> Option Explicit Sub GetProperties (strPackageName, dtsProperties, xmlDocument, xmlProperties) Dim dtsProperty If Not dtsProperties Is Nothing Then For Each dtsProperty in dtsProperties If dtsProperty.Set Then Dim xmlProperty Set xmlProperty = xmlProperties.insertBefore ( _ xmlDocument.createElement ("Property"), _ xmlProperties.selectSingleNode ("Property[@Name > '" & dtsProperty.Name & "']")) 'properties 'xmlProperty.setAttribute "Get", dtsProperty.Get 'xmlProperty.setAttribute "Set", dtsProperty.Set xmlProperty.setAttribute "Type", dtsProperty.Type xmlProperty.setAttribute "Name", dtsProperty.Name If not isnull(dtsProperty.Value) Then xmlProperty.setAttribute "Value", dtsProperty.Value End If 'collections 'getting properties of properties causes a stack overflow 'GetProperties strPackageName, dtsProperty.Properties, xmlDocument, xmlProperty.appendChild (xmlDocument.createElement ("Properties")) End If Next End If End Sub Sub GetOLEDBProperties (strPackageName, dtsOLEDBProperties, xmlDocument, xmlOLEDBProperties) Dim dtsOLEDBProperty For Each dtsOLEDBProperty in dtsOLEDBProperties If dtsOLEDBProperty.IsDefaultValue = 0 Then Dim xmlOLEDBProperty Set xmlOLEDBProperty = xmlOLEDBProperties.insertBefore ( _ xmlDocument.createElement ("OLEDBProperty"), _ xmlOLEDBProperties.selectSingleNode ("OLEDBProperty[@Name > '" & dtsOLEDBProperty.Name & "']")) 'properties xmlOLEDBProperty.setAttribute "Name", dtsOLEDBProperty.Name 'xmlOLEDBProperty.setAttribute "PropertyID", dtsOLEDBProperty.PropertyID 'xmlOLEDBProperty.setAttribute "PropertySet", dtsOLEDBProperty.PropertySet xmlOLEDBProperty.setAttribute "Value", dtsOLEDBProperty.Value 'xmlOLEDBProperty.setAttribute "IsDefaultValue", dtsOLEDBProperty.IsDefaultValue 'collections 'these properties are the same as the ones directly above 'GetProperties strPackageName, dtsOLEDBProperty.Properties, xmlDocument, xmlOLEDBProperty.appendChild (xmlDocument.createElement ("Properties")) End If Next End Sub Sub GetConnections (strPackageName, dtsConnections, xmlDocument, xmlConnections) Dim dtsConnection2 For Each dtsConnection2 in dtsConnections Dim xmlConnection2 Set xmlConnection2 = xmlConnections.insertBefore ( _ xmlDocument.createElement ("Connection2"), _ xmlConnections.selectSingleNode ("Connection2[@Name > '" & dtsConnection2.Name & "']")) 'properties xmlConnection2.setAttribute "ID", dtsConnection2.ID xmlConnection2.setAttribute "Name", dtsConnection2.Name xmlConnection2.setAttribute "ProviderID", dtsConnection2.ProviderID 'collections GetProperties strPackageName, dtsConnection2.Properties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement ("Properties")) Dim dtsOLEDBProperties On Error Resume Next Set dtsOLEDBProperties = dtsConnection2.ConnectionProperties If Err.Number = 0 Then On Error Goto 0 GetOLEDBProperties strPackageName, dtsOLEDBProperties, xmlDocument, xmlConnection2.appendChild (xmlDocument.createElement ("ConnectionProperties")) Else MsgBox Err.Description & vbCrLf & "ProviderID: " & dtsConnection2.ProviderID & vbCrLf & "Connection Name: " & dtsConnection2.Name, , strPackageName On Error Goto 0 End If Next End Sub Sub GetGlobalVariables (strPackageName, dtsGlobalVariables, xmlDocument, xmlGlobalVariables) Dim dtsGlobalVariable2 For Each dtsGlobalVariable2 in dtsGlobalVariables Dim xmlGlobalVariable2 Set xmlGlobalVariable2 = xmlGlobalVariables.insertBefore ( _ xmlDocument.createElement ("GlobalVariable2"), _ xmlGlobalVariables.selectSingleNode ("GlobalVariable2[@Name > '" & dtsGlobalVariable2.Name & "']")) 'properties xmlGlobalVariable2.setAttribute "Name", dtsGlobalVariable2.Name If Not Isnull(dtsGlobalVariable2.Value) Then xmlGlobalVariable2.setAttribute "Value", dtsGlobalVariable2.Value End If 'no extended properties 'collections 'GetProperties strPackageName, dtsGlobalVariable2.Properties, xmlDocument, xmlGlobalVariable2.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetSavedPackageInfos (strPackageName, dtsSavedPackageInfos, xmlDocument, xmlSavedPackageInfos) Dim dtsSavedPackageInfo For Each dtsSavedPackageInfo in dtsSavedPackageInfos Dim xmlSavedPackageInfo Set xmlSavedPackageInfo = xmlSavedPackageInfos.appendChild (xmlDocument.createElement ("SavedPackageInfo")) 'properties xmlSavedPackageInfo.setAttribute "Description", dtsSavedPackageInfo.Description xmlSavedPackageInfo.setAttribute "IsVersionEncrypted", dtsSavedPackageInfo.IsVersionEncrypted xmlSavedPackageInfo.setAttribute "PackageCreationDate", dtsSavedPackageInfo.PackageCreationDate xmlSavedPackageInfo.setAttribute "PackageID", dtsSavedPackageInfo.PackageID xmlSavedPackageInfo.setAttribute "PackageName", dtsSavedPackageInfo.PackageName xmlSavedPackageInfo.setAttribute "VersionID", dtsSavedPackageInfo.VersionID xmlSavedPackageInfo.setAttribute "VersionSaveDate", dtsSavedPackageInfo.VersionSaveDate Next End Sub Sub GetPrecedenceConstraints (strPackageName, dtsPrecedenceConstraints, xmlDocument, xmlPrecedenceConstraints) Dim dtsPrecedenceConstraint For Each dtsPrecedenceConstraint in dtsPrecedenceConstraints Dim xmlPrecedenceConstraint Set xmlPrecedenceConstraint = xmlPrecedenceConstraints.insertBefore ( _ xmlDocument.createElement ("PrecedenceConstraint"), _ xmlPrecedenceConstraints.selectSingleNode ("PrecedenceConstraint[@StepName > '" & dtsPrecedenceConstraint.StepName & "']")) 'properties xmlPrecedenceConstraint.setAttribute "StepName", dtsPrecedenceConstraint.StepName 'collections GetProperties strPackageName, dtsPrecedenceConstraint.Properties, xmlDocument, xmlPrecedenceConstraint.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetSteps (strPackageName, dtsSteps, xmlDocument, xmlSteps) Dim dtsStep2 For Each dtsStep2 in dtsSteps Dim xmlStep2 Set xmlStep2 = xmlSteps.insertBefore ( _ xmlDocument.createElement ("Step2"), _ xmlSteps.selectSingleNode ("Step2[@Name > '" & dtsStep2.Name & "']")) 'properties xmlStep2.setAttribute "Name", dtsStep2.Name xmlStep2.setAttribute "Description", dtsStep2.Description 'collections GetProperties strPackageName, dtsStep2.Properties, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement ("Properties")) GetPrecedenceConstraints strPackageName, dtsStep2.PrecedenceConstraints, xmlDocument, xmlStep2.appendChild (xmlDocument.createElement ("PrecedenceConstraints")) Next End Sub Sub GetColumns (strPackageName, dtsColumns, xmlDocument, xmlColumns) Dim dtsColumn For Each dtsColumn in dtsColumns Dim xmlColumn Set xmlColumn = xmlColumns.appendChild (xmlDocument.createElement ("Column")) GetProperties strPackageName, dtsColumn.Properties, xmlDocument, xmlColumn.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetLookups (strPackageName, dtsLookups, xmlDocument, xmlLookups) Dim dtsLookup For Each dtsLookup in dtsLookups Dim xmlLookup Set xmlLookup = xmlLookups.appendChild (xmlDocument.createElement ("Lookup")) GetProperties strPackageName, dtsLookup.Properties, xmlDocument, xmlLookup.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetTransformations (strPackageName, dtsTransformations, xmlDocument, xmlTransformations) Dim dtsTransformation For Each dtsTransformation in dtsTransformations Dim xmlTransformation Set xmlTransformation = xmlTransformations.appendChild (xmlDocument.createElement ("Transformation")) GetProperties strPackageName, dtsTransformation.Properties, xmlDocument, xmlTransformation.appendChild (xmlDocument.createElement ("Properties")) Next End Sub Sub GetTasks (strPackageName, dtsTasks, xmlDocument, xmlTasks) Dim dtsTask For each dtsTask in dtsTasks Dim xmlTask Set xmlTask = xmlTasks.insertBefore ( _ xmlDocument.createElement ("Task"), _ xmlTasks.selectSingleNode ("Task[@Name > '" & dtsTask.Name & "']")) ' The task can be of any task type, and each type of task has different properties. 'properties xmlTask.setAttribute "CustomTaskID", dtsTask.CustomTaskID xmlTask.setAttribute "Name", dtsTask.Name xmlTask.setAttribute "Description", dtsTask.Description 'collections GetProperties strPackageName, dtsTask.Properties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Properties")) If dtsTask.CustomTaskID = "DTSDataPumpTask" Then GetOLEDBProperties strPackageName, dtsTask.CustomTask.SourceCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("SourceCommandProperties")) GetOLEDBProperties strPackageName, dtsTask.CustomTask.DestinationCommandProperties, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("DestinationCommandProperties")) GetColumns strPackageName, dtsTask.CustomTask.DestinationColumnDefinitions, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("DestinationColumnDefinitions")) GetLookups strPackageName, dtsTask.CustomTask.Lookups, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Lookups")) GetTransformations strPackageName, dtsTask.CustomTask.Transformations, xmlDocument, xmlTask.appendChild (xmlDocument.createElement ("Transformations")) End If Next End Sub Sub FormatXML (xmlDocument, xmlElement, intIndent) Dim xmlSubElement For Each xmlSubElement in xmlElement.selectNodes ("*") xmlElement.insertBefore xmlDocument.createTextNode (vbCrLf & String (intIndent + 1, vbTab)), xmlSubElement FormatXML xmlDocument, xmlSubElement, intIndent + 1 Next If xmlElement.selectNodes ("*").length > 0 Then xmlElement.appendChild xmlDocument.createTextNode (vbCrLf & String (intIndent, vbTab)) End If End Sub Sub GetPackage (strServerName, strPackageName) Dim dtsPackage2 Set dtsPackage2 = CreateObject ("DTS.Package2") Dim DTSSQLStgFlag_Default Dim DTSSQLStgFlag_UseTrustedConnection DTSSQLStgFlag_Default = 0 DTSSQLStgFlag_UseTrustedConnection = 256 On Error Resume Next dtsPackage2.LoadFromSQLServer strServerName, , , DTSSQLStgFlag_UseTrustedConnection, , , , strPackageName If Err.Number = 0 Then On Error Goto 0 'fsoTextStream.WriteLine dtsPackage2.Name Dim xmlDocument Set xmlDocument = CreateObject ("Msxml2.DOMDocument.3.0") Dim xmlPackage2 Set xmlPackage2 = xmlDocument.appendChild (xmlDocument.createElement ("Package2")) 'properties xmlPackage2.setAttribute "Name", dtsPackage2.Name 'collections GetProperties strPackageName, dtsPackage2.Properties, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement("Properties")) GetConnections strPackageName, dtsPackage2.Connections, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Connections")) GetGlobalVariables strPackageName, dtsPackage2.GlobalVariables, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("GlobalVariables")) 'SavedPackageInfos only apply to DTS packages saved in structured storage files 'GetSavedPackageInfos strPackageName, dtsPackage2.SavedPackageInfos, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("SavedPackageInfos")) GetSteps strPackageName, dtsPackage2.Steps, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Steps")) GetTasks strPackageName, dtsPackage2.Tasks, xmlDocument, xmlPackage2.appendChild (xmlDocument.createElement ("Tasks")) FormatXML xmlDocument, xmlPackage2, 0 xmlDocument.save strPackageName + ".xml" Else MsgBox Err.Description, , strPackageName On Error Goto 0 End If End Sub Sub Main Dim strServerName strServerName = Trim (InputBox ("Server:")) If strServerName "" Then Dim cnSQLServer Set cnSQLServer = CreateObject ("ADODB.Connection") cnSQLServer.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=msdb;Data Source=" & strServerName Dim rsDTSPackages Set rsDTSPackages = cnSQLServer.Execute ("SELECT DISTINCT name FROM sysdtspackages ORDER BY name") Dim strPackageNames Do While Not rsDTSPackages.EOF GetPackage strServerName, rsDTSPackages ("name") rsDTSPackages.MoveNext Loop rsDTSPackages.Close set rsDTSPackages = Nothing cnSQLServer.Close Set cnSQLServer = Nothing Dim strCustomTaskIDs Dim strCustomTaskID MsgBox "Finished", , "GetPackages.vbs" End If End Sub Main </pre>
<p>You might try working with the system table sysdtspackages as demonstrated on sqldts.com in <a href="http://www.sqldts.com/204.aspx" rel="nofollow noreferrer">Transferring DTS Packages</a>.<br> Also, there used to be many tools available for MS SQL 2000 before the new versions proliferated. I found one, called <a href="http://labs.red-gate.com/index.php/DTS_Package_Compare" rel="nofollow noreferrer">DTS Package Compare</a>, as a free download at Red Gate Labs.</p>
11,282
<p>I'm trying to subclass NSCell for use in a NSTableView. The cell I want to create is fairly complicated so it would be very useful if I could design it in Interface Builder and then load the NSCell from a nib.</p> <p>Is this possible? How do I do it?</p>
<p>The question was about a subclass of NSCell; the other answers seem to be doing something else, likely taking advantage of UITableViewCell being a view.</p> <p>NSCell is not a view. While laying a custom cell out in IB would be a useful thing to be able to do, I think the answer is basically "no, this is not possible". When you subclass NSCell, you're pretty much just doing your own drawing. There isn't support subcells, or parameterized auto layout (ala NSView's springs and struts), which is I suspect what you're looking for.</p> <p>The only caveat is that you could design an NSCell subclass that <em>did</em> do layout of sub-elements and provided parameters for setting those subelements and all tweakable parameters. Then, you would need to write an IB plugin to make that cell and accompanying inspector available at design time in IB. </p> <p>This, however, is probably harder than writing a little custom app that does more or less the same thing. Put an NSCell in a control in the middle of a window, and make yourself UI for tweaking the parameters you're interested in. Bindings can make this pretty straightforward for positioning stuff (i.e. bind an x value to a slider), though you will not get direct manipulation of the elements of course. When you're done, you could archive your cell and load the archive at runtime in your real app, or you could just log out the properties and set them in code in your app.</p>
<p>Add your <code>UITableViewCell</code> to your <code>tableviewcontroller</code> and declare an <code>IBOutlet</code> property:</p> <pre><code>@interface KuguTableViewController : UITableViewController { IBOutlet UITableViewCell *customTypeCell; } @property (readonly) UITableViewCell *customTypeCell; </code></pre> <p>... then in <code>cellForRowAtIndexPath</code> you can just use your cell and set it to be reused:</p> <pre><code>static NSString *CellIdentifier = @"CustomCell" cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) cell = customTypeCell; cell.reuseIdentifier = CellIdentifier; </code></pre>
24,760
<p>So I have a "large" number of "very large" ASCII files of numerical data (gigabytes altogether), and my program will need to process the entirety of it sequentially at least once.</p> <p>Any advice on storing/loading the data? I've thought of converting the files to binary to make them smaller and for faster loading.</p> <p>Should I load everything into memory all at once?<br> If not, is opening what's a good way of loading the data partially?<br> What are some Java-relevant efficiency tips?</p>
<blockquote> <p>So then what if the processing requires jumping around in the data for multiple files and multiple buffers? Is constant opening and closing of binary files going to become expensive?</p> </blockquote> <p>I'm a big fan of <em>'memory mapped i/o'</em>, aka <em>'direct byte buffers'</em>. In Java they are called <strong><a href="http://docs.oracle.com/javase/8/docs/api/java/nio/MappedByteBuffer.html" rel="nofollow noreferrer">Mapped Byte Buffers</a></strong> are are part of java.nio. (Basically, this mechanism uses the OS's virtual memory paging system to 'map' your files and present them programmatically as byte buffers. The OS will manage moving the bytes to/from disk and memory auto-magically and very quickly. </p> <p>I suggest this approach because a) it works for me, and b) it will let you focus on your algorithm and let the JVM, OS and hardware deal with the performance optimization. All to frequently, they know what is best more so than us lowly programmers. ;)</p> <p>How would you use MBBs in your context? Just create an MBB for each of your files and read them as you see fit. You will only need to store your results. .</p> <p>BTW: How much data are you dealing with, in GB? If it is more than 3-4GB, then this won't work for you on a 32-bit machine as the MBB implementation is defendant on the addressable memory space by the platform architecture. A 64-bit machine &amp; OS will take you to 1TB or 128TB of mappable data.</p> <p>If you are thinking about performance, then know Kirk Pepperdine (a somewhat famous Java performance guru.) He is involved with a website, www.JavaPerformanceTuning.com, that has some more MBB details: <strong><a href="http://www.javaperformancetuning.com/tips/nio.shtml#REF1" rel="nofollow noreferrer">NIO Performance Tips</a></strong> and other Java performance related things.</p>
<p>You really haven't given us enough info to help you. Do you need to load each file in its entiretly in order to process it? Or can you process it line by line?</p> <p>Loading an entire file at a time is likely to result in poor performance even for files that aren't terribly large. Your best bet is to define a buffer size that works for you and read/process the data a buffer at a time.</p>
11,323
<p>So my project has a trunk where we make all development changes to. We also have a branch with slightly modified parameters to accommodate another department. We work in batches, and once we are done with a set of changes to the trunk, switch over to the branch and merge all appropriate revisions. This has been going on a while but I have noticed some odd behavior. If I open the revision graph and compare two head revisions (the trunk and the branch, I could also do this through the repo browser) it displays a list of all files that are different between the two. The problem is when I double-click on some files there are actually no textual differences in the files. There is not supposed to be any differences, but it shouldn't mark it as different then right? This is making it harder to audit both branches and keep track of differences because lots of files are appearing in the "changed files" dialog.</p> <p>A few things I have noticed:</p> <ul> <li><p>The revision numbers are different between the two files (as expected)</p></li> <li><p>I tried reproducing this issue in a test repository by merging and then comparing the branches, but it worked fine (no differences) </p></li> <li>I originally thought this might have something to do with differences between svn:mergeinfo properties but I am not so sure anymore.</li> </ul> <p>Any help would be appreciated.</p>
<p>A common culprit is line endings. Are some of your development machines windows and the others *nix-based? The different line endings, if not accounted for or translated, will cause files to not exactly match.</p>
<p>Well, what I'd recommend trying is using some other merging software. Not sure if Tortoise SVNCompare highlights whitespace changes as obviously as WinMerge does, for example.</p>
30,179
<p>I have a collection of classes that I want to serialize out to an XML file. It looks something like this:</p> <pre><code>public class Foo { public List&lt;Bar&gt; BarList { get; set; } } </code></pre> <p>Where a bar is just a wrapper for a collection of properties, like this:</p> <pre><code>public class Bar { public string Property1 { get; set; } public string Property2 { get; set; } } </code></pre> <p>I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form. </p> <p>I want to get a nice XML representation like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Foo&gt; &lt;BarList&gt; &lt;Bar&gt; &lt;Property1&gt;Value&lt;/Property1&gt; &lt;Property2&gt;Value&lt;/Property2&gt; &lt;/Bar&gt; &lt;Bar&gt; &lt;Property1&gt;Value&lt;/Property1&gt; &lt;Property2&gt;Value&lt;/Property2&gt; &lt;/Bar&gt; &lt;/Barlist&gt; &lt;/Foo&gt; </code></pre> <p>where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination.</p> <p>I've marked Foo with the attribute </p> <pre><code>[XmlRoot("Foo")] </code></pre> <p>and the <code>list&lt;Bar&gt;</code> with the attribute</p> <pre><code>[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")] </code></pre> <p>in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Foo&gt; &lt;Barlist /&gt; &lt;/Foo&gt; </code></pre> <p>I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me.</p>
<p>Just to check, have you marked Bar as [Serializable]?</p> <p>Also, you need a parameter-less ctor on Bar, to deserialize</p> <p>Hmm, I used:</p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Foo f = new Foo(); f.BarList = new List&lt;Bar&gt;(); f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" }); XmlSerializer ser = new XmlSerializer(typeof(Foo)); using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create)) { ser.Serialize(fs, f); } } } public class Foo { [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")] public List&lt;Bar&gt; BarList { get; set; } } [XmlRoot("Foo")] public class Bar { public string Property1 { get; set; } public string Property2 { get; set; } } </code></pre> <p>And that produced:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;BarList&gt; &lt;Bar&gt; &lt;Property1&gt;abc&lt;/Property1&gt; &lt;Property2&gt;def&lt;/Property2&gt; &lt;/Bar&gt; &lt;/BarList&gt; &lt;/Foo&gt; </code></pre>
<p>It has been over 5 years since this item was posted. I give my experience from July 2013 (.NET Framework 4.5). For what it's worth and to whom it may concern:</p> <p>When I define a class like so: (VB.Net code)</p> <pre><code>&lt;Serializable&gt; Public Class MyClass Public Property Children as List(of ChildCLass) &lt;XmlAttribute&gt; Public Property MyFirstProperty as string &lt;XmlAttribute&gt; Public Property MySecondProperty as string End Class &lt;Serializable&gt; Public Class ChildClass &lt;XmlAttribute&gt; Public Property MyFirstProperty as string &lt;XmlAttribute&gt; Public Property MySecondProperty as string End Class </code></pre> <p>With this definition the class is (de)serialized without any problems. This is the XML that comes out of here:</p> <pre><code>&lt;MyClass&gt; MyFirstProperty="" MySecondProperty="" &lt;Children&gt; &lt;ChildClass&gt; MyFirstProperty="" MySecondProperty="" &lt;/ChildClass&gt; &lt;/Children&gt; &lt;/MyClass&gt; </code></pre> <p>It only took me two days to figure it out that the solution was to leave out the <code>&lt;XmlElement&gt;</code> prefix of the List(of T) elements.</p>
21,568
<p>I have a list of objects, each containing an Id, Code and Description.</p> <p>I need to convert this list into a Hashtable, using <strong>Description</strong> as the key and <strong>Id</strong> as the value.</p> <p>This is so the Hashtable can then be serialised to JSON.</p> <p>Is there a way to convert from List&lt;Object&gt; to Hashtable without writing a loop to go through each item in the list?</p>
<p>Let's assume that your List contains objects of type Foo (with an int Id and a string Description).</p> <p>You can use Linq to turn that list into a Dictionary like this:</p> <pre><code>var dict = myList.Cast&lt;Foo&gt;().ToDictionary(o =&gt; o.Description, o =&gt; o.Id); </code></pre>
<p>Also look at the <code>System.Collections.ObjectModel.KeyedCollection&lt;TKey, TItem&gt;</code>. It seems like a better match for what you want to do.</p>
20,067
<p>I'm using a MSSQL database and would like to create a column that only has 4 possible values. Is there any way to define a 2-bit column? I see the bit datatype and then the next smallest is tinyint which is 1 full byte.</p> <p>If there is no such field, I'd be interesting in finding out why not.</p> <p>Thanks.</p>
<p>I don't see the reason for such a field.</p> <p>It definately cannot be space - that's cheap today, and an economy of 6 bits is really negligible unless you have lots of rows. But in that case it will take up much space anyway, and extra 6 bits per row will again hardly make a difference.</p> <p>Speed is also not a valid reason. Such bit fields would require additional manipulation to store and retrieve, making the whole process a lot slower than simply dealing with a whole byte.</p> <p>Lastly, if it's about constraints, then you should use foreign keys or user-defined types (though that would require additional coding in .NET). Although I'd simply use a byte and implement the constraint in my application. Not so nice perhaps, but heck of a lot easier.</p> <p><b>Update:</b> Although, yes, an "enum" constraint would be useful in MSSQL. But that's again a little different than simply a 2-bit field.</p>
<p>Unless your database is being stored on a floppy disk, I wouldn't sweat it. Take the advice of the rest here and move on with building the rest of the database.</p>
42,292
<p>I have a very standard <code>Gridview</code>, with Edit and Delete buttons auto-generated. It is bound to a <code>tableadapter</code> which is linked to my <code>RelationshipTypes</code> table.</p> <pre><code>dbo.RelationshipTypes: ID, Name, OriginConfigTypeID, DestinationConfigTypeID </code></pre> <p>I wish to use a label that will pull the name from the <code>ConfigTypes</code> table, using the <code>OriginConfigTypeID</code> and <code>DestinationTypeID</code> as the link.</p> <pre><code>dbo.ConfigTypes: ID, Name </code></pre> <p>My problem is, I can't automatically generate Edit and Delete buttons using an <code>Inner Join</code> in my dataset. Or can I?</p> <p>Here is my code:</p> <pre><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CssClass="TableList" DataKeyNames="ID" DataSourceID="dsRelationShipTypes1"&gt; &lt;Columns&gt; &lt;asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" Visible=False/&gt; &lt;asp:TemplateField HeaderText="Origin" SortExpression="OriginCIType_ID"&gt; &lt;EditItemTemplate&gt; &amp;nbsp;&lt;asp:DropDownList Enabled=true ID="DropDownList2" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='&lt;%# Bind("OriginCIType_ID") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &amp;nbsp; &lt;asp:Label ID="Label2" runat="server" Text='&lt;%# Bind("OriginCIType_ID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Name" SortExpression="Name"&gt; &lt;EditItemTemplate&gt; &lt;asp:TextBox ID="TextBox3" runat="server" Text='&lt;%# Bind("Name") %&gt;'&gt;&lt;/asp:TextBox&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label3" runat="server" Text='&lt;%# Bind("Name") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Destination" SortExpression="DestinationCIType_ID"&gt; &lt;EditItemTemplate&gt; &lt;asp:DropDownList ID="DropDownList3" runat="server" DataSourceID="dsCIType1" DataTextField="Name" DataValueField="ID" SelectedValue='&lt;%# Bind("DestinationCIType_ID") %&gt;'&gt; &lt;/asp:DropDownList&gt; &lt;/EditItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label1" runat="server" Text='&lt;%# Bind("DestinationCIType_ID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>So I did try to create my own edit and delete buttons, but kept receiving the error </p> <blockquote> <p>"cannot find update method"</p> </blockquote> <p>or something similar. Do I have to manually code the delete and update methods in my code-behind?</p>
<p>You'll have to skip the deferred execution with a call to ToList, which probably won't hurt your performance in large documents as you're just going to be iterating and replacing at a much lower big-O than the original search. As @jacob_c pointed out, I should be using element.Nodes() to replace it properly, and as @Panos pointed out, I should reverse the list in order to handle nested replacements accurately.</p> <p>Also, use <a href="http://msdn.microsoft.com/en-us/library/system.xml.linq.xelement.replacewith.aspx" rel="nofollow noreferrer">XElement.ReplaceWith</a>, much faster than your current approach in large documents:</p> <pre><code>var elements = doc.Descendants("RemovalTarget").ToList().Reverse(); /* reverse on the IList&lt;T&gt; may be faster than Reverse on the IEnumerable&lt;T&gt;, * needs benchmarking, but can't be any slower */ foreach (var element in elements) { element.ReplaceWith(element.Nodes()); } </code></pre> <p>One last point, in reviewing what this MAY be used for, I tend to agree with @Trull that XSLT may be what you're actually looking for, if say you're removing all say &lt;b&gt; tags from a document. Otherwise, enjoy this fairly decent and fairly well performing LINQ to XML implementation.</p>
<p>I would recommend either doing XSLT as Trull recommended as the best solution.</p> <p>Or you might look at using a string builder and regex matching to remove the items.</p> <p>You could look at walking through the document, and working with nodes and parent nodes to effectively move the code from inside the node to the parent, but it would be tedious, and very un-necessary with the other potential solutions out there.</p>
32,474
<p>What's the simplest way to add a click event handler to a canvas element that will return the x and y coordinates of the click (relative to the canvas element)?</p> <p>No legacy browser compatibility required, Safari, Opera and Firefox will do.</p>
<p>If you like simplicity but still want cross-browser functionality I found this solution worked best for me. This is a simplification of @Aldekein´s solution but <strong>without jQuery</strong>.</p> <pre><code>function getCursorPosition(canvas, event) { const rect = canvas.getBoundingClientRect() const x = event.clientX - rect.left const y = event.clientY - rect.top console.log("x: " + x + " y: " + y) } const canvas = document.querySelector('canvas') canvas.addEventListener('mousedown', function(e) { getCursorPosition(canvas, e) }) </code></pre>
<p>Hey, this is in dojo, just cause it's what I had the code in already for a project.</p> <p>It should be fairly Obvious how to convert it back to non dojo vanilla JavaScript. </p> <pre><code> function onMouseClick(e) { var x = e.clientX; var y = e.clientY; } var canvas = dojo.byId(canvasId); dojo.connect(canvas,"click",onMouseClick); </code></pre> <p>Hope that helps. </p>
7,949
<p><strong>Keep in mind that I'm not looking for a list of current browsers to support, I'm looking for logical ways to make that list, backed by some kind of hard statistics.</strong> </p> <p>Since it's been a while since my last web job, I decided to do this latest site up from scratch. Now I have to decide <em>again</em> what to support in terms of browsers. Certainly I have a list of what I'd like to support, but the decisions that went into that list seem to be a little arbitrary to me. Where can I go to get a reliable picture of browser usage and what seems to be a good point at which to cut off an old version of a browser from support?</p>
<p>Browsers don't die out completely for about a decade. The first thing you must realise is that you <em>will</em> have some visitors that are using a browser you don't support. The question is not which browsers are not dead, but which browsers are worth supporting (the benefit) relative to the work it takes to do so (the cost).</p> <p>I've never seen browser statistics I'm comfortable recommending, they all seem to be snake oil. A rule of thumb I feel is appropriate is that a browser isn't worth supporting if somebody using that browser is going to regularly run into problems on other websites as well. In other words "stick with what everybody else is supporting". To that end, <a href="http://developer.yahoo.com/yui/articles/gbs/index.html" rel="noreferrer">Yahoo's graded browser support</a> is useful.</p> <p>Ultimately, the best choice depends on your individual circumstances and will change over time. For instance, <a href="http://37signals.blogs.com/products/2008/07/basecamp-phasin.html" rel="noreferrer">37signals have recently dropped support for Internet Explorer 6</a> and <a href="http://www.kryogenix.org/days/2008/08/27/facebook-doesnt-really-support-ie6" rel="noreferrer">Facebook are slowly heading in the same direction</a>. This isn't a decision that most organisations can make yet, but give it a year or two and you'll see a lot more organisations follow suit. Right now, it's a bold step that you probably can't justify, but give it time.</p> <p>Don't fall into the trap of thinking that supporting as many browsers as possible is automatically the best choice - it may be that you are doing your visitors a disservice by wasting time working on compatibility with a browser used by five people when you could be improving the experience for the other million users you have.</p> <p>Also, it's worth considering that you can "officially" not support a browser. For example, one thing I've done in the past is use JavaScript served only to Internet Explorer 5.5 and below (via a conditional comment), to automatically remove stylesheets, JavaScript and replace images with their <code>alt</code> text. Without those measures, the site would be unreadable due to Internet Explorer's many layout bugs, but with it, the site at least works, even if it's too much work to "support" it.</p>
<p>My opinion (has always been) build it to the standards and leave it to the browsers to render it correctly.</p>
11,414
<p>I'm working on a Zend Framework (1.7) project with a structure loosely based on the structure of the quickstart application - front controller, action controllers, views &amp; models that use Zend_Db_Table to get to the database. One of my main models relies on some expensive joins to pull up its primary listing, so I'm looking into using Zend_Paginator to reduce the number of rows brought back from the database. My problem is that Zend_Paginator only comes with 4 adaptors, none of which really seem to be a good fit for me.</p> <ul> <li><strong>Array</strong> : Building the array to feed to ZP would involve fetching all the records which is what I'm trying to avoid</li> <li><strong>Iterator</strong> : A dumb iterator would present the same problems as an array and a smart one feels like it would be a poor fit for the Model</li> <li><strong>DbSelect</strong> : Getting a DbSelect object up to the Controller would uncomfortably tie the Controller to the inner workings of my DB (not to mention producing raw result rows rather than encapsulated objects)</li> <li><strong>DbTableSelect</strong> : same as DbSelect</li> <li><strong>Null Adapter</strong> : pass all the details back and forth manually.</li> </ul> <p>Passing the paginator into the model feels like it, too, would violate the MVC separation. Is the problem that I've built my model incorrectly, that I'm being to dogmatic about maintaining MVC separation or am I missing a clean, elegant way of sticking all the moving parts together?</p>
<p>You can provide an interface on your models that accepts <code>$current_page</code> and <code>$per_page</code> parameters and returns the current page's data set as well as a paginator object.</p> <p>This way all your pagination code is contained within the model and you are free to use the Db adapters without feeling like you've broken the concept.</p> <p>Plus, the controller really shouldn't be setting up the pager anyways since you are correct in it being tied to the data (and models are for data, not just database connections).</p> <pre><code>class Model { //... /** * @return array Array in the form: array( 'paginator' =&gt; obj, 'resultset' =&gt; obj ) */ public function getAll( $where = array(), $current_page = null, $per_page = null ); //... } </code></pre>
<p>Well, I can't give you an answer to your concerns with using DbSelect but I did come across this bit of code (in the comments of the ibuildings blog) relating to the issue of reducing the number of rows pulled. Might be useful to some readers. </p> <pre><code>$select = $db-&gt;from('users')-&gt;order('name'); $paginator = new Zend_Paginator(new Zend_Paginator_Adapter_DbSelect($select)); $paginator-&gt;setCurrentPageNumber($this-&gt;_getParam('page', 1)); $paginator-&gt;setItemCountPerPage(25); $this-&gt;view-&gt;paginator = $paginator; </code></pre>
44,568
<p>I've got such a simple code:</p> <pre><code>&lt;div class="div1"&gt; &lt;div class="div2"&gt;Foo&lt;/div&gt; &lt;div class="div3"&gt; &lt;div class="div4"&gt; &lt;div class="div5"&gt; Bar &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and this CSS:</p> <pre class="lang-css prettyprint-override"><code>.div1{ position: relative; } .div1 .div3 { position: absolute; top: 30px; left: 0px; width: 250px; display: none; } .div1:hover .div3 { display: block; } .div2{ width: 200px; height: 30px; background: red; } .div4 { background-color: green; color: #000; } .div5 {} </code></pre> <p>The problem is: When I move the cursor from <code>.div2</code> to <code>.div3</code> (<code>.div3</code> should stay visible because it's the child of <code>.div1</code>) then the hover is disabled. I'm testing it in IE7, in FF it works fine. What am I doing wrong? I've also realized that when i remove <code>.div5</code> tag than it's working. Any ideas?</p>
<p>IE7 won't allow you to apply <code>:hover</code> pseudo-classes to non-anchor elements unless you explicitly specify a doctype. Just add a doctype declaration to your page and it should work perfectly.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt; </code></pre> <p>More on IE7/quirks mode can be found on <a href="http://www.bernzilla.com/item.php?id=762" rel="noreferrer">this blog post</a>.</p>
<p>I found that this solution worked better and was a bit cleaner:</p> <pre><code> &lt;style type="text/css"&gt; * { color: #fff; } .wrapper { } .trigger { background: #223; } .appear { background: #334; display: none; } .trigger:hover .appear { display: block; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrapper"&gt; &lt;div class="trigger"&gt; &lt;p&gt;This is the trigger for the hover element.&lt;/p&gt; &lt;div class="appear"&gt; &lt;p&gt;I'm &lt;strong&gt;alive!&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p><a href="http://paste2.org/p/79237" rel="nofollow noreferrer">pastebin</a>.</p>
17,308
<p>I've been using Lisp on and off for a while but I'm starting to get more serious about doing some "real" work in Lisp. I'm a huge Vim fan and was wondering how I can be most productive using Vim as my editor for Lisp development. Plugins, work flow suggestions, etc. are all welcome.</p> <p>Please don't say "use emacs" as I've already ramped up on Vim and I'm really enjoying it as an editor.</p>
<p>Limp aims to be a fully featured Common Lisp IDE for Vim. It defaults to SBCL, but can be changed to support most other implementations by replacing "sbcl" for your favourite lisp, in the file /usr/local/limp/latest/bin/lisp.sh</p> <p>When discussing Lisp these days, it is commonly assumed to be Common Lisp, the language standardized by ANSI X3J13 (see <a href="http://l1sp.org/cl" rel="nofollow noreferrer">the HyperSpec</a>, and <a href="http://gigamonkeys.com/book" rel="nofollow noreferrer">Practical Common Lisp</a> for a good textbook) with implementations such as GNU Clisp, SBCL, CMUCL, AllegroCL, and many others.</p> <p>Back to Limp. There are other solutions that are more light-weight, or try to do other things, but I believe in providing an environment that gives you things like bracket matching, highlighting, documentation lookup, i.e. making it a turn-key solution as much as possible.</p> <p>In <a href="https://svn.jansson.be/limp" rel="nofollow noreferrer">the Limp repository</a> you'll find some of the previous work of the SlimVim project, namely the ECL (Embeddable Common Lisp) interface, merged with later releases (7.1); Simon has also made patches to 7.2 available yet to be merged. The ECL interface is documented in <a href="https://svn.jansson.be/limp/vim-ecl/vim/runtime/doc/if_ecl.txt" rel="nofollow noreferrer">if_ecl.txt</a>.</p> <p>Short-term work is to do said merging with 7.2 and submit a patch to vim_dev to get it merged into the official Vim tree.</p> <p>Which leads us to the long-term plans: having Lisp directly in Vim will make it convenient to start working on a SWANK front-end (the part of SLIME that runs in your Lisp, with slime.el being the part that runs in the editor - the frontend).</p> <p>And somewhere in between, it is likely that all of Limp will be rewritten in Common Lisp using the ECL interface, making Limp easier to maintain (VimScript isn't my favourite) and being easier for users to customize.</p> <p>The <a href="https://common-lisp.net/project/limp/" rel="nofollow noreferrer">official Limp site</a> goes down from time to time, but as pointed out, the <a href="http://www.vim.org/scripts/script.php?script_id=2219" rel="nofollow noreferrer">download at Vim.org</a> should always work, and the support groups <a href="http://groups.google.com/group/limp-devel" rel="nofollow noreferrer">limp-devel</a> and <a href="http://groups.google.com/group/limp-user" rel="nofollow noreferrer">limp-user</a> are hosted with Google Groups. Don't hesitate to join if you feel you need a question answered, or perhaps even want to join in on development. Most of the discussion takes place on the limp-devel list. If you're into IRC, I'm in #limp on irc.freenode.net as 'tic'.</p> <p>Good luck!</p>
<p>I know you said not to tell you to use Emacs.</p> <p>Use Emacs.</p> <p>Serious, the <a href="http://common-lisp.net/project/slime/" rel="nofollow noreferrer">SLIME</a> setup for Emacs is pretty much <em>the</em> standard development platform for Lisp, and for very good reason.</p>
12,039
<p>Are there any Web page designing software out there that allow me to drag and drop controls just like desktop applications. I found it quite difficult to design a web page using the designer in Visual Studio 2008 as it constrains me to a flow or grid layout. (I am not an accomplished designer but there should be some ease as one experiences while designing desk top applications).</p> <p>Thanx in advance.</p>
<p>You should have no problem with using Dreamweaver and then transferring it to Visual Studio.</p> <p>After all, they both spit out HTML and CSS.</p> <p>Be aware though, the HTML and CSS they spit out is very bloated and a maintenance nightmare if you decide to jump into the markup.</p> <p>You may also want to have a look into CSS grid layouts that already exist, such as <a href="http://www.blueprintcss.org/" rel="nofollow noreferrer">Blueprint</a>, <a href="http://960.gs/" rel="nofollow noreferrer">960 Grid system</a> and <a href="http://developer.yahoo.com/yui/grids/" rel="nofollow noreferrer">Yahoo Grids CSS</a>, and try and integrate those with Dreamweaver/VS. The Yahoo Grids CSS even has a tool which lets you build a grid from scratch.</p>
<p>Are you looking for something like <a href="http://www.adobe.com/products/dreamweaver/" rel="nofollow noreferrer">Dreamweaver?</a></p>
37,661
<pre><code>LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&amp;pUnkReturn, 0); </code></pre> <p>The value of result after the call is 0</p> <p>I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .</p> <p>Necessary Information before this call :</p> <pre><code>const UINT CMotionUtils::s_MaxGetTaskInterface = RegisterWindowMessage(_T("NI:Max:GetTaskInterface")); </code></pre> <p>The value of <code>s_MaxGetTaskInterface</code> i get here is 49896 . </p> <p>The value of hWnd is also proper . I checked that with Spy++ ( Visual Studio tool ) .</p> <p>Microft Spy++ Messages window shows me the following for this window . </p> <pre><code>&lt;00001&gt; 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000 &lt;00002&gt; 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000 </code></pre> <p>Please help me to get a valid address stored in pUnkReturn after the call . </p>
<p>I think the &amp; in &amp;pUnkReturn is needed, based on the hungarian prefix. I expect pUnkReturn to have type IUnknown*. The message receiver will provide the IUnknown*. The address where it will store that IUnknown* is an IUnknown**. Hence, this code passes in &amp;pUnkReturn and the message receiver writes to *(IUnknown**)wParam.</p>
<p>When I Googled for <code>NI:Max:GetTaskInterface</code> I couldn't find anything. In general, how a window will handle a given message depends entirely on the window concerned. Does the window (specified by <code>hWnd</code>) even support the <code>NI:Max:GetTaskInterface</code> message?</p>
12,595
<p>I'm trying to write some SQL that will delete files of type '.7z' that are older than 7 days.</p> <p>Here's what I've got that's not working:</p> <pre><code>DECLARE @DateString CHAR(8) SET @DateString = CONVERT(CHAR(8), DATEADD(d, -7, GETDATE()), 1) EXECUTE master.dbo.xp_delete_file 0, N'e:\Database Backups',N'7z', @DateString, 1 </code></pre> <p>I've also tried changing the '1' at the end to a '0'.</p> <p>This returns 'success', but the files aren't getting deleted.</p> <p>I'm using SQL Server 2005, Standard, w/SP2.</p>
<p>Had a similar problem, found various answers. Here's what I found.</p> <p>You can't delete 7z files with xp_delete_file. This is an undocumented extended stored procedure that's a holdover from SQL 2000. It checks the first line of the file to be deleted to verify that it is either a SQL backup file or a SQL report file. It doesn't check based on the file extension. From what I gather its intended use is in maintenance plans to cleanup old backups and plan reports. </p> <p>Here's a sample based on Tomalak's link to delete backup files older than 7 days. What trips people up is the 'sys' schema, the trailing slash in the folder path, and no dot in the file extension to look for. The user that SQL Server runs as also needs to have delete permissions on the folder.</p> <pre><code>DECLARE @DeleteDate datetime SET @DeleteDate = DateAdd(day, -7, GetDate()) EXECUTE master.sys.xp_delete_file 0, -- FileTypeSelected (0 = FileBackup, 1 = FileReport) N'D:\SQLbackups\', -- folder path (trailing slash) N'bak', -- file extension which needs to be deleted (no dot) @DeleteDate, -- date prior which to delete 1 -- subfolder flag (1 = include files in first subfolder level, 0 = not) </code></pre> <p>Note that xp_delete_file is broken in SP2 and won't work on report files; there's a hotfix for it at [<a href="http://support.microsoft.com/kb/938085]" rel="noreferrer">http://support.microsoft.com/kb/938085]</a>. I have not tested it with SP3. </p> <p>Since it's undocumented, xp_delete_file may go away or change in future versions of SQL Server. Many sites recommend a shell script to do the deletions instead.</p>
<p>Try changing the first parameter from 0 to 1.</p> <p>Here is a small <a href="http://nikeshikari.blogspot.com/2008/05/tech-mssql-xpdeletefile.html" rel="nofollow noreferrer">summary on <code>xp_delete_file</code></a> I just found. Sounds a bit like you'd be out of luck with this procedure.</p>
26,129
<p>I set my ASP.NET State service to automatic start the other day on a hosted VSP Win 2003 server. I came back today and the service has gone completely missing!?</p> <p>Any ideas why it has gone and how to get it back? Thanks!</p>
<p>You should ask your hosting service provider, they may have removed it (for some reason).</p>
<p>I have had the same problem, that the ASP.NET State service disappeared from the Administrative Tools / Services list. And the command "net start aspnet_state" didn't work either.</p> <p>For me it worked fine after doing a repair on the currently latest .net version. Net 4.0 in my case.</p>
17,811
<p>I have a big red button and I'm trying to use javascript to perform the following: -</p> <ol> <li>OnMouseDown change image so the button looks depressed</li> <li>OnMouseUp return to the initial image AND reveal a hidden div</li> </ol> <p>I can get the onMouse Down and onMouseUp image changes part to work.</p> <p>I can also get the hidden div to reveal by using OnClick</p> <p>The problem is I can't get it all to work together. </p> <p>How do I do this?</p> <p>BTW, I'm sure its obvious, but I'm fairly new to javascript, so I appreciate your help</p>
<p>You can use semicolons to separate multiple script statements in an event:</p> <pre><code>&lt;img src="..." alt="..." onmousedown="depressed();" onmouseup="undepressed(); revealDiv();" /&gt; </code></pre> <p>Also, I believe most browsers support the onclick event:</p> <pre><code>&lt;img src="..." alt="..." onmousedown="depressed();" onmouseup="undepressed();" onclick="revealDiv();" /&gt; </code></pre> <p>Since you said you had already figured out each of the 3 parts separately, I just wrote function calls that you can replace with your own code for each step.</p>
<p>Without seeing your code, it's hard to say, but I suspect a missing 'return true;' statement at the end of either the onclick or onmouseup event handlers.</p>
46,328
<p>I have a javascript heavy app which has widgets like autocomplete dropdowns and tabs and so forth. Sometimes when dropdowns appear and disappear, or when you switch between tabs, it changes the height of the document. This can cause annoyances if the scrollbar appears and disappears rapidly, because it shifts the page. I would like to detect when a page changes its height, so I can fix the height to the maximum so far, so that if the scrollbar appears it won't disappear only a second later. Any suggestions?</p> <p><em>Update: onresize won't work because that's for changes in the size of the viewport/window - I want changes in the length of the document. I hadn't known about the watch function, looks like it will work at least for FF, but IE doesn't support it.</em></p>
<p>I belive this question has already been answered on stackoverflow here: <a href="https://stackoverflow.com/questions/14866775/detect-document-height-change">Detect Document Height Change</a></p> <p>Basically you have to store the current document height and keep checking for a change via a timeoutcall</p> <p>The element to watch here is document.body.clientHeight (or in jquery $(document).height() )</p>
<p>One idea would be to use the watch() method on the clientHeight property:</p> <pre><code>document.body.watch("clientHeight", function(property, oldHeight, newHeight) { // what you want to do when the height changes }); </code></pre> <p>The function you specify will get executed whenever the specified property changes. At any point you can use the unwatch() method to get it to stop.</p>
46,692
<p>I'm working with my ASP.NET development team to try and create "better" <em>(i.e. cleaner)</em> HTML when rendering pages. At the moment, .NET has a nasty tendency to do things like dump JavaScript into the page, making it a mandatory requirement on form controls and not allowing forms to work when JS isn't available. In some instances, we're struggling to overcome this without having to add a notable chunk to development time estimates.</p> <p>I've worked with MVC before - via Struts in Java - and found that in that instance, I was able to keep HTML pages exactly as I'd wanted them to be. <em>(This viewpoint is based on the "best case" static HTML I typically developed beforehand, then handed over to the Java programmers to fill in the holes.)</em></p> <p>This worked out really well and we were able to produce some of the "best" web pages from a CMS that I've seen. Could .NET MVC give me the separation I need, or would it be a false economy to put aside valuable development time to test this?</p> <p>If .NET MVC isn't going to give me this fine-grained control over separation, any recommendations for .NET coding practices, libraries, etc. which might would be really helpful.</p>
<p>The ASP.NET MVC Framework would give you a much more familiar separation. Because there is no viewstate, etc in the MVC Framework you won't have to worry about JavaScript being dumped into your pages. The only JavaScript calls you see will be ones that you manually add.</p> <p>You can, for the most part, separate HTML / CSS / JS like you would in a different framework.</p>
<p>Asp.Net MVC will help you keep html/css/js separate in that it will present fewer features that would prevent you from keeping them separate.</p> <p>For example Html helpers typically return just that: Html. From that point you are free to choose to keep all style information associated only by class attributes. </p> <p>Consider also looking into the practices you usually follow with a library like jQuery. It's an excellent example of how to keep the scripted functionality entirely in your js and out of your html by applying the event handling behaviors to the elements on page load based on things like element type, class and id.</p>
8,043
<p>Does anyone know why when using BindingUtils on the selectedItem property of a ComboBox you get the following warning? Any ideas how to resolve the issue?</p> <p>The binding still works properly, but it would be nice to get rid of the warning.</p> <pre><code>warning: multiple describeType entries for 'selectedItem' on type 'mx.controls::ComboBox': &lt;accessor name="selectedItem" access="readwrite" type="Object" declaredBy="mx.controls::ComboBase"&gt; &lt;metadata name="Bindable"&gt; &lt;arg key="" value="valueCommit"/&gt; &lt;/metadata&gt; </code></pre>
<p>It is better to override the property in question and declare it final.</p>
<p>Here is the code. It is basically a copy of BindingUtils.bindProperty that is setup for a ComboBox so that both the combo box and the model are updated when either of the two change.</p> <pre><code>public static function bindProperty2(site:Object, prop:String, host:Object, chain:Object, commitOnly:Boolean = false):ChangeWatcher { var cbx:ComboBox = null; if ( site is ComboBox ) { cbx = ComboBox(site); } if ( host is ComboBox ) { cbx = ComboBox(host); } var labelField:String = &quot;listID&quot;; var w:ChangeWatcher = ChangeWatcher.watch(host, chain, null, commitOnly); if (w != null) { var func:Function; if ( site is ComboBox ) { func = function(event:*):void { var dp:ICollectionView = ICollectionView(site.dataProvider); var selItem:Object = null; for ( var i:int=0; i&lt;dp.length; i++ ) { var obj:Object = dp[i]; if ( obj.hasOwnProperty(labelField) ) { var val:String = String(obj[labelField]); if ( val == w.getValue() ) { selItem = obj; break; } } } site.selectedItem = selItem; }; w.setHandler(func); func(null); } else { func = function(event:*):void { var value:Object = w.getValue(); if ( value == null ) { site[prop] = null; } else { site[prop] = String(w.getValue()[labelField]); } }; w.setHandler(func); func(null); } } return w; } </code></pre>
2,784