instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is there a public, free web service that generates tag clouds? I'm looking for something like Google Chart--URL in, image out.</p>
<p>It still makes sense to me, but I haven't been able to find any such service. Actually, the API could be words in, styled text out or words in, image out. I'll just implement what I need in SWT and go from there.</p> <p>You can see an example of the kind of thing I'd like to generate at <a href="http://www.wordle.net/gallery/wrdl/359579/JUnit_Tests" rel="nofollow noreferrer">http://www.wordle.net/gallery/wrdl/359579/JUnit_Tests</a>. These are the words in the names of JUnit's self-tests.</p>
<p>Maybe you could make a use of this : <a href="http://www.wordle.net/" rel="nofollow noreferrer">http://www.wordle.net/</a></p>
44,069
<p>As part of our build process I need to set the version information for all of our compiled binaries. Some of the binaries already have version information (added at compile time) and some do not. </p> <p>I want to be able to apply the following information:</p> <ul> <li>Company Name </li> <li>Copyright Notice</li> <li>Product Name </li> <li>Product Description</li> <li>File Version </li> <li>Product Version</li> </ul> <p>All of these attributes are specified by the build script and must be applied after compilation. These are standard binaries (not assemblies) compiled with C++ Builder 2007.</p> <p>How can I do this?</p>
<p>While it's not a batch process, Visual Studio can also add/edit file resources. </p> <p>Just use File->Open->File on the .EXE or .DLL. This is handy for fixing version information post-build, or adding it to files that don't have these resources to begin with.</p>
<p>This is the best tool I've seen for the job, allows full control over all file resources, VersionInfo included.</p> <p>See: <a href="http://melander.dk/reseditor/" rel="nofollow noreferrer">ResourceEditor</a> by <a href="https://stackoverflow.com/users/2249664/speedfreak">Anders Melander</a>.</p>
36,060
<p>"Fatal error: Allowed memory size of 31457280 bytes exhausted (tried to allocate 9828 bytes)".</p> <p>This is the error i get but I am only trying to upload a 1mb image. I have increased the memory limit in php.ini and the execution time. I am trying this on a local MAMP server, on a Mac using firefox. This going to be for an online image gallery. Any ideas? Below is the code:</p> <pre><code> ini_set("memory_limit","30M"); if(isset($_POST['submit'])){ if (isset ($_FILES['new_image'])){ $imagename = $_FILES['new_image']['name']; $source = $_FILES['new_image']['tmp_name']; $target = "images/".$imagename; move_uploaded_file($source, $target); $imagepath = $imagename; //below here for the removed code $save = "thumbs/uploads/" . $imagepath; //This is the new file you saving $file = "images/" . $imagepath; //This is the original file $imagesize = getimagesize($file); list($width, $height) = $imagesize; unset($imagesize); if($width&gt;$height) { $modwidth = 150; $diff = $width / $modwidth; $modheight = $height / $diff; }else{ $modheight = 150; $diff = $height / $modheight; $modwidth = $width / $diff; } $tn = imagecreatetruecolor($modwidth, $modheight); $image = imagecreatefromjpeg($file); $imagecopy = imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height); imagedestroy($image); imagedestroy($im); imagedestroy($imagecopy); imagedestroy($source); $imagejpg = imagejpeg($tn, $save, 100); imagedestroy($tn); imagedestroy($imagejpg); </code></pre> <hr> <p>EDIT</p> <p>This has now been sorted out hopefully. One of my colleagues had a solution all along but neglected to tell me!</p>
<p>You're likely loading the image to do some manipulation of it. That causes the image data to be decompressed, which requires a lot of memory for big images (I think it's about 4 bytes per pixel).</p> <p>You can choose to either not process the image, or do your processing outside of PHP - for example by invoking ImageMagick or some other program. It depends a bit on what you're trying to accomplish.</p>
<p>Did you restart apache after you increased the memory limit? If yes, then increase a little more.</p>
38,751
<p>Developing a heavily XML-based Java-application, I recently encountered an interesting problem on Ubuntu Linux.</p> <p>My application, using the <a href="http://jpf.sourceforge.net/" rel="noreferrer">Java Plugin Framework</a>, appears unable to convert a <a href="http://www.dom4j.org/" rel="noreferrer">dom4j</a>-created XML document to <a href="http://xmlgraphics.apache.org/batik/" rel="noreferrer">Batik's</a> implementation of the SVG specification.</p> <p>On the console, I learn that an error occurs:</p> <pre> Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of &lt;bootloader&gt;) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature at org.apache.batik.dom.svg.SVGDOMImplementation.createDocument(SVGDOMImplementation.java:149) at org.dom4j.io.DOMWriter.createDomDocument(DOMWriter.java:361) at org.dom4j.io.DOMWriter.write(DOMWriter.java:138) </pre> <p>I figure that the problem is caused by a conflict between the original classloader from the JVM and the classloader deployed by the plugin framework.</p> <p>To my knowledge, it's not possible to specify a classloader for the framework to use. It might be possible to hack it, but I would prefer a less aggressive approach to solving this problem, since (for whatever reason) it only occurs on Linux systems.</p> <p>Has one of you encountered such a problem and has any idea how to fix it or at least get to the core of the issue?</p>
<p>LinkageError is what you'll get in a classic case where you have a class C loaded by more than one classloader and those classes are being used together in the same code (compared, cast, etc). It doesn't matter if it is the same Class name or even if it's loaded from the identical jar - a Class from one classloader is always treated as a different Class if loaded from another classloader.</p> <p>The message (which has improved a lot over the years) says:</p> <pre><code>Exception in thread "AWT-EventQueue-0" java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method "org.apache.batik.dom.svg.SVGOMDocument.createAttribute(Ljava/lang/String;)Lorg/w3c/dom/Attr;" the class loader (instance of org/java/plugin/standard/StandardPluginClassLoader) of the current class, org/apache/batik/dom/svg/SVGOMDocument, and the class loader (instance of ) for interface org/w3c/dom/Document have different Class objects for the type org/w3c/dom/Attr used in the signature </code></pre> <p>So, here the problem is in resolving the SVGOMDocument.createAttribute() method, which uses org.w3c.dom.Attr (part of the standard DOM library). But, the version of Attr loaded with Batik was loaded from a different classloader than the instance of Attr you're passing to the method. </p> <p>You'll see that Batik's version seems to be loaded from the Java plugin. And yours is being loaded from " ", which is most likely one of the built-in JVM loaders (boot classpath, ESOM, or classpath). </p> <p>The three prominent classloader models are:</p> <ul> <li>delegation (the default in the JDK - ask parent, then me)</li> <li>post-delegation (common in plugins, servlets, and places where you want isolation - ask me, then parent)</li> <li>sibling (common in dependency models like OSGi, Eclipse, etc)</li> </ul> <p>I don't know what delegation strategy the JPF classloader uses, but the key is that you want one version of the dom library to be loaded and everyone to source that class from the same location. That may mean removing it from the classpath and loading as a plugin, or preventing Batik from loading it, or something else.</p>
<p>As specified in <a href="https://stackoverflow.com/questions/2548384/java-get-a-list-of-all-classes-loaded-in-the-jvm">this question</a>, enabling the <code>-verbose:class</code> will make the JVM log information about all classes being loaded, which can be incredibly helpful to understand where the classes are coming from in more complex scenarios &amp; applications.</p> <p>The output you get looks roughly like this (copied from that question):</p> <pre><code>[Opened /usr/java/j2sdk1.4.1/jre/lib/rt.jar] [Opened /usr/java/j2sdk1.4.1/jre/lib/sunrsasign.jar] [Opened /usr/java/j2sdk1.4.1/jre/lib/jsse.jar] [Opened /usr/java/j2sdk1.4.1/jre/lib/jce.jar] [Opened /usr/java/j2sdk1.4.1/jre/lib/charsets.jar] [Loaded java.lang.Object from /usr/java/j2sdk1.4.1/jre/lib/rt.jar] [Loaded java.io.Serializable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar] [Loaded java.lang.Comparable from /usr/java/j2sdk1.4.1/jre/lib/rt.jar] [Loaded java.lang.CharSequence from /usr/java/j2sdk1.4.1/jre/lib/rt.jar] [Loaded java.lang.String from /usr/java/j2sdk1.4.1/jre/lib/rt.jar] </code></pre>
30,318
<p>I'm new to using LINQ to Entities (or Entity Framework whatever they're calling it) and I'm writing a lot of code like this:</p> <pre><code>var item = (from InventoryItem item in db.Inventory where item.ID == id select item).First&lt;InventoryItem&gt;(); </code></pre> <p>and then calling methods on that object like this:</p> <pre><code>var type = item.ItemTypeReference; </code></pre> <p>or</p> <pre><code>var orders = item.OrderLineItems.Load(); </code></pre> <p>to retrieve child or related objects.</p> <p>I haven't profiled the DB or dug too deeply but my guess is that when I call a .Load() or a *Reference property I'm actually making another call to the DB. If this is the case, is there any way to get those objects in my initial LINQ expression?</p>
<p>You want to use the .Include(string) method references in this <a href="http://msdn.microsoft.com/en-us/library/bb896272.aspx" rel="noreferrer">"Shaping query results"</a> article. </p> <pre><code>var item = from InventoryItem item in db.Inventory.Include("ItemTypeReference").Include("OrderLineItems") where item.ID == id select item; </code></pre> <p>There is probably a "sql" style syntax for the Includes as well. </p> <p>Also see this <a href="http://blogs.msdn.com/adonet/archive/2008/10/07/migrating-from-linq-to-sql-to-entity-framework-eager-loading.aspx" rel="noreferrer">article</a> about moving from LINQ-to-SQL to LINQ-to-Entities.</p> <p>For others looking for a solution to this problem for <strong>Linq to SQL</strong> you want to do the following (Substitute DataContext and other types for whatever you have):</p> <pre><code>using (DataContext db = new DataContext()) { DataLoadOptions options = new DataLoadOptions(); options.LoadWith&lt;InventoryItem&gt;(ii =&gt; ii.ItemTypeReference); options.LoadWith&lt;InventoryItem&gt;(ii =&gt; ii.OrderLineItems); db.LoadOptions = options; var item = from InventoryItem item in db.Inventory where item.ID == id select item; } </code></pre> <p>This will load the properties specified in LoadWith whenever the parent item (InventoryItem) is loaded, for that particular context.</p> <p>In response to some further questions from James and Jesper, check out this <a href="https://stackoverflow.com/questions/648782/how-do-i-create-a-where-condition-on-a-sub-table-in-linq">question</a></p>
<p>In addition to Robert's answer, you might like to check out this question for options for an extension method that that allows you to .Include() using an expression instead of a string, so you get compile time checking:</p> <p><a href="https://stackoverflow.com/questions/2921119/entity-framework-include-with-compile-time-checking">Entity Framework .Include() with compile time checking?</a></p>
40,798
<p>What is the difference between g++ and gcc? Which one of them should be used for general c++ development?</p>
<p><code>gcc</code> and <code>g++</code> are compiler-drivers of the GNU Compiler <em>Collection</em> (which was once upon a time just the GNU <em>C Compiler</em>).</p> <p>Even though they automatically determine which backends (<code>cc1</code> <code>cc1plus</code> ...) to call depending on the file-type, unless overridden with <code>-x language</code>, they have some differences.</p> <p>The probably most important difference in their defaults is which libraries they link against automatically.</p> <p>According to GCC's online documentation <a href="https://gcc.gnu.org/onlinedocs/gcc/Link-Options.html" rel="noreferrer">link options</a> and <a href="https://gcc.gnu.org/onlinedocs/gcc/Invoking-G_002b_002b.html" rel="noreferrer">how g++ is invoked</a>, <code>g++</code> is equivalent to <code>gcc -xc++ -lstdc++ -shared-libgcc</code> (the 1st is a compiler option, the 2nd two are linker options). This can be checked by running both with the <code>-v</code> option (it displays the backend toolchain commands being run).</p>
<p>gcc and g ++ are both GNU compiler. They both compile c and c++. The difference is for *.c files gcc treats it as a c program, and g++ sees it as a c ++ program. *.cpp files are considered to be c ++ programs. c++ is a super set of c and the syntax is more strict, so be careful about the suffix.</p>
20,795
<p>I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook. </p> <p>I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?</p> <p>Thanks</p>
<p>I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior:</p> <ul> <li>Every message starts with continuation off. </li> <li>Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed. </li> <li>Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off. </li> <li>Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?) </li> <li>Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters. </li> <li>Lines that start or end with a tab turn continuation off. </li> <li>Lines that start with 2 or more spaces turn continuation off. </li> <li>Lines that end with 3 or more spaces turn continuation off. </li> </ul> <p>Please note that I tried all of this with Outlook 2007. YMMV.<br> So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.</p>
<p>Try this:</p> <pre><code>message.setContent(new String(body.getBytes(), "iso-8859-1"), "text/html; charset=\"iso-8859-1\""); </code></pre> <p>Regards, Mohammad Rasool Javeed</p>
16,471
<p>What is the difference between <code>HAVING</code> and <code>WHERE</code> in an <code>SQL SELECT</code> statement?</p> <p>EDIT: I have marked Steven's answer as the correct one as it contained the key bit of information on the link:</p> <blockquote> <p>When <code>GROUP BY</code> is not used, <code>HAVING</code> behaves like a <code>WHERE</code> clause</p> </blockquote> <p>The situation I had seen the <code>WHERE</code> in did not have <code>GROUP BY</code> and is where my confusion started. Of course, until you know this you can't specify it in the question.</p>
<p>HAVING: is used to check conditions <em>after</em> the aggregation takes place.<br/> WHERE: is used to check conditions <em>before</em> the aggregation takes place.</p> <p>This code:</p> <pre><code>select City, CNT=Count(1) From Address Where State = 'MA' Group By City </code></pre> <p>Gives you a table of all cities in MA and the number of addresses in each city.</p> <p>This code:</p> <pre><code>select City, CNT=Count(1) From Address Where State = 'MA' Group By City Having Count(1)&gt;5 </code></pre> <p>Gives you a table of cities in MA with more than 5 addresses and the number of addresses in each city.</p>
<p>I use HAVING for constraining a query based on the results of an aggregate function. E.G. select * in blahblahblah group by SOMETHING having count(SOMETHING)>0</p>
36,573
<p>Assemblies A and B are privately deployed and strongly named. Assembly A contains references to Assembly B. There are two versions of Assembly B: B1 and B2. I want to be able to indicate for Assembly A that it may bind to either B1 or B2 -- ideally, by incorporating this information into the assembly itself. What are my options?</p> <p>I'm somewhat familiar with versioning policy and the way it applies to the GAC, but I don't want to be dependent on these assemblies being in the GAC.</p>
<p>There are several places you can indicate to the .Net Framework that a specific version of a strongly typed library should be preferred over another. These are:</p> <ul> <li>Publisher Policy file</li> <li>machine.config file</li> <li>app.config file</li> </ul> <p>All these methods utilise the <a href="http://msdn.microsoft.com/en-us/library/eftw1fys.aspx" rel="nofollow noreferrer" title=".NET Framework General Reference - &lt;bindingRedirect&gt; Element">"&lt;bindingRedirect&gt;"</a> element which can instruct the .Net Framework to bind a version or range of versions of an assembly to a specific version.</p> <p>Here is a short example of the tag in use to bind all versions of an assembly up until version 2.0 to version 2.5:</p> <pre><code>&lt;assemblyBinding&gt; &lt;dependantAssembly&gt; &lt;assemblyIdentity name="foo" publicKeyToken="00000000000" culture="neutral" /&gt; &lt;bindingRedirect oldVersion="0.0.0.0 - 2.0.0.0" newVersion="2.5.0.0" /&gt; &lt;/dependantAssembly&gt; &lt;/assemblyBinding&gt; </code></pre> <p>There are lots of details so it's best if you read about <a href="http://msdn.microsoft.com/en-us/library/7wd6ex19.aspx" rel="nofollow noreferrer" title=".NET Framework Developer's Guide - Redirecting Assembly Versions">Redirecting Assembly Versions on MSDN</a> to decide which method is best for your case.</p>
<p>You can set version policy in your app.config file. Alternatively you can manually load these assemblies with a call to <code>Assembly.LoadFrom()</code> when this is done assembly version is not considered.</p>
7,816
<p>How do I get the type of a generic typed class within the class?</p> <p>An example:</p> <p>I build a generic typed collection implementing <em>ICollection&lt; T></em>. Within I have methods like </p> <pre><code> public void Add(T item){ ... } public void Add(IEnumerable&lt;T&gt; enumItems){ ... } </code></pre> <p>How can I ask within the method for the given type <em>T</em>?</p> <p>The reason for my question is: If <em>object</em> is used as <em>T</em> the collection uses Add(object item) instead of Add(IEnumerable&lt;object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.</p> <p>So i need something like </p> <pre><code>if (T is object) { // Check for IEnumerable } </code></pre> <p>but of course that cannot work in C#. Suggestions?</p> <p>Thank you very much!</p> <p>Michael</p>
<p>Personally, I would side step the issue by renaming the <code>IEnumerable&lt;T&gt;</code> method to <code>AddRange</code>. This avoids such issues, and is consistent with existing APIs such as <a href="http://msdn.microsoft.com/en-us/library/z883w3dc.aspx" rel="noreferrer"><code>List&lt;T&gt;.AddRange</code></a>.</p> <p>It also keeps things clean when the <code>T</code> you want to add implements <code>IEnumerable&lt;T&gt;</code> (rare, I'll admit).</p>
<p>If you want to use the <code>is</code> operator in a generic class/method you have to limit <code>T</code> to a reference type:</p> <pre><code>public void MyMethod&lt;T&gt;(T theItem) where T : class { if (theItem is IEnumerable) { DoStuff(); } } </code></pre>
28,852
<p>I have nested dictionaries:</p> <pre><code>{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'}, u'key1': {'attrs': {'entity': 'r', 'hash': '34njasd3h43b4n3', 'id': '4130-1'}, u'key2': {'attrs': {'entity': 'c', 'hash': '34njasd3h43bdsfsd4n3', 'id': '4130-1-1'}}}, u'key3': {'attrs': {'entity': 'r', 'hash': '34njasasasd3h43b4n3', 'id': '4130-2'}, u'key4': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-1'}}, u'key5': {'attrs': {'entity': 'c', 'hash': '34njawersd3h43bdsfsd4n3', 'id': '4130-2-2'}}}}, 'someohterthing': 'someothervalue', 'something': 'somevalue'} </code></pre> <p>given an <code>id</code> - one of all the <code>ids</code> like <code>4130</code> to <code>4130-2-2</code>.<br /> whats the easiest way to navigate to the correct dictionary?</p> <p>If the given <code>id</code> is <code>4130-2-1</code> then it should reach the dictionary with <code>key=key5</code>.</p> <p>No XML approaches please.</p> <p><strong>Edit(1):</strong> The nesting is between <code>1</code> to <code>4</code> levels, but I know the nesting before I parse.</p> <p><strong>Edit(2)</strong>: Fixed the code.</p> <p><strong>Edit(3)</strong>: Fixed code again for string values of <code>ids</code>. Please excuse for the confusion created. This is final I hope :)</p>
<p>Your structure is unpleasantly irregular. Here's a version with a <strong>Visitor</strong> function that traverses the <code>attrs</code> sub-dictionaries.</p> <pre><code>def walkDict( aDict, visitor, path=() ): for k in aDict: if k == 'attrs': visitor( path, aDict[k] ) elif type(aDict[k]) != dict: pass else: walkDict( aDict[k], visitor, path+(k,) ) def printMe( path, element ): print path, element def filterFor( path, element ): if element['id'] == '4130-2-2': print path, element </code></pre> <p>You'd use it like this.</p> <pre><code>walkDict( myDict, filterFor ) </code></pre> <p>This can be turned into a generator instead of a <strong>Visitor</strong>; it would <code>yield path, aDict[k]</code> instead of invoking the visitor function.</p> <p>You'd use it in a for loop.</p> <pre><code>for path, attrDict in walkDictIter( aDict ): # process attrDict... </code></pre>
<p>Well, if you have to do it only a few times, you can just use nested dict.iteritems() to find what you are looking for.</p> <p>If you plan to do it several times, performances will quickly becomes an issue. In that case you could :</p> <ul> <li><p>change the way you data is returned to you to something more suitable.</p></li> <li><p>if you can't, convert the data once the fly to a dict between id and keys (using iteritems). Then use it.</p></li> </ul>
49,895
<p>I'm wondering if anyone can recommend a good C++ tree implementation, hopefully one that is stl compatible if at all possible.</p> <p>For the record, I've written tree algorithms many times before, and I know it can be fun, but I want to be pragmatic and lazy if at all possible. So an actual link to a working solution is the goal here.</p> <p>Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within. So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable. </p>
<p>I don't know about your requirements, but wouldn't you be better off with a graph (implementations for example in <a href="http://www.boost.org/doc/libs/release/libs/graph/doc/index.html" rel="noreferrer">Boost Graph</a>) if you're interested mostly in the structure and not so much in tree-specific benefits like speed through balancing? You can 'emulate' a tree through a graph, and maybe it'll be (conceptually) closer to what you're looking for.</p>
<p>Let suppose the question is about balanced (in some form, mostly red black tree) binary trees, even if it is not the case.</p> <p>Balanced binaries trees, like vector, allow to manage some ordering of elements without any need of key (like by inserting elements anywhere in vector), but :</p> <ul> <li>With optimal O(log(n)) or better complexity for all the modification of one element (add/remove at begin, end <strong>and</strong> before &amp; after any iterator)</li> <li>With <strong>persistance</strong> of iterators thru any modifications except direct destruction of the element pointed by the iterator.</li> </ul> <p>Optionally one may support access by index like in vector (with a cost of one size_t by element), with O(log(n)) complexity. If used, iterators will be random.</p> <p>Optionally order can be enforced by some comparison func, but persistence of iterators allow to use non repeatable comparison scheme (ex: arbitrary car lanes change during traffic jam).</p> <p>In practice, balanced binary tree have interface of vector, list, double linked list, map, multimap, deque, queue, priority_queue... with attaining theoretic optimal O(log(n)) complexity for all single element operations.</p> <p>&lt;sarcastic> this is probably why c++ stl does not propose it &lt;/sarcastic></p> <p>Individuals may not implement general balanced tree by themselves, due to the difficulties to get correct management of balancing, especially during element extraction.</p> <p>There is no widely available implementation of balanced binary tree because the state of the art red black tree (at this time the best type of balanced tree due to fixed number of costly tree reorganizations during remove) know implementation, slavishly copied by every implementers’ from the initial code of the structure inventor, does not allow iterator persistency. It is probably the reason of the absence of fully functionnal tree template.</p>
21,930
<p>Can someone please walk me through the process of loading a class or package in JSP with Tomcat?</p> <p>I think it might just be a Tomcat setup issue :S my JSP file runs fine without importing or using dbpool or dbpooljar. I've tried many suggestions to other peoples similar issues without any luck. Any help would be apreciated!</p> <p>My class/package placed in web-inf/classes (among other places)</p> <pre><code>package dbpooljar; public class DBPool { public DBPool() { System.out.println("dbpool evidence!"); } } </code></pre> <p>My compile commands</p> <pre><code>javac "C:\website\apache-tomcat-6.0.18\webapps\ROOT\WEB-INF\classes\dbpool.java" jar cf "C:\website\apache-tomcat-6.0.18\webapps\ROOT\WEB-INF\classes\dbpooljar.jar" DBPool.java </code></pre> <p>My <em>index.jsp</em></p> <pre><code>&lt;%@ page import="java.sql.*,java.util.List,java.util.ArrayList,DBPool" %&gt; &lt;html&gt; &lt;body&gt; Getting Length of a String &lt;% String s1 = "Length of a String!"; out.println("\"" + s1 + "\"" + " is of " + s1.length() + " characters "); DBPool test=new DBPool(); %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And lastly my horrible error (among others when I've tried different things)</p> <pre><code>An error occurred at line: 9 in the generated java file The import DBPool cannot be resolved </code></pre>
<p>You've typed </p> <p>[%@ page import="java.sql.*,java.util.List,java.util.ArrayList,<strong>DBPool</strong>" %]</p> <p>but</p> <pre><code>package dbpooljar; public class DBPool { ... </code></pre> <p>Therefor, it should be </p> <p>[%@ page import="java.sql.*,java.util.List,java.util.ArrayList,<strong>dbpooljar.DBPool</strong>" %]</p> <p>plus your java file should be located in a directory named WEB-INF/classes/dbpooljar or if you insist on packaging a jar file, place the jar file in WEB-INF/lib </p> <p>Of course the angled brackets "[" and "]" are meant to be proper xml brackets "&lt;" and ">" - I've preserved them here in order to be able to use bold typeface.</p>
<p>I dont know about windows, but in linux there is a the file(/usr/share/tomcat5/conf/jkconfig.manifest) that you can edit to add specific jars to the tomcat instance that is running.</p>
48,894
<p>Now, I know this is completely subjective, so please don't flame me. I've never been entirely satisfied with linux whenever I decided to install a distro like Ubuntu, Fedora etc. because of their awkward positioning and spacing of widgets.</p> <p>Have a look at <a href="http://art.gnome.org/themes/gtk2/?sort_by=popularity&amp;limit=12&amp;view=list&amp;order=DESC" rel="nofollow noreferrer">this</a>:</p> <p><img src="https://i.stack.imgur.com/HT5d9.png" alt="alt text"></p> <p><img src="https://i.stack.imgur.com/NyCiJ.png" alt="alt text"></p> <p>Notice the awkward spacing of the text field's text.</p> <p>I've seen many Gnome themes that look good on the surface but it all somehow breaks down, awkward spacings, strange borders. Etc. </p> <p>The entire linux desktop doesn't have the visual integrity of OSX for instance, and I wonder why. If there is any example of a nice integrated Linux environment, please please please show me, I really WANT to use Linux.</p> <p>(and I know, there's QT, and other managers like KDE etc. I noticed the same thing, so it probably isn't GTK or Gnome alone)</p>
<blockquote> <p>The entire linux desktop doesn't have the visual integrity of OSX for instance, and I wonder why. If there is any example of a nice integrated Linux environment, please please please show me, I really WANT to use Linux.</p> <p>(and I know, there's QT, and other managers like KDE etc. I noticed the same thing, so it probably isn't GTK or Gnome alone)</p> </blockquote> <p>You basically just answered your own question - Mac OS X has <strong>one</strong> desktop environment (centered around Cocoa), which has a lot of very good programmers <em>and</em> designers spending much time designing, discussing and implementing it.</p> <p>With &quot;Linux&quot;, there's not only different window managers (Gnome, KDE, Flux/OpenBox, Enlightenment, etc etc), there's different UI toolkits (QT, GTK+, Tk, wx, etc etc), different versions (in common use), and countless different ways of using/implementing them.. Compare <a href="http://en.wikipedia.org/wiki/List_of_widget_toolkits#Based_on_C_or_C.2B.2B_.28including_bindings_to_other_languages.2" rel="noreferrer">List of (mainly) Linux GUI toolkits</a> compared to for <a href="http://en.wikipedia.org/wiki/List_of_widget_toolkits#On_Macintosh" rel="noreferrer">Macintosh</a> (all of those, bar Cocoa, are for old Mac OS versions).</p> <p>There's many good designers and programmers working on GUI toolkits, but they are spread over so many different projects. Even if they somehow were put onto a single project (Say, &quot;wxQtGnome&quot;), there would still be countless applications that use a different framework, or even a different version of one.. Then you still have the problem with inconsistency. Again, compared to Mac OS X, where if you have a GUI application, chances are it will be using Cocoa (which has a decent UI creation tool, which helps developers layout applications according to Apples Human UI Guidelines)..</p> <p>As for a nice, integrated linux desktop environment - I would say the default Ubuntu installation is probably the closest to this. A decent theme, and all the applications fit fairly well together.</p>
<p>You know, it's just a different approach. The differences between particular themes are inevitable, as there isn't any sort of common guidelines, AFAIK.</p> <p>For me, Linux themes are completely integral, I've yet to experience any sort of feeling of awkwardness.</p>
24,793
<p>A lot of literature talks about using inline functions to "avoid the overhead of a function call". However I haven't seen quantifiable data. What is the actual overhead of a function call i.e. what sort of performance increase do we achieve by inlining functions?</p>
<p>On most architectures, the cost consists of saving all (or some, or none) of the registers to the stack, pushing the function arguments to the stack (or putting them in registers), incrementing the stack pointer and jumping to the beginning of the new code. Then when the function is done, you have to restore the registers from the stack. <a href="http://www.angelcode.com/dev/callconv/callconv.html" rel="noreferrer">This webpage</a> has a description of what's involved in the various calling conventions.</p> <p>Most C++ compilers are smart enough now to inline functions for you. The inline keyword is just a hint to the compiler. Some will even do inlining across translation units where they decide it's helpful. </p>
<p>Each new function requires a new local stack to be created. But the overhead of this would only be noticeable if you are calling a function on every iteration of a loop over a very large number of iterations.</p>
17,483
<p>I hear a lot of people talking about the revolution that is coming in programming due to multi-core processors and parallelism, but I can't shake the feeling that for most of us, CPU cycles aren't the bottleneck. Pretty much all of my programs have been I/O bound in one way or another (database, filesystem, network, user interaction, etc.) for a very long time.</p> <p>Now I can think of a few areas where CPU cycles are a limiting factor, like code breaking, graphics, sound, some forms of simulation (weather, physics, etc.), and some forms of mathematical research, but they all seem like fairly specialized application domains. My general impression is that most programs are still I/O bound and that for most of our industry CPUs have been plenty fast for quite a while now.</p> <p>Am I off my rocker? What other application domains are CPU bound today? Do any of them include a large portion of the programming population? In essence, I'm wondering whether the multi-core CPUs will impact very many of us, and if so, how?</p>
<p>Visual effects / rendering. (Entertainment industry.)<br> Artificial Intelligence. (Games and scientific research.)<br> Biomedical research.<br> Physical simulations. (Games and scientific research.)<br> Database applications including SaaS, most webpages, etc. </p> <p>As the personal computer becomes more and more a browser-based thin client for web applications, this industry will expand, as well as the need for more, and parallelized processing power on the backend. I could see gaming pushing parallel processing in personal computing.</p>
<p>One of the ways to leverage multi core is through a use of remote desktop technologies. </p> <p>It's much easier to deploy desktop applications to one big Citrix server instead of dozens of user desktops. </p>
30,952
<p>I wanted to add dynamic charts in the webpage. It goes like this...</p> <p>I get the start and end date from user and draw separate charts for each date bewteen the start and end date.</p> <p>I get the data from sql database and bind it with the chart like this:</p> <pre><code> SqlConnection UsageLogConn = new SqlConnection(ConfigurationManager.ConnectionStrings["UsageConn"].ConnectionString); UsageLogConn.Open();//open connection string sql = "SELECT v.interval,dateadd(mi,(v.interval-1)*2,'" + startdate + " 00:00:00') as 'intervaltime',COUNT(Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2) AS Total FROM usage_internet_intervals v left outer join (select * from Usage_Internet where " + name + " LIKE ('%" + value + "%') and DateTime BETWEEN '" + startdate + " 00:00:00' AND '" + enddate + " 23:59:59') d on v.interval = Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 GROUP BY v.interval,Datediff(minute,'" + startdate + " 00:00:00',d.DateTime)/2 ORDER BY Interval"; SqlCommand cmd = new SqlCommand(sql, UsageLogConn); SqlDataAdapter mySQLadapter = new SqlDataAdapter(cmd); Chart1.DataSource = cmd; // set series members names for the X and Y values Chart1.Series["Series 1"].XValueMember = "intervaltime"; Chart1.Series["Series 1"].YValueMembers = "Total"; UsageLogConn.Close(); // data bind to the selected data source Chart1.DataBind(); cmd.Dispose(); </code></pre> <p>The above code adds only one chart for one date and I have added 'chart1' to design view and its not created dynamic. But I wanted to add more charts dynamic at runtime to the webpage.</p> <p>Can anyone help me with this?</p> <p>I am using VS 2008, ASP.NET 3.5 and the charting lib is: using System.Web.UI.DataVisualization.Charting;</p>
<p>Ok so I may have overdone this, but I tried to make this pretty dynamic. Yeah, the list names are a bit odd, but I used another example of mine to build this.</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { Bench[] benchList; FoodIntake[] foodIntakeList; Panel panelChartHolder; panelChartHolder = new Panel(); Controls.Add(panelChartHolder); benchList = Bench.GetAll(); AddNewCharts(benchList, panelChartHolder, GetBenchXValue, GetBenchYValue); foodIntakeList = FoodIntake.GetAll(); AddNewCharts(foodIntakeList, panelChartHolder, GetFoodIntakeXValue, GetFoodIntakeYValue); } </code></pre> <p>Ok so this first part is simple. Create a panel to hold the charts you are adding, get the lists you want represented by the charts (For this example they happen to work with Linq to Sql) and call the method to create the charts.</p> <pre><code> private void AddNewCharts&lt;T&gt;(T[] listToAdd, Panel panelToAddTo, Func&lt;T, DateTime&gt; xMethod, Func&lt;T, Int32&gt; yMethod) { ChartArea mainArea; Chart mainChart; Series mainSeries; mainChart = new Chart(); mainSeries = new Series("MainSeries"); for (Int32 loopCounter = 0; loopCounter &lt; listToAdd.Length; loopCounter++) { mainSeries.Points.AddXY(xMethod(listToAdd[loopCounter]), yMethod(listToAdd[loopCounter])); } mainChart.Series.Add(mainSeries); mainArea = new ChartArea("MainArea"); mainChart.ChartAreas.Add(mainArea); panelToAddTo.Controls.Add(mainChart); } </code></pre> <p>As you can see, I just created a new chart, added a series to it, and added a ChartArea to it. Next part is pretty much just looping through the collection and adding each item in it to the list itself. It uses the passed in delegate methods (Func) to get the X and Y values. </p> <p>Last part holds the four methods responsible for getting the X and Y values from the two lists. Basically I did this to allow the chart creating method to be a generic as possible. Might be overkill.</p> <pre><code> private DateTime GetBenchXValue(Bench currentBench) { return currentBench.DateLifted; } private Int32 GetBenchYValue(Bench currentBench) { return currentBench.BenchAmount; } private DateTime GetFoodIntakeXValue(FoodIntake currentIntake) { return currentIntake.DateEaten; } private Int32 GetFoodIntakeYValue(FoodIntake currentIntake) { return currentIntake.Calories; } </code></pre> <p>And so when you run this, you will get two graphs side by side. Mind you, they will be very plain as there are million different properties that can be set to improve the look. Hope this is what you were asking for.</p> <pre><code> using System; using System.Web.UI.DataVisualization.Charting; using System.Web.UI.WebControls; </code></pre>
<p>I have updated the MS chart samples for .NET 4.0 and added two additional projects -- ChartsWithMVC and ChartsWithoutWebForms. You might find my sample code helpful, as I have a very basic implementation of a dynamic chart system using the asp.net chart control:</p> <p><a href="http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html" rel="nofollow noreferrer">http://develocity.blogspot.com/2010/04/aspnet-chart-controls-without-web-forms.html</a></p> <p>Hope it helps.</p>
43,455
<p>Is there anything like <a href="http://en.wikipedia.org/wiki/ELMAH" rel="noreferrer">ELMAH</a> for Windows Forms? </p> <p>I'm looking for a standard way to process unhandled exceptions and grab a screenshot and other environment information before packaging that up for support.</p>
<p>The very same Jeff Atwood coded a nice solution (albeit in VB.NET) which I had to modify and "fix" but that I am happily using since then.</p> <p>You can view his solution <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">Here</a></p>
<p>There is a commercial alternative called <a href="http://www.smartassembly.com/product/index.aspx" rel="nofollow noreferrer">{smartassembly}</a> that does error reporting.</p>
9,226
<p>I would like to know the best way to replace a standard textarea field with a rich text editor in Django Admin?</p>
<p>There's an <a href="http://pypi.python.org/pypi/django-tinymce/" rel="noreferrer">add-on Django application</a> to provide <a href="http://tinymce.moxiecode.com/" rel="noreferrer">TinyMCE</a> support for Django admin forms without having to muck around with admin templates or Django newform internals.</p>
<p>Install this package</p> <pre><code>pip install django-ckeditor </code></pre> <p>then run these commands to migrate.</p> <pre><code>python manage.py makemigrations python manage.py migrate python manage.py collectstatic </code></pre> <p>finally restart your Django server.</p> <p>Once you complete the above steps, you can see the rich text editor in your admin panel fields.</p>
42,747
<p>We've had an ongoing need here that I can't figure out how to address using the stock Maven 2 tools and documentation.</p> <p>Some of our developers have some very long running JUnit tests (usually stress tests) that under no circumstances should be run as a regular part of the build process / nightly build.</p> <p>Of course we can use the surefire plugin's exclusion mechanism and just punt them from the build, but ideally we'd love something that would allow the developer to run them at will through Maven 2.</p>
<p>Normally you would add a profile to your maven configuration that runs a different set of tests:</p> <p>run this with mvn -Pintegrationtest install</p> <pre><code> &lt;profile&gt; &lt;id&gt;integrationtest&lt;/id&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;argLine&gt;-client -Xmx896m -XX:MaxPermSize=192m&lt;/argLine&gt; &lt;forkMode&gt;once&lt;/forkMode&gt; &lt;includes&gt; &lt;include&gt;**/**/*Test.java&lt;/include&gt; &lt;include&gt;**/**/*IntTest.java&lt;/include&gt; &lt;/includes&gt; &lt;excludes&gt; &lt;exclude&gt;**/**/*SeleniumTest.java&lt;/exclude&gt; &lt;/excludes&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;activation&gt; &lt;property&gt; &lt;name&gt;integrationtest&lt;/name&gt; &lt;/property&gt; &lt;/activation&gt; &lt;/profile&gt; </code></pre>
<p>Another option is to have the stress test detect it is running in maven and run only once or twice. i.e. turn into a regular functional test. This way you can check the code is still good, but not run for a long time.</p>
31,360
<p>I got dtd in file and I cant remove it. When i try to parse it in Java I get "Caused by: java.net.SocketException: Network is unreachable: connect", because its remote dtd. can I disable somehow dtd checking?</p>
<p>You should be able to specify your own EntityResolver, or use specific features of your parser? See <a href="https://stackoverflow.com/questions/155101/make-documentbuilderparse-ignore-dtd-references">here</a> for some approaches.</p> <p>A more complete example:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!DOCTYPE foo PUBLIC "//FOO//" "foo.dtd"&gt; &lt;foo&gt; &lt;bar&gt;Value&lt;/bar&gt; &lt;/foo&gt; </code></pre> <p>And xpath usage:</p> <pre><code>import java.io.File; import java.io.IOException; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; public class Main { public static void main(String[] args) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(new EntityResolver() { @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { System.out.println("Ignoring " + publicId + ", " + systemId); return new InputSource(new StringReader("")); } }); Document document = builder.parse(new File("src/foo.xml")); XPathFactory xpathFactory = XPathFactory.newInstance(); XPath xpath = xpathFactory.newXPath(); String content = xpath.evaluate("/foo/bar/text()", document .getDocumentElement()); System.out.println(content); } } </code></pre> <p>Hope this helps...</p>
<p>I had this problem before. I solved it by downloading and storing a local copy of the DTD and then validating against the local copy. You need to edit the XML file to point to the local copy.</p> <pre><code>&lt;!DOCTYPE root-element SYSTEM "filename"&gt; </code></pre> <p>Little more info here: <a href="http://www.w3schools.com/dtd/dtd_intro.asp" rel="nofollow noreferrer">http://www.w3schools.com/dtd/dtd_intro.asp</a></p> <p>I think you can also manually set some sort of validateOnParse property to "false" in your parser. Depends on what library you're using to parse the XML.</p> <p>More info here: <a href="http://www.w3schools.com/dtd/dtd_validation.asp" rel="nofollow noreferrer">http://www.w3schools.com/dtd/dtd_validation.asp</a></p>
30,194
<p>I've had this problem many times before, and I've never had a solution I felt good about. </p> <p>Let's say I have a Transaction base class and two derived classes AdjustmentTransaction and IssueTransaction.</p> <p>I have a list of transactions in the UI, and each transaction is of the concrete type AdjustmentTransaction or IssueTransaction.</p> <p>When I select a transaction, and click an "Edit" button, I need to decide whether to show an AdjustmentTransactionEditorForm or an IssueTransactionEditorForm.</p> <p>The question is how do I go about doing this in an OO fashion without having to use a switch statement on the type of the selected transaction? The switch statement works but feels kludgy. I feel like I should be able to somehow exploit the parallel inheritance hierarchy between Transactions and TransactionEditors.</p> <p>I could have an EditorForm property on my Transaction, but that is a horrible mixing of my UI peanut butter with my Model chocolate.</p> <p>Thanks in advance.</p>
<p>You need to map your "EditorForm" to a transaction at some point. You have a couple options:</p> <ul> <li>A switch statement...like you, I think this stinks, and scales poorly.</li> <li>An abstract "EditorForm" property in base Transaction class, this scales better, but has poor seperation of concerns.</li> <li>A Type -> Form mapper in your frontend. This scales fairly well, and keeps good seperation.</li> </ul> <p>In C#, I'd implement a Type -> Form mapper like this:</p> <pre><code>Dictionary &lt;Type,Type&gt; typeMapper = new Dictionary&lt;Type,Type&gt;(); typeMapper.Add(typeof(AdjustTransaction), typeof(AdjustTransactionForm)); // etc, in this example, I'm populating it by hand, // in real life, I'd use a key/value pair mapping config file, // and populate it at runtime. </code></pre> <p>then, when edit is clicked:</p> <pre><code>Type formToGet; if (typeMapper.TryGetValue(CurrentTransaction.GetType(), out formToGet)) { Form newForm = (Form)Activator.CreateInstance(formToGet); } </code></pre>
<p>Do I miss something in the question? I just ask because the obvious OO answer would be: Polymorph</p> <p>Just execute Transaction.editWindow() (or however you want to call it), and overwrite the method in AdjustmentTransaction and IssueTrasaction with the required functionality. The call to element.editWindow() then opens the right dialog for you.</p>
39,431
<p>I have a visual studio 2005 solution which has a web application and a class library project. The web application has a reference to the library project. I'd like the library project's code documentation XML to output to the web application's bin folder, along with the library's DLL. I can't seem to find any easy way of doing this.</p>
<p>Post-build step, perhaps? A bit ugly, but I think it would work.</p>
<p>Here is the post-build command that worked:</p> <pre><code>copy "$(TargetDir)$(TargetName).xml" "$(SolutionDir)MyWebProject1\bin\$(TargetName).xml" copy "$(TargetDir)$(TargetName).xml" "$(SolutionDir)MyWebProject2\bin\$(TargetName).xml" </code></pre> <p>A couple of problems inherent with this solution:</p> <ul> <li>The xml is always copied even if that website is not part of the current build... so the documentation can get out of sync with the the dll in the bin folder until the next time that web project is built.</li> <li>If we add a new web project that refers to this library, we need to add another post-build command, rather than having this all happen automatically.</li> </ul> <p>I'm accepting this as a kludgy but workable solution... if anyone has a more elegant suggestion, please let me know!</p>
47,013
<p>I'm a complete beginner when it comes to programming. I'm taking a stab at PHP, and have seen how powerful the frameworks can be. But should I even consider trying to work with a framework until I have a strong grasp of PHP itself?</p> <p>Note: I'd most likely be using CodeIgnitor, but the question applies to any of the frameworks.</p>
<p>Preferably, you should have a strong grasp of the language (and programming in general) before you start using frameworks. Frameworks can and will save you a lot of work, but you they also introduce advanced concepts and implementations. </p> <p>After you gain some experience and start to wonder what's the best way to solve some common problems you have faced before - that will be a good time to give frameworks a try.</p> <p>I would suggest you try to read some of the source code of the different frameworks and see if it makes sense to you. If it doesn't - you are probably not ready yet.</p>
<p>Frameworks can abstract much of the language's complexity away from you, but at some point, you're going to run into something that requires you to know the language's control structures and standard library.</p> <p>It's really up to you, but I'd recommend at least learning some of the language's basic constructs, particularly dealing with control structures, before using a framework.</p>
40,397
<p>This is a C# question, but really could be language-agnostic</p> <p>I have inherited a large object model (100+ types), with a hierarchy of objects that 'own' 0..n of other typed objects that all share a base (where there is a 'relatively' strict type hierarachy).</p> <p>I want to start decoupling these objects though inheritance to put together an IoC based system to start to implement some unit tests with greater depth than currently exist.</p> <p>Where would be the best place to start?</p> <p>I can start at the top of the hierarchy, which is quite simple but would have the least initial benefit, and would be quite rote until I get further down the chain, but that would require me to implement a few cludges at the base object to overload function signatures to accept base interfaces until I get full coverages.</p> <p>I could start at the bottom of the hierarchy, which would be much trickier, as there is alot more interaction between classes down there, but would 'force' us to take a more holistic view of the refactoring.</p> <p>I could also start at the Base objects (those which all the objects are inheriting from) which would start the process off at the logical point, but would almost certainly create an uncompilable application until we get to swap out all the objects inheritances and function calls.</p> <p>Any thoughts?</p>
<p>if you can complete the entire process in a reasonable amount of time, start with the bases and go through the whole thing; the app will be broken until you are done</p> <p>if you must keep the app working in the meantime, start at the top and work your way down a few classes at a time</p> <p>i would look at the bottom-up perspective also, but doubt that it will be a practical way to implement since it likely will break everything and take longer than the other two approaches, but Your Mileage May Vary ;-)</p> <p>the base questions are: </p> <ul> <li>how long will each approach take?</li> <li>will each tactic eventually end up producing the same final code?</li> <li>how important is it to keep the app(s) working while the transformation is being completed?</li> <li>do you have enough unit tests to trust a massive refactoring?</li> </ul>
<p>This may be a little too academic, but there was a lot of research in the mid-nineties on how to automatically refactor large class hierarchies, for example by figuring out interfaces that are commonly used, etc. While this may not solve your problems, it may give you a good option of where to start or at least some interesting perspective on these sort of problems.</p> <p>A first paper in that chain was Godin and Mili's "Building and maintaining analysis-level class hierarchies using Galois Lattices" (google and you shall find the PDFs), and there was a whole series of following papers (see papers that cited this) on different tricks.</p>
44,583
<p>With .Net what is the best way to interact with a service (i.e. how do most tray-apps communicate with their servers). It would be preferred if this method would be cross-platform as well (working in Mono, so I guess remoting is out?)</p> <hr /> <h3>Edit:</h3> <p>Forgot to mention, we still have to support Windows 2000 machines in the field, so WCF and anything above .Net 2.0 won't fly.</p>
<p>Be aware that if you are planning to eventually deploy on Windows Vista or Windows Server 2008, many ways that this can be done today will not work. This is because of the introduction of a new security feature called "Session 0 Isolation". </p> <p>Most windows services have been moved to run in Session 0 now in order to properly isolate them from the rest of the system. An extension of this is that the first user to login to the system no longer is placed in Session #0, they are placed in Session 1. And hence, the isolation will break code that does certain types of communication between services and desktop applications.</p> <p>The best way to write code today that will work on Vista and Server 2008 going forward when doing communication between services and applications is to use a proper cross-process API like RPC, Named Pipes, etc. Do not use SendMessage/PostMessage as that will fail under Session 0 Isolation.</p> <p><a href="http://www.microsoft.com/whdc/system/vista/services.mspx" rel="noreferrer">http://www.microsoft.com/whdc/system/vista/services.mspx</a></p> <p>Now, given your requirements, you are going to be in a bit of a pickle. For the cross-platform concerns, I'm not sure if Remoting would be supported. You may have to drop down and go all the way back to sockets: <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.net.sockets.aspx</a></p>
<p>Remoting is an option, but it's not cross-platform. Some other ways are to use named pipes, IPC, or kernel events.</p>
11,039
<p>I cannot figure out how to change the title bar icon (the icon in the furthest top left corner of the application) in Adobe AIR. It is currently displaying the default 'Adobe AIR' red icon. </p> <p>I have been able to change it in the system tray, however.</p>
<p>Does the following help?</p> <p><a href="http://groups.google.com/group/chennai-flex-user-group/browse_thread/thread/cffb9ab56450c28e" rel="nofollow noreferrer">http://groups.google.com/group/chennai-flex-user-group/browse_thread/thread/cffb9ab56450c28e</a></p>
<p>The first link shows how to change the Taskbar Icon, the second shows the application icon I believe used on the desktop. I am going to recompile and install the application and see if it works.</p> <p>Edit: Yea, the one that changes the Desktop Icon also changes the Title Bar icon. It's in the app.xml file.</p>
3,892
<p>I've had some experience with Pygame, but there seems to be a lot of buzz around Pyglet these days.</p> <p>How do these two libraries compare? What would be the advantage of using one over the other, both in features and ease of use?</p> <p>Finally, would you say that one is more Pythonic than the other?</p>
<p>I was considering both Pygame and Pyglet for a small 2D shooter, and after looking at source code and some tutorials went with Pyglet. I was very happy with the results.</p> <p>Pyglet worked immediately and was enjoyable to work with, and conceptually very clean. It certainly had a Pythonic feel to me: you could get a straightforward and readable example going very quickly, and it uses decorators to good effect for event handling. It also didn't force a particular program structure, which made it easy for me to mix in the physics modelling of Pymunk (<a href="http://code.google.com/p/pymunk/" rel="noreferrer">http://code.google.com/p/pymunk/</a>). </p> <p>While it is based on OpenGL and you can use those features for special effects, I was able to do just fine without any knowledge of them.</p> <p>It also works well with py2exe and py2app, which is important because a lot of people do not have a Python interpreter installed.</p> <p>On the downside, there is less information about it on the web because it is newer, as well as fewer sample games to look at. </p> <p>Also, it changed quite a bit from previous versions, so some of the tutorials which are there are now out of date (there is the "new style event loop" and the Sprite class as major additions.)</p> <p>I would recommend downloading the examples (there is a nice Asteroids clone called Astraea included) and seeing if you like the style. </p>
<p>Having looked at both pygame and pyglet I found pyglet easier to pick up and was able to write a simple breakout style game within a few days.</p>
48,427
<p>Why am I getting a textbox that returns undefined list of variables?</p> <p>When I run this code:</p> <pre><code>var query = (from tisa in db.TA_Info_Step_Archives where tisa.ta_Serial.ToString().StartsWith(prefixText) select tisa.TA_Serial.ToString()).Distinct().Take(Convert.ToInt32(count)); return query.ToList&lt;string&gt;().ToArray(); </code></pre> <p>I get this XML file:</p> <pre><code>&lt;string&gt;200700160&lt;/string&gt; &lt;string&gt;200700161&lt;/string&gt; &lt;string&gt;200700162&lt;/string&gt; &lt;string&gt;200700163&lt;/string&gt; &lt;string&gt;200700164&lt;/string&gt; &lt;string&gt;200700170&lt;/string&gt; &lt;string&gt;200700171&lt;/string&gt; &lt;string&gt;200700172&lt;/string&gt; &lt;string&gt;200700173&lt;/string&gt; &lt;string&gt;200700174&lt;/string&gt; &lt;string&gt;200700175&lt;/string&gt; &lt;string&gt;200700176&lt;/string&gt; &lt;string&gt;200700177&lt;/string&gt; &lt;string&gt;200700178&lt;/string&gt; &lt;string&gt;200700179&lt;/string&gt; &lt;string&gt;200700180&lt;/string&gt; &lt;string&gt;200700181&lt;/string&gt; &lt;string&gt;200700182&lt;/string&gt; &lt;string&gt;200700183&lt;/string&gt; &lt;string&gt;200700184&lt;/string&gt; </code></pre> <p>BUT, the textbox returns a list of <code>undefined</code>....</p> <p>Help please?</p>
<p>updated my ajax kit to version 1.0.10920 then changed my code to the following:</p> <pre><code> foreach (DataRow dr in dt.Rows) { items.SetValue("\"" + dr["somenumber"].ToString() + "\"", i); i++; } </code></pre> <p>Late friday nights with .net is not fun. I have no life. :-P</p>
<p>It sounds like the problem isn't with the method, but with the way you are hooking up the autocomplete to the method... Is your Extender similar to the following:</p> <pre><code>&lt;cc1:AutoCompleteExtender ID="Result" runat="server" TargetControlID="txtSearch" ServiceMethod="YourMethodHere" ServicePath="~/Service/YourWebServiceHere.asmx" CompletionInterval="500" EnableCaching="false" CompletionListCssClass="AutoComplete_List" CompletionSetCount="10"&gt; &lt;/cc1:AutoCompleteExtender&gt; </code></pre>
22,897
<p>We are build a website using MVC pattern. So far all the pages we built used models which had to operate on Reference data(which is cached when the website loads for the first time). But now we have reached that stage of the flow where we have to deal with Transactional data (which is specific to that flow). Till now we created model classes by giving it all the data, since they were all cached already. But now that we have to deal with transactional data, should we do the same thing where we get all the data upfront and create a model object or should we make the model class get the data by making service calls. </p>
<p>If you're truly using MVC, then your controller should intercept the particular action that should be taken, invoke any data-related requests, and shove the data into your model objects so that the model can then be placed into the view. There is very little benefit to having the model populate itself from a database, because you already have a controller which can do the job in a more cohesive manner.</p>
<p>The disadvantage of the first approach is that the data that is fetched upfront might never be used. So we went with the second approach where the model gets the data. To decouple the model and the service calls we used a interface. Alternatives are welcome.</p>
19,759
<p>I've seen some very good questions on Stack Overflow concerning delegates, events, and the .NET implementation of these two features. One question in particular, "<a href="https://stackoverflow.com/questions/213638/how-do-c-events-work-behind-the-scenes#213651">How do C# Events work behind the scenes?</a>", produced a great answer that explains some subtle points very well. </p> <p>The answer to the above question makes this point:</p> <blockquote> <p>When you declare a field-like event ... the compiler generates the methods and a private field (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field</p> </blockquote> <p>An MSDN article linked from the same question ("<a href="http://msdn.microsoft.com/en-us/library/aa664455.aspx" rel="nofollow noreferrer">Field-like events</a>") adds:</p> <blockquote> <p>The notion of raising an event is precisely equivalent to invoking the delegate represented by the event — thus, there are no special language constructs for raising events.</p> </blockquote> <p>Wanting to examine further, I built a test project in order to view the IL that an event and a delegate are compiled to:</p> <pre><code>public class TestClass { public EventHandler handler; public event EventHandler FooEvent; public TestClass() { } } </code></pre> <p>I expected the delegate field <code>handler</code> and the event <code>FooEvent</code> to compile to roughly the same IL code, with some additional methods to wrap access to the compiler-generated <code>FooEvent</code> field. But the IL generated wasn't quite what I expected: </p> <pre><code>.class public auto ansi beforefieldinit TestClass extends [mscorlib]System.Object { .event [mscorlib]System.EventHandler FooEvent { .addon instance void TestClass::add_FooEvent(class [mscorlib]System.EventHandler) .removeon instance void TestClass::remove_FooEvent(class [mscorlib]System.EventHandler) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Constructor IL hidden } .field private class [mscorlib]System.EventHandler FooEvent .field public class [mscorlib]System.EventHandler handler } </code></pre> <p>Since events are nothing more than delegates with compiler-generated <code>add</code> and <code>remove</code> methods, I didn't expect to see events treated as anything more than that in IL. But the add and remove methods are defined in a section that begins <code>.event</code>, not <code>.method</code> as normal methods are. </p> <p>My ultimate questions are: if events are implemented simply as delegates with accessor methods, what is the point of having a <code>.event</code> IL section? Couldn't they be implemented in IL without this by using <code>.method</code> sections? Is <code>.event</code> equivalent to <code>.method</code>? </p>
<p>I'm not sure that is surprising... compare to the same for properties vs fields (since properties before the same function as events: encapsulation via accessors):</p> <pre><code>.field public string Foo // public field .property instance string Bar // public property { .get instance string MyType::get_Bar() .set instance void MyType::set_Bar(string) } </code></pre> <p>Also - events <em>do not</em> mention anything about fields; they <em>only</em> define the accessors (add/remove). The delegate backer is an implementation detail; it just so happens that field-like-events declare a field as a backing member - in the same way that auto-implemented-properties declare a field as a backing member. Other implementations are possible (and very common, especially in forms etc).</p> <p>Other common implementations:</p> <p>Sparse-events (Controls, etc) - EventHandlerList (or similar):</p> <pre><code>// only one instance field no matter how many events; // very useful if we expect most events to be unsubscribed private EventHandlerList events = new EventHandlerList(); protected EventHandlerList Events { get { return events; } // usually lazy } // this code repeated per event private static readonly object FooEvent = new object(); public event EventHandler Foo { add { Events.AddHandler(FooEvent, value); } remove { Events.RemoveHandler(FooEvent, value); } } protected virtual void OnFoo() { EventHandler handler = Events[FooEvent] as EventHandler; if (handler != null) handler(this, EventArgs.Empty); } </code></pre> <p>(the above is pretty-much the backbone of win-forms events)</p> <p>Facade (although this confuses the "sender" a little; some intermediary code is often helpful):</p> <pre><code>private Bar wrappedObject; // via ctor public event EventHandler SomeEvent { add { wrappedObject.SomeOtherEvent += value; } remove { wrappedObject.SomeOtherEvent -= value; } } </code></pre> <p>(the above can also be used to effectively rename an event)</p>
<p>The point of having events that are a pair of add, remove, methods is <strong>encapsulation</strong>.</p> <p>Most of the time events are used as is, but other times you don't want to store the delegates attached to the event in a field, or you want to do extra processing on add or remove event methods. </p> <p>For example one way to implement <a href="http://vaultofthoughts.net/EventPropertiesMemoryEfficientEvents.aspx" rel="nofollow noreferrer">memory efficient events</a> is to store the delegates in a dictionary rather than a private field, because fields are always allocated while a dictionary only grows in size when items are added. This model is similar with what Winforms and WPF uses make make efficient use of memory (winforms and WPF uses keyed dictionaries to store delegates not lists)</p>
27,058
<p>Is there any way to track the status of a posted upload in AS3? There is a ProgressEvent, but it gives data back about the response, not the actual POST upload. I'm posting binary data for an image, so it's usually in the 50-100kb range. </p> <p>The image data was generated inside Flash itself, so I can't use the upload method - at least as far as I know.</p> <p>Thanks!</p>
<p>Perhaps you can use a function at the server side to send progress events to the flash object?</p>
<p>Take a look at the <a href="http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/net/FileReference.html" rel="nofollow noreferrer">FileReference</a> class. The progress event in it will give you data about the upload:</p> <blockquote> <p>Dispatched periodically during the file upload or download operation. The progress event is dispatched while Flash Player transmits bytes to a server, and it is periodically dispatched during the transmission, even if the transmission is ultimately not successful. To determine if and when the file transmission is actually successful and complete, listen for the complete event. </p> </blockquote>
12,456
<p>Whenever I write a stored procedure for selecting data based on string variable (varchar, nvarchar, char) I would have something like:</p> <pre><code>procedure dbo.p_get_user_by_username( @username nvarchar(256) as begin select u.username ,u.email --,etc from sampleUserTable u where u.username = @username end </code></pre> <p>So in other words to match the record I would have</p> <pre><code>u.username = @username </code></pre> <p>But sometimes I come across code that would use <strong><em>LIK</strong>E</em> in place of <strong><em>=</em></strong></p> <pre><code>u.username like(@username) </code></pre> <p>When would you use it? Shouldn't that be used only when you need some wildcard matching?</p> <p><strong>EDIT</strong></p> <p>Thanks for the answers.</p> <p>I think that I need to clarify that what I was really trying to ask was: if there could be a situation when it was preferred to use like in place of "=" for exact string matching. From the answers I could say that there would not be. From my own experience even in situations when I need to ignore e.g case, and leading and ending spaces i would use ltrim, rtrim, lower on both strings and then "=". Thanks again for your input.</p>
<p>You are correct. There is no benefit in using LIKE unless you are doing wild card matching. In addition, using it without wildcard could lead to the use of an inefficient queryplan.</p>
<p>Yes, as far as I know, using like without any wildcards is the same as using the = operator. are you sure the input parameter doesn't have wildcards in it?</p>
38,831
<p>On our build server, we've installed the .NET Framework 2.0 SDK in order to kick off MSBuild and run our builds. Now we are upgrading to the .NET Framework 3.5. We do not want to install the complete Visual Studio, but we cannot find a .NET Framework 3.5 SDK on the internet either?</p> <p>The question: What do we need ot download and install to get the equivalent of a .NET Framework 3.5 SDK installation?</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF" rel="nofollow noreferrer">Microsoft Windows SDK for Windows Server 2008 and .NET Framework 3.5</a></p> <p>Actually, you only need the SDK for a few things (the RDL reports compiler <code>.targets</code> file leaps to mind, since that one has bitten me recently). The framework itself can do most things.</p>
<p>.net 3.5 comes with compiler and msbuild bundled with it. just download the normal .net 3.5 framework (not the client profile) and you'll be fine.</p>
35,023
<p>How do you manage your database connections in your ASP.Net application?</p> <p>My understanding tells me the "best" way is to open a connection, make a query, close the connection - and do that multiple times because connection pooling makes the cost negligable.</p> <p>The problem comes when I have a DAL where each method looks after its own connection. E.G.</p> <pre> User x = DAL.GetUserDetails(); Customer y = DAL.GetCustomer(); </pre> <p>This is fine until we start talking about TransactionScope</p> <pre> using (TransactionScope t.... { DAL.UpdateCustomer(y); DAL.UpdateUser(x); t.Complete(); } </pre> <p>ASP.Net wants to now use DTC because (I'm guessing) there are multiple connections involved.</p> <p>Someone is going to say "Cache the connection somwhere" but I need to explicitly destroy the connection because of the way I am managing security (execute as / revert) and I don't want to have to make a call on every page to do that because someone will forget to make the call. I could also pass the connection into each method but thats not ideal because the page has to manage a connection.</p> <p>Am I making sense or have I missed something fundamental here?</p>
<p>I was reading somewhere and I don't remember where that Microsoft was going to address that when you have two connections to the same DB that they would not escalate to DTC which would make this problem go away. </p> <p>Until then what we did was to develop our TransactionScope, our DALs would then ask the TS for a new connection, and when we disposed the TS it would close the connection. </p> <p>The connections were stored in LogicalCallContext, although I would look at using HTTP Context instead. I left the company before the app went live but from what I've heard they haven't had any issues.</p> <p>so you'd have </p> <pre><code>using (CustomTS.New()) { CustomerDal.Update() userDal.Update() } </code></pre> <p>CustomTS had a static method that would get the current transaction and connection.</p>
<p>Implement it in a similar idea on how TransactionContext works.</p> <p>I started writing how to do this, but I think an example makes it clearer:</p> <pre><code>public class MyConnectionManager : IDisposable { [ThreadStatic] // static per thread private static SqlConnection con; public static SqlConnection Connection { get { if (con == null) { con = new SqlConnection(); con.Open(); } return con; } } public void Dispose() { if (con != null) { con.Close(); } } } public class Program { public void Run() { using(new MyConnectionManager()) { MakeCall(); MakeCall(); } // Disposal happens here } public void MakeCall() { // The property can be accessed from anywhere SqlCommand cmd = new SqlCommand("SELECT 1", MyConnectionManager.Connection); } } </code></pre> <p>This will cause any calls within the scope of the using statement to use the same connection, as long as they all run on the same thread. You can throw a transaction context in there as well.</p> <p>Caveat: In an ASP.NET WebPages scenario the thread can change between connection and page_load. <a href="http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html" rel="nofollow noreferrer">See this article for more info</a>. Also the thread is re-used. However if you are developing a DAL that is shared among applications, you may not be able to use the HttpContext, as mentioned, as there is none.</p>
44,547
<pre><code>function array_value_from_key($array,$key) { return !empty($array[$key]) ? $array[$key] : null; } </code></pre> <p>The reason I ask is because I have a class function that returns an array.</p> <p>Instead of having to do</p> <pre><code>$myArray = myClass::giveMeArray(); $myValue = $myArray[$myKey]; </code></pre> <p>I'd like to do something along the lines of</p> <pre><code>$myValue = array_value_from_key(myClass::giveMeArray(),$myKey); </code></pre> <p>When an object is returned, you can chain the object such as</p> <pre><code>$myValue = myClass::giveMeObject()-&gt;aValue; </code></pre> <p>Voila, nice and clean.. not being able to find what seems to be a simple and trivial function is driving me crazy...</p> <p>PS.. one more example of how I'd like to use such a function</p> <pre><code>if(arrayKeyVal(aClass::giveMeArray(),$myKey)) { do_something(); } </code></pre>
<p>I haven't tried it, but:</p> <pre><code>$myValue = @$myArray[$myKey]; </code></pre> <p>might work, though i honestly think you would be better off using</p> <pre><code>$myValue = (array_key_exists($myKey, $myArray)) ? $myArray[$myKey] : null; </code></pre>
<p><strong>EDIT</strong>: turns out I need to brush up on my PHP5. My answer below is incorrect and only applies to PHP4, since PHP5 has <a href="http://www.talkphp.com/advanced-php-programming/1163-php5-method-chaining.html" rel="nofollow noreferrer">method chaining</a>.</p> <hr> <p>PHP doesn't allow you to chain together the return statements from functions like in many other languages. eg, in Javascript:</p> <pre><code>document.getElementById('abc').style.color = "#fff"; </code></pre> <p>It's a bit of a pain, but that's just how it is. The equivalent which you have to do in PHP is by storing temporary variables. Here's the above as you'd have to write it, if it were PHP: (obviously these aren't real PHP functions)</p> <pre><code>$myElement = $document-&gt;getElementById('abc'); $myElement-&gt;style-&gt;color = "#fff"; </code></pre> <p>One little positive of this is that it makes debugging a wee bit easier.</p> <p>Note that this only applies to functions: you can "chain" properties of objects:</p> <pre><code>$myObject-&gt;myArray[5]-&gt;anotherProperty-&gt;anotherArray[3]-&gt;anotherObject-&gt;aFunction(); </code></pre> <p>so, in short, if you want to use the result of a function, you have to store it temporarily first</p>
33,125
<p>If I understand correctly the .net runtime will always clean up after me. So if I create new objects and I stop referencing them in my code, the runtime will clean up those objects and free the memory they occupied.</p> <p>Since this is the case why then do some objects need to have a destructor or dispose method? Won’t the runtime clean up after them when they are not referenced anymore?</p>
<p>Finalizers are needed to guarantee the release of scarce resources back into the system like file handles, sockets, kernel objects, etc. Since the finalizer always runs at the end of the objects life, it’s the designated place to release those handles.</p> <p>The <code>Dispose</code> pattern is used to provide deterministic destruction of resources. Since the .net runtime garbage collector is non-deterministic (which means you can never be sure when the runtime will collect old objects and call their finalizer), a method was needed to ensure the deterministic release of system resources. Therefore, when you implement the <code>Dispose</code> pattern properly you provide deterministic release of the resources and in cases where the consumer is careless and does not dispose the object, the finalizer will clean up the object.</p> <p>A simple example of why <code>Dispose</code> is needed might be a quick and dirty log method:</p> <pre><code>public void Log(string line) { var sw = new StreamWriter(File.Open( "LogFile.log", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None)); sw.WriteLine(line); // Since we don't close the stream the FileStream finalizer will do that for // us but we don't know when that will be and until then the file is locked. } </code></pre> <p>In the above example, the file will remain locked until the garbage collector calls the finalizer on the <code>StreamWriter</code> object. This presents a problem since, in the meantime, the method might be called again to write a log, but this time it will fail because the file is still locked.</p> <p>The correct way is to dispose the object when are done using it:</p> <pre><code>public void Log(string line) { using (var sw = new StreamWriter(File.Open( "LogFile.log", FileMode.OpenOrCreate, FileAccess.Write, FileShare.None))) { sw.WriteLine(line); } // Since we use the using block (which conveniently calls Dispose() for us) // the file well be closed at this point. } </code></pre> <p>BTW, technically finalizers and destructors mean the same thing; I do prefer to call c# destructors 'finalizers' since otherwise they tend to confuse people with C++ destructors, which unlike C#, are deterministic.</p>
<p>Some objects might need to clean up low-level items. Such as hardware that needs to be closed, etc.</p>
42,989
<pre><code>AlertEvent::AlertEvent(const std::string&amp; text) : IMEvent(kIMEventAlert, alertText.c_str()), alertText(text) { //inspection at time of crash shows alertText is a valid string } IMEvent::IMEvent(long eventID, const char* details) { //during construction, details==0xcccccccc } </code></pre> <p>on a related note, the monospace font looks really terrible in chrome, whats up with that?</p>
<p>alertText may be shown as a string in a debugger, but it has not been constructed yet (and therefore alertText.c_str() will return an indeterminate pointer).</p> <p>To avoid this, one could initialize use text.c_str() as an argument to the IMEvent ctor.</p> <pre><code>AlertEvent::AlertEvent(const std::string&amp; text) : IMEvent(kIMEventAlert, text.c_str()), alertText(text) { //inspection at time of crash shows alertText is a valid string } IMEvent::IMEvent(long eventID, const char* details) { //during construction, details==0xcccccccc } </code></pre>
<p><em>The IMEvent constructor is called before alertText's constructor is called.</em></p> <p>Almost. <code>alertText.c_str()</code> is called before alertText is constructed, that is the real problem. The easiest solution is replacing it with <code>text.c_str()</code></p>
33,048
<p>Do web browsers send the file size in the http header when uploading a file to the server? And if that is the case, then, is it possible to refuse the file just by reading the header and not wait for the whole upload process to finish?</p>
<p><a href="http://www.faqs.org/rfcs/rfc1867.html" rel="noreferrer">http://www.faqs.org/rfcs/rfc1867.html</a></p> <p><em>HTTP clients are encouraged to supply content-length for overall file input so that a busy server could detect if the proposed file data is too large to be processed reasonably</em></p> <p>But the content-length is not required, so you cannot rely on it. Also, an attacker can forge a wrong content-length. </p> <p>To read the file content is the only reliable way. Having said that, if the content-lenght is present and is too big, to close the connection would be a reasonable thing to do.</p> <p>Also, the content is sent as multipart, so most of the modern frameworks decode it first. That means you won't get the file byte stream until the framework is done, which could mean "until the whole file is uploaded".</p>
<ol> <li><p>I'm not sure, but you should not really trust anything sent in the header, as it could be faked by the user.</p></li> <li><p>It depends on how the server works. For example in PHP your script will not run until the file upload is complete, so this wouldn't be possible.</p></li> </ol>
35,498
<p>I'm trying to use reflection to get a property from a class. Here is some sample code of what I'm seeing:</p> <pre><code> using System.Reflection; namespace ConsoleApplication { class Program { static void Main(string[] args) { PropertyInfo[] tmp2 = typeof(TestClass).GetProperties(); PropertyInfo test = typeof(TestClass).GetProperty( "TestProp", BindingFlags.Public | BindingFlags.NonPublic); } } public class TestClass { public Int32 TestProp { get; set; } } } </code></pre> <p>When I trace through this, this is what I see:</p> <ul> <li>When I fetch all properties using <code>GetProperties()</code>, the resulting array has one entry, for property <code>TestProp</code>.</li> <li>When I try to fetch <code>TestProp</code> using <code>GetProperty()</code>, I get null back.</li> </ul> <p>I'm a little stumped; I haven't been able to find anything in the MSDN regarding <code>GetProperty()</code> to explain this result to me. Any help?</p> <p>EDIT:</p> <p>If I add <code>BindingFlags.Instance</code> to the <code>GetProperties()</code> call, no properties are found, period. This is more consistent, and leads me to believe that <code>TestProp</code> is not considered an instance property for some reason. </p> <p>Why would that be? What do I need to do to the class for this property to be considered an instance property?</p>
<p>Add <code>BindingFlags.Instance</code> to the <code>GetProperty</code> call.</p> <p>EDIT: In response to comment...</p> <p>The following code returns the property.</p> <p>Note: It's a good idea to actually make your property do something before you try to retrieve it (VS2005) :)</p> <pre><code>using System.Reflection; namespace ConsoleApplication { class Program { static void Main(string[] args) { PropertyInfo[] tmp2 = typeof(TestClass).GetProperties(); PropertyInfo test = typeof(TestClass).GetProperty( "TestProp", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Console.WriteLine(test.Name); } } public class TestClass { public Int32 TestProp { get { return 0; } set { } } } } </code></pre>
<p>You need to specify whether it is static or an instance (or both) too.</p>
47,040
<p>I want to get started doing some game development using Microsoft's XNA. Part of that is Shader development, but I have no idea how to get started. I know that <a href="http://developer.nvidia.com/object/fx_composer_home.html" rel="noreferrer">nVidia's FX Composer</a> is a great tool to develop shaders, but I did not find much useful and updated content on how to actually get started.</p> <p>What tutorials would you recommend?</p>
<p>Development of shaders in XNA (which obviously uses DirectX) requires knowledge of <a href="http://msdn.microsoft.com/en-us/library/bb509561(VS.85).aspx" rel="noreferrer">HLSL</a> or shader assembly. I'd recommend getting familiar with the former before diving into the latter.</p> <p>Before writing any shaders, it's a good idea to get solid understanding of the shader pipeline, and attempt to get your mind around what is possible when using programmable shaders. When you're familiar with the life of a pixel (from source data all the way through to the screen) then understanding examples of shaders becomes a lot easier.</p> <p>Next make an attempt to write your own HLSL which does what the <a href="http://www.computerhope.com/jargon/t/tandl.htm" rel="noreferrer">Fixed T&amp;L</a> pipeline used to do, just to get you hands dirty. This is the equivalent of a "hello world" program in vertex/pixel shader world. When you're able to do that and you understand what you've written you're ready to go onto the more fun stuff.</p> <p>As a next step you might want to simulate basic <a href="http://www.gamasutra.com/features/20030418/engel_pfv.htm" rel="noreferrer">sepcular lighting</a> in one of your shaders from a single light source. You can then adapt this down the track to use multiple lights. Play with colours, and movement of lights. This will help get familiar with the use of shader constants as well.</p> <p>When you have a couple of basic shaders together, you should attempt to make it so that your game/engine uses multiple/different shaders on different objects. Start adding some other bits like basic <a href="http://www.paulsprojects.net/tutorials/simplebump/simplebump.html" rel="noreferrer">bump</a> or <a href="http://www.bencloward.com/tutorials_normal_maps1.shtml" rel="noreferrer">normal maps</a>.</p> <p>When you get to this stage, the world is your oyster. You can start diving into some funky effectcs, and even consider using the GPU for <a href="http://www.gpgpu.org/" rel="noreferrer">more</a> than it was originally intended.</p> <p>For those who are a little more advanced, there are a couple of good books that are available for free online which have some great information from Nvidia <a href="http://developer.nvidia.com/object/gpu_gems_home.html" rel="noreferrer">here</a> and <a href="http://developer.nvidia.com/object/gpu_gems_2_home.html" rel="noreferrer">here</a>.</p> <p>Don't forget that there's an excellent series of books called ShaderX which covers some awesome shader stuff. There's <a href="https://rads.stackoverflow.com/amzn/click/com/1556220413" rel="noreferrer" rel="nofollow noreferrer">1</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1556229887" rel="noreferrer" rel="nofollow noreferrer">2</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584503572" rel="noreferrer" rel="nofollow noreferrer">3</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584504250" rel="noreferrer" rel="nofollow noreferrer">4</a>, <a href="https://rads.stackoverflow.com/amzn/click/com/1584504994" rel="noreferrer" rel="nofollow noreferrer">5</a> and <a href="https://rads.stackoverflow.com/amzn/click/com/1584505443" rel="noreferrer" rel="nofollow noreferrer">6</a> already in print, and <a href="http://www.shaderx7.com/" rel="noreferrer">7</a> is coming soon.</p> <p>Good luck. If you get some shaders going, I'd love to see them :)</p>
<p>SAMS's <a href="https://rads.stackoverflow.com/amzn/click/com/0672329646" rel="nofollow noreferrer" rel="nofollow noreferrer">XNA Unleashed</a> by Chad Carter is a great starting point for XNA and assumes little knowledge of game development practices or hard maths before you start. It has two chapters on basic and advanced shaders.</p> <p>As a sidenote, keep an eye out on Google for WPF Shader tutorials, it now uses the same technology to allow customer shaders in WPF applications and tutorials for that I believe are largely compatible with XNA.</p>
2,861
<p>I want to insert some special characters at the caret inside textboxes using javascript on a button. How can this be done?</p> <p>The script needs to find the active textbox and insert the character at the caret in that textbox. The script also needs to work in IE and Firefox.</p> <p><strong>EDIT:</strong> It is also ok to insert the character "last" in the previously active textbox.</p>
<p>I think Jason Cohen is incorrect. The caret position is preserved when focus is lost.</p> <p>[<strong>Edit</strong>: Added code for FireFox that I didn't have originally.]</p> <p>[<strong>Edit</strong>: Added code to determine the most recent active text box.]</p> <p>First, you can use each text box's onBlur event to set a variable to "this" so you always know the most recent active text box.</p> <p>Then, there's an IE way to get the cursor position that also works in Opera, and an easier way in Firefox.</p> <p>In IE the basic concept is to use the document.selection object and <em>put</em> some text <em>into</em> the selection. Then, using indexOf, you can get the position of the text you added.</p> <p>In FireFox, there's a method called selectionStart that will give you the cursor position.</p> <p>Once you have the cursor position, you overwrite the whole text.value with</p> <p>text before the cursor position + the text you want to insert + the text after the cursor position</p> <p>Here is an example with separate links for IE and FireFox. You can use you favorite browser detection method to figure out which code to run.</p> <pre><code>&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt; &lt;script language="JavaScript"&gt; &lt;!-- var lasttext; function doinsert_ie() { var oldtext = lasttext.value; var marker = "##MARKER##"; lasttext.focus(); var sel = document.selection.createRange(); sel.text = marker; var tmptext = lasttext.value; var curpos = tmptext.indexOf(marker); pretext = oldtext.substring(0,curpos); posttest = oldtext.substring(curpos,oldtext.length); lasttext.value = pretext + "|" + posttest; } function doinsert_ff() { var oldtext = lasttext.value; var curpos = lasttext.selectionStart; pretext = oldtext.substring(0,curpos); posttest = oldtext.substring(curpos,oldtext.length); lasttext.value = pretext + "|" + posttest; } --&gt; &lt;/script&gt; &lt;form name="testform"&gt; &lt;input type="text" name="testtext1" onBlur="lasttext=this;"&gt; &lt;input type="text" name="testtext2" onBlur="lasttext=this;"&gt; &lt;input type="text" name="testtext3" onBlur="lasttext=this;"&gt; &lt;/form&gt; &lt;a href="#" onClick="doinsert_ie();"&gt;Insert IE&lt;/a&gt; &lt;br&gt; &lt;a href="#" onClick="doinsert_ff();"&gt;Insert FF&lt;/a&gt; &lt;/body&gt;&lt;/html&gt; </code></pre> <p>This will also work with textareas. I don't know how to reposition the cursor so it stays at the insertion point.</p>
<p>Note that if the user pushes a button, focus on the textbox will be lost and there will be no caret position!</p>
7,775
<p>Every class that wants to use java.util.logging generally needs to declare a logger like this:</p> <pre><code>public class MyClass { private static Logger _log = Logger.getLogger(MyClass.class.getName()); } </code></pre> <p>How do you avoid this MyClass.class.getName() boilerplate code?</p>
<p>I have a template set up in Eclipse so that I only have to type a portion of the declaration, and then Eclipse will auto-complete the rest for me.</p> <pre><code>${:import(org.apache.log4j.Logger)} private final static Logger log = Logger.getLogger(${enclosing_type}.class); ${cursor} </code></pre> <p>So, I only have to type <code>logger</code>, hit <code>Ctrl+Space</code>, followed by <code>Enter</code>, and Eclipse fills in the rest for me and adds the import declaration as well.</p> <p>This won't cut down on the amount of boilerplate code, but at least it cuts down on the amount of keystrokes.</p>
<p>If you make the logger nonstatic, you can at least inherit it:</p> <pre><code>public class SomeBaseClass { protected Logger logger = Logger.getLogger(getClass()); } public class SubClass extends SomeBaseClass { public void doit() { logger.debug("doit!!!!"); } } </code></pre> <p>That's how I've always done it.</p>
26,140
<p>Here's the issue:</p> <p>I have a hook in IE that reacts on <code>WebBrowser.OnNavigateComplete2</code> event to parse the content of the document for some precise info.</p> <p>That document contains frames, so I look into the <code>HTMLDocument.frames</code>. For each one, I look into the document.body.outerHTML property to check for the content. </p> <p>Problem is, the string I'm looking for never shows there, whereas it is displayed in the finale page. So, am I looking in the wrong place? If it is displayed when the page is fully loaded, then it's downloaded at some point, right? But in which object should I look ?</p> <p>BTW, I Don't know if that is of any importance, but the page I'm searching into comes from a ASP.NET application.</p> <pre><code>public void OnNavigateComplete2(object pDisp, ref object url) { document = (HTMLDocument)webBrowser.Document; mshtml.FramesCollection frames = document.frames; for (int i = 0; i &lt; frames.length; i++) { object refIdx = i; IHTMLWindow2 frame = (IHTMLWindow2)frames.item(ref refIdx); string frameContent = frame.document.body.outerHTML; } } </code></pre> <p>Thank your for your help.</p> <hr> <p>@rams This event is launched many times for each page, so I figured it was each time a framed is loaded, even if i don't get to catch the one I'm looking for. If not, what would be the event to catch the frames content?</p> <p>What I want to do is detect some precise info on a precise frame, then save it. later, a web page is loaded triggered by some user action, where I need the info I got from parsing the frame.</p>
<p>Do you know the name/id of the frame you are looking for content? If so, in your navigateComplete2 event, can you get a reference to the frame like </p> <pre><code>iFrame frm = document.frames(&lt;your frame id&gt;); int readyState=0; while(frm.readystate !=4){ // do nothing. be careful to not create an endless loop } if(frm.readyState==4){ // get your content now } </code></pre> <p>HTH</p>
<p>Are you using some kind of threading? Running the browser in a separate thread really messes up things. Try to execute it in an STAThread and check if you get the correct result.</p>
41,988
<p>I know that XSLT does not work in procedural terms, but unfortunately I have been doing procedural languages for too long. Can anyone help me out by explaining in simple terms how things like apply-templates works and help a thicko like me to understand it.</p>
<p>What makes you think that procedural terms do not apply here? It's just that the calling convention is somewhat more implicit than you would traditionally expect it, because there is an invisible context involved. Everything <code>apply-templates</code> does could be expressed in procedural terms.</p> <p>Basically, <code>apply-templates</code> is nothing more than a for-each loop. Starting from where where you currently are in the document (the context, think "<code>this</code>"), it iterates over the child nodes. </p> <p>For each child, the processor selects the matching <code>xsl:template</code> with the highest priority (based on their respective <code>match</code> and <code>priority</code> attributes), sets the context to the child at hand and runs this template (think "<code>function</code>"). After the template returns, the context snaps back and it's the next child's turn.</p> <p>Even when things become recursive (which is somewhat hard to avoid in XSLT), the whole process really does not become any more complicated. The context "pointer" is moved around, and templates get called.</p> <p>You can restrict the node set that <code>apply-templates</code> iterates over, using the <code>select</code> attribute:</p> <pre><code>&lt;!-- all children of the context node regardless --&gt; &lt;xsl:apply-templates /&gt; &lt;!-- all children of the context node being "data" with a @name of "Foo" --&gt; &lt;xsl:apply-templates select="data[@name='Foo']" /&gt; </code></pre> <p>You can sort the node-set prior to the iteration, if you wish:</p> <pre><code>&lt;!-- all children of the context node being "data" with a @name of "Foo", ordered by their respective "detail" count --&gt; &lt;xsl:apply-templates select="data[@name='Foo']"&gt; &lt;xsl:sort select="count(detail)" data-type="number" order="descending"/&gt; &lt;/xsl:apply-templates&gt; </code></pre> <p>And you can pass parameters to your template if you need, just like you would with a regular function call:</p> <pre><code>&lt;!-- pass in some parameter --&gt; &lt;xsl:apply-templates select="data[@name='Foo']"&gt; &lt;xsl:with-param name="DateSetIcon" select="$img_src" /&gt; &lt;/xsl:apply-templates&gt; </code></pre> <p>That's about all there is to it.</p> <p>EDIT:</p> <p>I know that the last comment is a bit provocative. This is very much intentional, for a basic understanding of how <code>apply-templates</code> works this is more or less it. The implications and possibilities that come from the fact that not <em>you</em> are defining what template to call, but rather let the processor choose the right one for you are of course bigger than what it sounds like to the untrained ear. The declarative/implicit approach of the whole thing surely needs some time to sink in.</p>
<p>I strongly agree with the answer and blog post of Greg Beech.</p> <p>For more detailed comparison between <code>&lt;xsl:for-each&gt;</code> and <code>&lt;xsl:apply-templates&gt;</code> see <a href="http://markmail.org/message/xbm7tsglnhqogdzd" rel="nofollow noreferrer"><strong>my answer</strong></a> to the question "xsl:for-each vs. xsl:apply-templates" in the xsl-list, and enjoy <a href="http://markmail.org/message/xbm7tsglnhqogdzd#query:+page:1+mid:u6vldphwj263tejm+state:results" rel="nofollow noreferrer"><strong>the whole thread</strong></a>.</p> <p>"<em>xsl:apply-templates is much richer and deeper than xsl:for-each, even simply because we don't know what code will be applied on the nodes of the selection -- in the general case this code will be different for different nodes of the node-list. <strong>Also, the code that will be applied can be written way after the xsl:apply templates was written and by people that do not know the original author</em></strong>".</p> <p>Another difference from a procedural programming language is that the order in which the templates will be applied is not predefined. There is no notion of "state" or "order of execution" in a pure functional programming language. </p> <p>Neither <a href="http://www.w3.org/TR/xslt20/#applying-templates" rel="nofollow noreferrer"><strong>XSLT 2.0</strong></a> nor <a href="http://www.w3.org/TR/xslt#section-Processing-Model" rel="nofollow noreferrer"><strong>XSLT 1.0</strong></a> specifies any particular order of applying the selected template rules -- only that their results will be combined according to the order of the nodes (in the sorted sequence, if there are any <code>&lt;xsl:sort&gt;</code> directives or otherwise in the document order of the nodes), on which the templates are applied.</p> <p>The <a href="http://www.w3.org/TR/xslt20/#applying-templates" rel="nofollow noreferrer"><strong>XSLT 2.0 Spec</strong></a> says:</p> <p>"<em>Each template rule that is evaluated produces a sequence of items as its result. The resulting sequences (one for each node in the sorted sequence) are then concatenated, to form a single sequence. They are concatenated retaining the order of the nodes in the sorted sequence. The final concatenated sequence forms the result of the xsl:apply-templates instruction</em>"</p> <p>The <a href="http://www.w3.org/TR/xslt#section-Processing-Model" rel="nofollow noreferrer"><strong>XSLT 1.0</strong></a> spec says:</p> <p>"<em>Implementations are free to process the source document in any way that produces the same result as if it were processed using this processing model</em>."</p> <p>It is even possible that an XSLT implementation may apply templates (or the body of an <code>&lt;xsl:for-each&gt;</code>) in parallel.</p>
43,225
<p>I have a table style page with rows. Each row has a checkbox. I can select all/many checkboxes and click "submit" and what is does is a Jquery ajax call for each row. </p> <p>Basically I have a form for each row and I iterate over all the checked rows and submit that form which does the jquery ajax call.</p> <p>So I have a button that does:</p> <pre><code> $("input:checked").parent("form").submit(); </code></pre> <p>Then each row has:</p> <pre><code> &lt;form name="MyForm&lt;%=i%&gt;" action="javascript:processRow(&lt;%=i%&gt;)" method="post" style="margin:0px;"&gt; &lt;input type="checkbox" name="X" value="XChecked"/&gt; &lt;input type="hidden" id="XNumber&lt;%=i%&gt;" name="X&lt;%=i%&gt;" value="&lt;%=XNumber%&gt;"/&gt; &lt;input type="hidden" id="XId&lt;%=i%&gt;" name="XId&lt;%=i%&gt;" value="&lt;%=XNumber%&gt;"/&gt; &lt;input type="hidden" id="XAmt&lt;%=i%&gt;" name="XAmt&lt;%=i%&gt;" value="&lt;%=XAmount%&gt;"/&gt; &lt;input type="hidden" name="X" value="rXChecked"/&gt; &lt;/form&gt; </code></pre> <p>This form submits to processRow:</p> <pre><code> function processRow(rowNum) { var Amount = $('#XAmt'+rowNum).val(); var XId = $('#XId'+rowNum).val(); var XNum = $('#OrderNumber'+rowNum).val(); var queryString = "xAmt=" + "1.00" + "&amp;xNumber=" + OrdNum + "&amp;xId=" + xId; $('#coda_'+rowNum).removeClass("loader"); $('#coda_'+rowNum).addClass("loading"); $.ajax({ url: "x.asp", cache: false, type: "POST", data: queryString, success: function(html){ $('#result_'+rowNum).empty().append(html); $('#coda_'+rowNum).removeClass("loading"); $('#coda_'+rowNum).addClass("loader"); } }); } </code></pre> <p>What I wanted to know is, from this is there a way I can tell if all my Ajax calls are complete. Reason being that want to enable/disable the submit button while all these calls are taking place.</p> <p>Thanks and please note that I had to mangle my variable names due to the sensitivity of the application, so many of them may be duplicated.</p>
<h1>The easy way</h1> <p>The easiest way is to use the <a href="http://api.jquery.com/ajaxStop/" rel="noreferrer"><code>.ajaxStop()</code> event handler</a>: </p> <pre><code>$(document).ajaxStop(function() { // place code to be executed on completion of last outstanding ajax call here }); </code></pre> <h1>The hard way</h1> <p>You can also manually detect if any ajax call is still active:</p> <p>Create a variable containing number of active Ajax connections: </p> <pre><code>var activeAjaxConnections = 0; </code></pre> <p>just before opening new Ajax connection increment that variable </p> <pre><code>$.ajax({ beforeSend: function(xhr) { activeAjaxConnections++; }, url (...) </code></pre> <p>in <code>success</code> part check if that variable equals to zero (if so, the last connection has finished) </p> <pre><code>success: function(html){ activeAjaxConnections--; $('#result_'+rowNum).empty().append(html); $('#coda_'+rowNum).removeClass("loading"); $('#coda_'+rowNum).addClass("loader"); if (0 == activeAjaxConnections) { // this was the last Ajax connection, do the thing } }, error: function(xhr, errDesc, exception) { activeAjaxConnections--; if (0 == activeAjaxConnections) { // this was the last Ajax connection, do the thing } } </code></pre> <p>As you can see, I've added also checking for return with error</p>
<p>How about just simply use <strong>if</strong>?</p> <pre><code>success: function(html){ if(html.success == true ){ $('#result_'+rowNum).empty().append(html); $('#coda_'+rowNum).removeClass("loading"); $('#coda_'+rowNum).addClass("loader"); } } </code></pre>
36,530
<p>Ideally I'd like a way to enable the mouse wheel for scrolling in old compiled java runtime apps, but java code to explicitly utilise it for an individual app would suffice. </p>
<p>You shouldn't have to recompile against 1.5 or 1.6 to get mousewheel, unless you wrote custom components. The mousewheel behaviors were added to the swing classes, so just running old java apps against the new JRE should have mousewheel support without having to do anything (at least in scrollable/JScrollPane based stuff)</p>
<p>Mousewheel scrolling is supported in current Swing applications. You could try compiling your application using JDK 1.4, 1.5 or 1.6. Depending on the complexity and environment moving to a new version may or may not be a viable option.</p> <p><a href="http://java.sun.com/docs/books/tutorial/uiswing/events/mousewheellistener.html" rel="nofollow noreferrer">This tutorial</a> shows how to write your own mousewheel listener if you want something different to the normal behaviour.</p>
13,121
<p>I would like to monitor the number of threads used by a specific process on Linux. Is there an easy way to get this information without impacting the performance of the process?</p>
<p>try</p> <pre><code>ps huH p &lt;PID_OF_U_PROCESS&gt; | wc -l </code></pre> <p>or <a href="http://htop.sourceforge.net/" rel="noreferrer">htop</a></p>
<p>VisualVM can show clear states of threads of a given JVM process</p> <p><a href="https://i.stack.imgur.com/kbLlz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kbLlz.png" alt="enter image description here"></a></p>
33,726
<p>Is there a one statement or one line way to accomplish something like this, where the string s is declared AND assigned the first non-null value in the expression?</p> <pre><code>//pseudo-codeish string s = Coalesce(string1, string2, string3); </code></pre> <p>or, more generally,</p> <pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx); </code></pre>
<p>As Darren Kopp said.</p> <p>Your statement</p> <pre><code>object obj = Coalesce(obj1, obj2, obj3, ...objx); </code></pre> <p>Can be written like this:</p> <pre><code>object obj = obj1 ?? obj2 ?? obj3 ?? ... objx; </code></pre> <p>to put it in other words:</p> <pre><code>var a = b ?? c; </code></pre> <p>is equivalent to</p> <pre><code>var a = b != null ? b : c; </code></pre>
<p>the <strong>??</strong> operator.</p> <pre><code>string a = nullstring ?? "empty!"; </code></pre>
6,383
<p>Without spending a long time reviewing the boost source code, could someone give me a quick rundown of how boost bind is implemented? </p>
<p>I like this piece of the <code>bind</code> source:</p> <pre><code>template&lt;class R, class F, class L&gt; class bind_t { public: typedef bind_t this_type; bind_t(F f, L const &amp; l): f_(f), l_(l) {} #define BOOST_BIND_RETURN return #include &lt;boost/bind/bind_template.hpp&gt; #undef BOOST_BIND_RETURN }; </code></pre> <p>Tells you almost all you need to know, really.</p> <p>The <code>bind_template</code> header expands to a list of inline <code>operator()</code> definitions. For example, the simplest:</p> <pre><code>result_type operator()() { list0 a; BOOST_BIND_RETURN l_(type&lt;result_type&gt;(), f_, a, 0); } </code></pre> <p>We can see the <code>BOOST_BIND_RETURN</code> macro expands to <code>return</code> at this point so the line is more like <code>return l_(type...)</code>.</p> <p>The one parameter version is here:</p> <pre><code>template&lt;class A1&gt; result_type operator()(A1 &amp; a1) { list1&lt;A1 &amp;&gt; a(a1); BOOST_BIND_RETURN l_(type&lt;result_type&gt;(), f_, a, 0); } </code></pre> <p>It's pretty similar.</p> <p>The <code>listN</code> classes are wrappers for the parameter lists. There is a lot of deep magic going on here that I don't really understand too much though. They have also overloaded <code>operator()</code> that calls the mysterious <code>unwrap</code> function. Ignoring some compiler specific overloads, it doesn't do a lot:</p> <pre><code>// unwrap template&lt;class F&gt; inline F &amp; unwrap(F * f, long) { return *f; } template&lt;class F&gt; inline F &amp; unwrap(reference_wrapper&lt;F&gt; * f, int) { return f-&gt;get(); } template&lt;class F&gt; inline F &amp; unwrap(reference_wrapper&lt;F&gt; const * f, int) { return f-&gt;get(); } </code></pre> <p>The naming convention seems to be: <code>F</code> is the type of the function parameter to <code>bind</code>. <code>R</code> is the return type. <code>L</code> tends to be a list of parameter types. There are also a lot of complications because there are no less than nine overloads for different numbers of parameters. Best not to dwell on that too much.</p>
<p>I think it's a template class that declares a member variable for the arguments you want to bind and overloads () for the rest of the arguments.</p>
13,779
<p>to do some visualization of data I would like to include rectangles, circles and text within my graphs. Does anyone know a Java based framework (maybe similar to very basic Powerpoint functionality) that can export SVG graphics?</p>
<p>Have a look at Java Advanced Imaging (<a href="http://java.sun.com/javase/technologies/desktop/media/jai/" rel="nofollow noreferrer">JAI</a>) and <a href="http://xmlgraphics.apache.org/batik/" rel="nofollow noreferrer">Batik</a> SVG toolkit:</p>
<p>You could use the built in java.awt package for basic drawing functionality.</p> <p><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html" rel="nofollow noreferrer">http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Graphics2D.html</a></p> <p>extend your class from the java.awt.Drawable interface and implement the : </p> <p><code>public void draw(Graphics graphicsIn)</code> method.</p> <p>Edit: I didn't read that you needed SVG export. My suggestion might be stupid in that case.</p>
38,717
<p>Ok I need to change the value of a hidden field in a gridview and here is what I have so far:</p> <pre><code>for(var i = 0; i &lt; gv_Proofs.rows.length; i++) { var tbl_Cell = gv_Proofs.rows[i].cells[0]; var sdiFound = false; for(var x = 0; x &lt; tbl_Cell.childNodes.length; x++) { if(tbl_Cell.childNodes[x].id == "_ctl0_MasterContentPlaceHolder_gv_Proofs__ctl2_lbl_SDI") { if(tbl_Cell.childNodes[x].innerHTML == sdi) sdiFound = true; } if(tbl_Cell.childNodes[x].id == "_ctl0_MasterContentPlaceHolder_gv_Proofs__ctl2_lbl_Updated" &amp;&amp; sdiFound) tbl_Cell.childNodes[x].value = "true"; } } </code></pre> <p>can anyone tell me what I am doing wrong? Thank You!</p>
<p>I got it working. The above loop was working just right but apparently my value of sdi was not always getting set right, and therefore the value I was checking was always set to false. So the above worked perfectly in my case if anyone ever has this issue again.</p>
<p><strong>Edit: classic case of check before you post. <a href="http://www.beansoftware.com/ASP.NET-Tutorials/GridView-Hidden-Column.aspx" rel="nofollow noreferrer">Apparently</a> setting hidden=true actually prevents databinding which will be why the JS is having issues. <em>I</em> would say this is one of those typical problems with ASP.NET which make me curse it's very name, but <em>you</em> might just choose to adapt the control with one of the many googleable solutions.</strong></p> <p><em>Comments about using element ID in ASP.NET left intact because it's evil.</em></p> <hr> <p>Hard to know without more code (when is this executing exactly? is something else overwriting it? what does the markup look like?) but I can say right now that referencing an element by it's ASP.NET deformed ID is a Bad Idea(TM).</p> <p>If you can I suggest you try and modify this in the codebehind where the reference is handled for you, or at least write out the JS there where you can use clientID. Failing that I would try and find the element through an expanded element hunter - your own or a library util like jquery et al's "$" function - which will allow you to use a robust CSS or Xpath argument instead.</p>
44,772
<pre><code>$array = explode(&quot;.&quot;, $row[copy]); $a = $array.length -1; </code></pre> <p>I want to return the last element of this array but all i get from this is -1.</p>
<p>You can also use:</p> <p>$a = end($array);</p> <p>This also sets the arrays internal pointer to the end of the array, but it does get you the last element easily.</p>
<p>My PHP is a bit rusty, but shouldn't this be:</p> <pre><code>$array = explode(".", $row[$copy]); $a = $array[count($array)]; </code></pre> <p>i.e.: isn't a "$" missing in front of "copy", and does .length actually work?</p>
19,915
<p>I found this in the code I'm working on at the moment and thought it was the cause of some problems I'm having.</p> <p>In a header somewhere:</p> <pre><code>enum SpecificIndexes{ //snip INVALID_INDEX = -1 }; </code></pre> <p>Then later - initialization:</p> <pre><code>nextIndex = INVALID_INDEX; </code></pre> <p>and use</p> <pre><code>if(nextIndex != INVALID_INDEX) { //do stuff } </code></pre> <p>Debugging the code, the values in nextIndex didn't quite make sence (they were very large), and I found that it was declared:</p> <pre><code>unsigned int nextIndex; </code></pre> <p>So, the initial setting to INVALID_INDEX was underflowing the unsigned int and setting it to a huge number. I assumed that was what was causing the problem, but looking more closely, the test</p> <pre><code>if(nextIndex != INVALID_INDEX) </code></pre> <p>Was behaving correctly, i.e, it never executed the body of the if when nextIndex was the "large +ve value".</p> <p>Is this correct? How is this happening? Is the enum value being implicitly cast to an unsigned int of the same type as the variable, and hence being wrapped in the same way?</p>
<p>Yes to everything. It is valid code, it is also commonly used library-side C++ code, more so in modern C++ (it is strange when you see it the first time but its a very common pattern in reality).</p> <p>Then enums are signed ints, but they get implicitly cast into unsigned ints, now this depending on your compiler might give a warning, but its still very commonly used, however you should explicitly cast to make it clear to maintainers.</p>
<p>Yes, I believe enums are signed. Change </p> <pre><code>unsigned int nextIndex; </code></pre> <p>to </p> <pre><code>int nextIndex; </code></pre> <p>and your program should work.</p>
38,709
<p>Okay, I guess this is entirely subjective and whatnot, but I was thinking about entropy sources for random number generators. It goes that most generators are seeded with the current time, correct? Well, I was curious as to what other sources could be used to generate perfectly valid, random (The loose definition) numbers.</p> <p>Would using multiple sources (Such as time + current HDD seek time [We're being fantastical here]) together create a "more random" number than a single source? What are the logical limits of the amount of sources? How much is really enough? Is the time chosen simply because it is convenient?</p> <p>Excuse me if this sort of thing is not allowed, but I'm curious as to the theory behind the sources.</p>
<p>The Wikipedia article on <a href="http://en.wikipedia.org/wiki/Hardware_random_number_generator" rel="noreferrer">Hardware random number generator's</a> lists a couple of interesting sources for random numbers using physical properties. </p> <p>My favorites: </p> <ul> <li>A nuclear decay radiation source detected by a Geiger counter attached to a PC.</li> <li>Photons travelling through a semi-transparent mirror. The mutually exclusive events (reflection — transmission) are detected and associated to "0" or "1" bit values respectively.</li> <li>Thermal noise from a resistor, amplified to provide a random voltage source.</li> <li><strong>Avalanche noise generated from an avalanche diode.</strong> (How cool is that?)</li> <li>Atmospheric noise, detected by a radio receiver attached to a PC</li> </ul> <p>The <a href="http://en.wikipedia.org/wiki/Hardware_random_number_generator#Problems" rel="noreferrer">problems section</a> of the Wikipedia article also describes the fragility of a lot of these sources/sensors. Sensors almost always produce decreasingly random numbers as they age/degrade. These physical sources should be constantly checked by statistical tests which can analyze the generated data, ensuring the instruments haven't broken silently. </p>
<p>Some use keyboard input (timeouts between keystrokes), I heard of I think in a novel that radio static reception can be used - but of course that requires other hardware and software...</p>
38,580
<p>What is the 'correct' way to store a native pointer inside a Java object?</p> <p>I could treat the pointer as a Java <code>int</code>, if I happen to know that native pointers are &lt;= 32 bits in size, or a Java <code>long</code> if I happen to know that native pointers are &lt;= 64 bits in size. But is there a better or cleaner way to do this?</p> <p><strong>Edit</strong>: Returning a native pointer from a JNI function is exactly what I <em>don't</em> want to do. I would rather return a Java object that represents the native resource. However, the Java object that I return must presumably have a field containing a pointer, which brings me back to the original question.</p> <p>Or, alternatively, is there some better way for a JNI function to return a reference to a native resource?</p>
<p>IIRC, both <code>java.util.zip</code> and <code>java.nio</code> just use <code>long</code>.</p>
<p>You could look to the way C# handles this with the IntPtr type. By creating your own type for holding pointers, the same type can be used as a 32-bit or 64-bit depending on the system you're on.</p>
43,761
<p>I have an associative array, ie</p> <pre><code>$primes = array( 2=&gt;2, 3=&gt;3, 5=&gt;5, 7=&gt;7, 11=&gt;11, 13=&gt;13, 17=&gt;17, // ...etc ); </code></pre> <p>then I do</p> <pre><code>// seek to first prime greater than 10000 reset($primes); while(next($primes) &lt; 10000) {} prev($primes); // iterate until target found while($p = next($primes)) { $res = doSomeCalculationsOn($p); if( IsPrime($res) ) return $p; } </code></pre> <p>The problem is that IsPrime also loops through the $primes array,</p> <pre><code>function IsPrime($num) { global $primesto, $primes, $lastprime; if ($primesto &gt;= $num) // using the assoc array lets me do this as a lookup return isset($primes[$num]); $root = (int) sqrt($num); if ($primesto &lt; $root) CalcPrimesTo($root); foreach($primes as $p) { // &lt;- Danger, Will Robinson! if( $num % $p == 0 ) return false; if ($p &gt;= $root) break; } return true; } </code></pre> <p>which trashes the array pointer I am iterating on.</p> <p>I would like to be able to save and restore the array's internal pointer in the IsPrime() function so it doesn't have this side effect. Is there any way to do this?</p>
<p>You can "save" the state of the array:</p> <pre><code>$state = key($array); </code></pre> <p>And "restore" (not sure if there's a better method):</p> <pre><code>reset($array); while(key($array) != $state) next($array); </code></pre>
<p>If speed is not an issue and you aren't pushing php memory limits the quickest solution is just to duplicate your primes array and iterate 2 different ones.</p> <pre><code>$awesomePrimes=$primes; </code></pre> <p>Then change globals and foreach in your function to <code>$awesomePrimes</code></p>
42,551
<p>I'm trying to write a script that will create a file on the server then use <code>header()</code> to redirect the user to that file. Then, after about 10 seconds I want to delete the file. I've tried this:</p> <pre><code>header('Location: '.$url); flush(); sleep(10); unlink($url); </code></pre> <p>But the browser just waits for the script to complete then gets redirected, but the file hes been deleted by that time. Is there someway to tell the browser "end of file", then keep computing? Or maybe have PHP start another script, but not wait for that script to finish?</p>
<p>You might be better off having the PHP page serve the file. No need to create a temporary file in this case and delete it, just send out the data you intended to write to the temporary file. You will need to set the headers correctly so the browser can identify the type of file you are sending. i.e. Content-Type: text/xml; for xml or image/jpeg for jpg's. </p> <p>This method also handles slow clients that take longer to download the file. </p>
<p>You're going about this the wrong way. You can create the file and serve it to them, and delete it in one step.</p> <pre><code>&lt;?php $file_contents = 'these are the contents of your file'; $random_filename = md5(time()+rand(0,10000)).'.txt'; $public_directory = '/www'; $the_file = $public_directory.'/'.$random_filename; file_put_contents($the_file, $file_contents); echo file_get_contents($the_file); unlink($the_file); ?&gt; </code></pre> <p>If you do it that way, the files get deleted immediately after the user sees them. Of course, this means that the file need not exist in the first place. So you could shorten the code to this:</p> <pre><code>&lt;?php $file_contents = 'these are the contents of your file'; echo $file_contents; ?&gt; </code></pre> <p>It all depends on where you're getting the content you want to show them. If it's from a file, try:</p> <pre><code>&lt;?php $file_contents = file_get_contents($filename_or_url); echo $file_contents; ?&gt; </code></pre> <p>As for deleting files automatically, just setup a cron job that runs every 10 seconds, and deletes all the files in your temp folder that where filemtime($filename) is greater than 5 minutes' worth of seconds.</p>
46,635
<p>How can I add a line break to text when it is being set as an attribute i.e.:</p> <pre><code>&lt;TextBlock Text="Stuff on line1 \n Stuff on line2" /&gt; </code></pre> <p>Breaking it out into the exploded format isn't an option for my particular situation. What I need is some way to emulate the following:</p> <pre><code>&lt;TextBlock&gt; &lt;TextBlock.Text&gt; Stuff on line1 &lt;LineBreak/&gt; Stuff on line2 &lt;/TextBlock.Text&gt; &lt;TextBlock/&gt; </code></pre>
<pre><code>&lt;TextBlock Text="Stuff on line1&amp;#x0a;Stuff on line 2"/&gt; </code></pre> <p>You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" <code>vbCrLf</code>, then you can use <code>&amp;#x0d;&amp;#x0a;</code></p> <p>By the way, note the syntax: It's the ampersand, a pound, the letter <em>x</em>, then the hex value of the character you want, and then finally a semi-colon.</p> <p>ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.</p>
<p>Code behind solution</p> <pre><code>private void Button1_Click(object sender, RoutedEventArgs e) { System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder(); myStringBuilder.Append("Orange").AppendLine(); myStringBuilder.Append("").AppendLine(); myStringBuilder.Append("Apple").AppendLine(); myStringBuilder.Append("Banana").AppendLine(); myStringBuilder.Append("").AppendLine(); myStringBuilder.Append("Plum").AppendLine(); TextBox1.Text = myStringBuilder.ToString(); } </code></pre>
22,169
<p>I have IIS 5.1 installed on Windows XP Pro SP2. Besides I have installed VS 2008 Express with .NET 3.5. So obviously IIS is configured for ASP.NET automatically for .NET 3.5</p> <p>The problem is whenever I access <a href="http://localhost" rel="noreferrer">http://localhost</a> IE &amp; Firefox both presents authentication box. Even if I enter Administrator user and its password, the authentication fails. I have already checked the anonymous user access (with IUSR_ user and password is controlled by IIS) in Directory Security options of default website.</p> <p>However other deployed web apps work fine (does not ask for any authentication).</p> <p>In IE this authentication process stops if I add <a href="http://localhost" rel="noreferrer">http://localhost</a> in Intranet sites option.</p> <p>Please note that the file system is FAT32 when IIS is installed.</p> <p>Regards, Jatan</p>
<p>This is most likely a NT file permissions problem. IUSR_ needs to have file system permissions to read whatever file you're requesting (like /inetpub/wwwroot/index.htm).<p>If you still have trouble, check the IIS logs, typically at \windows\system32\logfiles\W3SVC*.</p>
<p>What worked for me is ,,,</p> <p>Click Start>control panel>Administrative Tools>Internet Information Services</p> <p>Expand the left tree, right-click your WebSite>Properties</p> <p>Click on Directory Security, then in "Anonymous access and authentication control" click on Edit</p> <p>Enable Anonymous access>browse> enter the credentials of the admin (like Administrator) (check names),> Click OK</p> <p>Apply the settings and it should work fine.</p>
7,691
<p>If you call <code>LoadLibrary</code> without a path (e.g., <code>LoadLibrary("whatever.dll")</code>, Windows will generally follow its standard search algorithm, the same one it uses to find EXEs.</p> <p>My question is this: suppose that an application manifest specifies specifies a particular version of a system DLL, say, comctl32.dll 6.0. In that case, will <code>LoadLibrary("comctl32.dll")</code> go immediately to the correct side-by-side folder, or does it still perform some kind of search?</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/ms682586.aspx" rel="noreferrer">Microsoft:</a></p> <blockquote> <p>Applications can control the location from which a DLL is loaded by specifying a full path, using DLL redirection, or by using a manifest. If none of these methods are used, the system searches for the DLL at load time as described in this topic.</p> </blockquote> <p>So yes, if a manifest is present, it will directly go to the SxS folder.</p>
<p>To probe the loader when having troubles with missing libraries, you can use the "sxstrace" feature. <a href="http://www.codeproject.com/KB/DLL/QueryAssemblyIdentities.aspx" rel="nofollow noreferrer">www.codeproject.com/KB/DLL/QueryAssemblyIdentities.aspx</a> gives some details about the dependencies between manifest and WinSxs.</p>
18,643
<p>I have a form containing a web browser control. This browser control will load some HTML from disk and display it. I want to be able to have a button in the HTML access C# code in my form. </p> <p>For example, a button in the HTML might call the Close() method on the form.</p> <p>Target platform: C# and Windows Forms (any version)</p>
<p>Look at the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx" rel="noreferrer">WebBrowser.ObjectForScripting</a> property. Managed to get Google Maps talking to a windows forms application using this.</p>
<p>This is possible, but I haven't done it in .NET. A few years back I had a C++ application that hosted a web browser control (ActiveX). From the HTML in the control, it was possible to call 'out' to the ActiveX control and get it to do things. </p> <p>The same should be possible in .NET, although HTML DOM/JavaScript won't know about C#. But if you wrap your .NET functionality in a COM object, you should be able to call methods on the COM/ActiveX objects which will in-turn call your C# code.</p> <p>Hope this helps.</p>
39,358
<p>This appears to be the most commonly asked C# interop question and yet seems to be difficult to find a working solution for.</p> <p>I am in need of allocating an array of matrix datastructure in C# passing it to a C DLL which fills up the data and returns it to the caller to deal with.</p> <p>Based on various pages on the web, I seem to have managed to get data and memory from C# into C++ but not, it appears, back...</p> <p>Code follows.</p> <p>thanks in advance for any help Shyamal</p> <hr> <p>I have a C++ structure as follows</p> <pre><code>typedef struct tagTMatrix { int Id; int NumColumns; int NumRows; double* aData; } TMatrix; </code></pre> <p>which I declare in C# as</p> <pre><code>[StructLayout(LayoutKind.Sequential)] unsafe public struct TMatrix { public Int32 id; public Int32 NumCols; public Int32 NumRows; public Int32 NumPlanes; public IntPtr aData; }; [DllImport("kernel32.dll")] internal static extern IntPtr LoadLibrary(String dllname); [DllImport("kernel32.dll")] internal static extern IntPtr GetProcAddress(IntPtr hModule, String procname); unsafe internal delegate void FillMatrices(IntPtr mats, long num); [DllImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] // Saw this mentioned somewhere static extern void CopyMemory(IntPtr dest, IntPtr[] src, int cb); unsafe private void butTest_Click(object sender, EventArgs e) { IntPtr library = LoadLibrary("TestDLL.dll"); IntPtr procaddr = GetProcAddress(library, "FillMatrices"); FillMatrices fm = (FillMatrices)Marshal.GetDelegateForFunctionPointer(procaddr, typeof(FillMatrices)); TMatrix[] mats = new TMatrix[2]; mats[0]=new TMatrix(); mats[1]=new TMatrix(); mats[0].id=1; mats[0].NumCols=2;mats[0].NumRows=1;mats[0].NumPlanes=0; mats[0].aData = Marshal.AllocHGlobal(sizeof(double) * 2); double [] array=new double[2]; array[0]=12.5;array[1]=2.3; fixed (double* a = array) { IntPtr intPtr = new IntPtr((void*)a); mats[1].aData = Marshal.AllocHGlobal(sizeof(double) * 2); //mats[1].aData = 13; mats[1].aData = intPtr; mats[1].id = 2; mats[1].NumCols = 1; mats[1].NumRows = 2; mats[1].NumPlanes = 0; } IntPtr[] ptrs = new IntPtr[2]; int total=0; for (int i = 0; i &lt; ptrs.Length; i++) { total = total + sizeof(IntPtr) * (4 + mats[i].NumCols * mats[i].NumRows); ptrs[i] = Marshal.AllocHGlobal(sizeof(IntPtr)*(4+mats[i].NumCols*mats[i].NumRows)); } Marshal.StructureToPtr(mats[0], ptrs[0], false); Marshal.StructureToPtr(mats[1], ptrs[1], false); //_list.test_list = IntPtr pointer=Marshal.AllocHGlobal(total); CopyMemory(pointer, ptrs, 2 * IntPtr.Size); //TMatrix m1=new TMatrix(); //mats[0].aData = 10;// new double[20]; //TMatrix m2 = new TMatrix(); // mats[1].aData = 20;// new double[9]; //Marshal.StructureToPtr(m2, p1, false); //mats.Add(m2); //Marshal.StructureToPtr(mats, p1, false); //IntPtr p2=Marshal.AllocHGlobal(270); //Marshal.StructureToPtr(mats.ToArray(),p2,false); fm(pointer,2); // Now I want to get back this data ??? } // C++ function extern "C" void FillMatrices(TMatrix** mats, int matcount) { FILE* fp=fopen("C:\\mats.txt","w+"); fprintf(fp,"Number of matrices = %d\n",matcount); fflush(fp); for(int i=0;i&lt;matcount;++i) { TMatrix* m=mats[i]; fprintf(fp,"id = %d rows %d cols %d \n",m-&gt;Id,m-&gt;NumRows,m-&gt;NumColumns); fflush(fp); for(int j=0;j&lt;m-&gt;NumRows;++j) { fprintf(fp,"%d ",j); fflush(fp); for(int k=0;k&lt;m-&gt;NumColumns;++k) { fprintf(fp,"%f ", m-&gt;aData[k*m-&gt;NumRows+j]); // modify the data - it should be available back in C# m-&gt;aData[k*m-&gt;NumRows+j]=k; fflush(fp); } fprintf(fp,"\n"); fflush(fp); } fprintf(fp,"--------------------------\n"); fflush(fp); } fclose(fp); } </code></pre>
<p>Here's a modified version of my initial code that works with an array of matrices:</p> <pre><code>typedef struct Matrix { int rowsCount; int colsCount; int* data; } TMatrix; extern "C" __declspec(dllexport) void InitializeMatrix(TMatrix** matrices, int count) { srand(time(NULL)); printf("&lt;unmanaged&gt;\n"); for(int i = 0; i &lt; count; i++) { TMatrix* m = matrices[i]; printf("rows %d cols %d\n", m-&gt;rowsCount, m-&gt;colsCount); for(int j = 0; j &lt; m-&gt;rowsCount; j++) { for(int k = 0; k &lt; m-&gt;colsCount; k++) { printf("%d ", m-&gt;data[k * m-&gt;rowsCount + j]); // modify the data - it should be available back in C# m-&gt;data[k * m-&gt;rowsCount + j] = rand() % 10; } printf("\n"); } } printf("&lt;/unmanaged&gt;\n\n"); } </code></pre> <p>And the managed part:</p> <pre><code>[StructLayout(LayoutKind.Sequential)] struct Matrix { public int RowsCount; public int ColsCount; public IntPtr Data; } class Program { [DllImport("TestLib.dll")] private static extern void InitializeMatrix(IntPtr ptr, int count); static void Main(string[] args) { const int count = 3; // Allocate memory IntPtr ptr = Marshal.AllocHGlobal(count * Marshal.SizeOf(typeof(IntPtr))); IntPtr[] matrices = new IntPtr[count]; for (int i = 0; i &lt; count; i++) { Matrix matrix = new Matrix(); // Give some size to the matrix matrix.RowsCount = 4; matrix.ColsCount = 3; int size = matrix.RowsCount * matrix.ColsCount; int[] data = new int[size]; matrix.Data = Marshal.AllocHGlobal(size * Marshal.SizeOf(typeof(int))); Marshal.Copy(data, 0, matrix.Data, size); matrices[i] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(Matrix))); Marshal.StructureToPtr(matrix, matrices[i], true); } Marshal.Copy(matrices, 0, ptr, count); // Call unmanaged routine InitializeMatrix(ptr, count); Console.WriteLine("&lt;managed&gt;"); // Read data back Marshal.Copy(ptr, matrices, 0, count); for (int i = 0; i &lt; count; i++) { Matrix m = (Matrix)Marshal.PtrToStructure(matrices[i], typeof(Matrix)); int size = m.RowsCount * m.ColsCount; int[] data = new int[size]; Marshal.Copy(m.Data, data, 0, size); // Pretty-print the matrix Console.WriteLine("rows: {0} cols: {1}", m.RowsCount, m.ColsCount); for (int j = 0; j &lt; m.RowsCount; j++) { for (int k = 0; k &lt; m.ColsCount; k++) { Console.Write("{0} ", data[k * m.RowsCount + j]); } Console.WriteLine(); } } Console.WriteLine("&lt;/managed&gt;"); // Clean the whole mess (try...finally block omitted for clarity) for (int i = 0; i &lt; count; i++) { Matrix m = (Matrix)Marshal.PtrToStructure(matrices[i], typeof(Matrix)); Marshal.FreeHGlobal(m.Data); Marshal.FreeHGlobal(matrices[i]); } Marshal.FreeHGlobal(ptr); } } </code></pre> <p>HTH</p>
<p>Here's how I did it in an old project in which I had to pass a matrix of integers to a C routine that would fill it with values and then I had to get back the values in managed code.</p> <p>I had a routine in unmanaged code that would fill a matrix of integers with some values:</p> <pre><code>#include "stdafx.h" #include "TestLib.h" #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; extern "C" __declspec(dllexport) void InitializeMatrix(int** matrix, int rows, int cols) { srand(time(NULL)); printf("rows: %d\ncols: %d\n", rows, cols); for (int i = 0; i &lt; rows; i++) { for (int j = 0; j &lt; cols; j++) { matrix[i][j] = rand() % 10; } } } </code></pre> <p>And then in managed code I did something among the lines:</p> <pre><code>class Program { [DllImport(@"TestLib.dll")] private static extern void InitializeMatrix(IntPtr ptr, int rows, int cols); static void Main(string[] args) { const int rowsCount = 3; const int colsCount = 4; // Allocate memory for the matrix: (rowsCount * sizeof(IntPtr)) * (colsCount * sizeof(int)) IntPtr ptr = AllocateMatrix(rowsCount, colsCount); try { // Call unmanaged routine to fill the allocated memory with data InitializeMatrix(ptr, rowsCount, colsCount); // Marshal back data int[][] matrix = GetMatrixFromPointer(ptr, rowsCount, colsCount); // Pretty-print the matrix for (int i = 0; i &lt; rowsCount; i++) { for (int j = 0; j &lt; colsCount; j++) { Console.Write("{0} ", matrix[i][j]); } Console.WriteLine(); } } finally { // Release allocated memory FreeMatrix(ptr, rowsCount, colsCount); } } private static IntPtr AllocateMatrix(int rowsCount, int colsCount) { IntPtr ptr = Marshal.AllocHGlobal(rowsCount * Marshal.SizeOf(typeof(IntPtr))); IntPtr[] rows = new IntPtr[rowsCount]; for (int i = 0; i &lt; rowsCount; i++) { int[] cols = new int[colsCount]; rows[i] = Marshal.AllocHGlobal(colsCount * Marshal.SizeOf(typeof(int))); Marshal.Copy(cols, 0, rows[i], colsCount); } Marshal.Copy(rows, 0, ptr, rows.Length); return ptr; } private static int[][] GetMatrixFromPointer(IntPtr ptr, int rowsCount, int colsCount) { int[][] result = new int[rowsCount][]; IntPtr[] rows = new IntPtr[rowsCount]; Marshal.Copy(ptr, rows, 0, rowsCount); for (int i = 0; i &lt; rowsCount; i++) { int[] cols = new int[colsCount]; Marshal.Copy(rows[i], cols, 0, colsCount); result[i] = cols; } return result; } private static void FreeMatrix(IntPtr ptr, int rowsCount, int colsCount) { IntPtr[] rows = new IntPtr[rowsCount]; Marshal.Copy(ptr, rows, 0, rowsCount); for (int i = 0; i &lt; rowsCount; i++) { Marshal.FreeHGlobal(rows[i]); } Marshal.FreeHGlobal(ptr); } } </code></pre> <p>P/Invoke is a PITA. I would strongly recommend you to avoid it as much as possible and in cases where it is not possible try to organize your functions in a way to minimize marshaling data.</p>
48,957
<p>I have a question regarding handling errors in a J2EE application. Our current application is in use by many many users and as a result we get a lot of support tickets. Most of these tickets are user-related but 5-10% are system related exceptions, unhandled errors, etc.</p> <p>We have the basic exception handling checks in the code (needs works), but from my experience showing a generic message to the user doesn't help the troubleshooting process to be expedited. </p> <p>What I'm looking for is a recommendation on a good error handling design pattern so that let's consider a scenario:</p> <ol> <li>Code has an error</li> <li>Error is handled</li> <li>User is shown a non-technical error message with a specific error code.</li> <li>Non-tech Support team can use this error code to see the area (page, section, ..) in the application where this happened and what the user might have been doing (information prepopulated by dev team in a customer support reference guide).</li> <li>Tech support team can use the code to zero right in on the class/JSP etc and line of code which trigged that exception.</li> <li>We use a logging module where <em>most</em> (not all) Tomcat stdout errors are logged by user session ... to the error code the user will receive we can include the log ID if it exists as well so that the tech team can look at that too.</li> </ol> <p>Basically what I'm interested is to reduce the support analysis-explanation-research cycle and give every department access to the information at their fingertips which can get them started faster for their respective jobs:</p> <ol> <li>Customer support can give a canned explanation for this error code or have alternative steps the user could follow.</li> <li>Tech team could start troubleshooting the line of code or what the user was doing which triggered that line. </li> </ol> <p>Essential each error code triggers of the required next-steps for each department and in effect reducing the research phase of the issue and moving to the solution phase.</p> <p>I'm not sure if the above is even a good idea. Any suggestions would be appreciated on a good "design pattern" for such a need. Or if it would even be a good route to look at.</p> <p>Thanks in advance.</p> <p>SP</p>
<p>It sounds like you need to spend some serious time bucketing your support issues for some code triage. My experience has been that you can nearly always create a "top 10 list" of items that are causing 50%+ of the support issues. After you've knocked off the first 10, reexamine the call logs. Data is imperative.</p> <p>A program dedicated to tackling the support issues and knocking them out of the park should be able to winnow down code issues fairly quickly. After which, you'll be left with human/usability issues that have to be handled with training, experience, or typically some longer term workflow/usability refactoring. </p> <p>If you're being swamped in errors for which you think you need to develop a list of error codes / conditions, it sounds like your product needs another 6 months of stabilization. You're probably <em>not</em> developing an OS, and for 99% of projects developing an IBMesque black book of error codes is not the model to emulate.</p>
<p>Use log4j to log all errors and exceptions to a logger which emails you the information. Don't worry about user messaging; all they need to know is there was an error and that it was logged.</p>
34,515
<p>Is there a quick one-liner to call datepart in Sql Server and get back the name of the day instead of just the number?</p> <pre><code>select datepart(dw, getdate()); </code></pre> <p>This will return 1-7, with Sunday being 1. I would like 'Sunday' instead of 1.</p>
<pre><code>select datename(weekday, getdate()); </code></pre>
<p>This is not possible without using the result to select the day yourself. For one thing the textual representation of the day is locale-dependent. For another the returned value depends upon the 'datefirst' setting.</p>
3,356
<p>Okay, what is it, and why does it occur on Win2003 server, but not on WinXP.</p> <p>It doesn't seem to affect my application at all, but I get this error message when I close the application. And it's annoying (as errors messages should be).</p> <p>I am using pyOpenGl and wxPython to do the graphics stuff. Unfortunately, I'm a C# programmer that has taken over this Python app, and I had to learn Python to do it.</p> <p>I can supply code and version numbers etc, but I'm still learning the technical stuff, so any help would be appreciated.</p> <p>Python 2.5, wxPython and pyOpenGL</p>
<p>Looks like OpenGL is trying to report some error on Win2003, however you've not configured your system where to output logging info.</p> <p>You can add the following to the beginning of your program and you'll see details of the error in stderr.</p> <pre><code>import logging logging.basicConfig() </code></pre> <p>Checkout documentation on <a href="https://docs.python.org/2/library/logging.html" rel="noreferrer">logging</a> module to get more config info, conceptually it's similar to log4J.</p>
<p>After adding the Logging above, I was able to see that the problem was caused by missing TConstants class, which I was excluding in the py2exe setup.py file. </p> <p>After removing the "Tconstants" from the excluded list, I no longer had problems.</p>
45,019
<p>I am getting the following error:</p> <pre><code>Open OLE error code:80004005 in Microsoft OLE DB Provider for SQL Server [DBNETLIB][ConnectionOpen (Connect()).]SQL Server does not exist or access denied. HRESULT error code:0×80020009 Exception occurred. </code></pre> <p>I have tried following the directions <a href="http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer" rel="nofollow noreferrer">here</a> with no luck.</p> <p>Any ideas?</p> <p><strong><em>FIXED</em></strong></p> <p>My specific issue I believe was related to having to many mixed systems installed on my laptop. I had Visual Studio 2005 and 2008 components and SQL Server Management Standard loaded with SQL Server Express Edition as well as various other components that might have affected the stability of my environment. Once I reloaded Vista and went back through the steps <a href="http://wiki.rubyonrails.org/rails/pages/HowtoConnectToMicrosoftSQLServer" rel="nofollow noreferrer">from the link above</a> it worked without issue.</p> <p>I only loaded the Express Editions of SQL Server and SQL Server Management Studio.</p>
<p>Usually a authentication/permissions error.</p> <p>Is the SQL Server on the same box as the web server, review the accounts they are running under, and review the type of connection you are making (integrated or otherwise)?</p>
<p>Random guess: By default SQL Server (express, at least anyway) does NOT enable network access. The SQL Admin manager tools connect to it using named pipes, however rails most likely will be trying to use TCP.</p>
18,761
<p>The default Courier New 10pt is larger than necessary for me. However, using that font at 8pt does not look very good.</p> <p>Are there better choices for a more readable, very small (e.g., 8pt) font for eclipse?</p>
<p>If running on Windows, you may give Microsoft Consolas a shot (included in Vista or later, and available as a separate download). I use it everywhere.</p>
<p>Check out <a href="http://www.lowing.org/fonts/" rel="nofollow noreferrer">Monospace/Fixed Width Programmer's Fonts</a>. It addresses many important aspects for using a font with programming.</p>
17,589
<p>I want to create an <code>NSOpenPanel</code> that can select any kind of file, so I do this</p> <pre><code>NSOpenPanel* panel = [NSOpenPanel openPanel]; if([panel runModalForTypes:nil] == NSOKButton) { // process files here } </code></pre> <p>which lets me select all files <em>except</em> symbolic links.<br> They're simply not selectable and the obvious <code>setResolvesAliases</code><br> does nothing.</p> <p>What gives?</p> <p><b>Update 1:</b> I did some more testing and found that this strangeness<br> is present in Leopard (10.5.5) but not in Tiger (10.4.8). </p> <p><b>Update 2:</b> The code above can select mac aliases (persistent path<br> data that lives in the resource fork) but not symlinks (files created with ln -s).</p>
<p>I cannot reproduce this. I just tried it and it works just fine. If symlink points to a directory, it shows the directory content when I select the symlink and if the symlink points to a file, I can select it as well.</p> <p>Of course if the symlink points to a directory, you can only select it if choosing directories is allowed</p> <pre><code>NSOpenPanel * panel = [NSOpenPanel openPanel]; [panel setCanChooseDirectories:YES]; if ([panel runModalForTypes:nil] == NSOKButton) { NSLog(@"%@", [panel filenames]); } </code></pre>
<p>Your code sample worked for me, as well - I'm using 10.5.5 and XCode 3.1, if it matters.</p> <p>If the alias is to a directory, I couldn't select the alias, since it resolved to the directory that it was pointing to, not the alias itself (the panel seems to resolve aliases by default). I was able to select an alias to a file, though.</p>
23,164
<p>I have a content type that has required fields. I have associated Word document with the content type as a template. I now want to edit the Word template, but word won't allow me to save the template without filling in the required fields. However, if I fill in the required fields and save the document, then those fields get populated with my values when you create a new document. This isn't good because I want the fields to be blank when a new document is created - I want the users to be forced to fill in those values. </p> <p>I can update the templace by updating the colums and making them optional, editing the word template, saving the template &amp; then changing the columns back to required. This is a PITA - there's got to be a better way, does anyone know what it is?</p>
<p>I've been using this work around: When I edit the template (ie go to the content type settings --> Advanced settings --> Edit Template), I make my changes and save the file locally. Then, on the same page that I clicked the "Edit Template" link, I upload the copy that I saved locally. Saving it locally avoids the validation that happens when you try to save it back to SharePoint. But the validation still gets applied to any new documents of that content type. So no need to toggle the settings off &amp; on! :)</p>
<p>Have you tried saving the document as a normal document content type, making the changes, saving it, then moving back over the top of where the old version of the template was?</p>
36,134
<p>I'm a bit stuck here, I have a .net 3.5 sp1 application that I want to deploy locally to other machines on my network using ClickOnce.</p> <p>On installation they get a warning message saying that this application is from an unknown publisher etc.</p> <p>My boss does not want to buy a verisgn certificate. He just want's it to install and without prompting i.e bypassing security messages.</p> <p>Is this possible???</p> <p>Some notes on the Microsoft website suggest changes have been made in this area i.e.</p> <p>"ClickOnce application publishers can now decide to opt out of signing and hashing the ClickOnce manifests as they see appropriate for their scenarios."</p> <p>Thanks</p> <p>Tim</p>
<p>Since you're on your own network you could create your own trusted certificate publisher. To do so, install Certificate Authority services on one of your servers and create a code-signing certificate. By default your user's computers won't trust the certificate, so run the following on each computer: </p> <p>certmgr.exe -add -c MYRootCertificate.cer -s -r localMachine root</p> <p>certmgr.exe -add -c MyCodeSigningCert.cer -s -r localMachine TrustedPublisher</p> <p>The first is to get your computers to trust your internal CA server (to get rid of the "not a trusted publisher" message), and the second is to get it to trust the apps signed by your certificate.</p> <p>After that, any of your signed applications will run without security warnings.</p>
<p>Mitchell's answer is good, but unless you have an Enterprise Edition server you can't customize templates and the Code Signing template is marked as "unexportable". That means that you cannot use the certificate within Visual Studio and have to have an after-process that signs your manifests.</p> <p>Now this is a feature, not a bug, make no mistake. A typical software shop doesn't want developers to be signing manifests for public consumption from within Visual Studio. That said, I'm personally in a shop where I <strong>do</strong> want precisely that functionality. Fortunately, I managed to figure out the long-way around <a href="http://theruntime.com/blogs/jacob/archive/2006/12/04/creating-a-domain-publisher-cert-for-a-small-internal-software-shop.aspx" rel="nofollow noreferrer">getting a pfx key file exported</a> that has code signing priveleges. If you find you need that, it can be useful.</p>
44,205
<p>Is the new ControlState feature only applicable to custom controls or is it available for the standard server controls as well?</p> <p>That is..can you disable ViewState for an entire page with standard controls like Detailsview, Gridview and would it still work? <strong>Does ControlState apply to standard server controls?</strong></p> <p>Or in order to work with ControlState for standard server controls you have to modify their behavior by creating a new custom GridView/DetailsView?</p>
<p>From the <a href="http://msdn.microsoft.com/en-us/library/1whwt1k7.aspx" rel="nofollow noreferrer">Microsoft Documentation</a>.</p> <blockquote> <p>Use control state only for small amounts of critical data that are essential for the control across postbacks. Do not use control state as an alternative to view state.</p> </blockquote> <p>From this you can guess that GridView and other items would not be storing that large of an amount of information in ControlState, so I'm guessing that if you wanted to do it, against Microsoft's recommendation you would have to extend the base control to do it.</p>
<p>You can disable view state for all page but you need to rebind datagrid, dataview in every postback. </p> <p>Sometimes it works better then saving a huge viewstate on the client.</p> <p>For standard server controls: if you modify Control Properties after init, then all modifications will be saved in ViewState too.</p> <p>Here is awesome Scott Mitchell <a href="http://msdn.microsoft.com/en-us/library/ms972976.aspx" rel="nofollow noreferrer">Post about ViewState</a>. </p>
49,987
<p>You know how Subversion stores a copy of every file it has checked-out in the hidden .svn folders? The website I'm building is pretty big (has over 1Gig of PDF files). These PDF files will very rarely change throughout the existence of the website.</p> <p>I was wondering if there was a way of telling Subversion that it shouldn't store a local revision copy of a certain set of files (my PDF files) but just sync with the server whenever a change is made to any of these files?</p>
<p>Subversion uses the version in the .svn folders to be able to diff the new file against the old file, and send just the differences to the subversion server. </p> <p>So no, there's no way to not have the files inside the .svn folders, that still allows you to commit these files</p>
<p>You might want to consider managing the "live" copy of your website using <code>svn export</code> instead of a checkout. This would completely avoid the problem of large files in .svn folders.</p> <p>Your workflow could be like this:</p> <ol> <li>Edit files locally, test in test deployment</li> <li>Commit changes to repository</li> <li>Run a <code>svn export</code> from the repository to the live system</li> </ol> <p>The disadvantage of this is that any changes that might have been made to the live system in the meantime will get overwritten. But you can arrange your workflow to avoid that.</p> <p>Actually, it occurs to me that I don't know whether you are concerned about these hidden PDF files in your working checkout, or in the server deployment. If it's in your working checkout, then I don't know of a way to avoid these files using Subversion. However, if you use Git with <code>git-svn</code>, then Git will manage its own compressed history without full copies of all the files.</p>
42,684
<p>I have Windows 2003 Standard, IIS 6, PHP, MySQL and amy trying to get mcrypt working so I can use phpMyAdmin.</p> <p>I have uncommended php_mcrypt.dll in php.ini and this file is in my extensions folder (c:\php).</p> <p>I have downloaded libmcrypt.dll to c:\php, c:\php\ext, c:\windows, c:\windows\system32. I have also found a second version of this file on the next and tried that. After each change I have restarted IIS.</p> <p>Whatever I try mcrypt does not seem to be loaded when I check php_info();. But there are no errors showing. </p> <p>Is there another version of php_mcrypt.dll? does anyone have a version of phpMyAdmin that does not need mcrypt? Has anyone experienced this problem / have a solution?</p> <p>All help will be greatly apprecaited.</p> <p>Many thanks,</p> <p>Tim</p>
<p>I had the same problem and found that the version of libmcrypt.dll I had was corrupt and when I downloaded a version from the net it was fine. As you have already done this I doubt this helps?</p>
<ul> <li>Make sure your extension_dir in php.ini points to the right path (e.g. c:/php5/ext)</li> <li>Try restarting windows after each change instead of IIS.</li> <li>libmcrypt.dll only has to be in c:\windows\system32</li> <li>To be sure mcrypt is (not) loaded, use phpinfo() to check.</li> </ul> <p>I'm also having difficulty getting mcrypt to load, but above has helped me a lot in getting closer to a solution.</p>
24,813
<p>I need to store sensitive data across few pages (run over https) per session.</p> <p>I can't use session object, for the primary reason being that the session store is designed as just as backup store (primarily make service calls and load the session). If the session has been restarted or in other words that the key in the session does not exist, make the service and re-populate the session.</p> <p>So, in the case of user keyed in sensitive data, i need to carry this data forward across pages, we do not have a persistent store for now, therefore option left is storing these sensitive data in Viewstate. </p> <p>1) Should I encrypt the data and store then in Viewstate (not recommended though - sec &amp; perf. implications) OR 2) Should i store the data in a serializable class and store that in Viewstate? (not recommended again due to perf. implications)</p> <p>Any opinion please?</p>
<blockquote> <p>I need to store sensitive data across few pages (run over https) per session.</p> </blockquote> <p>ViewState is set and maintained on the page level. It cannot be carried across different page requests, only postbacks of the current page. Assuming you really mean you have to carry the data "across a few pages" rather than postbacks.</p> <p>You could potentially store your sensitive data in a cookie, but that comes with some security risks.</p> <p>You could also store your sensitive data in a server side data store (xml file, database, etc.) and store a key to the data in the client side cookie. Slightly more secure.</p>
<p>Storing modest amounts of data in the viewstate, whether or not you use a serializable class, shouldn't be a performance concern.</p> <p>You will need to use encryption to protect the data values within the viewstate. Again, performance should not be a concern for modest amounts of data. See <a href="http://weblogs.asp.net/varad/archive/2005/02/04/367056.aspx" rel="nofollow noreferrer">this page</a> for details on how to enable viewstate encryption.</p>
33,142
<p>I'm building the HTML code within an XML DOM object to be used as the contents of the innerHTML of a div element using an XSL template. Traditionally we create a new XML DOM document and add the input parameters as XML Elements for the transform via javascript. This is all very time-consuming as we are basically hand picking the data from another XML document that represents our current account and copying the data into a transient XML DOM document. </p> <p>What I'd like to do is clone the relevant node of the account document (i.e. customer info) and use it as the basis for the transform. I don't want to use the account document directly as I'd like to be able to add transform specific input, without making changes to the account object.</p> <p>How efficient is using .cloneNode(true) for a desired node of about typically less than 200 elements from a document of typically 2000+ elements? The target platform is IE6 with no external tools (i.e. ActiveX).</p>
<p>CloneNode is pretty efficient but it will be consuming more memory doing it that way.</p> <p>Another approach to consider is to use a Template object and a processor, pass your additional/changed data as parameters to the processor and the element that you would have otherwise cloned as the input element. This approach would require fairly significant mods the XSL though.</p>
<p>If you don't need form-elements, cloneNode is a real reliable tool ...</p> <p>-- and in inserting ajax-data it is incredible in efficiency ...</p> <p>However, as especially IE has a history of having problems with name-attributes, it is inconvenient to address any of these if you insert data ...</p> <p>-- I don't really understand your XSL(T)-using, to me it sounds like using a gas-station as a (not !-) convenient place to change a 1960 WV to a 2008 Skoda ...</p> <p>Userely they have some common technology, though it is not used in the same way, computerization in some way is just a minor problem, the major problems is in nearly <strong>any</strong> other way !o]</p> <p>Have you got any need for form-elements ?-)</p>
34,388
<p>I had a plugin installed in Visual Studio 2008, and it created some extra dockable windows. I have uninstalled it, and I can't get rid of the windows it created - I close them, but they always come back. They're just empty windows now, since the plugin is no longer present, but nothing I've tried gets rid of them. I've tried:</p> <ul> <li>Window -> Reset Window Layout</li> <li>Deleting the .suo files in my project directories</li> <li>Deleting the Visual Studio 9.0 folder in my Application Settings directory</li> </ul> <p>Any ideas?</p>
<p>Have you tried this? In Visual Studio go to <strong>Tools</strong> > <strong>Import and Export Settings</strong> > <strong>Reset all settings</strong></p> <p>Be sure you <strong>back up</strong> your settings before you do this. I made the mistake of trying this to fix an issue and didn't realize it would undo all my appearance settings and toolbars as well. Took a lot of time to get back to the way I like things.</p>
<p><code>Window -&gt; Reset Window Layout</code> didn't exist for me. For anybody looking in 2022 or later, I finally found the answer! The crucial information, buried in a VSCode update release note, was right at the bottom of <a href="https://code.visualstudio.com/updates/v1_64#_workbench" rel="nofollow noreferrer">this section</a>. Here it is if the link breaks in the future:</p> <blockquote> <p>If you'd like to reset all views back to the default layout, you can run <code>Views: Reset View Locations</code> from the Command Palette.</p> </blockquote>
4,652
<p>I've been trying to fix this for two hours straight and I can't figure it out.</p> <pre><code>onclick = "location='exceltest.asp?vanjaar=&lt;%=vanjaar%&gt;&amp;vanmaand=&lt;%=vanmaand%&gt;&amp;vandag=&lt;%=vandag%&gt;&amp;totjaar=&lt;%=totjaar%&gt;&amp;totmaand=&lt;%=totmaand%&gt;&amp;totdag=&lt;%=totdag%&gt;'" </code></pre> <p>That line of code is in an &lt; input type="button" /> attribute. The button links to a page where an Excel download should be triggered. The values in the URL are from- and to-date-parts. (year, month, day)</p> <p>this:</p> <pre><code>onclick = "location='exceltest.asp?fromdate=&lt;%=fromdate%&gt;&amp;todate=&lt;%=todate%&gt;'" /&gt; </code></pre> <p>does not work, because somehow IE7 reads the date (eg. 2008/1/1) wrong. Something to do with the slashes I think. </p> <p>But when I try to click the button in IE and thus download the generated file, Internet explorer tries do download the file </p> <blockquote> <p>exceltest.asp?vanjaar=2008vanmaand=1vandag=1totjaar=2008totmaand=2totdag=1</p> </blockquote> <p>instead of the excel file I want.<br> FF offers to download the excelfile, but gives (in that excelfile) an overview of an htmlpage with an errormessage telling me my query is wrong (Item cannot be found in the collection corresponding to the requested name or ordinal.) But that CAN'T be, I'm using that exact same query elsewhere, using the same (but restarted) connection.</p> <p>This is the bit of code I use to instantiate the download of the file:</p> <pre><code>Response.Buffer = TRUE Response.ContentType = "application/vnd.ms-excel" Response.AddHeader "content-disposition", "attachment; filename=overicht.xls" </code></pre> <p>There might actually being to things going on here, but I am most insterested in why IE wants to download the asp page and FF offers the right download.</p>
<p>The <code>&amp;</code> inside <code>onclick=""</code> should be html-encoded to <code>&amp;amp;</code></p> <p>If fromdate contains slashes you're probably safest to url-encode that as well (though you seem to contradict that with your example URL).</p>
<p>Something that might help: <a href="http://www.w3schools.com/asp/met_urlencode.asp" rel="nofollow noreferrer"><code>Server.URLEncode</code></a></p> <pre><code>fromdate=&lt;%=Server.URLEncode(fromdate)%&gt; </code></pre> <p>But, your Excel file error -- <strong>Item cannot be found in the collection corresponding to the requested name or ordinal.</strong> -- is from <strong><code>Recordset.Fields()</code></strong>. You're trying to grab a field that isn't available -- either a column name that isn't in your query or an index that's beyond your column count.</p>
46,795
<p>The following code writes no data to the back buffer on Intel integrated video cards,for example, on a MacBook. On ATI cards, such as in the iMac, it draws to the back buffer. The width and height are correct (and 800x600 buffer) and m_PixelBuffer is correctly filled with 0xAA00AA00.</p> <p>My best guess so far is that there is something amiss with needing glWindowPos set. I do not currently set it (or the raster position), and when I get GL_CURRENT_RASTER_POSITION I noticed that the default on the ATI card is 0,0,0,0 and the Intel it's 0,0,0,1. When I set the raster pos on the ATI card to 0,0,0,1 I get the same result as the Intel card, nothing drawn to the back buffer. Is there some transform state I'm missing? This is a 2D application so the view transform is a very simple glOrtho.</p> <pre><code>glDrawPixels(GetBufferWidth(), GetBufferHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_PixelBuffer); </code></pre> <p>Any more info I can provide, please ask. I'm pretty much an OpenGL and Mac newb so I don't know if I'm providing enough information.</p>
<p>I've always had problems with OpenGL implementations from Intel, though I'm not sure that's your problem this time. I think you're running into some byte-order issues. Give this a read and feel free to experiment with different constants for packing and color order.</p> <p><a href="http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_25.html" rel="nofollow noreferrer">http://developer.apple.com/documentation/MacOSX/Conceptual/universal_binary/universal_binary_tips/chapter_5_section_25.html</a></p> <p>I know it's OSX guide, you can probably find similar OpenGL articles on other sites for other platforms. This should be applicable.</p>
<blockquote> <p>I've always had problems with OpenGL implementations from Intel</p> </blockquote> <p>This is kind of what I'm worried about, but I have a hard time believing they'd screw up something as basic as glDrawPixels, and also, since I can "duplicate" the problem by changing the raster position vector, it makes me think it's my fault and I'm missing something basic.</p> <blockquote> <p>I think you're running into some byte-order issues</p> </blockquote> <p>That was my first inclination, and I've tried packing differently, with no result. I also tried packing the buffer with values that would present a usable alpha if swizzled, with no result. This is why I'm barking up the raster pos tree, but I'm still honestly not 100% sure. Note that I'm targeting only Intel Macs if that makes a difference.</p> <p>Thanks for the link, it was a good read, and good to tuck away for future reference. I'd upmod but I can't until I get 3 more rep points :)</p>
4,524
<p>I have some integration points where I want to test various responses - where do you think should I store these artifacts in my spec/ directory of my rails application?</p>
<p>In the past I've created a test/resources or spec/resources directory for other test/spec related files. That seems to keep it clear that it's some sort of other file used only for testing.</p>
<p>you could just create a spec/fixtures dir and stick em in there.</p>
15,688
<p>I have some code like this:</p> <pre><code>If key.Equals("search", StringComparison.OrdinalIgnoreCase) Then DoSomething() End If </code></pre> <p>I don't care about the case. Should I use <code>OrdinalIgnoreCase</code>, <code>InvariantCultureIgnoreCase</code>, or <code>CurrentCultureIgnoreCase</code>?</p>
<p><strong><a href="https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#choosing-a-stringcomparison-member-for-your-method-call" rel="noreferrer">Newer .Net Docs now has a table to help you decide which is best to use in your situation.</a></strong></p> <p>From MSDN's "<a href="https://learn.microsoft.com/en-us/previous-versions/dotnet/articles/ms973919(v=msdn.10)" rel="noreferrer">New Recommendations for Using Strings in Microsoft .NET 2.0</a>"</p> <blockquote> <p>Summary: Code owners previously using the <code>InvariantCulture</code> for string comparison, casing, and sorting should strongly consider using a new set of <code>String</code> overloads in Microsoft .NET 2.0. <em>Specifically, data that is designed to be culture-agnostic and linguistically irrelevant</em> should begin specifying overloads using either the <code>StringComparison.Ordinal</code> or <code>StringComparison.OrdinalIgnoreCase</code> members of the new <code>StringComparison</code> enumeration. These enforce a byte-by-byte comparison similar to <code>strcmp</code> that not only avoids bugs from linguistic interpretation of essentially symbolic strings, but provides better performance.</p> </blockquote>
<p>The very simple answer is, unless you are using Turkish, you don't need to use InvariantCulture.</p> <p>See the following link:</p> <p><a href="https://stackoverflow.com/questions/3550213/in-c-sharp-what-is-the-difference-between-toupper-and-toupperinvariant">In C# what is the difference between ToUpper() and ToUpperInvariant()?</a> </p>
9,832
<p>I am an advocate of ORM-solutions and from time to time I am giving a workshop about Hibernate.</p> <p>When talking about framework-generated SQL, people usually start talking about how they need to be able to use "hints", and this is supposedly not possible with ORM frameworks.</p> <p>Usually something like: "We tried Hibernate. It looked promising in the beginning, but when we let it loose on our very very complex production database it broke down because we were not able to apply hints!".</p> <p>But when asked for a concrete example, the memory of those people is suddenly not so clear any more ...</p> <p>I usually feel intimidated, because the whole "hints"-topic sounds like voodoo to me... So can anybody enlighten me? What is meant by SQL-hints or DB-Hints?</p> <p>The only thing I know, that is somehow "hint-like" is SELECT ... FOR UPDATE. But this is supported by the Hibernate-API...</p>
<p>A SQL statement, especially a complex one, can actually be executed by the DB engine in any number of different ways (which table in the join to read first, which index to use based on many different parameters, etc).</p> <p>An experienced dba can use hints to <em>encourage</em> the DB engine to choose a particular method when it generates its execution plan. You would only normally need to do this after extensive testing and analysis of the specific queries (because the DB engines are usually pretty darn good at figuring out the optimum execution plan).</p> <p>Some MSSQL-specific discussion and syntax here: <br> <a href="http://msdn.microsoft.com/en-us/library/ms181714.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/ms181714.aspx</a></p> <p>Edit: some additional examples at <br> <a href="http://geeks.netindonesia.net/blogs/kasim.wirama/archive/2007/12/31/sql-server-2005-query-hints.aspx" rel="noreferrer">http://geeks.netindonesia.net/blogs/kasim.wirama/archive/2007/12/31/sql-server-2005-query-hints.aspx</a></p>
<p>All modern RDBMS-es have some sort of query optimizer that calculates best query plan, which is sequence of read/write operations needed to execute SQL query. </p> <p>Sometimes plans can be suboptimal, so RDBMS designers included "hints" in SQL. Hints are instructions you can embed in your SQL that affect query optimizer, With hints you can instruct query optimizer e.g. which indexes it should use, in what order data should be read from tables, ...</p> <p>So, with hints you can resolve some bottlenecks that the query optimizer cannot solve by itself.</p> <p>For example, here is list of <a href="http://www.psoug.org/reference/hints.html" rel="nofollow noreferrer">Oracle hints</a>.</p>
32,771
<p>In <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6525150" rel="nofollow noreferrer">http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6525150</a> it says Release Fixed 7(b14), 6u2(b01) (Bug ID:2147561)</p> <p>What does 6u2 mean? (Am I right in assuming it as 1.6.0_02 ?) </p>
<p>yes, release 6 update 2. Also, (b01) is build 01</p>
<p>Yes. You are right. :) u2 -> Update 2</p>
23,835
<p>We are troubleshooting a SQL Server 2005 connection issue on a closed-source third-party ASP.NET application. The application is a .NET application and the developing company is using a custom formatted configuration file that stores the SQL Server authentication information.</p> <p>The application when trying to connect to our SQL Server box is getting a "Cannot open database 'databasename'. Login failed for user 'username'" error. We have tested connecting to the SQL Server box from the web server using SQL Server Management Studio and the login information provided to their app, it works perfectly.</p> <p>Is there any easy way that we can sniff/determine the SQL Server Connection information they are trying to use inside their SqlCommand? Debugging their code is not an option, as it is compiled in Release Mode, and we don't have source. We simply need something to be able to identify why their app cannot connect.</p>
<p>run profiler and choose Security Audit: Audit Login, Audit Login Failed and Audit Logout events. choose all columns. from that you'll get the app name, and the user that tries to log in from the login failed event. once you get that check which database is default for that user in SQL Server users.</p>
<p>I just asked some of the guys here and they both recommended trying reflector. If you had some hard coded values in the library, you should be able to see something there.</p>
32,348
<p>I have just discovered that if generating assemblies via Reflection.Emit, the .NET framework keeps references in a static member that prevents Reflection.Emit classes not to be GC'ed. </p> <p>I cannot use DynamicMethod due to limitations. I also generate a lot of assemblies (incremental compiler of IronScheme) over the course of a program (could be 1000+).</p> <p>Hence, I was thinking to just handle the code generation in a separate domain, and unload it later (have not decided how to handle this). </p> <p>Does anyone have any experience how expensive this would be?</p>
<p>As I understand it, it's just a little slower than spawning a thread.</p> <hr> <p>Been doing some research, trying to find a real reference for this. So far, this is the best I can come up with:<br> <a href="http://msdn.microsoft.com/en-us/library/aa159887.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa159887.aspx</a></p> <p>About 2/3 of the way down it calls creating AppDomains "expensive", but then you might say the same about threads in certain contexts- it really depends on what the particular thread does at creation. </p> <p>Again: it's my understanding that an AppDomain is essentially a thread (or multiple threads) within a process &mdash; a logical delimiter, if you will &mdash; such that the run-time guarantees certain additional protections are in effect that prevent separate AppDomains from interfering with each other. To create a new AppDomain within an existing process (application) the framework has to do all the work associated with creating a new thread, plus some additional overhead to set it up within the rest of the applicaion (that may also involve loading one or more assemblies into memory). In the end, an AppDomain lives somewhere between a thread and a process.</p>
<p>As I understand it, it's just a little slower than spawning a thread.</p> <hr> <p>Been doing some research, trying to find a real reference for this. So far, this is the best I can come up with:<br> <a href="http://msdn.microsoft.com/en-us/library/aa159887.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa159887.aspx</a></p> <p>About 2/3 of the way down it calls creating AppDomains "expensive", but then you might say the same about threads in certain contexts- it really depends on what the particular thread does at creation. </p> <p>Again: it's my understanding that an AppDomain is essentially a thread (or multiple threads) within a process &mdash; a logical delimiter, if you will &mdash; such that the run-time guarantees certain additional protections are in effect that prevent separate AppDomains from interfering with each other. To create a new AppDomain within an existing process (application) the framework has to do all the work associated with creating a new thread, plus some additional overhead to set it up within the rest of the applicaion (that may also involve loading one or more assemblies into memory). In the end, an AppDomain lives somewhere between a thread and a process.</p>
43,433
<p>I like using "Vase Mode" (or single outline corkscrew printing mode) for quick nonfunctional prints, but it tends to leave gaps in horizontal or near horizontal surfaces. I understand why it does this, but is there a way (beyond printing with no infill*) to get a little more horizontal coverage out of it?</p> <p>*Is the answer to this literally just "Try to print without infill?"</p>
<p>Version 4 allows you to have multi-process vase mode prints -- do the vertical surfaces in vase mode, then switch over to normal mode for the horizontals. This lets you have the best of both worlds in the same print. :)</p>
<p>Vase mode is what it is... As it prints one perimeter there is just one extrusion. Try increasing extrusion rate to see if that will fix the gaps. </p> <p>but yes, printing without infill will do the job better than vase mode.</p>
684
<p>What is the best way to create fluid width/height rounded corners with jQuery?</p> <hr> <p>That plugin doesn't keep the height the same. I have a 10px high div that I want to round the corners on, when I use that script it adds about 10px onto whats there.</p>
<pre><code>$(this).corner(); </code></pre> <p>See: <a href="http://malsup.com/jquery/corner" rel="nofollow noreferrer">malsup.com/jquery/corner</a> and <a href="http://github.com/malsup/corner" rel="nofollow noreferrer">github repository for future ref</a></p>
<p>If you want full control about the border an d gradient, you can use my iQuery Background Canvas plugin. It works with a HTML5 Canvas element and allows to draw borders and backgrounds in any variation. But you should be able to program JavaScript</p> <p>This is a full featured sample with a background gradient and rounded corners. as you can see, the drawing is completely done in JavaScript, you can set every parameter you want. The drawing is redone on every resize (Due to the resize Event), you can adapt the background drawing to show wat you want on this specific size. </p> <pre><code>$(document).ready(function(){ $(".Test").backgroundCanvas(); }); function DrawBackground() { $(".Test").backgroundCanvasPaint(TestBackgroundPaintFkt); } // Draw the background on load and resize $(window).load(function () { DrawBackground(); }); $(window).resize(function() { DrawBackground(); }); function TestBackgroundPaintFkt(context, width, height, elementInfo){ var options = {x:0, height: height, width: width, radius:14, border: 0 }; // Draw the red border rectangle context.fillStyle = "#FF0000"; $.canvasPaint.roundedRect(context,options); // Draw the gradient filled inner rectangle var backgroundGradient = context.createLinearGradient(0, 0, 0, height - 10); backgroundGradient.addColorStop(0 ,'#AAAAFF'); backgroundGradient.addColorStop(1, '#AAFFAA'); options.border = 5; context.fillStyle = backgroundGradient; $.canvasPaint.roundedRect(context,options); } </code></pre> <p>Here is the plugin, and this site makes a vast use of it: <a href="http://www.maierhofer.de/en/open-source/jquery-background-canvas-plugin.aspx" rel="nofollow noreferrer">jQuery Background Canvas Plugin</a></p>
5,597
<p>I need to create a panel which should be invisible but the components inside it (for example, JTextArea, JButton, etc.) should be visible. When I click on the invisible panel, it should become visible.</p> <p>I can only use JRE 1.4 and nothing more than that. :(</p> <p>Any idea how to create such a transparent panel???</p>
<p>Transparancy is controlled with</p> <pre><code>setOpaque(false) </code></pre>
<p><code>JComponent.setOpaque(false)</code> is the way to go.</p>
32,201
<p>I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL_SCROLLABLE. How do I do this with a UNION query (with two selects)?</p> <p>The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.</p> <p>This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL_FETCH_FIRST or SQL_FETCH_LAST as well as):</p> <pre> SQLSetStmtAttr(hstmt1Fetch, SQL_ATTR_CURSOR_SCROLLABLE, (SQLPOINTER)SQL_SCROLLABLE, SQL_IS_INTEGER); SQLSetStmtAttr(hstmt1Fetch, SQL_ATTR_CURSOR_SENSITIVITY, (SQLPOINTER)SQL_INSENSITIVE, SQL_IS_INTEGER); ... retcode = SQLGetStmtAttr(hstmt1Fetch, SQL_ATTR_ROW_NUMBER, &CurrentRowNumber, SQL_IS_UINTEGER, NULL); ... retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position); </pre> <p>(The above is is a fragment from working code for a single SELECT).</p> <p>Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)</p> <p>Assuming yes to the above, how do I achieve the same result with a UNION query?</p> <p>LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something.</p>
<p>can you not define a view on the db server that does the union query for you, so from the client code it just looks like a single select?</p> <p>if you can't, can you just issue the union operation as part of your select, e.g.</p> <pre><code>select some_fields from table1 union select same_fields from table2 </code></pre> <p>and treat the result as a single result set?</p>
<p>If the issue is just needing to get the last row to get the number of rows and caching the last few rows (I assume if there are a million items in the select that you're not populating a drop-list with all of them) then you may be able to take advantage of the <code>ROW_NUMBER()</code> function of SQL Server 2005</p> <p>You could:</p> <pre><code>select count(*) from (select blah UNION select blah) </code></pre> <p>to get the number of rows.</p> <p>Then:</p> <pre><code>select ROW_NUMBER() as rownum,blah from (select blah UNION select blah) where rownum between minrow and maxrow </code></pre> <p>to just fetch the rows that you need to display/cache</p> <p>But seriously folks, if you're selecting items from a million-row table, you might want to consider a different mechanism</p> <p>Good luck!</p>
12,466
<p>I am doing a BHO (extension for IE) that receives events on other thread. When I access the DOM from that other thread, IE crashes. Is it possible to make the DOM accessed from the same thread as the main BHO thread so that it does not crash? </p> <p>It seems like a general COM multithreading problem, which I don't understand much.</p>
<p>Look into using <a href="http://msdn.microsoft.com/en-us/library/ms678428.aspx" rel="nofollow noreferrer">CoMarshalInterface</a> or <a href="http://msdn.microsoft.com/en-us/library/ms693316.aspx" rel="nofollow noreferrer">CoMarshalInterThreadInterfaceInStream</a></p> <p>These will give you a wrapped interface to an STA COM object that is thread safe.</p>
<p>ah, fun fun fun multithreading with COM.</p> <p><a href="https://stackoverflow.com/questions/199972/com-calling-from-other-thread-causes-crashes-how-to-make-it-run-on-the-same-thr#200012">Gerald's answer</a> looks right if you want to transfer an interface pointer from one thread to another exactly once. I've found that the GIT (global interface table) is a big help for this kind of thing if you're in a multithreaded system... basically you don't keep around interface pointers but rather DWORD cookies used by the GIT to get an appropriately-marshaled interface pointer for whatever thread you are using it. (you have to register the object in question with the GIT first, and unregister it later when you are done or your object is finished)</p>
24,387
<p>I have set a canvas' background to an image of a company logo. I would like for this image to be aligned to the bottom right corner of the canvas.<br> Is it possible to do this, or would it require for the image to be added into the canvas as a child? That would not work with this program as all children of the canvas are handled differently.</p> <p>Thank You</p>
<p>Will this work? (It worked for me, anyway.)</p> <pre><code> &lt;Canvas&gt; &lt;Canvas.Background&gt; &lt;ImageBrush ImageSource="someimage.jpg" AlignmentX="Right" AlignmentY="Bottom" Stretch="None" /&gt; &lt;/Canvas.Background&gt; &lt;/Canvas&gt; </code></pre>
<p>AFAIK The WPF Canvas needs child UI elements to be positioned using absolute co-ordinates. To achieve the right-bottom-anchored effect, I think you'd need to <strong>handle the window resize event, recalculate and apply the Top,Left co-ordinates</strong> for the child Image element to always stick to the right buttom corner.</p> <pre><code>&lt;Window x:Class="HelloWPF.Window1" xmlns... Title="Window1" Height="300" Width="339"&gt; &lt;Canvas&gt; &lt;Image Canvas.Left="195" Canvas.Top="175" Height="87" Name="image1" Stretch="Fill" Width="122" Source="dilbert2666700071126ni1.gif"/&gt; &lt;/Canvas&gt; &lt;/Window&gt; </code></pre>
33,844
<p>Obviously I can do and <code>DateTime.Now.After</code> - <code>DateTime.Now.Before</code> but there must be something more sophisticated.</p> <p>Any tips appreciated.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.environment.tickcount.aspx" rel="nofollow noreferrer">System.Environment.TickCount</a> and the <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx" rel="nofollow noreferrer">System.Diagnostics.Stopwatch</a> class are two that work well for finer resolution and straightforward usage.</p> <p>See Also:</p> <ul> <li><a href="https://stackoverflow.com/questions/28637/is-datetimenow-the-best-way-to-measure-a-functions-performance">Is DateTime.Now the best way to measure a function’s performance?</a></li> <li><a href="https://stackoverflow.com/questions/163022/high-resolution-timer-in-net">High resolution timer in .NET</a></li> <li><a href="https://stackoverflow.com/questions/243351/environmenttickcount-vs-datetimenow">Environment.TickCount vs DateTime.Now</a></li> <li><a href="https://stackoverflow.com/questions/145103/whats-the-best-way-to-benchmark-programs-in-windows">What’s the best way to benchmark programs in Windows?</a></li> </ul>
<p>Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.</p>
49,919
<p>I've been trying to modify the following menu to make it look indentical in IE, Firefox, and Safari/Chrome but I can't seem to get it to look right in Safari/Chrome.</p> <p>Could anyone tell me how to fix it? When viewed in Safari or Chrome, notice that the menu is ignoring the padding.</p> <p><a href="http://www.candesprojects.com/downloads/flickr-horizontal-menu/" rel="nofollow noreferrer">View flickr-like menu</a></p> <p>Thanks in advance!</p>
<p>Padding on elements that are or are displayed as inline. <a href="http://www.maxdesign.com.au/presentation/inline/" rel="nofollow noreferrer">http://www.maxdesign.com.au/presentation/inline/</a></p>
<p>Try making the <code>inline</code> elements <code>inline-block</code> in order to get the padding working properly.</p>
29,134
<p>I have a customer who needs to send some direct mailing to his contacts which is being collected from trade shows etc. I am thinking about providing a web based solution for them on sending direct mailing material- however this kind of solution always face a major difficulty on having the server blacklisted. I would like to know if there is any suggestions on how to maintain such SMTP server?</p>
<ul> <li>Have your SMTP server respond to HELO/EHLO commands with your specific DNS name, not generic IP nor generic reversal (YES: mail.example.com ; NO: 1.2.3.4 , 4-3-2-1.dsl.example.com )</li> <li>Have a Reverse DNS matching the HELO response (example: nslookup mail.example.com -> 1.2.3.4, nslooup 1.2.3.4 -> mail.example.com)</li> <li>Make sure nobody but legit users can send emails, no open relays or forwarders!</li> <li>Have the mandatory email addresses correctly delivered (abuse, postmaster and info, IIRC), and that the reply-to address of the email exists and are regularly checked (repeatedly sending to dead email addresses can incur in blacklisting)</li> <li>Check that double opt-in is in use for internet-driven subscriptions</li> <li>Also make sure opt-out is working</li> <li>Have a clear disclaimer</li> </ul> <p>And, just in case: - Make sure the IP address of the SMTP is different from your other SMTPs, so in case something fail you're still able to send mails from other accounts!</p>
<p>Aside from the server (just set up exim or postfix and a web interface to send newsletters from, and do this on a server with an IP address that is different from your own personal mail server (maybe even a different network)), you will want to get your terms and conditions of use nice and tight so that you can remove access to the systems from any customer that has complaints made about emailing. Indeed you can mandate that all emails sent must be lawful (e.g., unsubscription option that works, etc).</p>
27,296
<p>I recently ran up against a wall doing some bash shell programming where an associative array would have solved my problems. I googled about features of the KornShell (ksh) and learned that it supports associative arrays, so I installed Cygwin's pdksh (Public Domain KornShell).</p> <p>However, when trying to create an associative array in the prescribed manner (typeset -A varName), I received the following errors, so I'm beginning to suspect pdksh does not support associative arrays.</p> <pre><code>./find_actions.ksh: line 2: typeset: -A: invalid option typeset: usage: typeset [-afFirtx] [-p] name[=value] ... </code></pre> <p>Guess I will be considering Perl instead, but I really wanted a good excuse to learn a dialect/language new to me.</p>
<p>Take a look at ksh93, it supports associative arrays and is a much more complete/correct implementation of ksh.</p> <p>See: <a href="http://kornshell.com/" rel="nofollow noreferrer">kornshell.com</a></p>
<p>Why not just use bash? It might not have explicit associative arrays, but you can <a href="http://linuxshellaccount.blogspot.com/2008/05/how-to-fake-associative-arrays-in-bash.html" rel="nofollow noreferrer">fake them</a>.</p> <p>Alternatively, zsh has <a href="http://zsh.dotsrc.org/Doc/Release/zsh_14.html#SEC72" rel="nofollow noreferrer">excellent associative array support</a>.</p>
44,476
<p>I want to create a list of columns in SQL Server 2005 that have identity columns and their corresponding table in T-SQL.</p> <p>Results would be something like:</p> <p>TableName, ColumnName</p>
<p>Another potential way to do this for SQL Server, which has less reliance on the system tables (which are subject to change, version to version) is to use the INFORMATION_SCHEMA views:</p> <pre><code>select COLUMN_NAME, TABLE_NAME from INFORMATION_SCHEMA.COLUMNS where COLUMNPROPERTY(object_id(TABLE_SCHEMA+'.'+TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1 order by TABLE_NAME </code></pre>
<p>Get all columns with Identity. Modern version for MSSQL 2017+. Locks down to specific database:</p> <pre><code>SELECT [COLUMN_NAME] , [TABLE_NAME] , [TABLE_CATALOG] FROM [INFORMATION_SCHEMA].[COLUMNS] WHERE COLUMNPROPERTY(OBJECT_ID(CONCAT_WS('.' ,[TABLE_CATALOG] ,[TABLE_SCHEMA] ,[TABLE_NAME])) ,[COLUMN_NAME] ,'IsIdentity') = 1 ORDER BY [TABLE_NAME] </code></pre>
11,331
<p>I am attempting to bind a WPF textbox's Maxlength property to a known constant deep within a class. I am using c#.</p> <p>The class has a structure not too dissimilar to the following:</p> <pre><code>namespace Blah { public partial class One { public partial class Two { public string MyBindingValue { get; set; } public static class MetaData { public static class Sizes { public const int Length1 = 10; public const int Length2 = 20; } } } } } </code></pre> <p>Yes it is deeply nested, but unfortunately in this instance I can't move things round very much without huge rewrites required.</p> <p>I was hoping I'd be able to bind the textbox MaxLength to the Length1 or Length2 values but I can't get it to work.</p> <p>I was expecting the binding to be something like the following:</p> <pre><code>&lt;Textbox Text="{Binding Path=MyBindingValue}" MaxLength="{Binding Path=Blah.One.Two.MetaData.Sizes.Length1}" /&gt; </code></pre> <p>Any help is appreciated.</p> <p>Many thanks</p>
<pre><code>MaxLength="{x:Static local:One+Two+MetaData+Sizes.Length1}" </code></pre> <p>Periods reference properties. Plus signs refer to inner classes.</p>
<p>try to bind with x:Static. add a xmlns:local namespace with the namespace of Sizes to your xaml header and then bind with something like this:</p> <pre><code>{x:Static local:Sizes.Length1} </code></pre>
28,835
<p>I'm trying to install a .NET service I wrote. As recommended by MSDN, I'm using InstallUtil. But I have missed how I can set the default service user on the command-line or even in the service itself. Now, when InstallUtil is run, it will display a dialog asking the user for the credentials for a user. I'm trying to integrate the service installation into a larger install and need the service installation to remain silent.</p>
<p>I think I may have found it. In the service itself, the automatically created ServiceProcessInstaller component has a property "Account" which can be set to "LocalService", "LocalSystem", "NetworkService" or "User". It was defaulting to "User" which must have displayed the prompt. </p>
<p>Are you being asked for the account to run the service under, or for rights to install the service? For the second, installing as admin should prevent that from happening. For the first, you have to add a ServiceProcessInstaller to your Installer.</p> <p>I believe the design surface for a service has a link to create a Project Installer. On that designer, you can add a process installer of type System.ServiceProcess.ServiceProcessInstaller. The properties of this object allow you to set the account to use for the service.</p>
5,212
<p>Just got a question about generics, why doesn't this compile when using a generic List? If its not possible, anyway around it? Much appreciate any answer.</p> <pre><code>// Interface used in the ServiceAsync inteface. public interface BaseObject { public String getId(); } // Class that implements the interface public class _ModelDto implements BaseObject, IsSerializable { protected String id; public void setId(String id) { this.id = id; } public String getId() { return id; } } // Interface used in the ServiceAsync inteface. public interface MyAsync&lt;T&gt; { // Nothing here. } // Service interface use both interfaces above. public interface ServiceAsync { public void getList(MyAsync&lt;List&lt;? extends BaseObject&gt;&gt; callback); } public class MyClass { ServiceAsync service = (some implementation); MyAsync&lt;List&lt;_ModelDto&gt;&gt; callBack = new MyAsync&lt;List&lt;_ModelDto&gt;&gt;() { }; service.getList(callBack); // This does not compile, says arguments are not applicable???? } </code></pre>
<p>The fact that your MyAsync interface doesn't contain any method signatures and doesn't have a particularly informative name is a code smell from my perspective, but I'll assume that this is just a dummy example. As it is written, getList() couldn't ever have any reasonable implementation that used the callback in any way; remember that type erasure will erase this method signature to <code>getList(MyAsync callback);</code></p> <p>The reason that this doesn't compile is that your bound is wrong. <code>MyAsync&lt;List&lt;? extends BaseObject&gt;&gt;</code> gives T as <code>List&lt;? extends BaseObject&gt;</code>, a list of some unknown type.</p> <p>It looks to me like what you want is for the getList method itself to be generic:</p> <pre><code>public interface ServiceAsync { public &lt;T extends BaseObject&gt; void getList(MyAsync&lt;List&lt;T&gt;&gt; callback); } public class MyClass { public void foo() { ServiceAsync service = null; MyAsync&lt;List&lt;_ModelDto&gt;&gt; callBack = new MyAsync&lt;List&lt;_ModelDto&gt;&gt;() {}; service.getList (callBack); // This compiles } } </code></pre>
<p>The '?' in generic types can be pretty confusing. Honestly I'm not sure why this won't compile. It has to do with using the '?' in a nested generic type. But I do know some ways to work around it.</p> <p>Is there a reason that the declaration of the MyAsync in MyClass has to reference _ModelDto? It would work if you changed it to look like this:</p> <pre><code> ServiceAsync service = (some implementation); MyAsync&lt;List&lt;? extends BaseObject&gt;&gt; callBack = new MyAsync&lt;List&lt;? extends BaseObject&gt;&gt;() { }; service.getList(callBack); </code></pre> <p>If you need to reference the type _ModelDto directly you could change the definition of ServiceAsync and it will fix the problem.<br/> Change it to look like this:</p> <pre><code>public interface ServiceAsync&lt;T extends BaseObject&gt; { public void getList(MyAsync&lt;List&lt;T&gt;&gt; callback); } </code></pre> <p><br/> Then add the parameter type to the declaration in MyClass</p> <pre><code>public class MyClass { public void method() { ServiceAsync&lt;_ModelDto&gt; service = (some implementation); MyAsync&lt;List&lt;_ModelDto&gt;&gt; callBack = new MyAsync&lt;List&lt;_ModelDto&gt;&gt;() { }; service.getList(callBack); } } </code></pre>
24,917
<p>From a previous question I have seen that the CLR has workstation and server modes for its garbage collector. I know that these can be set from configuration using the <a href="http://msdn.microsoft.com/en-us/library/ms229357.aspx" rel="nofollow noreferrer"><code>gcServer</code></a> element.</p> <p><strong>If you don't specify this, does the CLR use some magic to decide for you whether the garbage collector should run in server mode?</strong> Something based on CPU count, or memory profiling maybe?</p>
<p>Certainly not. The CLR runs in concurrent mode unless you explicitly tell it to do otherwise.</p>
<p>According to the documentation you linked to, the default is "false". I would expect this to be constant on all installations and instances, the MS documentation is pretty good on this sort of thing.</p> <p>The only caveat is that perhaps the installer (or someone) sets this setting in the machine.config (for ASP.NET) to "true" on server O/S. This is pure speculation and probably is not the case.</p>
39,164