instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have a div container and have defined its style as follows:</p> <pre><code>div#tbl-container { width: 600px; overflow: auto; scrollbar-base-color:#ffeaff } </code></pre> <p>This gives me both horizontal and vertical scroll bars automatically once I populate my table which is contained by this div. I just want only horizontal scroll bars to appear automatically. I will modify the height of the table programmatically.</p> <p>How do I do this?</p>
<p>You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.</p> <p>However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.</p> <p>IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:</p> <pre><code>overflow: auto; overflow-y: hidden; </code></pre> <p>You may also need to add for IE8:</p> <pre><code>-ms-overflow-y: hidden; </code></pre> <p>as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)</p> <p>On the other hand it's entirely possible IE8 will have fixed the bug anyway.</p>
<p>We should set to <code>overflow: auto</code> and hide a scrollbar which we don't use for working on unsupporting CSS3 browser. Look at this <a href="http://xme.im/css-overflow-strict-how-to-display-horizontal-or-verticle-only" rel="nofollow">CSS Overflow; XME.im</a></p>
32,254
<p>I need to put an LDAP contextSource into my Java EE container's JNDI tree so it can be used by applications inside the container.</p> <p>I'm using Spring-LDAP to perform queries against ORACLE OVD. For development, I simply set up the contextSource in the Spring xml configuration file. For production, however, I need to be able to use a JNDI lookup to grab the connection/context from the container (as suggested here: <a href="http://forum.springframework.org/showthread.php?t=35122&amp;highlight=jndi" rel="noreferrer">http://forum.springframework.org/showthread.php?t=35122&amp;highlight=jndi</a>). I'm not allowed to have access to the URL/username/pwd for the production OVD instance, so that seems to rule out putting it in a jndi.properties file.</p> <p>Ideally, I'd like to have a pool of connections (just like JDBC), as my application may have many LDAP queries executing at the same time. Grabbing the object from a JNDI lookup and injecting it into my SimpleLdapTemplate seems pretty straightforward, but I'm at a loss as to how to get the connection/context/pool into the JNDI tree. Would I need to construct it and package it into a RAR? If so, what are some options for letting the operations team specify the URL/username/pwd in a way that they are not accessible to the developers?</p> <p>The specific container I'm using is OAS/OC4J, though I welcome strategies that have worked on other containers as well.</p>
<p>Specifically in reference to the actual pooling of LDAP connections, if you are using the built in JNDI LDAP provider, the connections are pooled already using semantics similar to JDBC data sources where separate pools are maintained for different LDAP URLs and security properties.</p> <p>When creating a JNDI <code>DirContext</code>, configure the property com.sun.jndi.ldap.connect.pool to be <strong>true</strong> and pooling will be enabled.</p> <p>There is more information on LDAP pooling <a href="http://java.sun.com/products/jndi/tutorial/ldap/connect/pool.html" rel="noreferrer">here</a>.</p> <p>Details on configuring LDAP pooling are <a href="http://java.sun.com/products/jndi/tutorial/ldap/connect/config.html" rel="noreferrer">here</a>.</p>
<p>Any chance you can setup a dev version of LDAP and use that? Then you can use a jndi.properties file, which would be environment specific, but agnostic to your system.</p> <p>Edit: the difference here is that when you build your app, your admin can deploy it to the production system, thereby protecting the precious ldap password as it only exists in the properties file on the production box.</p>
43,418
<p>I am currently in the process of searching for a rules engine that works in .NET. Our logic is pretty simple, +, -, *, /, and, or, basic order of operations stuff. However we are going to need to store this information in the database and then generate the rules file when a new version is pulled from the database. So the common UI editors are going to be useless to us, unless one of them has a web version UI editor. </p> <p>So my question is, given what I have said, which is going to be the best rules engine for us in terms of programmatic configuration and integration with ASP.NET.</p>
<p>My experience with WWF has been pretty bad. Its great for developing a workflow that you know is going to exist (such as "this document goes to a person's manager, then to HR, if its invalid it goes back to the submitter") but a real pain if you want dynamic configuration. As you can tell we tried to use it for a fully configurable system, something that BizTalk does really well, and it looks like MS isn't keen on letting developers replace BizTalk so cheaply.</p> <p>We also looked at using the <a href="http://www.acumenbusiness.com/products.htm" rel="noreferrer">Acumen rules engine and tools</a> which looked like a great fit for what we needed though we never got the time to remove WWF and replace it.</p> <p>I would strongly recommend that if your rules are going to be relatively simple that you either use a rules engine you have the source code to or write it yourself. <a href="http://www.codethinked.com/" rel="noreferrer">Justin Etheredge</a> has a <a href="http://www.codethinked.com/post/2008/10/12/Thoughts-On-Domain-Validation-Part-1.aspx" rel="noreferrer">two</a> <a href="http://www.codethinked.com/post/2008/10/16/Thoughts-On-Domain-Validation-Part-2.aspx" rel="noreferrer">part</a> article about performing domain validation through custom rules using the pattern identified in <a href="https://rads.stackoverflow.com/amzn/click/com/0321125215" rel="noreferrer" rel="nofollow noreferrer">Domain-Driven Designs</a> (Evans). </p> <p>I've implemented a similar system in my current project following the same guidelines and I serialize/deserialize rules from the database. I will have to take a look at <a href="http://droolsdotnet.codehaus.org/" rel="noreferrer">Drools.NET</a>.</p>
<p>the fact that biztalk is not going to be replaced easily by wwf is true. The objectives are very different between them, drools compares to biztalk and not with wwf, reasons, both use the same alogorithm (rete)!!</p> <p>Now, using drools is something else, biztalk also functions as an ESB, can drools do that?</p>
28,471
<p>I am working on interactive SVG/AJAX interfaces where elements are created and repositioned on-the-fly by users. I'd like to support the ability for users to export their current view to a PNG image and/or an SVG document. I'd really like the SVG document to be as simple as possible (without a lot of nested transforms). Is there any framework that already supports this?</p> <p>I'm currently asking my users to use the Ctrl+Alt+PrntScrn technique, and I don't want to ask them to install any software/plugins. </p> <p>The server-side code is implemented in PHP right now, if that helps. I've already implemented the ability to generate a PNG image from the "original" document (before the client makes any modifications) using ImageMagick.</p>
<p>I'm assuming you need this to work only in browsers that support SVG.</p> <p>Firefox, Safari, and Opera provide the non-standard <code>XMLSerializer</code> API, so you could do something like this:</p> <pre><code>var svg = document.getElementById('svg_root'); // or whatever you call it var serializer = new XMLSerializer(); var str = serializer.serializeToString(svg); </code></pre> <p>From there, you can send it to the server and receive a PNG in return.</p> <p>Here's <a href="https://developer.mozilla.org/en/Parsing_and_serializing_XML" rel="noreferrer">Mozilla's developer page on serializing XML from the DOM</a>.</p>
<p>Opera has implementation of <a href="http://www.w3.org/TR/DOM-Level-3-LS/load-save.html" rel="nofollow noreferrer">W3C's DOM→XML serializer</a>. In XML mode <code>innerHTML</code> returns well-formed XML in Gecko.</p> <p>HTML5 <code>&lt;canvas&gt;</code> can export its content as PNG file using <code>toDataURL()</code> and it's possible to paint any <code>&lt;img&gt;</code> element on canvas using <code>drawImage()</code>, so it should be possible to create <code>&lt;img src="data:application/svg+xml,…"&gt;</code>, paint it on canvas and export as <code>data:</code> URL.</p>
28,111
<p>For my Java apps with very long classpaths, I cannot see the main class specified near the end of the arg list when using ps. I think this stems from my Ubuntu system's size limit on /proc/pid/cmdline. How can I increase this limit?</p>
<p>You can't change this dynamically, the limit is hard-coded in the kernel to PAGE_SIZE in fs/proc/base.c:</p> <pre><code> 274 int res = 0; 275 unsigned int len; 276 struct mm_struct *mm = get_task_mm(task); 277 if (!mm) 278 goto out; 279 if (!mm-&gt;arg_end) 280 goto out_mm; /* Shh! No looking before we're done */ 281 282 len = mm-&gt;arg_end - mm-&gt;arg_start; 283 284 if (len &gt; PAGE_SIZE) 285 len = PAGE_SIZE; 286 287 res = access_process_vm(task, mm-&gt;arg_start, buffer, len, 0); </code></pre>
<p>Perhaps the 'w' parameter to ps is what you want. Add two 'w' for greater output. It tells ps to ignore the line width of the terminal.</p>
24,273
<p>What does Java do with long variables while performing addition?</p> <p>Wrong version 1:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = speeds.size() + estimated; // time = 21; string concatenation?? </code></pre> <p>Wrong version 2:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long time = estimated + speeds.size(); // time = 12; string concatenation?? </code></pre> <p>Correct version:</p> <pre><code>Vector speeds = ... //whatever, speeds.size() returns 2 long estimated = 1l; long size = speeds.size(); long time = size + estimated; // time = 3; correct </code></pre> <p>I don't get it, why Java concatenate them.</p> <p>Can anybody help me, why two primitive variables are concatenated?</p> <p>Greetings, guerda</p>
<p>My guess is you are actually doing something like:</p> <pre><code>System.out.println("" + size + estimated); </code></pre> <p>This expression is evaluated left to right:</p> <pre><code>"" + size &lt;--- string concatenation, so if size is 3, will produce "3" "3" + estimated &lt;--- string concatenation, so if estimated is 2, will produce "32" </code></pre> <p>To get this to work, you should do:</p> <pre><code>System.out.println("" + (size + estimated)); </code></pre> <p>Again this is evaluated left to right:</p> <pre><code>"" + (expression) &lt;-- string concatenation - need to evaluate expression first (3 + 2) &lt;-- 5 Hence: "" + 5 &lt;-- string concatenation - will produce "5" </code></pre>
<p>I suspect you're not seeing what you think you're seeing. Java doesn't do this.</p> <p>Please try to provide a <a href="http://pobox.com/~skeet/csharp/complete.html" rel="nofollow noreferrer">short but complete program</a> which demonstrates this. Here's a short but complete program which demonstrates correct behaviour, but with your "wrong" code (i.e. a counterexample).</p> <pre><code>import java.util.*; public class Test { public static void main(String[] args) { Vector speeds = new Vector(); speeds.add("x"); speeds.add("y"); long estimated = 1l; long time = speeds.size() + estimated; System.out.println(time); // Prints out 3 } } </code></pre>
30,100
<p>I am developing a prototype for a game, and certain gameplay rules are to be defined in an ini file so that the game designers can tweak the game parameters without requiring help from me in addition to a re-compile. This is what I'm doing currently:</p> <pre><code>std::ifstream stream; stream.open("rules.ini"); if (!stream.is_open()) { throw new std::exception("Rule file could not be opened"); } // read file contents here stream.close(); </code></pre> <p>However, my stream never opens succesfully. Diving deep into the STL source during debugging reveals that _getstream() (as defined in stream.c) keeps on returning NULL, but I just can't figure out why this is. Help, anyone?</p> <p>Edit: Rules.ini is in the same directory as the .exe file.</p>
<p>You are assuming that the <strong>working directory</strong> is the directory that your executable resides in. That is a bad assumption.</p> <p>Your executable can be run from any working directory, so it's usually a bad idea to hard-code relative paths in your software.</p> <p>If you want to be able to access files relative to the location of your executable, you should first determine the path of your executable and create a fully qualified path from that.</p> <p>You can get the name of your executable by examining the <code>argv[0]</code> parameter passed to <code>main()</code>. Alternatively, if you're on Windows, you can get it with <a href="http://msdn.microsoft.com/en-us/library/ms683197(VS.85).aspx" rel="noreferrer"><code>GetModuleFileName()</code></a> by passing NULL as the first parameter.</p>
<p>(wild assumption here) you are using visual studio. During debug, your program is going to search the project directory for "rules.ini"</p> <p>However, if you try executing your program from "myproject/debug/myexe.exe", it should run fine because it is going to search "/debug" for rules.ini</p> <p>Like its been mentionned you should specify the full path because relative path tend to lead to errors</p>
46,679
<p>How to get function's name from <a href="http://en.wikipedia.org/wiki/Function_pointer" rel="noreferrer">function's pointer</a> in C?</p> <p>Edit: The real case is: I'm writing a linux kernel module and I'm calling kernel functions. Some of these functions are pointers and I want to inspect the code of that function in the kernel source. But I don't know which function it is pointing to. I thought it could be done because, when the system fails (kernel panic) it prints out in the screen the current callstack with function's names. But, I guess I was wrong... am I?</p>
<p>That's not directly possible without additional assistance.</p> <p>You could:</p> <ol> <li><p>maintain a table in your program mapping function pointers to names</p></li> <li><p>examine the executable's symbol table, if it has one.</p></li> </ol> <p>The latter, however, is hard, and is not portable. The method will depend on the operating system's binary format (ELF, a.out, .exe, etc), and also on any relocation done by the linker.</p> <p>EDIT: Since you've now explained what your real use case is, the answer is actually not that hard. The kernel symbol table is available in <code>/proc/kallsyms</code>, and there's an API for accessing it:</p> <pre><code>#include &lt;linux/kallsyms.h&gt; const char *kallsyms_lookup(unsigned long addr, unsigned long *symbolsize, unsigned long *ofset, char **modname, char *namebuf) void print_symbol(const char *fmt, unsigned long addr) </code></pre> <p>For simple debug purposes the latter will probably do exactly what you need - it takes the address, formats it, and sends it to <code>printk</code>, or you can use <code>printk</code> with the <code>%pF</code> format specifier.</p>
<p>You can't. The function name isn't attached to the function by the time it's compiled and linked. It's all by memory address at that point, not name.</p>
45,708
<p>I have a really large VB6 code base with a ton of 3rd party controls. Want to move it to .NET. Rewriting it is out of question - the client sees no value in spending money to get the same thing. Moving to .NET with the built-in upgrade wizard is basically a non-starter.</p> <p>Has anyone tried the VB Migration Partner from <a href="http://www.vbmigration.com/" rel="nofollow noreferrer">http://www.vbmigration.com/</a> If so, what have been the experiences like? </p>
<p>I am the lead author of the VB Migration Partner tool (featured at www.vbmigration.com). In general we answer very quickly to all requests coming from existing or potential customers. I am sorry if found it difficult to contact us. Please try again at <a href="http://www.vbmigration.com/contactus.aspx" rel="noreferrer">http://www.vbmigration.com/contactus.aspx</a></p> <p>We do believe that our tool is capable to tackle very large VB6 applications. Actually, most of our customers are using it to migrate applications in the range 200-500K lines of code. We are currently working on a "monster app" of over 13 millions LOCs partitioned in 1200+ projects. </p> <p>As RSConley suggests, any conversion tool works best if your application can be migrated and tested in parts. We support VB6 project groups (that are converted in a single operation), batch conversions, and we support integration with source code control tools. (For example, we preserve solution/project guids from previous generation, so that your SC tool knows how to deal the newly generated code.)</p> <p>Finally, we are about to release version 1.11, which can generate .NET DLLs that are binary compatible with the original COM DLLs, so that you can migrate one component at the time starting with the most basic ones that are used by all others portions of your app, without having to re-compile them. (As far as we know, VB Migration Partner is the only tool with this feature.)</p> <p>Francesco Balena -- VB Migration Partner Team</p>
<p>I've never worked with the VB migration guys before, however I would highly recommend against migrating the code base to .NET. It really doesn't add value.</p> <p>What I've had great success doing is adding new functionality in .NET and getting at it via COM interop from the VB6 application. This is pretty effortless and is a good way of utilizing .NET in legacy applications.</p> <p>...my 2 cents</p>
33,112
<p>I have an HTTPHandler that is reading in a set of CSS files and combining them and then GZipping them. However, some of the CSS files contain a Byte Order Mark (due to a bug in TFS 2005 auto merge) and in FireFox the BOM is being read as part of the actual content so it's screwing up my class names etc. How can I strip out the BOM characters? Is there an easy way to do this without manually going through the byte array looking for ""?</p>
<p>Expanding on <a href="https://stackoverflow.com/questions/288111/remove-byte-order-mark-from-a-file-readallbytes-byte#comment21871755_288111">Jon's comment</a> with a sample.</p> <pre><code>var name = GetFileName(); var bytes = System.IO.File.ReadAllBytes(name); System.IO.File.WriteAllBytes(name, bytes.Skip(3).ToArray()); </code></pre>
<p>For larger file, use the following code; memory efficient!</p> <pre><code>StreamReader sr = new StreamReader(path: @"&lt;Input_file_full_path_with_byte_order_mark&gt;", detectEncodingFromByteOrderMarks: true); StreamWriter sw = new StreamWriter(path: @"&lt;Output_file_without_byte_order_mark&gt;", append: false, encoding: new UnicodeEncoding(bigEndian: false, byteOrderMark: false)); var lineNumber = 0; while (!sr.EndOfStream) { sw.WriteLine(sr.ReadLine()); lineNumber += 1; if (lineNumber % 100000 == 0) Console.Write("\rLine# " + lineNumber.ToString("000000000000")); } sw.Flush(); sw.Close(); </code></pre>
36,665
<p>What's the deal with Visual Studio?</p> <p>I tried importing the Caching App Block and got this message:</p> <blockquote> <p>The assembly or one of its dependencies you're are trying to import requires a later version of .NET Framework.</p> </blockquote> <p>I went to the properties of my application in Visual Studio, but I can't find the dropdown to switch....what's the deal?</p>
<p>Found it....went to "Advanced Compile Options" on Compile Tab.....weird!</p>
<p>Go to the properties of a project (Solution Explorer --> Project --> Properties or Menu Bar --> Project --> Properties) and on the Application tab you'll see Target Framework.</p>
22,793
<p>I use Intellij Idea 7 for Java dev. My dev is 'limited' to all J2SE features plus light JSP, Servlets, and super light usage of JPA. No J2EE, no massive use of random frameworks, etc.</p> <p>Is it worth upgrading to ver 8? "Worth it" to me means better "core functionality" in terms of speed (ESPECIALLY startup speed), memory utilization (seems like it starts having serious problems with four or more projects open), and auto bug-finding. More frameworks supported and more languages supported (other than perhaps Haskell and C++), and more refactorings don't interest me at this time.</p> <p>A while back, I installed a preview version of 8 and it seemed -exactly- the same as 7, as far as my needs were concerned.</p> <p>Anyone loving the upgrade to 8, and if so, why?</p> <p>Thanks</p>
<p>It also seems to be easier to configure a new project over top of a complex collection of existing code.</p> <p>For example, something that you would naturally configure into 5 or more modules.</p>
<p>IntelliJ 8 has a configure plugins feature that allows you to disable plugins with dependencies. Nothing trial and error couldn't replicate, but it is nice.</p>
46,637
<p>At what point is it better to switch from java.net to java.nio? .net (not the Microsoft entity) is easier to understand and more familiar, while nio is scalable, and comes with some extra nifty features.</p> <p>Specifically, I need to make a choice for this situation: We have one control center managing hardware at several remote sites (each site with one computer managing multiple hardware units (a transceiver, TNC, and rotator)). My idea was to have write a sever app on each machine that acts as a gateway from the control center to the radio hardware, with one socket for each unit. From my understanding, NIO is meant for one server, many clients, but what I'm thinking of is one client, many servers. </p> <p>I suppose a third option is to use MINA, but I'm not sure if that's throwing too much at a simple problem.</p> <hr> <p>Each remote server will have up to 8 connections, all from the same client (to control all the hardware, and separate TX/RX sockets). The single client will want to connect to several servers at once, though. Instead of putting each server on different ports, is it possible to use channel selectors on the client side, or is it better to go multi-threaded io on the client side of things and configure the servers differently?</p> <hr> <p>Actually, since the remote machines serve only to interact with other hardware, would RMI or IDL/CORBA be a better solution? Really, I just want to be able to send commands and receive telemetry from the hardware, and not have to make up some application layer protocol to do it.</p>
<p>Scalability will probably drive your choice of package. java.net will require one thread per socket. Coding it will be significantly easier. java.nio is much more efficient, but can be hairy to code around.</p> <p>I would ask yourself how many connections you expect to be handling. If it's relatively few (say, &lt; 100), I'd go with java.net.</p>
<p>The number of connections you're talking about tells me you should use java.net. Really, there's no reason to complexify your task with non-blocking I/O. (Unless your remote systems are underpowered, but then why are you using Java on them?)</p> <p>Take a look at <a href="http://ws.apache.org/xmlrpc/" rel="nofollow noreferrer">Apache's XML-RPC</a> package. It's easy to use, completely hides the network stuff from you, and works over good ol' HTTP. No need to worry about protocol issues ... it'll all look like method calls to you, on both ends.</p>
33,526
<p>When making changes using <code>SubmitChanges()</code>, LINQ sometimes dies with a <code>ChangeConflictException</code> exception with the error message <code>Row not found or changed</code>, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.</p> <p>Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?</p> <p>Additionally, does anybody know whether this exception occurs when <em>any</em> data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?</p>
<p>Here's a way to see where the conflicts are (this is an MSDN example, so you'll need to heavily customize):</p> <pre><code>try { db.SubmitChanges(ConflictMode.ContinueOnConflict); } catch (ChangeConflictException e) { Console.WriteLine("Optimistic concurrency error."); Console.WriteLine(e.Message); Console.ReadLine(); foreach (ObjectChangeConflict occ in db.ChangeConflicts) { MetaTable metatable = db.Mapping.GetTable(occ.Object.GetType()); Customer entityInConflict = (Customer)occ.Object; Console.WriteLine("Table name: {0}", metatable.TableName); Console.Write("Customer ID: "); Console.WriteLine(entityInConflict.CustomerID); foreach (MemberChangeConflict mcc in occ.MemberConflicts) { object currVal = mcc.CurrentValue; object origVal = mcc.OriginalValue; object databaseVal = mcc.DatabaseValue; MemberInfo mi = mcc.Member; Console.WriteLine("Member: {0}", mi.Name); Console.WriteLine("current value: {0}", currVal); Console.WriteLine("original value: {0}", origVal); Console.WriteLine("database value: {0}", databaseVal); } } } </code></pre> <p>To make it ignore the problem and commit anyway:</p> <pre><code>db.SubmitChanges(ConflictMode.ContinueOnConflict); </code></pre>
<p>"and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?"</p> <p>You can set the 'Update Check' property on your entity to 'Never' to stop that field being used for optimistic concurrency checking.</p> <p>You can also use:</p> <pre><code>db.SubmitChanges(ConflictMode.ContinueOnConflict) </code></pre>
5,264
<p>I am trying to install PHP onto my development box (XP SP3 / IIS 5.1) I've got PHP 5.2.6 stable downloaded (the MSI installer package) and I am getting an error "Cannot find httpd.conf". After that the install seems to breeze by quickly (more quickly than I would have expected) and when I try to execute a simple PHP script from my localhost test directory that I created, I get a slew of missing DLL errors. I have seen posts out there which indicate that its possible and has been done. I dont see any bug reports for this MSI at PHP.NET support. Any ideas?</p>
<p>Not sure if you already have this but I use WAMP from <a href="http://www.wampserver.com/en" rel="nofollow noreferrer">http://www.wampserver.com/en</a></p> <p>It's easy and simple to set up, it has an icon in the system tray to show that its active and you can make it go online or available to the outside by clicking the icon and setting it. I used this when I was first learning PHP since it has everything in one, no need to setup any other service like IIS.</p>
<p>Probably the installer didn't configure your server to use PHP properly. Check out Microsoft's page on <a href="http://www.iis.net/php" rel="nofollow noreferrer">enabling PHP on IIS</a> or alternatively switch to Apache if that's a viable option.</p>
15,198
<p>I have this piece of Javascript and it just won't work. I allready checked JSlint but that said everything works. Still doesn't work. The javascript is located not in the HTML but is linked in the <code>&lt;head&gt;</code></p> <p>note: I am working with a local server, so pageload in instant.</p> <pre><code>function changeVisibility() { var a = document.getElementById('invisible'); a.style.display = 'block'; } var changed = document.getElementById('click1'); changed.onchange = changeVisibility; </code></pre> <p>This here is the corresponding HTML</p> <pre><code>&lt;input type="file" name="click[]" size="35" id="click1" /&gt; &lt;div id="invisible" style="display: none;"&gt; &lt;a href="javascript:addFileInput();"&gt;Attach another File&lt;/a&gt; &lt;/div&gt; </code></pre> <p>So what happens is I click on the input, select a file and approve. Then then onchange event triggers and the style of my invisible div is set to block.</p> <p>Problem is, I keep getting this error:</p> <p>"changed is null: changed.onchange = changeVisibility;"</p> <p>i don't get it, I seriously don't get what I'm overlooking here.</p> <hr> <p>EDIT: question answered, thank you Mercutio for your help and everyone else too of course. Final code: </p> <pre><code>function loadEvents() { var changed = document.getElementById('click1'); var a = document.getElementById('invisible'); document.getElementById('addField').onclick = addFileInput; changed.onchange = function() { a.style.display = 'block'; } } if (document.getElementById) window.onload = loadEvents; </code></pre> <p>This here is the corresponding HTML:</p> <pre><code>&lt;input type="file" name="click[]" size="35" id="click1" /&gt; &lt;div id="invisible" style="display: none;"&gt; &lt;a href="#"&gt;Attach another File&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Also, thanks for the link to <a href="http://www.jsbin.com" rel="nofollow noreferrer">JSbin</a>, didn't know about that, looks nifty. </p>
<p>This sounds like the DOM object doesn't exist at the time of referencing it. Perhaps change your code to execute once the document has fully loaded (or place the javascript at the bottom of your page)</p> <blockquote> <p>note: I am working with a local server, so pageload in instant.</p> </blockquote> <p>that's not the issue - the constituent parts of a document are loaded in order. It doesn't matter how fast they are loaded, some things happen before others :D</p> <blockquote> <p>The onlything I'd like to do now is remove the Javascript link from the ...</p> </blockquote> <p>Place an id on there, and inside your function do this:</p> <pre><code>document.getElementById('addField').onclick = addFileInput; </code></pre> <p>Or, as you already have the div as the variable 'a':</p> <pre><code>a.firstChild.onclick = addFileInput; </code></pre> <p>But this obviously leaves you with an invalid anchor tag. Best practice suggests that you should provide a way to do it without javascript, and override that functionality with your javascript-method if available.</p>
<p>You need to wrap your code in a window.onload event handler, a domReady event handler (available in most modern js frameworks and libraries) or place at the bottom of the page.</p> <p>Placing at the bottom of the page works fine, as you can see <a href="http://jsbin.com/azoke/edit" rel="nofollow noreferrer">here</a>.</p> <p>Decoupling event responder from your markup is covered under the topic of "Unobtrusive JavaScript" and can be handled in a variety of ways. In general, you want to declare event responders in a window.onload or document.ready event.</p>
35,348
<p>When using the unmanaged API for the .NET framework to profile a .NET process in-process, is it possible to look up the IL instruction pointer that correlates to the native instruction pointer provided to the StackSnapshotCallback function?</p> <p>As is probably obvious, I am taking a snapshot of the current stack, and would like to provide file and line number information in the stack dump. The <em>Managed Stack Explorer</em> does this by querying <code>ISymUnmanagedMethod::GetSequencePoints</code>. This is great, but the sequence points are associated to offsets, and I have so far assumed these are offsets from the beginning of the method ( in intermediate language ).</p> <p>In a follow-up comment to his blog post <a href="https://web.archive.org/web/20190114032244/https://blogs.msdn.microsoft.com/davbr/2005/10/06/profiler-stack-walking-basics-and-beyond" rel="nofollow noreferrer">Profiler stack walking: Basics and beyond</a>, David Broman indicates that this mapping can be achieved using <code>ICorDebugCode::GetILToNativeMapping</code>. However, this is not ideal as getting this interface requires attaching to my process from another, debugger process.</p> <p>I would like to avoid that step because I would like to continue to be able to run my application from within the visual studio debugger while I am taking these snapshots. It makes it easier to click on the line number in the output window and go to the code in question.</p> <p>The functionality is possible.... you can spit out a line-numbered stack trace at will inside of managed code, the only question, is it accessible. Also, I don't want to use the <code>System::Diagnostics::StackTrace</code> or <code>System::Environment::StackTrace</code> functionality because, for performance reasons, I need to delay the actual dump of the stack.... so saving the cost for resolution of method names and code location for later is desirable... along with the ability to intermix native and managed frames.</p>
<p>In order to translate from a native instruction pointer as provided by <code>ICorProfilerInfo2::DoStackSnapshot</code> to an intermediate language method offset, you must take two steps since <code>DoStackSnapshot</code> provides a <code>FunctionID</code> and native instruction pointer as a virtual memory address.</p> <p>Step 1, is to convert the instruction pointer to a native code method offset. ( an offset from the beginning of the JITed method). This can be done with <code>ICorProfilerInfo2::GetCodeInfo2</code></p> <pre><code>ULONG32 pcIL(0xffffffff); HRESULT hr(E_FAIL); COR_PRF_CODE_INFO* codeInfo(NULL); COR_DEBUG_IL_TO_NATIVE_MAP* map(NULL); ULONG32 cItem(0); UINT_PTR nativePCOffset(0xffffffff); if (SUCCEEDED(hr = pInfo-&gt;GetCodeInfo2(functioId, 0, &amp;cItem, NULL)) &amp;&amp; (NULL != (codeInfo = new COR_PRF_CODE_INFO[cItem]))) { if (SUCCEEDED(hr = pInfo-&gt;GetCodeInfo2(functionId, cItem, &amp;cItem, codeInfo))) { COR_PRF_CODE_INFO *pCur(codeInfo), *pEnd(codeInfo + cItem); nativePCOffset = 0; for (; pCur &lt; pEnd; pCur++) { // 'ip' is the UINT_PTR passed to the StackSnapshotCallback as named in // the docs I am looking at if ((ip &gt;= pCur-&gt;startAddress) &amp;&amp; (ip &lt; (pCur-&gt;startAddress + pCur-&gt;size))) { nativePCOffset += (instructionPtr - pCur-&gt;startAddress); break; } else { nativePCOffset += pCur-&gt;size; } } } delete[] codeInfo; codeInfo = NULL; } </code></pre> <p>Step 2. Once you have an offset from the begining of the natvie code method, you can use this to convert to an offset from the begining of the intermediate language method using <code>ICorProfilerInfo2::GetILToNativeMapping</code>.</p> <pre><code>if ((nativePCOffset != -1) &amp;&amp; SUCCEEDED(hr = pInfo-&gt;GetILToNativeMapping(functionId, 0, &amp;cItem, NULL)) &amp;&amp; (NULL != (map = new COR_DEBUG_IL_TO_NATIVE_MAP[cItem]))) { if (SUCCEEDED(pInfo-&gt;GetILToNativeMapping(functionId, cItem, &amp;cItem, map))) { COR_DEBUG_IL_TO_NATIVE_MAP* mapCurrent = map + (cItem - 1); for (;mapCurrent &gt;= map; mapCurrent--) { if ((mapCurrent-&gt;nativeStartOffset &lt;= nativePCOffset) &amp;&amp; (mapCurrent-&gt;nativeEndOffset &gt; nativePCOffset)) { pcIL = mapCurrent-&gt;ilOffset; break; } } } delete[] map; map = NULL; } </code></pre> <p>This can then be used to map the code location to a file and line number using the symbol APIs</p> <p>Thanks to <a href="http://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/thread/ee47a207-5ee6-4e24-a89f-e2134a8eb7c8" rel="noreferrer">Mithun Shanbhag</a> for direction in finding the solution.</p>
<pre><code>Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace); </code></pre> <p>Make sure your build generates symbols.</p> <p>Expanding on the discussion:</p> <blockquote> <blockquote> <p>As is probably obvious, I am taking a snapshot of the current stack, and would like to provide file and line number information in the stack dump.</p> </blockquote> </blockquote> <p>Given this - It looks like the only reason you're not attaching to process is so that you can debug your tool , or parts of it , easily, as you're developing it. That IMO is a poor excuse for not choosing a better design (ICorDebug or w/e ) when its available. The reason its poor design is because your code executes in the process space of (presumably) external binaries , causing nasty ('sometimes' rare) side effects (including corrupting somebody else data) in known (or worse - unknown) corrupt process states. That should be enough to begin with, but even otherwise, there are several edge cases with multi-threaded code, etc where the design needs to be worked around. </p> <p>Most people generally ask "What are you really trying to do?" as a reply to an overtly complex way of doing things. In <strong>most</strong> cases there is a simpler/easier way. Having written a stack tracer for native code, I know it can get messy. </p> <p>Now maybe you might end up making everything work , so - Just my $.02</p>
24,224
<p>On a server I have to take care of, errors from a vhost do not go to the standard PHP error log.</p> <p>In the php.ini we have </p> <pre><code>log = /var/log/file </code></pre> <p>and <code>phpinfo()</code> does not show any difference between the vhost and the whole server.</p> <p>But the callback function set up by <code>set_error_handler()</code> catches errors which are not in the php log.</p> <p><code>error_reporting</code> is set to <code>E_ALL</code> once and never modified.</p> <p>Could you help me to find a way to explore what's happening here?</p>
<p>Perhaps the errors that aren't logged <a href="http://php.net/error-reporting" rel="nofollow noreferrer">aren't supposed to be logged</a>? The <a href="http://php.net/set_error_handler" rel="nofollow noreferrer">error reporting settings have no effect when set_error_handler is used</a>, hence you see more errors than are in the logfile.</p>
<p>I would take a look at error_log, log_error and error_reporting directive in php.ini and also take a look in the httpd.conf because directives can also be added there using "php_admin_value" and others.</p>
22,079
<p>Just need to use find a simple way to have AD authenticate as the login for a Sharepoint site. This fairly quick and simple to get going ? </p> <p>Thanks! </p>
<p>For SharePoint 2007, see this <a href="http://technet.microsoft.com/en-us/library/cc262350.aspx" rel="nofollow noreferrer">article</a>. You probably want to set it up to do Windows integrated authentication with NTLM. Getting authentication working is probably not too hard, getting your site setup the way you want with permissions/authorization working probably isn't. Depends on how complex your site is. I wasn't directly involved but I know that it took a few months to get our intranet up and bug free.</p> <p>One recommendation that I would have is to use AD groups or SharePoint groups that contain AD groups rather than individuals to control access. It's much easier to clean up AD group membership when an individual leaves than to track down all the places where you've given them individual access (including membership in SharePoint groups).</p>
<p>Here is a decent discussion of SharePoint security links</p> <p><a href="http://blogs.msdn.com/joelo/archive/2007/06/29/sharepoint-groups-permissions-site-security-and-depreciated-site-groups.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/joelo/archive/2007/06/29/sharepoint-groups-permissions-site-security-and-depreciated-site-groups.aspx</a></p> <p>Essentially, you will either need to add users to the appropriate SharePoint group. The defaults for a site are generally xxx_Visitor, xxx_Members and xxx_Owners, with each group having increasing security rights.</p> <p>You can either add an AD domain to these groups or else add individual AD users</p>
39,607
<p>When I generate CSS or JavaScript files using PHP I like to use .js.php or .css.php file extensions. so that I know what's going on.</p> <p>Is there a way of associating these "compound" file extensions to their respective languages?</p>
<p>I don't use NetBeans or PHP, but the following trick helped me in a similar setting:</p> <pre><code>&lt;?php if(0) { ?&gt;&lt;script&gt;&lt;?php } ?&gt; # code goes here &lt;?php if(0) { ?&gt;&lt;/script&gt;&lt;?php } ?&gt; </code></pre> <p>Simply surround the js code with <code>&lt;script&gt;</code> or <code>&lt;style&gt;</code> tags that don't get rendered. No need to configure any special associations, assuming the editor is smart enough about HTML.</p>
<p>What I usually do is condense such "compound" extensions into one, following the tradition of condensing .tar.gz into .tgz.</p>
40,184
<p>I have been using anonymous namespaces to store local data and functions and wanted to know when the data is initialized? Is it when the application starts in the same way as static data or is it compiler dependent? For example:</p> <pre><code>// foo.cpp #include "foo.h" namespace { const int SOME_VALUE = 42; } void foo::SomeFunc(int n) { if (n == SOME_VALUE) { ... } } </code></pre> <p>The question arises out of making some code thread-safe. In the above example I need to be certain that <code>SOME_VALUE</code> is initialized before SomeFunc is called for the first time.</p>
<p>C++ Standard, <strong>3.6.2/1</strong> :</p> <blockquote> <p>Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place. Objects with static storage duration defined in namespace scope in the same translation unit and dynamically initialized shall be initialized in the order in which their definition appears in the translation unit.</p> </blockquote> <p>This effectively means, even when another translation unit calls your SomeFunc function from outside, your SOME_VALUE constant will always be correctly initialized, because it's initialized with a <em>constant expression</em>. </p> <p>The only way for your function being called early (before main) is while initializing an object with dynamic initialiation. But by that time, according to the standard quote, the initialization of your POD variable is already done.</p>
<p>For the right answer to your actual question see Mathieu's answer.</p> <p>However, note that the anonymous namespace doesn't affect the beginning and end of the lifetimes of global and / or static objects. In other words, you're just as vulnerable to <a href="http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12" rel="nofollow noreferrer">static initialization order</a> problems as by using plain old globals.<BR></p> <p>The link also has some tips on avoiding the issue, using "construction on first use", in the next topic.</p>
42,880
<p>I am using Apache Axis to connect my Java app to a web server. I used wsdl2java to create the stubs for me, but when I try to use the stubs, I get the following exception:</p> <blockquote> <p>org.apache.axis.ConfigurationException: No service named <code>&lt;web service name&gt;</code> is available</p> </blockquote> <p>any idea?</p>
<p>According to the <a href="http://wiki.apache.org/ws/FrontPage/Axis/DealingWithCommonExceptions">documentation</a> linked to by @arnonym, this exception is somewhat misleading. In the first attempt to find the service a ConfigurationException is thrown and caught. It is logged at DEBUG level by the ConfigurationException class. Then another attempt is made using a different method to find the service that may then succeed. The workaround for this is to just change the log level on the ConfigurationException class to INFO in your log4j.properties:</p> <pre><code>log4j.logger.org.apache.axis.ConfigurationException = INFO </code></pre>
<p>This is what my code looks like. It seems to work fine. Are you using a service locator or just creating your service?</p> <pre><code>SomeServiceLocator locator = new SomeServiceLocator(); SomeService service = null; try { service = locator.getSomeServiceImplPort(); } catch (ServiceException e) { e.printStackTrace(); } </code></pre>
9,107
<p>Is there a way to determine how many capture groups there are in a given regular expression?</p> <p>I would like to be able to do the follwing:</p> <pre><code>def groups(regexp, s): """ Returns the first result of re.findall, or an empty default &gt;&gt;&gt; groups(r'(\d)(\d)(\d)', '123') ('1', '2', '3') &gt;&gt;&gt; groups(r'(\d)(\d)(\d)', 'abc') ('', '', '') """ import re m = re.search(regexp, s) if m: return m.groups() return ('',) * num_of_groups(regexp) </code></pre> <p>This allows me to do stuff like:</p> <pre><code>first, last, phone = groups(r'(\w+) (\w+) ([\d\-]+)', 'John Doe 555-3456') </code></pre> <p>However, I don't know how to implement <code>num_of_groups</code>. (Currently I just work around it.)</p> <p><strong>EDIT:</strong> Following the <a href="https://stackoverflow.com/questions/127055/find-out-number-of-capture-groups-in-python-regular-expressions/127089#127089">advice from rslite</a>, I replaced <code>re.findall</code> with <code>re.search</code>. </p> <p><code>sre_parse</code> seems like the most robust and comprehensive solution, but requires tree traversal and appears to be a bit heavy.</p> <p>MizardX's regular expression seems to cover all bases, so I'm going to go with that.</p>
<pre><code>def num_groups(regex): return re.compile(regex).groups </code></pre>
<p>Might be wrong, but I don't think there is a way to find the number of groups that would have been returned had the regex matched. The only way I can think of to make this work the way you want it to is to pass the number of matches your particular regex expects as an argument.</p> <p>To clarify though: When findall succeeds, you only want the first match to be returned, but when it fails you want a list of empty strings? Because the comment seems to show all matches being returned as a list.</p>
15,462
<p>In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible?</p> <p>(EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.)</p> <pre><code>function foo1($a,$b) { return $a/$b; } class Bar { static function foo2($a,$b) { return $a/$b; } public function UseReferences() { // WORKS FINE: $fn = foo1; print $fn(1,1); // WORKS FINE: print self::foo2(2,1); print Bar::foo2(3,1); // DOES NOT WORK ... error: Undefined class constant 'foo2' //$fn = self::foo2; //print $fn(4,1); // DOES NOT WORK ... error: Call to undefined function self::foo2() //$fn = 'self::foo2'; //print $fn(5,1); // DOES NOT WORK ... error: Call to undefined function Bar::foo2() //$fn = 'Bar::foo2'; //print $fn(5,1); } } $x = new Bar(); $x-&gt;UseReferences(); </code></pre> <p>(I am using PHP v5.2.6 -- does the answer change depending on version too?)</p>
<p>PHP handles callbacks as strings, not function pointers. The reason your first test works is because the PHP interpreter assumes <strong>foo1</strong> as a string. If you have E_NOTICE level error enabled, you should see proof of that.</p> <p>"Use of undefined constant foo1 - assumed 'foo1'"</p> <p>You can't call static methods this way, unfortunately. The scope (class) is relevant so you need to use call_user_func instead.</p> <pre><code>&lt;?php function foo1($a,$b) { return $a/$b; } class Bar { public static function foo2($a,$b) { return $a/$b; } public function UseReferences() { $fn = 'foo1'; echo $fn(6,3); $fn = array( 'self', 'foo2' ); print call_user_func( $fn, 6, 2 ); } } $b = new Bar; $b-&gt;UseReferences(); </code></pre>
<p>"A member or method declared with static can not be accessed with a variable that is an instance of the object and cannot be re-defined in an extending class"</p> <p>(<a href="http://theserverpages.com/php/manual/en/language.oop5.static.php" rel="nofollow noreferrer">http://theserverpages.com/php/manual/en/language.oop5.static.php</a>)</p>
23,346
<p>I am developing a web app which requires a username and password to be stored in the web.Config, it also refers to some URLs which will be requested by the web app itself and never the client.</p> <p>I know the .Net framework will not allow a web.config file to be served, however I still think its bad practice to leave this sort of information in plain text. </p> <p>Everything I have read so far requires me to use a command line switch or to store values in the registry of the server. I have access to neither of these as the host is online and I have only FTP and Control Panel (helm) access.</p> <p>Can anyone recommend any good, free encryption DLL's or methods which I can use? I'd rather not develop my own!</p> <p>Thanks for the feedback so far guys but I am not able to issue commands and and not able to edit the registry. Its going to have to be an encryption util/helper but just wondering which one!</p>
<ul> <li><a href="http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx" rel="noreferrer">Encrypting and Decrypting Configuration Sections</a> (ASP.NET) on MSDN</li> <li><a href="http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx" rel="noreferrer">Encrypting Web.Config Values in ASP.NET 2.0</a> on ScottGu's <a href="http://weblogs.asp.net/scottgu/default.aspx" rel="noreferrer">blog</a></li> <li><a href="http://odetocode.com/Blogs/scott/archive/2006/01/08/2707.aspx" rel="noreferrer">Encrypting Custom Configuration Sections</a> on K. Scott Allen's <a href="http://odetocode.com/Blogs/scott/default.aspx" rel="noreferrer">blog</a></li> </ul> <p><strong>EDIT:</strong><br> If you can't use asp utility, you can encrypt config file using <a href="http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.protectsection.aspx" rel="noreferrer">SectionInformation.ProtectSection</a> method.</p> <p>Sample on codeproject:</p> <p><a href="https://secure.codeproject.com/KB/aspnet/webconfig.aspx" rel="noreferrer">Encryption of Connection Strings inside the Web.config in ASP.Net 2.0</a> </p>
<p>Use aspnet_setreg.exe <a href="http://support.microsoft.com/kb/329290" rel="nofollow noreferrer">http://support.microsoft.com/kb/329290</a></p>
7,781
<p>Is there a .NET Framework compiler for the Ruby language? I've heard of the DLR (Dynamic Language Runtime), is this going to enable Ruby to be used with .NET development?</p>
<p><a href="http://www.ironruby.net/" rel="noreferrer">IronRuby</a> is a project supported by Microsoft, built on the Dynamic Language Runtime.</p>
<p><a href="http://rubydotnet.googlegroups.com/web/Home.htm?gda=8ES3fzoAAACraJYLasopJnHm_A4zSrefscDsHtcsS-deqHbu90w8mzCLtOtCUOXSAV3CbWid_sX97daDQaep90o7AOpSKHW0" rel="nofollow noreferrer">Yep, the Ruby.NET project</a>. Note, it hasn't been updated since November 2007, so I'm not sure what the support's like now. </p> <p>Edit: As others have pointed out, IronRuby is supported by Microsoft, so it's probably a better idea</p>
24,342
<p>I would like to completely reset the scroll position of a UITableView, so that every time I open it, it is displaying the top-most items. In other words, I would like to scroll the table view to the top every time it is opened.</p> <p>I tried using the following piece of code, but it looks like I misunderstood the documentation:</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionTop animated:NO]; } </code></pre> <p>Is this the wrong approach here?</p>
<p>August got the UITableView-specific method. Another way to do it is:</p> <pre><code>[tableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO]; </code></pre> <p>This method is defined in UIScrollView, the parent class to UITableView. The above example tells it to scroll to the 1x1 box at 0,0 - the top left corner, in other words.</p>
<p>What I ended up doing was this:</p> <p>Swift 4</p> <pre><code>self.tableView.contentOffset = CGPoint.zero DispatchQueue.main.async { self.tableView.reloadData() } </code></pre>
39,640
<p>Would you recommend me the best approach to edit SQL query with Visual Studio 2008 Professional, please?</p> <p>I know I can open Query window from context menu in Server Explorer and edit text in SQL Pane. But unfortunately I am not allowed to save query to a file and Find and Replace commands are not working there. </p> <p>Alternatively I can open text file with extension .SQL in Visual Studio editor obtaining syntax highlighting and full editing capabilities but losing possibility to execute the script.</p> <p>Now I copy query text from one window to another and back but I hope there is better solution.</p> <p>Many thanks for suggestions!</p>
<p>If you create a Database project within your solution in Visual Studio, then you can set up a default database connection for that project. Then any *.sql files that are included in the database project can be executed against that connection. What I usually do is select the text to be exectued and right-click it, then select "Run Selection".</p> <p>You can set up any number of database connections under the "Database References" node in the solution explorer, and choose the one you want to run your query against.</p>
<p>Wow you are right, this is a real pain. Would it be acceptable for you to use a local copy of the SQL Management Studio (the name might be wrong)? You would be outside of VS but you could still edit your query and run it at the same time. Definitely not optimal but better than nothing.</p> <p>Good luck.</p>
23,929
<p>What are you using for binding XML to Java? JAXB, Castor, and XMLBeans are some of the available choices. The comparisons that I've seen are all three or four years old. I'm open to other suggestions. Marshalling / unmarshalling performance and ease of use are of particular interest.</p> <p>Clarification: I'd like to see not just what framework you use, but your reasoning for using one over the others.</p>
<p><a href="http://www.jibx.org" rel="noreferrer">JiBX</a>. Previously I used <a href="http://www.castor.org/xml-framework.html" rel="noreferrer">Castor XML</a>, but JiBX proved to be significantly better, particularly in terms of performance (a straight port of some application code from Castor XML to JiBX made it 9x faster). I also found the mapping format for JiBX to be more elegant than Castor's.</p> <p>JiBX achieves its performance by using post-compilation bytecode manipulation rather than the reflection approach adopted by Castor. This has the advantage that it places fewer demands on the way that you write your mapped classes. There is no need for getters, setters and no-arg constructors just to satisfy the tools. Most of the time you can write the class without considering mapping issues and then map it without modifications.</p>
<p>We use Castor. It suits our needs fairly well.</p>
25,210
<p>I really like the way gmail has the archive system implemented. I can archive any file after adding a tag to it (if needed) and I can search for it whenever I want to. Is there any program in Windows/Linux which behaves in a similar fashion?</p>
<p>When you "Archive" in gmail you are just removing a hidden tag ("INBOX"). It does not seem a useful thing to do in your own file system, since you are not actually "archiving" anything. Good luck!</p>
<p>You might like google's GoogleDesktop... it doesn't have tagging per-se, but it seems to have pretty effective desktop search.</p>
23,893
<p>How do you make the authentication for a browser-based application dependent on the client machine? Say the admin can login only from <b>this</b> machine.</p> <p>Assumptions: There is complete control over the network and all machines (client and server) involved.</p> <p>I am looking for an apache/linux solution.</p>
<p>You need to come up with some way of identifying <strong>this</strong> machine. What iis important in your application? Physical location? IP address?</p> <p>If you have complete control over the machines I would use SSL with client certficates, and put the client certificate only on the machine that must be used. See <a href="http://www.garex.net/apache/" rel="nofollow noreferrer">here</a> for details on how to configure this with Apache</p> <p>As that article says, you can set Apache to require the certificate, a user name and password AND limit connectivity to specifc IP addresses. </p> <p>EDIT: You don't need a separate web server to use client certificates.</p> <p>You might need a separate URL depending on how your application works. </p> <p>Note the example configures certificates only for a certain Directory</p> <pre><code> &lt;Directory "/www/hidden/docs"&gt; </code></pre> <p>. So have certain classes of user login differently, or redirect them after login to the client-certificate-protected part of your website</p>
<p>If you are worried about malicious attempts to spoof the client workstation on the network, you could look into setting up IPSEC on the client and server, then you can simply use the IP address and treat it as trusted - i.e. use standard Apache techniques to control access by IP. </p> <p>Or if you consider your network trusted, just give the client a static IP and use standard apache techniques to limit access by IP.</p> <p>Both require some admin work on the network level but the bonus is you shouldn't need to change your application.</p>
47,664
<p>We have a C# service that is deployed to a remote customer system. The application writes a substantial amount of "diagnostic" information to the console (i.e. Console.WriteLine()). The service isn't "doing what it should." How can we capture the console output from the service in another application?</p> <p>A WinForm version the application can be loaded at the customer location. It, unfortunately, functions correctly.</p> <p>Update:</p> <p>We are able to change the change the service, but would prefer not to make major changes at this time.</p> <p>We are also logging to MSMQ, but only for "important" events. This service does interact with MSMQ for its normal operations. Or, at least, it should. The service doesn't seem to be pulling items from MSMQ when the WinForm version does. So, writing the messages that are going to the console could be problematic.</p>
<p>Are you able to change the service code <em>at all</em>? If so, using Console.SetOut to write to a file instead would be the most obvious first port of call. Then change to using a proper logging library for the next release :)</p>
<p>I found <a href="http://social.msdn.microsoft.com/Forums/en-US/winformsdatacontrols/thread/2e827551-6cbc-4b3d-a04f-e4dc6c262ae1" rel="nofollow noreferrer">this post</a> on MSDN which binds the Console output to a rich text box, worked for me very quickly and easily.</p> <p>It overrides WriteLine, and could be expanded to override other methods.</p>
24,623
<p>I have a multidimensional array. I need to search it for a specific range of values, edit those values and return the edited data.</p> <p>Example array:</p> <pre><code>array(3) { ["first"]=&gt; array(1) { [0]=&gt; string(4) "baz1" } ["second"]=&gt; array(1) { [0]=&gt; string(4) "foo1" } ["third"]=&gt; array(1) { [0]=&gt; string(4) "foo2" } </code></pre> <p>Now I want to find any values that match foo (foo1 and foo2 in the example array), insert "-bar" into them (foo-bar1, foo-bar2) and return that value. What are the best ways to approach this? </p> <p><em>EDIT</em> I should have mentioned that foo could actually be anythingfoo (ex. examplefoo1, somethingelsefoo2, blahblahfoo3). I think this rules out str_replace.</p>
<p>If your array will not be extremely deep, this can work. ($array being what you want to replace later with yours)</p> <pre><code>$array= array('first' =&gt; array('bazi1'), 'second' =&gt; array('foo1'), 'third' =&gt; array('foo2') ); function modify_foo(&amp;$item, $key) { $item = str_replace('foo', 'foo-bar', $item); } array_walk_recursive( $array, 'modify_foo' ); </code></pre> <p>If you want foo to be replaced even in somethingelsefoo2, then str_replace will be just fine.</p>
<pre><code> function test_replace1(&amp;$input, $search, $replace) { $result = array(); $numReplacements = 0; foreach ($input as &amp;$value) { if (is_array($value)) { $result = array_merge($result, test_replace1($value, $search, $replace)); } else { $value = str_replace($search, $replace, $value, $numReplacements); if ($numReplacements) { $result[] = $value; } } } return $result; } $changed_values = test_replace1($arr, 'foo', 'foo-bar'); </code></pre>
33,018
<p>I was wondering what and why you would choose to be able to make a database that can support no more than 100 users with no more than 10 using it at once with a Visual Studio 2008 C# Windows Form front end to access it by. I have to access the database over a network connection, not just on the local machine. I also need to define where the database is found at run-time in the code as opposed to the "Data Source" view in Visual Studio. If my question needs reframing or is not understood, let me know and I will adjust. Part of my problem is I am not sure even how to ask the right question, much less what the answer is.</p>
<p>If it is not for comercial purposes you can try SQL Server 2008 Express. It can integrate nicely with Visual Studio 2008 for development and has support for LINQ, Entity Data Model and ADO.NET Entity Framework to make it easy to create next generation data-enabled applications.</p> <p><a href="http://www.microsoft.com/express/sql/default.aspx" rel="nofollow noreferrer">http://www.microsoft.com/express/sql/default.aspx</a></p> <p>You can also store your connections strings in the application configuration file and retrieve them programatically for setting up the database connection.</p> <p><a href="http://www.codeguru.com/columns/DotNet/article.php/c7987/" rel="nofollow noreferrer">http://www.codeguru.com/columns/DotNet/article.php/c7987/</a></p>
<p>I know using mssql you can pick between different connection strings for all of your db calls, just do something like</p> <p>Command.Connection = GetMyConnectionWithWhateverLogicINeed();</p>
13,504
<p>When calling a remote service (e.g. over RMI) to load a list of entities from a database using Hibernate, how do you manage it to initialize all the fields and references the client needs?</p> <p>Example: The client calls a remote method to load all customers. With each customer the client wants the reference to the customer's list of bought articles to be initialized.</p> <p>I can imagine the following solutions:</p> <ol> <li><p>Write a remote method for each special query, which initializes the required fields (e.g. Hibernate.initialize()) and returns the domain objects to the client.</p></li> <li><p>Like 1. but create DTOs</p></li> <li><p>Split the query up into multiple queries, e.g. one for the customers, a second for the customers' articles, and let the client manage the results</p></li> <li><p>The remote method takes a DetachedCriteria, which is created by the client and executed by the server</p></li> <li><p>Develop a custom "Preload-Pattern", i.e. a way for the client to specify explicitly which properties to preload.</p></li> </ol>
<p>I have used 1 in the past and it worked well.</p>
<p>This remote service... is it another part of the same application? if so, there's no problem sharing classes and sending instances back and forth (same goes for RMI, using stubs). <P>Then there's the option of accessing a web-service or something similar, where the two applications communicating share no classes, and this makes things even trickier. I'm about to face this problem in the near future, and I'll be very interested to know the answer. <P>Anyway, my vote is for DTOs. I think they provide the best and easiest solution, where applicable, and help keep the code simple and maintainable. <p>Yuval =8-)</p>
14,559
<p><strong>Edited:</strong> What is the easiest way to <s>scrape</s> extract SharePoint list data to a separate SQL Server table? One condition: you're in a work environment where you don't control the SQL Server behind the SharePoint Server, so you can't just pull from the <em>UserData</em> table. </p> <p>Is there there any utilities that you can use to schedule a nightly extract? </p> <p>Is Microsoft planning any improvement here for "SharePoint 4"?</p> <p><strong>Update Jan 06, 2009:</strong><br> <a href="http://connectionstrings.com/sharepoint" rel="noreferrer">http://connectionstrings.com/sharepoint</a><br> For servers where office is not installed you will need:<br> <a href="http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&amp;displaylang=en" rel="noreferrer">this download</a></p>
<p>There is a SSIS SharePoint task you can use to grab the data info a regular dataflow: <a href="http://www.codeplex.com/SQLSrvIntegrationSrv" rel="noreferrer">http://www.codeplex.com/SQLSrvIntegrationSrv</a></p>
<p>Depending on the exact nature of the data you need to insert, it may be possible to just use the auto generated RSS feed to get the information you want, a process will need to read the rss and formulate a query.</p> <p>Otherwise a consoleapp/service could use the object model to do the same thing, but with more control over field information.</p>
39,596
<p>i would to know how to write a profiler? What books and / or articles recommended? Can anyone help me please?</p> <p>Someone has already done something like this?</p>
<p>Encouraging lot, aren't we :)</p> <p>Profilers aren't too hard if you're just trying to get a reasonable idea of where the program's spending most of its time. If you're bothered about high accuracy and minimum disruption, things get difficult.</p> <p>So if you just want the answers a profiler would give you, go for one someone else has written. If you're looking for the intellectual challenge, why not have a go at writing one?</p> <p>I've written a couple, for run time environments that the years have rendered irrelevant.</p> <p>There are two approaches</p> <ul> <li><p>adding something to each function or other significant point that logs the time and where it is.</p> </li> <li><p>having a timer going off regularly and taking a peek where the program currently is.</p> </li> </ul> <p>The JVMPI version seems to be the first kind - the link provided by uzhin shows that it can report on quite a number of things (see section 1.3). What gets executed changes to do this, so the profiling can affect the performance (and if you're profiling what was otherwise a very lightweight but often called function, it can mislead).</p> <p>If you can get a timer/interrupt telling you where the program counter was at the time of the interrupt, you can use the symbol table/debugging information to work out which function it was in at the time. This provides less information but can be less disruptive. A bit more information can be obtained from walking the call stack to identify callers etc. I've no idea if these is even possible in Java...</p> <p>Paul.</p>
<p>As another answer, I just looked at LukeStackwalker on sourceforge. It is a nice, small, example of a stack-sampler, and a nice place to start if you want to write a profiler.</p> <p>Here, in my opinion, is what it does right:</p> <ul> <li>It samples the entire call stack.</li> </ul> <p>Sigh ... so near yet so far. Here, IMO, is what it (and other stack samplers like xPerf) should do:</p> <ul> <li><p>It should retain the raw stack samples. As it is, it summarizes at the function level as it samples. This loses the key line-number information locating the problematic call sites.</p></li> <li><p>It need not take so many samples, if storage to hold them is an issue. Since typical performance problems cost from 10% to 90%, 20-40 samples will show them quite reliably. Hundreds of samples give more measurement precision, but they do not increase the probability of locating the problems.</p></li> <li><p>The UI should summarize in terms of statements, not functions. This is easy to do if the raw samples are kept. The key measure to attach to a statement is the fraction of samples containing it. For example:</p> <p>5/20 MyFile.cpp:326 for (i = 0; i &lt; strlen(s); ++i)</p></li> </ul> <p>This says that line 326 in MyFile.cpp showed up on 5 out of 20 samples, in the process of calling <code>strlen</code>. This is very significant, because you can instantly see the problem, and you know how much speedup you can expect from fixing it. If you replace <code>strlen(s)</code> by <code>s[i]</code>, it will no longer be spending time in that call, so these samples will not occur, and the speedup will be approximately 1/(1-5/20) = 20/(20-5) = 4/3 = 33% speedup. (Thanks to David Thornley for this sample code.)</p> <ul> <li><p>The UI should have a "butterfly" view showing statements. (If it shows functions too, that's OK, but the statements are what really matter.) For example:</p> <p>3/20 MyFile.cpp:502 MyFunction(myArgs)<br> 2/20 HisFile.cpp:113 MyFunction(hisArgs)</p> <p>5/20 MyFile.cpp:326 for (i = 0; i &lt; strlen(s); ++i)</p> <p>5/20 strlen.asm:23 ... some assembly code ...</p></li> </ul> <p>In this example, the line containing the <code>for</code> statement is the "focus of attention". It occurred on 5 samples. The two lines above it say that on 3 of those samples, it was called from <code>MyFile.cpp:502</code>, and on 2 of those samples, it was called from <code>HisFile.cpp:113</code>. The line below it says that on all 5 of those samples, it was in <code>strlen</code> (no surprise there). In general, the focus line will have a tree of "parents" and a tree of "children". If for some reason, the focus line is not something you can fix, you can go up or down. The goal is to find lines that you can fix that are on as many samples as possible.</p> <p>IMPORTANT: Profiling should not be looked at as something you do <strong>once</strong>. For example, in the sample above, we got a 4/3 speedup by fixing one line of code. When the process is repeated, other problematic lines of code should show up at 4/3 the frequency they did before, and thus be easier to find. I never hear of people talking about iterating the profiling process, but it is crucial to getting overall large compounded speedups.</p> <p>P.S. If a statement occurs more than once in a single sample, that means there is recursion taking place. It is not a problem. It still only counts as one sample containing the statement. It is still the case that the cost of the statement is approximated by the fraction of samples containing it.</p>
48,158
<p>I want to do something like this: </p> <p>page A has a link to page B<br> page B gets content from a database and processes it<br> the result from page B is displayed on a div in page A </p> <p>Please notice that I don't want to leave page A while page B processes the information of the database.</p> <p>What I'm really trying to do is avoid using frames in the site, and I want to make the pages appear in a <code>div</code>. Is this possible?</p> <p>I'm guessing its kinda of a newbie question, but it's really bugging me and i don't even know where to start looking.</p>
<p>You want AJAX!</p> <p>AJAX will do that, but the steps will be a little different from what you describe</p> <ul> <li>page A has a link that calls a javascript function</li> <li>the javascript function makes an AJAX call to page B which gets content from a database and processes it</li> <li>the result from page B is returned to the javascript function</li> <li>page a displays it in a div</li> </ul>
<p>Short answer: no.</p> <p>You will need some client side scripts or AJAX to do this.</p>
49,152
<p>I've noticed that plenty of opensource project doesn't use BITWISE flags anymore, even if it's fully supported by programming enviroment common for web ( php/Mysql). It's that a "lost practise" for some effective problem, or is just that a lot of php programmers don't know how to handle this type of implementation?</p> <p>Nothing too important, just very curious :) thanks to you all</p>
<p>I'll stick my neck out and say that every technical position requires a sound understanding of bitwise operations.</p> <p>And I have an anecdote that indirectly addresses the topic.</p> <p>January 2007 I was in Cochin, India, recruiting for permanent development staff. Since I wasn't involved in the preliminary screening of candidates I had no idea what standard to expect so I had prepared a range of questions and topics ranging from simple understanding of binary and hexidecimal through to architecture, design, and project management.</p> <p>When I discussed my approach with the Indian HR guy I was (gently) chided for pitching too low. He made it clear that my questions about hex would possibly be construed as an insult to the candidates experience or education.</p> <p>But my experience of interviewing hundreds of candidates in the UK had fixed in me a conviction that it wasn't possible to pitch too low. My opinion was and still is that if it becomes obvious a candidate is well qualified then it's simple and easy to adjust the level of discussion. I've never had anyone express feelings of being insulted, on the contrary I think a well qualified candidate might feel relieved at a flying start to the interview. It also helps to break the ice and build a rapport needed for a meaningful interview. On the other hand, unqualified candidates usually fall at these lower hurdles.</p> <p>But not wanting to completely ignore local advice I cautiously decided to include my basic interview topics, and was quite prepared to abandon them if they didn't work.</p> <p>As the interviews progressed I was glad that I started at that level. It didn't offend anyone, and unsuitable candidates were easily identified. </p> <p>This is not to say that I expect candidates to deal with bit-twiddling day to day, but whatever the language a sound understanding of the fundamentals of programming is essential. Even developers at the higher levels of abstraction are exposed to hex on a regular basis (RGB values, for example). Parroting <a href="http://www.codeproject.com/" rel="noreferrer">stuff you find on the net</a> will only help to the extent that things work perfectly first time.</p> <p>But for developers starting out in the past five years I believe it's all too easy to gloss over the fundamentals, cosseted by well intentioned IDEs and the meme of "codeless" programming. The Visual Studio installation spash screens boast about developing without writing code. Indeed, <a href="http://www.charlespetzold.com/etc/DoesVisualStudioRotTheMind.html" rel="noreferrer">does Visual Studio rot the mind</a>?</p>
<p>I still use bitwise operators, though as my main language of choice (and professionally) is C# I often use Flag enums for it :) But yeah, I think alot of people who code in things like PHP are self taught, and don't know about bitwise operations or the usages of them.</p> <p>Being self taught myself, I didn't know much about them until I started writing C and C++ code. Now I use them where they make sense :)</p>
27,789
<p>We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser. </p> <p>We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object. </p> <p>However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:</p> <pre><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;Test&lt;/TITLE&gt; &lt;SCRIPT type="text/javascript"&gt; var field = 'hello world'; &lt;/SCRIPT&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;input type="button" value="See field" onclick="javascript:alert(field);"/&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre> <p>We want to access the <em>field</em> variable and assign a value to it. In VB6 the code for this was pretty straightforward:</p> <pre><code>doc.Script.field = 'newValue' </code></pre> <p>However, in C# we've had to resort to other tricks, like this: </p> <pre><code>Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null); </code></pre> <p>The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".</p> <p>That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable <code>field</code>. </p> <p>Has anyone had any experience doing this type of operation before?</p>
<p>These two articles helped us find a solution to our problem. They outline the basics of what one needs to know:</p> <p><a href="http://www.codeproject.com/KB/cs/mshtml_automation.aspx" rel="nofollow noreferrer">Microsoft Web Browser Automation using C#</a></p> <p><a href="http://www.codeproject.com/KB/cs/advhost.aspx?target=idochostuihandler" rel="nofollow noreferrer">Using MSHTML Advanced Hosting Interfaces</a></p> <p>So we implemented a DocHostUIHandler interface and that allowed us to set a UIHandler, allowing us to reference the method from Javascript.</p>
<p>The usual method we use is to add a hidden text input box (the ASP.Net control version) on the page. That way you can easily set its value in the C# codebehind and read the value in client side JavaScript (and vice-versa, of course).</p>
16,487
<p>Let's say I have a complex .NET class, with lots of arrays and other class object members. I need to be able to generate a deep clone of this object - so I write a Clone() method, and implement it with a simple BinaryFormatter serialize/deserialize - or perhaps I do the deep clone using some other technique which is more error prone and I'd like to make sure is tested.</p> <p>OK, so now (ok, I should have done it first) I'd like write tests which cover the cloning. All the members of the class are private, and my architecture is so good (!) that I haven't needed to write hundreds of public properties or other accessors. The class isn't IComparable or IEquatable, because that's not needed by the application. My unit tests are in a separate assembly to the production code.</p> <p>What approaches do people take to testing that the cloned object is a good copy? Do you write (or <em>rewrite</em> once you discover the need for the clone) all your unit tests for the class so that they can be invoked with <em>either</em> a 'virgin' object <em>or</em> with a clone of it? How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?</p>
<p>You method of testing will depend on the type of solution you come up with. If you write some custom cloning code and have to manually implement that in each cloneable type then you should really test the cloning of each one of those types. Alternatively, if you decide to go a more generic route (where the aforementioned reflection would likely fit in), your tests would only need to test the specific scenarios that you cloning system will have to deal with.</p> <p>To answer your specific questions:</p> <blockquote> <p>Do you write (or rewrite once you discover the need for the clone) all your unit tests for the class so that they can be invoked with either a 'virgin' object or with a clone of it?</p> </blockquote> <p>You should have tests for all the methods that can be performed on both the original and cloned objects. Note that it should be pretty easy to set up a simple test design to support this without manually updating the logic for each test.</p> <blockquote> <p>How would you test if part of the cloning wasn't deep enough - as this is just the kind of problem which can give hideous-to-find bugs later?</p> </blockquote> <p>It depends on the cloning method you choose. If you have to manually update the cloneable types then you should test that each type is cloning all (and only) the members you expect. Whereas, if you are testing a cloning framework I would create some test cloneable types to test each scenario you need to support.</p>
<p>Here is a sample of how I implemented this a while back, although this will need to be tailored to the scenario. In this case we had a nasty object chain that could easily change and the clone was used as a very critical prototype implementation and so I had to patch (hack) this test together.</p> <pre><code>public static class TestDeepClone { private static readonly List&lt;long&gt; objectIDs = new List&lt;long&gt;(); private static readonly ObjectIDGenerator objectIdGenerator = new ObjectIDGenerator(); public static bool DefaultCloneExclusionsCheck(Object obj) { return obj is ValueType || obj is string || obj is Delegate || obj is IEnumerable; } /// &lt;summary&gt; /// Executes various assertions to ensure the validity of a deep copy for any object including its compositions /// &lt;/summary&gt; /// &lt;param name="original"&gt;The original object&lt;/param&gt; /// &lt;param name="copy"&gt;The cloned object&lt;/param&gt; /// &lt;param name="checkExclude"&gt;A predicate for any exclusions to be done, i.e not to expect IPolicy items to be cloned&lt;/param&gt; public static void AssertDeepClone(this Object original, Object copy, Predicate&lt;object&gt; checkExclude) { bool isKnown; if (original == null) return; if (copy == null) Assert.Fail("Copy is null while original is not", original, copy); var id = objectIdGenerator.GetId(original, out isKnown); //Avoid checking the same object more than once if (!objectIDs.Contains(id)) { objectIDs.Add(id); } else { return; } if (!checkExclude(original)) { Assert.That(ReferenceEquals(original, copy) == false); } Type type = original.GetType(); PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); FieldInfo[] fieldInfos = type.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); foreach (PropertyInfo memberInfo in propertyInfos) { var getmethod = memberInfo.GetGetMethod(); if (getmethod == null) continue; var originalValue = getmethod.Invoke(original, new object[] { }); var copyValue = getmethod.Invoke(copy, new object[] { }); if (originalValue == null) continue; if (!checkExclude(originalValue)) { Assert.That(ReferenceEquals(originalValue, copyValue) == false); } if (originalValue is IEnumerable &amp;&amp; !(originalValue is string)) { var originalValueEnumerable = originalValue as IEnumerable; var copyValueEnumerable = copyValue as IEnumerable; if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy }); int count = 0; List&lt;object&gt; items = copyValueEnumerable.Cast&lt;object&gt;().ToList(); foreach (object o in originalValueEnumerable) { AssertDeepClone(o, items[count], checkExclude); count++; } } else { //Recurse over reference types to check deep clone success if (!checkExclude(originalValue)) { AssertDeepClone(originalValue, copyValue, checkExclude); } if (originalValue is ValueType &amp;&amp; !(originalValue is Guid)) { //check value of non reference type Assert.That(originalValue.Equals(copyValue)); } } } foreach (FieldInfo fieldInfo in fieldInfos) { var originalValue = fieldInfo.GetValue(original); var copyValue = fieldInfo.GetValue(copy); if (originalValue == null) continue; if (!checkExclude(originalValue)) { Assert.That(ReferenceEquals(originalValue, copyValue) == false); } if (originalValue is IEnumerable &amp;&amp; !(originalValue is string)) { var originalValueEnumerable = originalValue as IEnumerable; var copyValueEnumerable = copyValue as IEnumerable; if (copyValueEnumerable == null) Assert.Fail("Copy is null while original is not", new[] { original, copy }); int count = 0; List&lt;object&gt; items = copyValueEnumerable.Cast&lt;object&gt;().ToList(); foreach (object o in originalValueEnumerable) { AssertDeepClone(o, items[count], checkExclude); count++; } } else { //Recurse over reference types to check deep clone success if (!checkExclude(originalValue)) { AssertDeepClone(originalValue, copyValue, checkExclude); } if (originalValue is ValueType &amp;&amp; !(originalValue is Guid)) { //check value of non reference type Assert.That(originalValue.Equals(copyValue)); } } } } } </code></pre>
3,216
<p>I have a table with a view_name field (varchar(256)) and I would like to use that field in an sql query.</p> <p>Example :</p> <p>TABLE university_members</p> <p><strong>id | type | view_name | count</strong></p> <p>1 | professors | view_professors | 0</p> <p>2 | students | view_students2 | 0</p> <p>3 | staff | view_staff4 | 0</p> <p>And I would like to update all rows with some aggregate calculated on the corresponding view (for instance <code>..SET count = SELECT count(*) FROM view_professors</code>).</p> <p>This is probably a newbie question, I'm guessing it's either obviously impossible or trivial. Comments on the design, i.e. the way one handle meta-data here (explicity storing DB object names as strings) would be appreciated. Although I have no control over that design (so I'll have to find out the answer anyway), I'm guessing it's not so clean although some external constraints dictated it so I would really appreciate the community's view on this for my personal benefit.</p> <p>I use SQL Server 2005 but cross-platform answers are welcome.</p>
<p>To do this you would have to do it as a bit of dynamic SQL, something like this might work, obviously you would need to edit to actually match what you are trying to do.</p> <pre><code>DECLARE @ViewName VARCHAR(500) SELECT @ViewName = view_name FROM University_Members WHERE Id = 1 DECLARE @SQL VARCHAR(MAX) SET @SQL = ' UPDATE YOURTABLE SET YOURVALUE = SELECT COUNT(*) FROM ' + @ViewName + ' WHERE yourCriteria = YourValue' EXEC(@SQL) </code></pre>
<p>The way I see it, you could generate SQL code in a VARCHAR(MAX) variable and then execute it using EXEC keyword. I don't know of any way to do it directly, as you tried.</p> <p>Example:</p> <pre><code>DECLARE @SQL VARCHAR(MAX) SET @SQL = '' SELECT @SQL = @SQL + 'UPDATE university_members SET count = (SELECT COUNT(*) FROM ' + view_name + ') WHERE id = ' + id + CHAR(10) + CHAR(13) FROM university_members EXEC @SQL </code></pre> <p>Warning! This code is not tested. It's just a hint...</p>
43,349
<p>What is the C++ equivalent to <code>GetObject</code> in <a href="http://en.wikipedia.org/wiki/JavaScript" rel="nofollow noreferrer">JavaScript</a> and <a href="http://en.wikipedia.org/wiki/VBScript" rel="nofollow noreferrer">VBScript</a>?</p> <p>The closest match I found to my question is:</p> <p><a href="http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html" rel="nofollow noreferrer">http://codewiz51.blogspot.com/2008/06/vb-script-getobject-c-api-cogetobject.html</a></p> <p>However the sample use an unexisting interface and asking for the <code>IUnknown</code> returns null. Did someone have an example that works?</p>
<p>I figured out the issue. The object I wanted to access was </p> <p><code> winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv </code></p> <p>I mistakenly took \\ for an escapement. In C++ the correct query is :</p> <p><code> ::CoGetObject(L"winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\default:StdRegProv", NULL, IID_IUnknown, (void**)&amp;pUnk); </code></p> <p>Thank you :)</p>
<p>If asking for IUnknown returns NULL, there is no object by that name. Each COM object implements IUnknown.</p>
44,163
<p>Does anyone know how function indexes work in databases?</p>
<p>The main difference is that InnoDB supports transactions while MyISAM does not.</p> <p>There are numerous other differences, however the common one's i am aware of are:</p> <ul> <li>MyISAM has typically been considered faster at searching, but recent InnoDB improvements are removing this difference and improving high concurrency workload performance</li> <li>InnoDB support transactions whilst MyISAM does not</li> <li>InnoDB supports referential integrity whilst MyISAM does not</li> <li>InnoDB handles indexes a bit differently, storing the primary key as part of every index (making indexes take up more room on the disk, but also making a covering index more likely)</li> <li>MyISAM does table level locking while InnoDB can do row level locking</li> <li>Different memory/buffer/index settings are used in the MySQL configuration files</li> <li>InnoDB is typically said to have better crash recovery</li> <li>As mentioned in another answer, the data is store on disk differently. I believe InnoDB is configurable in this area and can have one file per table etc. if required</li> </ul> <p>I'm sure a google search or the MySQL site will bring up numerous other differences in more detail.</p>
<p>Here is a description of differences between InnoDB and MyIsam:</p> <p><a href="http://tag1consulting.com/MySQL_Engines_MyISAM_vs_InnoDB" rel="nofollow noreferrer">Differences between InnoDB and MyIsam</a></p> <p>Few differences:</p> <ul> <li><strong>MYISAM</strong> doesnt support any database transactions, </li> <li><strong>INNODB</strong> will provide transactions</li> <li><strong>MYISAM</strong> provides a table level locking, </li> <li><strong>INNODB</strong> provides a row level locking</li> <li><strong>INNOBD</strong> supports foreign keys, <strong>MYISAM</strong> does not...</li> </ul>
35,011
<p>I am working with a large Java web application from a commercial vendor. I've received a patch from the vendor in the form of a new .class file that is supposed to resolve an issue we're having with the software. In the past, applying patches from this vendor have caused new and completely unrelated problems to arise, so I want to understand the change being made even before applying it to a test instance.</p> <p>I've got the two .class files side by side, the one extracted from the currently running version and the updated one from the vendor. <a href="http://www.kpdus.com/jad.html" rel="noreferrer">JAD</a> and <a href="http://jreversepro.blogspot.com/" rel="noreferrer">JReversePro</a> both decompile and disassemble (respectively) the two versions to the same output. However, the .class files are different sizes and I see differences in the output of <code>od -x</code>, so they're definitely not identical.</p> <p>What other steps could I take to determine the difference between the two files?</p> <p><hr/> Conclusion:</p> <p>Thanks for the great responses. Since <code>javap -c</code> output is also identical for the two class files, I am going to conclude that Davr's right and the vendor sent me a placebo. While I'm accepting Davr's answer for that reason, it was Chris Marshall and John Meagher who turned me on to javap, so thanks to all three of you.</p>
<p>It's possible that they just compiled it with a new version of the java compiler, or with different optimization settings etc, so that the functionality is the same, and the code is the same, but the output bytecode is slightly different.</p>
<p>You could try using a diff tool (such as SourceGear's free DiffMerge tool) on the decompiled sources. That should pick up the file differences, although it will likely pick up "insignificant" differences, for example if variables have been named differently in the two versions.</p> <p><a href="http://www.sourcegear.com/diffmerge/" rel="nofollow noreferrer">http://www.sourcegear.com/diffmerge/</a></p>
11,380
<p>When someone uses the term XXX architecture I tend to cringe. It often indicates that there's another architectural discipline or perspective that I'm probably not considering. What perspectives of architecture are you considering and do you have any good resources for information on them?</p> <p>I hope this helps others who are working their way through the architecture profession.</p> <ul> <li>Survivability</li> <li>Performance Management</li> <li>Operational Monitoring &amp; Management</li> <li>Service Orientation</li> <li>TOGAF defines a number of quality of service attributes</li> </ul> <p>Sorry for the edit, but your answers were spot on and I think the question needed to be refined. </p>
<p>Architecture and architectural decisions are primarily about the "non-functional" requirements of a system; <em>pace</em> RoadWarrier, but each of the things he mentions are consequences of the architectural decisions more than independent in and of themselves. (Proof: what leads to a particular choice in any of those domains? It's always the need to satisfy some nonfunctional requirement.)</p> <p>With that in mind, it's a two part issue. First, you need to decide what NFRs are important. preferably by stating them with some specificity using a rigorous method, eg, don't just say "highly available", say "the system must be available (MTTF/(MTTF+MTTR)) 99.99 percent, with the longest single duration outage being 4 minutes."</p> <p>Second, you need to consider what views will help you to design to satisfy these requirements <em>and justify your decisions</em>. Depending on the stringency of your requirements, this may be anything from a white board block diagram to a formal simulation study.</p> <p>In a <em>business</em> domain, say in an IT system available over a web interface, you might, for example, want:</p> <ul> <li>reliability (MMTF)</li> <li>availability (MTTF/(MTTF+MTTR))</li> <li>scaleability (system must be able to add 10 pct capacity within 72 hours at X cost)</li> <li>capacity (system must sustain 1 million active users)</li> <li>throughput (system must process 100 transactions per second mean with &sigma;=2.5 tps)</li> <li>response time (under test load user must receive full page in ≤ 2 seconds)</li> <li>security (metrics here is a topic for a while article in itself)</li> </ul> <p>You should also, if you're specifying the performance etc characteristics, describe the <em>workload</em>, ie, the size of a user's data, the arrival rate of web requests, etc.</p>
<ul> <li>testability</li> <li>scalability</li> <li>fault-tolerance</li> <li>performance degradation (gracefully, one hopes)</li> <li>upgradability (hardware and software)</li> </ul> <p>BTW these are all reasons why I like enterprise service busses (ESBs)!</p>
48,820
<p>Sometimes I find myself in the situation where I want to execute several sequential commands like such:</p> <pre><code>try: foo(a, b) except Exception, e: baz(e) try: bar(c, d) except Exception, e: baz(e) ... </code></pre> <p>This same pattern occurs when exceptions simply need to be ignored.</p> <p>This feels redundant and the excessive syntax causes it to be surprisingly difficult to follow when reading code.</p> <p>In C, I would have solved this type of problem easily with a macro, but unfortunately, this cannot be done in straight python.</p> <p>Question: How can I best reduce the code footprint and increase code readability when coming across this pattern?</p>
<p>You could use the <a href="https://www.python.org/dev/peps/pep-0343/" rel="noreferrer"><code>with</code> statement</a> if you have python 2.5 or above:</p> <pre><code>from __future__ import with_statement import contextlib @contextlib.contextmanager def handler(): try: yield except Exception, e: baz(e) </code></pre> <p>Your example now becomes:</p> <pre><code>with handler(): foo(a, b) with handler(): bar(c, d) </code></pre>
<p>In your specific case, you can do this:</p> <pre><code>try: foo(a, b) bar(c, d) except Exception, e: baz(e) </code></pre> <p>Or, you can catch the exception one step above:</p> <pre><code>try: foo_bar() # This function can throw at several places except Exception, e: baz(e) </code></pre>
15,702
<p>What VM technologies exist for Linux, their pros and cons, and which is recommended for which application?</p> <p>Since this kind of question can be asked for X other than "VM technologies for Linux", and since the answer changes with progress, I suggest to define a template for this kind of pages. Those pages will have the tag 'stateoftheart' and they will be revisited each month and each month there will be up-to-date list of technologies, up-to-date reviews and up-to-date recommendations.</p>
<p>This is a job for ... <strong><a href="http://en.wikipedia.org/wiki/Main_Page" rel="nofollow noreferrer">Wikipedia</a></strong>!</p> <ul> <li><a href="http://en.wikipedia.org/wiki/Virtualization" rel="nofollow noreferrer">Types of Virtualization</a></li> <li><a href="http://en.wikipedia.org/wiki/Platform_virtualization" rel="nofollow noreferrer">Platform Virtualization</a></li> <li><a href="http://en.wikipedia.org/wiki/Comparison_of_virtual_machines" rel="nofollow noreferrer">Comparison of Virtual Machines</a></li> </ul> <p>Now that the obvious stuff is out of the way...</p> <p>Linux runs fine as a guest on every VM host I've used, so I'm going to assume that you're referring to Linux as the host operating system. I'm also going to assume x86 or amd64 hardware.</p> <p>Platform virtualization breaks down into two major forms: Desktop virtualization and Server virtualization. Both types will allow you to load and run multiple OS instances as guests that virtualize their I/O through the host OS. Desktop virtualization concentrates on providing a highly interactive console experience for each of the guest VMs, while Server virtualization concentrates on maximizing computing performance, generally while sacrificing console services and more exotic devices (Sound cards, USB, etc.) Server virtualization implementations typically include either <a href="http://en.wikipedia.org/wiki/Remote_Desktop_Protocol" rel="nofollow noreferrer">RDP</a> or <a href="http://en.wikipedia.org/wiki/VNC" rel="nofollow noreferrer">VNC</a> for remote access to a virtual console.</p> <p>On Linux, your choices for <strong>Desktop Virtualization</strong> include:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/VMware_Workstation" rel="nofollow noreferrer">VMware Workstation</a> -- it's commercial, somewhat expensive, mature, and provides the most hardware, device, and guest OS support of any solution.</li> <li><a href="http://en.wikipedia.org/wiki/VMware_Player" rel="nofollow noreferrer">VMware Player</a> -- it's commercial (freeware) and only supports VMs that were created elsewhere. Available with Ubuntu.</li> <li><a href="http://en.wikipedia.org/wiki/Parallels_Workstation" rel="nofollow noreferrer">Parallels Workstation</a> -- it's commercial, somewhat expensive, and not up to par with VMware. Doesn't support 64-bit guests.</li> <li><a href="http://en.wikipedia.org/wiki/VirtualBox" rel="nofollow noreferrer">VirtualBox</a> -- available in commercial (freeware) and community versions (GPL). Fedora's preferred solution.</li> </ul> <p>On Linux, your choices for <strong>Server Virtualization</strong> include:</p> <ul> <li><a href="http://en.wikipedia.org/wiki/VMware_Server" rel="nofollow noreferrer">VMware Server</a> -- it's commercial (freeware), mature, and provides the most hardware, device, and guest OS support of any solution. Available with Ubuntu.</li> <li><a href="http://en.wikipedia.org/wiki/Xen" rel="nofollow noreferrer">Xen</a> -- it's open source. A para-virtualization solution, it has only recently added hardware-virtualization, so Windows guest support depends upon specific CPU support.</li> <li><a href="http://en.wikipedia.org/wiki/Virtual_Iron" rel="nofollow noreferrer">Virtual Iron</a> -- a commercialized version of Xen that adds native virtualization.</li> <li><a href="http://en.wikipedia.org/wiki/Kernel-based_Virtual_Machine" rel="nofollow noreferrer">KVM</a> -- it's open source. It depends upon <a href="http://en.wikipedia.org/wiki/QEMU" rel="nofollow noreferrer">QEMU</a> for the last mile. Ubuntu's preferred solution.</li> <li><a href="http://en.wikipedia.org/wiki/Linux-VServer" rel="nofollow noreferrer">Linux-VServer</a> -- it's open source. It provides virtual jails based on the host OS kernel, so no Windows guests.</li> </ul> <p>For myself, I stick with VMware Workstation (7+ years) and VMware Server for my Linux-hosted virtualization needs. At work, it's VMware Workstation (on Windows), VMware Server (on Windows), and VMware ESX (on bare metal). I'll probably have another look at Xen, KVM, and VirtualBox at some point, but for right now compatibility between work and home is paramount.</p>
<h1>2008 Oct</h1> <p>To be filled in at October to reflect the market status then.</p> <h1>2008 Sept</h1> <h2>Products/services/technologies currently existing</h2> <ol> <li><a href="http://www.vmware.com" rel="nofollow noreferrer">VMware</a></li> <li><a href="http://www.xen.org" rel="nofollow noreferrer">Xen</a></li> <li><a href="http://www.virtualbox.org" rel="nofollow noreferrer">VirtualBox</a></li> <li><a href="http://linux-vserver.org" rel="nofollow noreferrer">VServer</a></li> <li>???</li> </ol> <h2>Comparisons</h2> <p>???</p> <h2>Recommendations for particular application areas</h2> <ol> <li>Home multi-boot replacement</li> <li>Small business which has MS-Windows legacy applications</li> <li>Datacenter of multinational corporation</li> <li>???</li> </ol>
13,503
<p>From what I have gleaned from reflector, RunWithElevatedPriveleges simply reverts the current thread identity to the base (non-impersonated) identity. This makes perfect sense in the case of code running inside the WSS application pool, since the base service account is a super-user. Does it have any effect when running in an external (console or service) application, when no impersonation exists? I'm guessing not, but I'd like to know for sure. I've seen varying opinions on this from googling.</p>
<p>Normally Runwithelevatedprivileges will get your code running as the app pool identity, but it doesn't work from the console. What we've done in this case is either use <a href="http://technet.microsoft.com/en-us/library/cc781769.aspx" rel="nofollow noreferrer">runas</a> or a set the identity of a scheduled task to the same account as the app pool identity.</p>
<p>RunWithElevatedPriveleges don't work when HTTPContext is null. In console, HTTPContext is null.</p>
14,776
<p>The <code>unzip</code> command doesn't have an option for recursively unzipping archives.</p> <p>If I have the following directory structure and archives:</p> <pre> /Mother/Loving.zip /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes.zip </pre> <p>And I want to unzip all of the archives into directories with the same name as each archive:</p> <pre> /Mother/Loving/1.txt /Mother/Loving.zip /Scurvy/Sea Dogs/2.txt /Scurvy/Sea Dogs.zip /Scurvy/Cures/Limes/3.txt /Scurvy/Cures/Limes.zip </pre> <p>What command or commands would I issue?</p> <p>It's important that this doesn't choke on filenames that have spaces in them.</p>
<p>If you want to extract the files to the respective folder you can try this</p> <pre><code>find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done; </code></pre> <p>A multi-processed version for systems that can handle high I/O:</p> <pre><code>find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"' </code></pre>
<p>this works for me</p> <pre><code>def unzip(zip_file, path_to_extract): &quot;&quot;&quot; Decompress zip archives recursively Args: zip_file: name of zip archive path_to_extract: folder where the files will be extracted &quot;&quot;&quot; try: if is_zipfile(zip_file): parent_file = ZipFile(zip_file) parent_file.extractall(path_to_extract) for file_inside in parent_file.namelist(): if is_zipfile(os.path.join(os.getcwd(),file_inside)): unzip(file_inside,path_to_extract) os.remove(f&quot;{zip_file}&quot;) except Exception as e: print(e) </code></pre>
13,336
<p>Microsoft <a href="http://weblogs.asp.net/scottgu/archive/2008/09/28/jquery-and-microsoft.aspx" rel="nofollow noreferrer">recently announced</a> that the Javascript/HTML DOM library <strong>jQuery will be integrated</strong> into the ASP.NET MVC framework and into ASP.NET / Visual Studio.</p> <p>What is the best practice or strategy adopting jQuery using <strong>ASP.NET 2.0</strong>? I'd like to prepare a large, existing ASP.NET Web Application (<strong>not</strong> MVC) for jQuery. How would I deal with versioning and related issues?</p> <p>Are the any caveats integrating jQuery and <strong>ASP.NET Ajax</strong>? Or <strong>3rd party components</strong> like Telerik or Intersoft controls?</p>
<p>For me, problems arise when using UpdatePanels and jQuery (no problem with MVC, which doesn't have a Page Life-Cycle and is truly stateless). For instance, the useful jQuery idiom </p> <pre><code> $(function() { // some actions }); </code></pre> <p>used to enhance your DOM or attach events to the DOM elements may not interact very well with the ASP.NET PostBack model if there are UpdatePanels in the page. By now, I circumvent it with the following code snippet <pre><code> if (Sys.WebForms.PageRequestManager) { Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() { $('#updateListView1').trigger("gridLoaded"); }); } </pre></code> where <code>gridLoaded</code> will be the replacement of <code>$(document).ready</code>.</p> <p>I think you have to take extra care and know very well the ASP.NET Page/Controls Life-Cycle in order to mix both technologies.</p>
<p>There's a small issue which is mentioned by David Ward here: <a href="http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/" rel="nofollow noreferrer">http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/</a></p> <p>But there should not be any major concerns about integrating jQuery into an existing application, you wouldn't notice major advantages unless you're planning a lot of updating/ reworking of existing code to take advantages of jQuerys power.</p>
17,858
<p>It looks interesting and I've played around with it some --- but the development IDE in a web browser seems to be nightmare eventually.</p> <p>Does anyone have experience using it and what are your thoughts?</p>
<p>We evaluated GI a few months ago for a project but didn't end up selecting it.</p> <p>The IDE-in-a-browser (which is itself build with GI) actually works surprisingly well, though there are some features you normally expect from an editor that it lacks, most notably (and irritatingly) an Undo command. It's also impossible to do things like subdocument includes (practically a necessity for team development) from the IDE, though you can do them manually in the underlying XML and the IDE will respect them.</p> <p>In the end the main reason we didn't go with it was that it was difficult to make the resulting web application look as good as the designers really wanted. It was relatively easy to build functionality, but the components were very restrictive in look and feel. The way GI renders its own document model to HTML involves a lot of <code>style</code> attributes which makes skinning in CSS all but impossible. It seems to prefer making web applications that look like applications, instead of web applications that look like websites.</p> <p>So it would probably be great for building intranet type applications where look and feel isn't a huge issue, but I probably wouldn't use it to make a public facing site.</p> <p>By the way for those that don't know, TIBCO GI is a completely separate product from the rest of TIBCO's SOA business integration stuff - General Interface was a separate company that was acquired by TIBCO a couple of years ago.</p>
<p>Kieron does a good job of summarizing GI. It's really for enterprise web applications, not consumer-y widgets. The overhead of loading the entire GI framework and waiting a second or two for it to load doesn;t seem like much if you're firing up a call center or an employee provisioning application you're going to use for the next few hours. But, it seems like forever if you're waiting for a widget to load into an existing web page. And, even though, GI supports some nice functional and performance QA tools, they really are overkill unless you're working on something important and complex. So, if all you want is to toss a sexy looking datepicker on screen, use something else for sure.</p>
3,357
<p>We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:</p> <blockquote> <p>error initializing safe control - Assembly: ...</p> </blockquote> <p>The assembly actually loads fine. Additionally, it is correctly listed in the <code>web.config</code> and <code>GAC</code>.</p> <p>Any ideas about how to stop these (Phantom?) errors would be appreciated. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
<p>You need to add a safecontrol entry to the web,config file, have a look at the following:</p> <pre><code>&lt;SafeControls&gt; &lt;SafeControl Assembly = "Text" Namespace = "Text" Safe = "TRUE" | "FALSE" TypeName = "Text"/&gt; ... &lt;/SafeControls&gt; </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms413697.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms413697.aspx</a></p>
<p>This is because of the amount of list items in the lists. Your server takes to much time to migrate all the list items and it fails, try deleiting the list items or configuring the server.</p> <p>Regards, Mariano.</p>
4,546
<p>Macs are renowned (or bemoaned) for having an extensive number of shortcuts. However, OS X itself pales in comparison to the shortcut lists in <a href="http://macromates.com/" rel="noreferrer">TextMate</a> and its bundles.</p> <p>What are some useful keyboard shortcuts you use?</p>
<p>These are my favorite shortcuts:</p> <ul> <li><kbd>cmd</kbd>+<kbd>t</kbd> Start typing name of a file to open it</li> <li><kbd>ctrl</kbd>+<kbd>w</kbd> Select word</li> <li><kbd>cmd</kbd>+<kbd>r</kbd> Run the ruby or php-script that is open</li> <li><kbd>cmd</kbd>+<kbd>opt</kbd>+<kbd>m</kbd> Define a new macro</li> <li><kbd>cmd</kbd>+<kbd>shift</kbd>+<kbd>m</kbd> Run the macro</li> <li><kbd>opt</kbd> Switch to vertical selection mode</li> <li><kbd>cmd</kbd>+<kbd>opt</kbd>+<kbd>a</kbd> Edit ends of selected lines</li> </ul>
<p>(these are mostly html-related) </p> <ul> <li><kbd>cmd</kbd> + <kbd>option</kbd> <kbd>+</kbd> closes current open html tag </li> <li><kbd>shift</kbd> + <kbd>cmd</kbd> + <kbd>w</kbd> wrap selection in tags</li> <li><kbd>ctrl</kbd> + <kbd>return</kbd> insert escaped line end, i.e. <code>\n</code> or <code>&lt;br&gt;</code> depending on the occasion. </li> </ul>
12,503
<p>I need to know this since this is a pre-req for .NET 3.5 and if I'm including the .NET bootstrapper, I should also see if Windows Installer 3.1 is needed.</p> <p>Right now I'm checking for the registry key:</p> <pre><code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Updates\Windows XP\SP3\KB893803v2 </code></pre> <p>Which will check for Windows Installer 3.1 but I suspect it doesn't check for higher versions. (Haven't been able to confirm or deny that)</p> <p>What registry key should I look at to find this information?</p> <p>Edit: I need to check this in Inno Setup which is what I'm using as my bootstrapper, and I'm not sure how to check a dll version in there.</p>
<p>locate the installer msi.dll with this registry path: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Installer</p> <p>value: InstallerLocation</p> <p>then get the version information from that file.</p> <p>update: the way above is old! new way to detect the version is documented here: <a href="http://msdn.microsoft.com/en-us/library/aa368280%28VS.85%29.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa368280%28VS.85%29.aspx</a></p>
<p>Please check <a href="http://www.pitribe.com/posts.aspx?id=2603.1467569276_check-windows-installer-version" rel="nofollow">this link</a> may help you as already <strong>works for me</strong> for <strong>Windows 7</strong>, hopefully may work for other versions of <strong>windows</strong> as well to check Windows Installer version.</p>
40,757
<p>Are there any commonly used patterns in Javascript for storing the URL's of endpoints that will be requested in an AJAX application?</p> <p>For example would you create a "Service" class to abstract the URL's away?</p>
<p>You could create a collection of ValuePairs where you'd store each URL value and an identifier:</p> <pre><code>function ControlValuePair(Id, Value) { this.Id = Id; this.Value = Value; } function CreateCollection(ClassName) { var obj=new Array(); eval("var t=new "+ClassName+"()"); for(_item in t) { eval("obj."+_item+"=t."+_item); } return obj; } function ValuePairsCollection() { this.Container=""; this.Add=function(obj) { this.push(obj); } } </code></pre> <p>Later you can iterate through the collection or look up the id.</p>
<p>Is your question similar to <a href="https://stackoverflow.com/questions/108853/relative-urls-for-javascript-files">this already-answered question</a>? If so, does the answer apply to your code also?</p>
17,455
<p>Which industry-class database has the most <strong>unique</strong> features? (with "unique" meaning that no other RDBMS has them)</p> <p>I think my choice here is Oracle 11g:</p> <ol> <li>Flashback query (you can estract data as it was a moment in the past)</li> <li>ASM - automatic storage management</li> <li>Native code compilation of stored procedures</li> <li>Audit features (tracing everything, from logins to statements)</li> </ol> <p>and many others.</p>
<p>Funny, I rate vendors by their conformance with the ANSI/ISO SQL Standards e.g. for SQL Server my shopping list is deferrable <code>CHECK</code> constraints that support subqueries and proper support for <code>DOMAIN</code>s and <code>ASSERTION</code>s -- and these date from as long ago as SQL-92. For me, vendors should put in proprietary features only after they've implemented the Standard ones :)</p>
<p><a href="http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Comparison_of_relational_database_management_systems</a> &amp;&amp; <a href="http://en.wikipedia.org/wiki/Comparison_of_object-relational_database_management_systems" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Comparison_of_object-relational_database_management_systems</a> would be where I'd start.</p> <p>As to truly "unique" features? I've seen things I thought were unique that turned out to be common once I did more digging :)</p>
27,588
<p>I've got the a SQL Server stored procedure with the following T-SQL code contained within:</p> <pre><code>insert into #results ([ID], [Action], [Success], [StartTime], [EndTime], [Process]) select 'ID' = aa.[ActionID], 'Action' = cast(aa.[Action] as int), 'Success' = aa.[Success], 'StartTime' = aa.[StartTime], 'EndTime' = aa.[EndTime], 'Process' = cast(aa.[Process] as int) from [ApplicationActions] aa with(nolock) where 0 = case when (@loggingLevel = 0) then 0 when (@loggingLevel = 1 and aa.[LoggingLevel] = 1) then 0 end and 1 = case when (@applicationID is null) then 1 when (@applicationID is not null and aa.[ApplicationID] = @applicationID) then 1 end and 2 = case when (@startDate is null) then 2 when (@startDate is not null and aa.[StartTime] &gt;= @startDate) then 2 end and 3 = case when (@endDate is null) then 3 when (@endDate is not null and aa.[StartTime] &lt;= @endDate) then 3 end and 4 = case when (@success is null) then 4 when (@success is not null and aa.[Success] = @success) then 4 end and 5 = case when (@process is null) then 5 when (@process is not null and aa.[Process] = @process) then 5 end </code></pre> <p>It's that "dynamic" WHERE clause that is bothering me. The user doesn't have to pass in every parameter to this stored procedure. Just the ones that they are interested in using as a filter for the output.</p> <p>How would I go about using SQL Server Studio or Profiler to test whether or not this store procedure is recompiling every time?</p>
<p>Just offhand, you can simplify these:</p> <pre><code> 2 = case when (@startDate is null) then 2 when (@startDate is not null and aa.[StartTime] &gt;= @startDate) then 2 end </code></pre> <p>to this:</p> <pre><code> (@startDate is null OR aa.[StartTime] &gt;= @startDate) </code></pre> <p>As far as the recompile - is it declared <code>WITH RECOMPILE</code>?</p>
<p>Your inserting into a temp table in your example which causes the SP to be recompiled every time because it cannot be precompiled. </p> <p>This is one of the differences between using temp tables and table variables - a good article on the differences can be found <a href="http://www.codeproject.com/KB/database/SQP_performance.aspx" rel="nofollow noreferrer">here</a></p> <p>Pertinent extract...</p> <blockquote> <p>The second major difference is that any procedure with a temporary table cannot be pre-compiled, while an execution plan of procedures with table-variables can be statically compiled in advance. Pre-compiling a script gives a major advantage to its speed of execution. This advantage can be dramatic for long procedures, where recompilation can be too pricy.</p> </blockquote>
41,314
<p>I am putting together a Samba-based server as a Primary Domain Controller, and ran into a cute little problem that should have been solved many times over. But a number of searches did not yield a result. I need to be able to remove an existing user from an existing group with a command line script. It appears that the usermod easily allows me to add a user to a supplementary group with this command:</p> <pre><code>usermod -a -G supgroup1,supgroup2 username </code></pre> <p>Without the "-a" option, if the user is currently a member of a group which is not listed, the user will be removed from the group. Does anyone have a perl (or Python) script that allows the specification of a user and group for removal? Am I missing an obvious existing command, or well-known solution forthis? Thanks in advance!</p> <p>Thanks to J.J. for the pointer to the Unix::Group module, which is part of Unix-ConfigFile. It looks like the command deluser would do what I want, but was not in any of my existing repositories. I went ahead and wrote the perl script using the Unix:Group Module. Here is the script for your sysadmining pleasure.</p> <pre><code>#!/usr/bin/perl # # Usage: removegroup.pl login group # Purpose: Removes a user from a group while retaining current primary and # supplementary groups. # Notes: There is a Debian specific utility that can do this called deluser, # but I did not want any cross-distribution dependencies # # Date: 25 September 2008 # Validate Arguments (correct number, format etc.) if ( ($#ARGV &lt; 1) || (2 &lt; $#ARGV) ) { print "\nUsage: removegroup.pl login group\n\n"; print "EXIT VALUES\n"; print " The removeuser.pl script exits with the following values:\n\n"; print " 0 success\n\n"; print " 1 Invalid number of arguments\n\n"; print " 2 Login or Group name supplied greater than 16 characters\n\n"; print " 3 Login and/or Group name contains invalid characters\n\n"; exit 1; } # Check for well formed group and login names if ((16 &lt; length($ARGV[0])) ||(16 &lt; length($ARGV[1]))) { print "Usage: removegroup.pl login group\n"; print "ERROR: Login and Group names must be less than 16 Characters\n"; exit 2; } if ( ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$}) || ( $ARGV[0] !~ m{^[a-z_]+[a-z0-9_-]*$} ) ) { print "Usage: removegroup.pl login group\n"; print "ERROR: Login and/or Group name contains invalid characters\n"; exit 3; } # Set some variables for readability $login=$ARGV[0]; $group=$ARGV[1]; # Requires the GroupFile interface from perl-Unix-Configfile use Unix::GroupFile; $grp = new Unix::GroupFile "/etc/group"; $grp-&gt;remove_user("$group", "$login"); $grp-&gt;commit(); undef $grp; exit 0; </code></pre>
<p>Web Link: <a href="http://www.ibm.com/developerworks/linux/library/l-roadmap4/" rel="nofollow noreferrer">http://www.ibm.com/developerworks/linux/library/l-roadmap4/</a></p> <p>To add members to the group, use the gpasswd command with the -a switch and the user id you wish to add:</p> <p>gpasswd -a userid mygroup</p> <p>Remove users from a group with the same command, but a -d switch rather than -a:</p> <p>gpasswd -d userid mygroup </p> <p>"man gpasswd" for more info...</p> <p>I looked for ages to find this. Sometimes it takes too much effort not to reinvent the wheel...</p>
<p>It looks like <em>deluser --group [groupname]</em> should do it.</p> <p>If not, the <em>groups</em> command lists the groups that a user belongs to. It should be fairly straightforward to come up with some Perl to capture that list into an array (or <em>map</em> it into a hash), delete the unwanted group(s), and feed that back to <em>usermod</em>.</p>
15,677
<p>I was in need of a way to compress images in .net so i looked into using the .net GZipStream class (or DeflateStream). However i found that decompression was not always successful, sometimes the images would decompress fine and other times i would get a GDI+ error that something is corrupted.</p> <p>After investigating the issue i found that the decompression was not giving back all the bytes it compressed. So if i compressed 2257974 bytes i would sometimes get back only 2257870 bytes (real numbers).</p> <p>The most funny thing is that sometimes it would work. So i created this little test method that compresses only 10 bytes and now i don't get back anything at all.</p> <p>I tried it with both compression classes GZipStream and DeflateStream and i double checked my code for possible errors. I even tried positioning the stream to 0 and flushing all the streams but with no luck.</p> <p>Here is my code:</p> <pre><code> public static void TestCompression() { byte[] test = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; byte[] result = Decompress(Compress(test)); // This will fail, result.Length is 0 Debug.Assert(result.Length == test.Length); } public static byte[] Compress(byte[] data) { var compressedStream = new MemoryStream(); var zipStream = new GZipStream(compressedStream, CompressionMode.Compress); zipStream.Write(data, 0, data.Length); return compressedStream.ToArray(); } public static byte[] Decompress(byte[] data) { var compressedStream = new MemoryStream(data); var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress); var resultStream = new MemoryStream(); var buffer = new byte[4096]; int read; while ((read = zipStream.Read(buffer, 0, buffer.Length)) &gt; 0) { resultStream.Write(buffer, 0, read); } return resultStream.ToArray(); } </code></pre>
<p>You need to <code>Close()</code> the <code>ZipStream</code> after adding all the data you want to compress; it retains a buffer of unwritten bytes internally (even if you <code>Flush()</code>) that needs to be written.</p> <p>More generally, <code>Stream</code> is <code>IDisposable</code>, so you should also be <code>using</code> each... (yes, I know that <code>MemoryStream</code> isn't going to lose any data, but if you don't get into this habit, it will bite you with other <code>Stream</code>s).</p> <pre><code>public static byte[] Compress(byte[] data) { using (var compressedStream = new MemoryStream()) using (var zipStream = new GZipStream(compressedStream, CompressionMode.Compress)) { zipStream.Write(data, 0, data.Length); zipStream.Close(); return compressedStream.ToArray(); } } public static byte[] Decompress(byte[] data) { using(var compressedStream = new MemoryStream(data)) using(var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress)) using (var resultStream = new MemoryStream()) { ... } } </code></pre> <p>[edit : updated re comment] Re not <code>using</code> things like <code>MemoryStream</code> - this is always a fun one, with lots of votes on either side of the fence: but ultimatey...</p> <p>(rhetorical - we all know the answer...) How is <code>MemoryStream</code> implemented? is it a byte[] (owned by .NET)? is it a memory-mapped file (owned by the OS)?</p> <p>The reason you aren't <code>using</code> it is because you are letting knowledge of internal implementation details change how you code against a public API - i.e. you just broke the laws of encapsulation. The public API says: I am <code>IDisposable</code>; you "own" me; therefore, it is your job to <code>Dispose()</code> me when you are through.</p>
<p>Also - keep in mind the DeflateStream in System.IO.Compression does not implement the most efficient deflate algorithm. If you like, there is an alternative to the BCL GZipStream and DeflateStream; it is implemented in a fully-managed library based on zlib code, that performs better than the built-in {Deflate,GZip}Stream in this respect. [ But you still need to Close() the stream to get the full bytestream. ] </p> <p>These stream classes are shipped in the DotNetZlib assembly, available in the DotNetZip distribution at <a href="http://DotNetZip.codeplex.com/" rel="nofollow noreferrer">http://DotNetZip.codeplex.com/</a>. </p>
34,107
<p>The code below continues many lines until it ends with a expected /veotherwise /vechoose. I started working on a development firm a little ago where they use this html version called vhtml. I have search the web but it brings different definitions for vhtml. I have seen some posts in Joomla about vhtml but they don't look like the code below. I was expecting to get a pointer on how to understand the language. </p> <p>It looks very similar to normal html with even very similar commands, or maybe smalltalk. But I just can decipher it. Any help will be appreciated. Please post comments if you want more information.</p> <pre><code>&lt;vechoose&gt; &lt;vewhen criteria='isPortalEdit'&gt; widget: practices-landing-page &lt;/vewhen&gt; &lt;veotherwise&gt; &lt;veinclude src='private/webportal/webtemplate-content.vhtml'&gt; &lt;vesection name='content-body'&gt; &lt;% // Determine portlet visibility %&gt; &lt;vecalc expression='isEmpty = false' output='none' /&gt; &lt;vechoose&gt; &lt;vewhen criteria='isEmpty'&gt; &lt;veif criteria='portlet.ifEmptyDo == "Hide"'&gt; &lt;script&gt;getTag( 'portlet_&lt;%=portlet.order%&gt;' ).style.display = "none";&lt;/script&gt; &lt;/veif&gt; &lt;veif criteria='portlet.ifEmptyDo == "Show Message"'&gt; &lt;%#portlet.ifEmptyMessage%&gt; &lt;/veif&gt; &lt;/vewhen&gt; ... </code></pre>
<p>I looked through the help and didn't see a full list...so poking around the code it appears the compiler warning constants are all listed in: CodeGear\RAD Studio\6.0\sources\toolsapi\DCCStrs.pas</p> <p>Search for "Implicit_String_Cast_Loss" and you'll see the constant sIMPLICIT_STRING_CAST_LOSS = 'DCC_IMPLICIT_STRING_CAST_LOSS';</p> <p>I would assume the rest of the DCC_xxx strings with corresponding X_true/_false/_error defines are what you are after.</p> <p>Online help hasn't been very good since Delphi 7.</p>
<p>If you press <em>Ctrl+O</em> twice it will add all the compiler directives to the top of the unit including all the warnings. Find the one you want and delete the rest.</p>
49,330
<p>Is there any way to set the style for the lineends for the TCanvas.LineTo method? It seems to default to rounded ends, which looks very bad for several lines in a row of different colours when Pen.Width is set to a large value (e.g. 9).</p> <p>It looks like this (rounded ends):</p> <pre><code> ********........****** **********........****** **********........****** ********........****** </code></pre> <p>(where * is e.g. blue and . is yellow)</p> <p>It is even worse if the two outer lines are drawn after the middle line:</p> <pre><code> ********........****** **********......******** **********......******** ********........****** </code></pre> <p>I'd like it to look like this (streight ends):</p> <pre><code> ********........****** ********........****** ********........****** ********........****** </code></pre> <p>Pen does not seem to offer any setting for this and neither does the LineTo method. Is there maybe a windows API function I could call?</p>
<p>Maybe <a href="https://msdn.microsoft.com/en-us/library/dd162705(v=vs.85).aspx" rel="nofollow noreferrer">ExtCreatePen</a> helps. Check the <code>PS_ENDCAP_*</code> and <code>PS_JOIN_*</code> flags.</p>
<p>Sample code from <a href="https://www.delphipraxis.net/92808-tcanvas-pen-und-die-abgerundeten-ecken.html" rel="nofollow noreferrer">DelphiPraxis forum (German language)</a></p> <pre><code>procedure TForm1.FormCreate(Sender: TObject); var LogBrush:TLOGBRUSH; begin ZeroMemory(@LogBrush, SizeOf(LogBrush)); LogBrush.lbColor:=ColorToRGB(Canvas.Pen.Color); LogBrush.lbHatch:=0; DeleteObject(Canvas.Pen.Handle); Canvas.Pen.Handle:=ExtCreatePen(PS_Geometric or PS_Solid or PS_EndCap_Square or PS_Join_Miter, 10, LogBrush, 0, nil); end; procedure TForm1.FormPaint(Sender: TObject); begin Canvas.MoveTo(0, 0); Canvas.LineTo(50, 50); end; </code></pre>
48,100
<p>I want to be able to apply a style at runtime to an object <strong>ONLY</strong> if the current style is the default style. I don't want to override any user defined styles. Anyone know how to do this?</p>
<p>It appears you can do it this way:</p> <pre><code>DependencyPropertyHelper.GetValueSource( someControl, FrameworkElement.StyleProperty).BaseValueSource == BaseValueSource.Default; </code></pre> <p>You can wrap that up in an extension method like this:</p> <pre><code>static public bool HasDefaultStyle(this FrameworkElement item) { return DependencyPropertyHelper.GetValueSource( item, FrameworkElement.StyleProperty).BaseValueSource == BaseValueSource.Default; } </code></pre> <p>Then you can just call <code>someControl.HasDefaultStyle()</code>.</p> <p>Also, have a look at this article: <a href="http://www.interact-sw.co.uk/iangblog/2007/02/14/wpfdefaulttemplate" rel="nofollow noreferrer">Default Templates in WPF</a></p>
<p>Check the DefaultStyleKeyProperty, which is a static property of any custom control.</p> <pre><code>string styleKeyName = DefaultStyleKeyProperty.Name; </code></pre> <p>Usually if there is no style associated with the control, the Name will be "DefaultStyleKey"</p>
43,978
<p>If for example you follow the link:</p> <p><code>data:application/octet-stream;base64,SGVsbG8=</code></p> <p>The browser will prompt you to download a file consisting of the data held as base64 in the hyperlink itself. Is there any way of suggesting a default name in the markup? If not, is there a JavaScript solution?</p>
<p>Use the <code>download</code> attribute:</p> <pre><code>&lt;a download='FileName' href='your_url'&gt; </code></pre> <p><a href="http://caniuse.com/#search=download" rel="noreferrer">The <code>download</code> attribute works on</a> Chrome, Firefox, Edge, Opera, desktop Safari 10+, iOS Safari 13+, and not IE11.</p>
<pre><code>var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6 var sessionId ='\n'; var token = '\n'; var caseId = CaseIDNumber + '\n'; var url = casewebUrl+'\n'; var uri = sessionId + token + caseId + url;//data in file var fileName = "file.i4cvf";// any file name with any extension if (isIE) { var fileData = ['\ufeff' + uri]; var blobObject = new Blob(fileData); window.navigator.msSaveOrOpenBlob(blobObject, fileName); } else //chrome { window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(window.TEMPORARY, 1024 * 1024, function (fs) { fs.root.getFile(fileName, { create: true }, function (fileEntry) { fileEntry.createWriter(function (fileWriter) { var fileData = ['\ufeff' + uri]; var blob = new Blob(fileData); fileWriter.addEventListener("writeend", function () { var fileUrl = fileEntry.toURL(); var link = document.createElement('a'); link.href = fileUrl; link.download = fileName; document.body.appendChild(link); link.click(); document.body.removeChild(link); }, false); fileWriter.write(blob); }, function () { }); }, function () { }); }, function () { }); } </code></pre>
36,017
<p>I'm wondering how the few Delphi users here are doing unit testing, if any? Is there anything that integrates with the IDE that you've found works well? If not, what tools are you using and do you have or know of example mini-projects that demonstrate how it all works?</p> <h3>Update:</h3> <p>I forgot to mention that I'm using BDS 2006 Pro, though I occasionally drop into Delphi 7, and of course others may be using other versions.</p>
<p><a href="http://dunit.sourceforge.net/" rel="noreferrer">DUnit</a> is a xUnit type of unit testing framework to be used with win32 Delphi. Since Delphi 2005 DUnit is integrated to a certan point into the IDE. Other DUnit integration tools for the Delphi IDE can be found <a href="http://www.elvenware.com/charlie/conferences/2004/talks/UnitTests/dunit/test_tools/index.html" rel="noreferrer">here</a>. DUnit comes with <a href="http://dunit.sourceforge.net/README.html" rel="noreferrer">documentation with examples</a>.</p>
<p>We tried to use DUnit with Delphi 5, but it didn't work well. Specially if you are implementing COM interfaces, we found many dependencies to setup all the test infrastructure. I don't know if the test support has improved in newer versions.</p>
3,890
<p>XP-specific answers preferred, but others are welcome too.</p>
<p>From <code>%windir%\System32\Shell32.dll</code></p>
<p>From <code>%windir%\System32\Shell32.dll</code></p>
21,994
<pre><code>&lt;div style="width: 300px"&gt; &lt;div id="one" style="float: left"&gt;saved&lt;/div&gt;&lt;input type="submit" id="two" style="float: right" value="Submit" /&gt; &lt;/div&gt; </code></pre> <p>I would like div#one to be centred in the space between the left edge of the parent div and the left edge of the submit button.</p>
<p>A few more ways to do it:</p> <pre><code>&lt;div style="width: 300px"&gt; &lt;input type="submit" id="two" style="float: right" value="Submit" /&gt; &lt;div id="one" style="text-align:center;"&gt;saved&lt;/div&gt; &lt;/div&gt; </code></pre> <p>It's hard to tell that the text <code>saved</code> isn't centered between the left edge of the container <code>div</code> and the left edge of the submit button.</p> <p>Here is an exact version of the above:</p> <pre><code>&lt;div style="width: 300px;"&gt; &lt;input type="submit" id="two" style="float: right; width:64px;" value="Submit" /&gt; &lt;div id="one" style="text-align:center;margin-right:64px;"&gt;saved&lt;/div&gt; &lt;/div&gt; </code></pre>
<p>This is an example of a general problem with CSS, which is that there is no way to compute the 'remaining space' in various layouts. </p> <p>I've run into situations where you (a) need an exact layout, and (b) where you don't know the size of the floating item.</p> <p>Example:</p> <blockquote> <p>[---- input field that takes 100% of the remaining space ----] [button of unknown width] </p> </blockquote> <p>You would think that this was possible, but AFAIK, you have to use tables to achieve this. There isn't even a proposal in CSS for how this would be fixed in the future. <em>sigh</em></p>
28,382
<p>I get an Access is Denied error message when I use the strong name tool to create a new key to sign a .NET assembly. This works just fine on a Windows XP machine but it does not work on my Vista machine.</p> <pre><code>PS C:\users\brian\Dev\Projects\BELib\BELib&gt; sn -k keypair.snk Microsoft (R) .NET Framework Strong Name Utility Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Failed to generate a strong name key pair -- Access is denied. </code></pre> <p>What causes this problem and how can I fix it?</p> <hr> <blockquote> <p>Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look until you get used to User Access Control or by turning User Access Control off.</p> </blockquote> <p>Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up.</p>
<blockquote> <p>Yes I have tried running PS and the regular command prompt as administrator. The same error message comes up.</p> </blockquote> <p>Another possible solution could be that you need to give your user account access to the key container located at C:\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys</p>
<p>Are you running your PowerShell or Command Prompt as an Administrator? I found this to be the first place to look until you get used to User Access Control or by turning User Access Control off.</p>
3,300
<p>I'm looking to run a Jabber server on a Windows 2003 server(web farm) and like some practical advice from anyone who has run a live environment with ~500 concurrent users.</p> <p>Criteria for comment:</p> <ul> <li>Performance</li> <li>Capacity (ie ~number of concurrent users)</li> <li>Stability</li> </ul>
<p>OpenFire is a good gpl java implementation of a jabber server. It has plenty of option plugins you can use and it can intergrate quite well with Active Directory <a href="http://www.igniterealtime.org/projects/openfire/index.jsp" rel="noreferrer">OpenFire</a></p>
<p>I think you're going to need to be a bit more explicit - you looking for server configurations, or software e.g. Jabber Server?</p> <p>If you're thinking Jabber server, <a href="http://www.ejabberd.im/" rel="nofollow noreferrer">EJabberD</a> is probably the most stable, flexible, capable of being clustered etc.</p> <p>Really useful comparison of Open Source servers here...</p> <p><a href="http://www.saint-andre.com/jabber/jsc/" rel="nofollow noreferrer">http://www.saint-andre.com/jabber/jsc/</a></p>
12,833
<p>(y/N)</p> <p>Edit: Read-only access is fine.</p>
<p>I haven't tried this yet, but I think I've found a workaround.</p> <p>Adobe AIR cannot write to Windows Registry, but you can, however, launch a native process in AIR 2. Here's a blog post that shows how to do that: <a href="http://www.adobe.com/devnet/air/flex/quickstart/articles/interacting_with_native_process.html" rel="noreferrer">http://www.adobe.com/devnet/air/flex/quickstart/articles/interacting_with_native_process.html</a></p> <p>Now, on Windows, you are able to modify the Windows registry with .reg files. .reg files are just plain text files that's read by regedit.exe. So in theory, you can write a .reg file to the file system, then launch regedit.exe with the .reg file passed in and...TADA! You just modified Windows registry from your AIR app!</p> <p>To read value, you can use regedit's export function to write to a reg file and read from the reg file. Details to regedit's options: <a href="http://www.robvanderwoude.com/regedit.php" rel="noreferrer">http://www.robvanderwoude.com/regedit.php</a></p> <p>Here are some additional resources:<br/> .reg file syntax: <a href="http://support.microsoft.com/kb/310516" rel="noreferrer">http://support.microsoft.com/kb/310516</a><br/> write to file with AIR: <a href="http://www.adobe.com/devnet/air/flex/articles/exploring_file_capabilities.html" rel="noreferrer">http://www.adobe.com/devnet/air/flex/articles/exploring_file_capabilities.html</a></p>
<p>You could theoretically modify the actual registry files, but I would highly discourage that idea.</p>
2,573
<p>What is the difference between <code>int *a[3]</code> and <code>int (*a)[3]</code>?</p>
<p>There is no difference between <code>int a[3]</code> and <code>int (a)[3]</code>, they both declare <code>a</code> as an array of 3 <code>int</code>s. There is a difference between <code>int *a[3]</code> and <code>int (*a)[3]</code>, the former declares an array of 3 pointers to <code>int</code> whereas the second declares a pointer to an array of 3 <code>int</code>s. The parenthesis make a difference here because in C brackets have a higher precedence than *.</p>
<p><code>int *a[3]</code> : a is a array of 3 pointers to integer type</p> <p><code>int (*a)[3]</code> : a is a pointer to an array of 3 integer type</p>
31,114
<p>How do I convert function input parameters to the right type?</p> <p>I want to return a string that has part of the URL passed into it removed.</p> <p><strong>This works, but it uses a hard-coded string:</strong></p> <pre><code>function CleanUrl($input) { $x = "http://google.com".Replace("http://", "") return $x } $SiteName = CleanUrl($HostHeader) echo $SiteName </code></pre> <p><strong>This fails:</strong></p> <pre><code>function CleanUrl($input) { $x = $input.Replace("http://", "") return $x } Method invocation failed because [System.Array+SZArrayEnumerator] doesn't contain a method named 'Replace'. At M:\PowerShell\test.ps1:13 char:21 + $x = $input.Replace( &lt;&lt;&lt;&lt; "http://", "") </code></pre>
<p>The concept here is correct.</p> <p>The problem is with the variable name you have chosen. $input is a reserved variable used by PowerShell to represent an array of pipeline input. If you change your variable name, you should not have any problem.</p> <p>PowerShell does have <a href="https://technet.microsoft.com/en-us/library/hh847759.aspx" rel="nofollow noreferrer">a replace operator</a>, so you could make your function into</p> <pre><code>function CleanUrl($url) { return $url -replace 'http://' } </code></pre>
<p>This worked for me:</p> <pre><code>function CleanUrl($input) { return $input.Replace("http://", "") } </code></pre>
3,586
<p>I am working on developing an on-screen keyboard with java. This keyboard has a <code>JComponent</code> for every possible key. When a mouse down is detected on the button, I want to send a specific keyboard code to the application currently on focus. The keyboard itself is within a <code>JFrame</code> with no decorations and set to always-on-top.</p> <p>I found that the Robot class can be used to simulate these keyboard events on the native queue. However, in this case, selecting the <code>JComponent</code> would mean that the key-press is received on the <code>JFrame</code>, and I wouldn't be able to receive it in the other application</p> <p>How can I keep my on-screen keyboard "Always-without-focus"? Is it maybe possible to use another approach to send the key-press? </p>
<p>Apparently the only way to do this is to have a JNI layer that will make the conversion from java to native. Java has no easy way to provide such funcionality.</p> <p>This could be an interesting concept for a small, third party library for someone who wants to learn JNI...</p>
<p>have you tried to call native setfocus() or setactivewindow() functions to move focus before you use robot class?</p>
18,989
<p>how to validate letters and whitespaces using Zend Framework ?</p>
<p>The Zend Framework does have a <a href="http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.alpha" rel="nofollow noreferrer">Zend_Validate_Alpha</a> (as well as an <a href="http://framework.zend.com/manual/en/zend.validate.set.html#zend.validate.set.alnum" rel="nofollow noreferrer">alphanumeric version</a>).</p> <p>Normally it doesn't allow white space, but if you pass a <code>true</code> into the constructor of the <a href="http://framework.zend.com/apidoc/core/Zend_Validate/Zend_Validate_Alpha.html#__construct" rel="nofollow noreferrer">Zend_Validate_Alpha</a> class it will allow whitespace. Same with <a href="http://framework.zend.com/apidoc/core/Zend_Validate/Zend_Validate_Alnum.html#__construct" rel="nofollow noreferrer">Zend_Validate_Alnum</a>.</p> <p>For example:</p> <pre><code>$validator = new Zend_Validate_Alpha(true); //will allow whitespace and non number letters </code></pre>
<p>i think Zend_Validate_Regex is best for this situation</p>
44,190
<p>How do you select a datagridview row on a right-click?</p>
<p>Make it behave similarly to the left mouse button? e.g.</p> <pre><code>private void dataGridView_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.Button == MouseButtons.Right) { dataGridView.CurrentCell = dataGridView[e.ColumnIndex, e.RowIndex]; } } </code></pre>
<p>You can use JvR's code in the MouseDown event of your DataGridView.</p>
20,879
<p>I ran into this bug where an element of an array, if its index is the string "0", is inaccessible. </p> <p>It's not a bug with unserialize, either, as this occurred in my code without invoking it.</p> <pre><code>$arr = unserialize('a:1:{s:1:"0";i:5;}'); var_dump($arr["0"]); //should be 5, but is NULL var_dump($arr[0]); //maybe this would work? no. NULL </code></pre> <p>Am I doing something wrong here? How do I access this element of the array?</p>
<p>Yes, it looks as though it is a bug, related to PHPs automatic conversion of strings to integers. More information is available here: <a href="http://bugs.php.net/bug.php?id=43614" rel="nofollow noreferrer">http://bugs.php.net/bug.php?id=43614</a></p> <pre><code>var_dump( $arr ); // =&gt; array(1) { ["0"]=&gt; int(5) } $arr2["0"]=5; var_dump($arr2); // =&gt; array(1) { [0]=&gt; int(5) } print serialize($arr2); // a:1:{i:0;i:5;} </code></pre> <p>So it seems that older versions of PHP5 don't perform the string index to integer index conversion in unserialize.</p> <p>This bug was reported in PHP 5.2.5, and is fixed in PHP 5.2.6 (see <a href="http://www.php.net/ChangeLog-5.php#5.2.6" rel="nofollow noreferrer">http://www.php.net/ChangeLog-5.php#5.2.6</a>).</p>
<p>Actually, the code in your question yields</p> <pre><code>int(5) </code></pre>
40,842
<p>What is the best way to create reverse index for full text search in Common Lisp ? Is there any proven and (relatively) bug-free open library for SBCL or LispWorks ?</p> <p>I managed to create my own library on top of AllegroCache - it was fairly easy to create, reliable and fast, but lacks advanced search options (phrases, wildcarded words in phrases, etc).</p> <p>Is there any open library that can be used with SBCL or LispWorks so I don't have to reinvent the wheel by writing my own ?</p>
<p><a href="http://www.cl-user.net/asp/libs/montezuma" rel="noreferrer">montezuma</a> is the same thing as lucene, but written in lisp.</p> <p>i don't think anyone uses this actively, nor that it's heavily tested... but it's a good start if you want to work on the thing itself. it already has the most used features. read the google-group archive to get a feel...</p>
<p>I know you're asking about Common Lisp, but there are a number of inverted text search service oriented applications. One well known and respected on is <a href="http://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a>.</p> <p>Could a solution be to use that search engine, but interface your Common Lisp code via a web-service API? (xml-rpc, xml over http or just text over http)? </p> <p>Is there a further reason why you'd like it to be in Common Lisp? Packages like Lucene may cover all the search related features you need, while using a remote api may still allow you to perform your more complex logic in Common Lisp.</p>
15,568
<p>In short, how do you unit test an error condition such as EINTR on a system call.</p> <p>One particular example I'm working on, which could be a case all by itself, is whether it's necessary to call fclose again when it returns EOF with (errno==EINTR). The behavior depends on the implementation of fclose:</p> <pre><code>// Given an open FILE *fp while (fclose(fp)==EOF &amp;&amp; errno==EINTR) { errno = 0; } </code></pre> <p>This call can be unsafe if fp freed when EINTR occurs. How can I test the error handling for when (errno==EINTR)?</p>
<p>I don't think there is an easy way to actually test this at will.</p> <p>EINTR will be generated if the fclose operation is interrupted by a signal. This implies that fclose was in a background thread which received a signal as it was processing the close request.</p> <p>Good luck trying to reproduce that set of circumstances.</p>
<p>As Kris suggests, temporarily replace calls to the "real" <code>fclose()</code> with your own implementation defined in your unit test code. Your implementation could do something as simple as:</p> <pre><code>int my_fclose(FILE *fp) { errno = EINTR; return EOF; } </code></pre> <p>But, as fizzer points out, you shouldn't call <code>fclose()</code> again as the behavior is undefined, so you needn't bother even checking for the condition.</p> <p>The other question to ask is whether you really need to worry about this; if your application code were to block all possible signals (except SIGKILL and SIGSTOP) during your <code>fclose()</code> then you wouldn't get a EINTR and wouldn't need to worry at all.</p>
21,264
<p>I have a requirement to be be able to embed scanned tiff images into some SSRS reports.</p> <p>When I design a report in VS2005 and add an image control the tiff image displays perfectly however when I build it. I get the warning :</p> <p><code>Warning 2 [rsInvalidMIMEType] The value of the MIMEType property for the image ‘image1’ is “image/tiff”, which is not a valid MIMEType. c:\SSRSStuff\TestReport.rdl 0 0</code></p> <p>and instead of an image I get the little red x.</p> <p>Has anybody overcome this issue?</p>
<p>Assuming you're delivering the image file via IIS, use an ASP.NET page to change image formats and mime type to something that you <em>can</em> use. </p> <pre><code>Response.ContentType = "image/png"; Response.Clear(); using (Bitmap bmp = new Bitmap(tifFilepath)) bmp.Save(Response.OutputStream, ImageFormat.Png); Response.End(); </code></pre>
<p>Thanks <a href="https://stackoverflow.com/users/19931/peter-wone">Peter</a> your code didn't compile but the idea was sound.</p> <p>Here is my attempt that works for me.</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { Response.ContentType = "image/jpeg"; Response.Clear(); Bitmap bmp = new Bitmap(tifFileLocation); bmp.Save(Response.OutputStream, ImageFormat.Jpeg); Response.End(); } </code></pre>
15,397
<p>I was watching a tutorial on Rails and was very impressed that you could so easily create an editing system for a class just by defining it.</p> <p>Can this be done in ASP.NET?</p> <p>I know there are ORMs out there, but do they come with an editing system?</p> <p>To explain what I mean by an editing system, consider a class for defining people</p> <pre><code>class Person { string First_Name; string Last_Name } </code></pre> <p>And then perhaps with one bold stroke something like this:</p> <pre><code>CreateEditAbleClass(Person) </code></pre> <p>You would get the functionality below in a browser:</p> <p><a href="http://www.yart.com.au/images/orm_editor.jpg" rel="nofollow noreferrer">http://www.yart.com.au/images/orm_editor.jpg</a></p> <p>And this functionality would extend to all the UML definitions – inheritance, association, aggregation etc. In addition, there would be a simple way of adding customisable validation and so forth.</p> <p>I currently use DataGrids and a lot of manual coding to achieve these results.</p>
<p>First of all, change your function to <code>return</code> the value. <code>print</code>ing it will complicate things since you want to get the value back. Suppose your <code>MyModule.py</code> looks like this:</p> <pre><code>import thirdparty def MyFunc(some_arg): result = thirdparty.go() return result </code></pre> <p>Now, to do what you want, you have to go beyond basic embedding, as the <a href="http://docs.python.org/extending/embedding.html" rel="noreferrer">documentation says</a>. Here is the full code to run your function:</p> <pre><code>#include &lt;Python.h&gt; int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pArg, *pResult; int i; Py_Initialize(); pName = PyString_FromString("MyModule.py"); /* Error checking of pName left out as exercise */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, "MyFunc"); /* pFunc is a new reference */ if (pFunc) { pArgs = PyTuple_New(0); pArg = PyString_FromString("some parameter") /* pArg reference stolen here: */ PyTuple_SetItem(pArgs, 0, pArg); pResult = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pResult != NULL) { printf("Result of call: %s\n", PyString_AsString(pResult)); Py_DECREF(pResult); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function"); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load module"); return 1; } Py_Finalize(); return 0; } </code></pre>
<p>You should be able to return the result from MyFunc, which would then end up in the variable you are currently calling "ignored". This eliminates the need to access it in any other way.</p>
26,523
<p>In a client-server system, is it considered good architecture for a server method to "ask the client" for more information? If so, what's the best way to design such a scenario? Is there a "pattern" for this?</p> <p>For example, suppose the end user selects a set of records they want to delete in the client UI, then the client makes a "delete records" call to the server with the set of records as a parameter. Then the server finds a subset of those records which are "special" in some way and thus need to be confirmed by the user. Is it appropriate for the server to somehow "call back" to the client to a method called "confirm records" while still continuing the original call from the client to the server?</p> <p>And what about more complex server calls that could require a long "dialog" between server and client?</p>
<p>Some sort of reply that say "Records x, y and z were not deleted, try again with <code>I_RELLY_WANT_TO</code> set to delete them" would seem like a reasonable solution to me.</p> <p>General pattern; don't ask, do stuff and report back, let the client decide what to do next. This could be done in the context of a persistent connection as a form of dialog.</p> <p>Not really my field so... add 64mg NaCl</p>
<p>I think that kind of arrangement is totally fine. There's nothing preventing the server from replying with a query to the client for more information and for the client to provide it. As long as the socket connection is open, you have free reign to send messages back and forth.</p> <p>I've seen an arrangement where the client sent a message to the server and after that didn't do much more than be a small layer above stdin/out and the file-system on the local machine as the server controlled it. It worked fine and was very fast.</p>
47,164
<p>we'd like to add movable panels to an application. presently we've used DevExpress docking library but have found them to be disappointingly quirky &amp; difficult to work with. it also has some limitations that aren't so great.</p> <p>auto-hide, pinning, and moving of pages by drag-and-drop are all features we'd like to use.</p> <p>the built-in delphi docking doesn't seem to be full-featured enough to do the things we need (also see sample below). perhaps i should dig deeper into delphi's docking abilities...my initial impression is that they seem very toolbar-oriented rather than something i can drop a frame into.</p> <p>i'm not experienced at docking topics. my only experience has been with the DevExpress docking library where i needed to programmatically create &amp; dock panels.</p> <p><a href="https://i.stack.imgur.com/f8REv.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/f8REv.gif" alt="screenshot"></a></p> <p>is it my imagination or are DevExpress's products unduly difficult to use/learn? the DevExpress Ribbon Bar component compared to the d2009 Ribbon Bar was certainly a useful experience. i will migrate to the d2009 Ribbon Bar as soon as convenient to do so. it was refreshingly straight-forward to learn and use. a sharp contrast compared to the DevExpress equivalent. if it takes 4x as longer to make it using the DevExpress equivalent, it's time to change direction.</p> <p>what would <em>you</em> suggest in regard to the docking library?</p> <p>thank you for your suggestions/comments!</p>
<p>AutomatedDocking <a href="http://www.automatedqa.com/products/aqdocking/index.asp" rel="nofollow noreferrer">http://www.automatedqa.com/products/aqdocking/index.asp</a></p> <p>and for free one JVCL Docking <a href="http://jvcl.delphi-jedi.org/" rel="nofollow noreferrer">http://jvcl.delphi-jedi.org/</a></p>
<p>I'm glad to read your post, I'm using Automated QA' docking components, and I'm fed up with them. I was considering switching to DevExpress, but I think I willl give it a second thought now. The most problematic with AutomatedQA's component is bugs, sometimes floating windows disappears, when pinned panels are unpinned and stuff like this.</p> <p>AutomatedQA does not offer a decent support and new releases should not be expected on a yearly basis, even if you have pointed out a bug that can be easily reproduced. I have a suspicion that the docking framework doesn't get much focus within AutomatedQA.</p> <p>I gues one have to turn to the built in VCL or perhaps JEDI, but I can't find any valuable samples (the mediocre docking sample included with Delphi does not provide much help), but I guess it must be possible, after all they built Delphi using this...</p> <p>Does anyone know a good JEDI docking sample application?</p>
28,231
<p>I have some code in a javascript file that needs to send queries back to the server. The question is, how do I find the url for the script that I am in, so I can build a proper request url for ajax.</p> <p>I.e., the same script is included on <code>/</code>, <code>/help</code>, <code>/whatever</code>, and so on, while it will always need to request from <code>/data.json</code>. Additionally, the same site is run on different servers, where the <code>/</code>-folder might be placed differently. I have means to resolve the relative url where I include the Javascript (ez-publish template), but not within the javascript file itself.</p> <p>Are there small scripts that will work on all browsers made for this?</p>
<p>For this I like to put <code>&lt;link&gt;</code> elements in the page's <code>&lt;head&gt;</code>, containing the URLs to use for requests. They can be generated by your server-side language so they always point to the right view:</p> <pre><code>&lt;link id="link-action-1" href="${reverse_url ('action_1')}"/&gt; </code></pre> <p>becomes</p> <pre><code>&lt;link id="link-action-1" href="/my/web/root/action-1/"/&gt; </code></pre> <p>and can be retrieved by Javascript with:</p> <pre><code>document.getElementById ('link-action-1').href; </code></pre>
<p>I include the following code in my libraries main entry point (main.php):</p> <pre><code>/** * Build current url, depending on protocal (http/https), * port, server name and path suffix */ $site_root = 'http'; if (isset($_SERVER["HTTPS"]) &amp;&amp; $_SERVER["HTTPS"] == "on") $site_root .= "s"; $site_root .= "://" . $_SERVER["SERVER_NAME"]; if ($_SERVER["SERVER_PORT"] != "80") $site_root .= ":" . $_SERVER["SERVER_PORT"]; $site_root .= $g_config["paths"]["site_suffix"]; $g_config["paths"]["site_root"] = $site_root; </code></pre> <p>$g_config is a global array containing configuration options. So site_suffix might look like: "/sites_working/thesite/public_html" on your development box, and just "/" on a server with a virtual host (domain name).</p> <p>This method is also good, because if somebody types in the IP address of your development box, it will use that same IP address to build the path to the javascript folder instead of something like "localhost," and if you use "localhost" it will use "localhost" to build the URL.</p> <p>And because it also detects SSL, you wont have to worry about weather your resources will be sent over HTTP or HTTPS if you ever add SSL support to your server.</p> <p>Then, in your template, either use</p> <pre><code>&lt;link id="site_root" href="&lt;?php echo $g_config["paths"]["site_root"] ?&gt;"/&gt; </code></pre> <p>Or</p> <pre><code>&lt;script type = "text/javascript"&gt; var SiteRoot = "&lt;?php echo $g_config["paths"]["site_root"]; ?&gt;"; &lt;/script&gt; </code></pre> <p>I suppose the latter would be faster.</p>
13,418
<p>Is it possible to receive DllMain like notifications about thread attach/detach in stand-alone exe without using any extra dlls?</p> <p><strong>Edit:</strong> This is just a theoretical question that has to do with some testing I'm doing. not a real life situation.</p>
<p>There is no external code that runs on the thread and loads the executable, hence no thread attach/detach notifications [1]. The code in the executable usualy control the threading [2].</p> <p>If you describe your scenario, people might be able to give you some ideas how to achieve it.</p> <hr> <p>[1] Well, most of the time. It is possible to load an executable in another process, but people don't do it usually.<br> [2] There are certain exceptions where the threading model and the threads are created by the OS, instead of the executable code. These are mostly related to COM/RPC.</p>
<p>Your question is to get notification while the process is getting loaded and unloaded. This is more applicable for DLLs as they are getting loaded by other processes.</p> <p>For Exes, you have InitInstance and ExitInstance which you can handle equivalently!</p>
22,567
<p>I am searching for a host for a new commercial website. Among other things, I'd like to know what the various OS - Webserver combinations have in terms of vulnerabilities. What are the vulnerabilities of Redhat + Apache?</p>
<p>See: <a href="http://httpd.apache.org/security/vulnerabilities_20.html" rel="nofollow noreferrer">http://httpd.apache.org/security/vulnerabilities_20.html</a></p>
<p>Its kind of a difficult question to answer, the development life cycles are so active you're asking for something that's likely to have been solved already ( and if its been reported so that we know of it, the likelihood its fixed is really high )</p> <p>What you need is a 0-day hack for them, and asking this list really wont get you those. </p>
11,302
<p>Is there a way to select data where any one of multiple conditions occur on the same field?</p> <p>Example: I would typically write a statement such as:</p> <pre><code>select * from TABLE where field = 1 or field = 2 or field = 3 </code></pre> <p>Is there a way to instead say something like:</p> <pre><code>select * from TABLE where field = 1 || 2 || 3 </code></pre> <p>Any help is appreciated.</p>
<p>Sure thing, the simplest way is this:</p> <pre><code>select foo from bar where baz in (1,2,3) </code></pre>
<p>while <code>in</code> is a shortcut for <code>or</code> and I wasn't sure how I could combine <code>in</code> with <code>and</code>, I did it this way</p> <pre><code> SELECT * FROM table WHERE column1='x' AND (column2='y' OR column2='z'); </code></pre>
3,845
<p>I need to launch a server on the remote machine and retrieve the port number that the server process is lsitening on. When invoked, the server will listen on a random port and output the port number on stderr.</p> <p>I want to automate the process of logging on to the remote machine, launching the process, and retrieving the port number. I wrote a Python script called "<code>invokejob.py</code>" that lives on the remote machine to act as a wrapper that invokes the job and then returns the port number, it looks like this:</p> <pre><code>import re, subprocess executable = ... # Name of executable regex = ... # Regex to extract the port number from the output p = subprocess.Popen(executable, bufsize=1, # line buffered stderr=subprocess.PIPE ) s = p.stderr.readline() port = re.match(regex).groups()[0] print port </code></pre> <p>If I log in interactively, this script works:</p> <pre><code>$ ssh remotehost.example.com Last login: Thu Aug 28 17:31:18 2008 from localhost $ ./invokejob.py 63409 $ exit logout Connection to remotehost.example.com closed. </code></pre> <p>(Note: successful logout, it did not hang).</p> <p>However, if I try to invoke it from the command-line, it just hangs:</p> <pre><code>$ ssh remotehost.example.com invokejob.py </code></pre> <p>Does anybody know why it hangs in the second case, and what I can do to avoid this? </p> <p>Note that I need to retrieve the output of the program, so I can't just use the ssh "-f" flag or redirect standard output.</p>
<blockquote> <pre><code>s = p.stderr.readline() </code></pre> </blockquote> <p>I suspect it's the above line. When you invoke a command directly through ssh, you don't get your full pty (assuming Linux), and thus no stderr to read from.</p> <p>When you log in interactively, stdin, stdout, and stderr are set up for you, and so your script works.</p>
<p>what if you do the following:</p> <h2><code>ssh &lt;remote host&gt; '&lt;your command&gt; ;&lt;your regexp using awk or something&gt;'</code></h2> <p>For example</p> <h2><code>ssh &lt;remote host&gt; '&lt;your program&gt;; ps aux | awk \'/root/ {print $2}\''</code></h2> <p>This will connect to , execute and then print each PSID for any user root or any process with root in its description.</p> <p>I have used this method for running all kinds of commands on remote machines. The catch is to wrap the command(s) you wish to execute in single quotation marks (') and to separate each command with a semi-colon (;).</p>
5,354
<p>Is there anyway to disable the repair option so that if a user runs the msi again it automatically uninstalls without prompting for Repair/Remove options?</p> <p>Edit: This is for a controlled corporate environment and has been passed down as a requirement.</p>
<p>After reading your edit, I'll try to give a guess, though I don't really know if it's possible just with an msi file. A tool "orca" can be downloaded from Microsoft (unrelated to "orcas" which was code name for a Visual Studio version). "Orca" can edit some properties of msi files, so that would be one place I'd look for a possibility of disabling a repair option.</p> <p>Another guess is that you might be able to insert a custom action early enough.</p>
<p>Isn't that really an unfriendly thing to do? Shouldn't the user get to decide whether they want a repair or an uninstall? Write a separate uninstall program if you want to provide an uninstaller with one less click.</p>
46,306
<p>What do you think the benefits of functional programming are? And how do they apply to programmers today?</p> <p>What are the greatest differences between functional programming and OOP? </p>
<p>The style of functional programming is to describe what you want, rather than how to get it. ie: instead of creating a for-loop with an iterator variable and marching through an array doing something to each cell, you'd say the equivalent of "this label refers to a version of this array where this function has been done on all the elements."</p> <p>Functional programming moves more basic programming ideas into the compiler, ideas such as list comprehensions and caching.</p> <p>The biggest benefit of Functional programming is brevity, because code can be more concise. A functional program doesn't create an iterator variable to be the center of a loop, so this and other kinds of overhead are eliminated from your code.</p> <p>The other major benefit is concurrency, which is easier to do with functional programming because the compiler is taking care of most of the operations which used to require manually setting up state variables (like the iterator in a loop).</p> <p>Some performance benefits can be seen in the context of a single-processor as well, depending on the way the program is written, because most functional languages and extensions support lazy evaluation. In Haskell you can say "this label represents an array containing all the even numbers". Such an array is infinitely large, but you can ask for the 100,000th element of that array at any moment without having to know--at array initialization time--just what the largest value is you're going to need. The value will be calculated only when you need it, and no further.</p>
<p>If you don't already know functional programming then learning it gives you more ways to solve problems.</p> <p>FP is a simple generalization that promotes functions to first class values whereas OOP is for large-scale structuring of code. There is some overlap, however, where OOP design patterns can be represented directly and much more succinctly using first-class functions.</p> <p>Many languages provide both FP and OOP, including OCaml, C# 3.0 and F#.</p> <p>Cheers, Jon Harrop.</p>
15,589
<p>If you want a cryptographically strong random numbers in Java, you use <code>SecureRandom</code>. Unfortunately, <code>SecureRandom</code> can be very slow. If it uses <code>/dev/random</code> on Linux, it can block waiting for sufficient entropy to build up. How do you avoid the performance penalty?</p> <p>Has anyone used <a href="https://uncommons-maths.dev.java.net/" rel="noreferrer">Uncommon Maths</a> as a solution to this problem?</p> <p>Can anybody confirm that this performance problem has been solved in JDK 6?</p>
<p>If you want true random data, then unfortunately you have to wait for it. This includes the seed for a <code>SecureRandom</code> PRNG. Uncommon Maths can't gather true random data any faster than <code>SecureRandom</code>, although it can connect to the internet to download seed data from a particular website. My guess is that this is unlikely to be faster than <code>/dev/random</code> where that's available.</p> <p>If you want a PRNG, do something like this:</p> <pre><code>SecureRandom.getInstance("SHA1PRNG"); </code></pre> <p>What strings are supported depends on the <code>SecureRandom</code> SPI provider, but you can enumerate them using <code>Security.getProviders()</code> and <code>Provider.getService()</code>.</p> <p>Sun is fond of SHA1PRNG, so it's widely available. It isn't especially fast as PRNGs go, but PRNGs will just be crunching numbers, not blocking for physical measurement of entropy.</p> <p>The exception is that if you don't call <code>setSeed()</code> before getting data, then the PRNG will seed itself once the first time you call <code>next()</code> or <code>nextBytes()</code>. It will usually do this using a fairly small amount of true random data from the system. This call may block, but will make your source of random numbers far more secure than any variant of "hash the current time together with the PID, add 27, and hope for the best". If all you need is random numbers for a game, though, or if you want the stream to be repeatable in future using the same seed for testing purposes, an insecure seed is still useful.</p>
<p>Something else to look at is the property securerandom.source in file lib/security/java.security <P>There may be a performance benefit to using /dev/urandom rather than /dev/random. Remember that if the quality of the random numbers is important, don't make a compromise which breaks security.</p>
16,594
<p>I am writing an xmpp library and I am trying to write a stream to support the zlib compressed data. I have two different versions one based on zlib.net and the other using SharpZipLib. The zlib.net version doesn't recognize the compression and the SharpZipLib version enters an infinite loop. You can find the appropriate code at <a href="http://github.com/coder2000/ubiety/tree/master/" rel="nofollow noreferrer">http://github.com/coder2000/ubiety/tree/master/</a> in xmpp.compression.zlib and xmpp.compression.sharpziplib. Any help to solve this problem would be appreciated.</p>
<p>This isn't a direct solution to your problem but have you tried System.IO.Compression.GZipStream or DeflateStream?</p>
<p>I haven't looked in depth, but it is curious that your SharpZipLib wrapper ignores <code>offset</code> and <code>count</code> in BeginRead:</p> <pre><code>public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback cback, object state) { _outBuff = buffer; if ( _in.IsNeedingInput ) return _innerStream.BeginRead(_inBuff, 0, _inBuff.Length, cback, state); ZlibStreamAsyncResult ar = new ZlibStreamAsyncResult(state); cback(ar); return ar; } </code></pre> <p>Call me crazy, but probably use <code>GZipOutputStream</code> etc directly (or the System.Compression counterparts)... saves a lot of implementation details...</p>
42,703
<p>i want to find the mime-type for a given file extension on an IIS ASP.NET web-server from the code-behind file.</p> <p>i want to search the same list that the server itself uses when serving up a file. This means that any mime types a web-server administrator has added to the <em>Mime Map</em> will be included.</p> <p>i could blindly use</p> <pre><code>HKEY_CLASSES_ROOT\MIME\Database\Content Type </code></pre> <p>but that isn't documented as being the same list IIS uses, nor is it documented where the <em>Mime Map</em> is stored.</p> <p>i could blindly call <a href="http://msdn.microsoft.com/en-us/library/ms775107(VS.85).aspx" rel="noreferrer">FindMimeFromData</a>, but that isn't documented as being the same list IIS uses, nor can i guarantee that the IIS <em>Mime Map</em> will also be returned from that call.</p>
<p>Here's one I made earlier:</p> <pre><code>public static string GetMimeTypeFromExtension(string extension) { using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap")) { PropertyValueCollection propValues = mimeMap.Properties["MimeMap"]; foreach (object value in propValues) { IISOle.IISMimeType mimeType = (IISOle.IISMimeType)value; if (extension == mimeType.Extension) { return mimeType.MimeType; } } return null; } } </code></pre> <p>Add a reference to <code>System.DirectoryServices</code> and a reference to <code>Active DS IIS Namespace Provider</code> under the COM tab. The extension needs to have the leading dot, i.e. <code>.flv</code>.</p>
<p>IIS stores the MIME information in its own database. Searching for "MimeMap IIS" on the internet will reveal how to read it or even change it. See for example <a href="http://blog.crowe.co.nz/archive/2006/06/02/647.aspx" rel="nofollow noreferrer">C# - How to display MimeMap entries to the console from an instance of IIS.</a></p>
21,087
<p>For my application there are several entity classes, User, Customer, Post, and so on</p> <p>I'm about to design the database and I want to store the date when the entities were created and updated. This is where it gets tricky. Sure one option is to add created_timestamp and update_timestamp columns for each of the entity tables but that isn't that redudant?</p> <p>Another possibility could be to create a log table that stores this information, and it could be made to contain keep track of updates for <strong>any</strong> entity.</p> <p>Any thoughts? I'm leaning on implementing the latter.</p>
<p>The single-log-table-for-all-tables approach has two main problems that I can think of:</p> <ol> <li>The design of the log table will (probably) constrain the design of all the other tables. Most likely the log table would have one column named TableName and then another column named PKValue (which would store the primary key value for the record you're logging). If some of your tables have compound primary keys (i.e. more than one column), then the design of your log table would have to account for this (probably by having columns like PKValue1, PKValue2 etc.).</li> <li>If this is a web application of some sort, then the user identity that would be available from a trigger would be the application's account, instead of the ID of the web app user (which is most likely what you really want to store in your CreatedBy field). This would only help you distinguish between records created by your web app code and records created otherwise.</li> </ol> <p>CreatedDate and ModifiedDate columns aren't redundant just because they're defined in each table. I would stick with that approach and put insert and update triggers on each table to populate those columns. If I also needed to record the end-user who made the change, I would skip the triggers and populate the timestamp and user fields from my application code.</p>
<p>How often will you need to include the created/updated timestamps in your presentation layer? If the answer is anything more than "once in a great great while", I think you would be better served by having those columns in each table.</p>
29,359
<p>I'm creating a invoice crystal report for sage mas 500 AR module. In it, I'm attempting to add the <code>tarinvoice.balance</code> field with the following formula: </p> <pre><code>if {tarPrintInvcHdrWrk.Posted} = 1 then ToText({tarInvoice.Balance}) </code></pre> <p>I'm assuming that when the <code>{tarPrintInvcHdrWrk.Posted} = 1</code> conditional statement holds FALSE, it doesn't attempt to pull the invoice field because when I remove the formula from the report, the form displays correctly without it. </p> <p>When the conditional statement renders true in the report, the balance fields behaves correctly. However, with the formula renders FALSE in the CR form, the entire crystal report bombs and displays blank. Any ideas why or what I'm doing wrong?</p> <hr> <p>Just tried setting everything to zero and the report still bombs. I'm starting to think its more of a query error in the report. I wish there was a way to exclude the field in the query when posted = 0. </p> <p>With <code>tarinvoice.balance</code> removed when the posted = 0, the report works fine.<br> With <code>tarinvoice.balance</code> included and posted = 1, report works fine. </p> <p>With <code>tarinvoice.balance</code> included and posted =0, report bombs.</p>
<p>I believe the conditional statement fails immediately if you encounter a NULL, so your formula needs to test <strong>IsNull({tarPrintInvcHdrWrk.Posted})</strong> before it tests equality with "1".</p>
<p>You can change the way Crystal handles a null value for a value in a formula. At the top of the Formula Workshop there is a drop down box that usually says "Exceptions For Nulls".<br> Change this to the other option "Default Values For Nulls" and your formula should no longer bomb out. You used to be able to specify the what the default values applied were, but more recent versions of Crystal have these hard coded. Search the help for "Null Treatment" for a table showing them. </p>
24,801
<p>The questions says everything, take this example code: </p> <pre><code>&lt;ul id="css-id"&gt; &lt;li&gt; &lt;something:CustomControl ID="SomeThingElse" runat="server" /&gt; &lt;something:OtherCustomControl runat="server" /&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Now if an error gets thrown somewhere inside these controlls (that are located in a master page) they will take down the entire site, how would one catch these exceptions?</p>
<p>You can catch all exception not handled elswhere in the Global.asax page / class. Look at:</p> <pre><code>protected void Application_Error(Object sender, EventArgs e) </code></pre> <p>method.</p>
<p>Add a global.asax en implement the Application_Error handler. Use the Server.GetLastError() function to get a handle on the exception thrown.</p>
16,702
<p>How would you explain JavaScript closures to someone with a knowledge of the concepts they consist of (for example functions, variables and the like), but does not understand closures themselves?</p> <p>I have seen <a href="http://en.wikipedia.org/wiki/Scheme_%28programming_language%29" rel="noreferrer">the Scheme example</a> given on Wikipedia, but unfortunately it did not help.</p>
<p>A closure is a pairing of:</p> <ol> <li>A function and</li> <li>A reference to that function's outer scope (lexical environment)</li> </ol> <p>A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.</p> <p>Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to &quot;see&quot; variables declared outside the function, regardless of when and where the function is called.</p> <p>If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.</p> <p>In the following code, <code>inner</code> forms a closure with the lexical environment of the execution context created when <code>foo</code> is invoked, <em>closing over</em> variable <code>secret</code>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function foo() { const secret = Math.trunc(Math.random() * 100) return function inner() { console.log(`The secret number is ${secret}.`) } } const f = foo() // `secret` is not directly accessible from outside `foo` f() // The only way to retrieve `secret`, is to invoke `f`</code></pre> </div> </div> </p> <p>In other words: in JavaScript, functions carry a reference to a private &quot;box of state&quot;, to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.</p> <p>And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.</p> <p>If JavaScript did not have closures, then more states would have to be passed between functions <em>explicitly</em>, making parameter lists longer and code noisier.</p> <p>So, if you want a function to always have access to a private piece of state, you can use a closure.</p> <p>...and frequently we <em>do</em> want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating the state with functionality.</p> <p>In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, <code>secret</code> remains available to the function object <code>inner</code>, <em>after</em> it has been returned from <code>foo</code>.</p> <h2>Uses of Closures</h2> <p>Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.</p> <h3>Private Instance Variables</h3> <p>In the following code, the function <code>toString</code> closes over the details of the car.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function Car(manufacturer, model, year, color) { return { toString() { return `${manufacturer} ${model} (${year}, ${color})` } } } const car = new Car('Aston Martin', 'V8 Vantage', '2012', 'Quantum Silver') console.log(car.toString())</code></pre> </div> </div> </p> <h3>Functional Programming</h3> <p>In the following code, the function <code>inner</code> closes over both <code>fn</code> and <code>args</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function curry(fn) { const args = [] return function inner(arg) { if(args.length === fn.length) return fn(...args) args.push(arg) return inner } } function add(a, b) { return a + b } const curriedAdd = curry(add) console.log(curriedAdd(2)(3)()) // 5</code></pre> </div> </div> </p> <h3>Event-Oriented Programming</h3> <p>In the following code, function <code>onClick</code> closes over variable <code>BACKGROUND_COLOR</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const $ = document.querySelector.bind(document) const BACKGROUND_COLOR = 'rgba(200, 200, 242, 1)' function onClick() { $('body').style.background = BACKGROUND_COLOR } $('button').addEventListener('click', onClick)</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button&gt;Set background color&lt;/button&gt;</code></pre> </div> </div> </p> <h3>Modularization</h3> <p>In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions <code>tick</code> and <code>toString</code> close over the private state and functions they need to complete their work. Closures have enabled us to modularize and encapsulate our code.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>let namespace = {}; (function foo(n) { let numbers = [] function format(n) { return Math.trunc(n) } function tick() { numbers.push(Math.random() * 100) } function toString() { return numbers.map(format) } n.counter = { tick, toString } }(namespace)) const counter = namespace.counter counter.tick() counter.tick() console.log(counter.toString())</code></pre> </div> </div> </p> <h2>Examples</h2> <h3>Example 1</h3> <p>This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables <em>themselves</em>. It is as though the stack-frame stays alive in memory even after the outer function exits.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function foo() { let x = 42 let inner = () =&gt; console.log(x) x = x + 1 return inner } foo()() // logs 43</code></pre> </div> </div> </p> <h3>Example 2</h3> <p>In the following code, three methods <code>log</code>, <code>increment</code>, and <code>update</code> all close over the same lexical environment.</p> <p>And every time <code>createObject</code> is called, a new execution context (stack frame) is created and a completely new variable <code>x</code>, and a new set of functions (<code>log</code> etc.) are created, that close over this new variable.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function createObject() { let x = 42; return { log() { console.log(x) }, increment() { x++ }, update(value) { x = value } } } const o = createObject() o.increment() o.log() // 43 o.update(5) o.log() // 5 const p = createObject() p.log() // 42</code></pre> </div> </div> </p> <h3>Example 3</h3> <p>If you are using variables declared using <code>var</code>, be careful you understand which variable you are closing over. Variables declared using <code>var</code> are hoisted. This is much less of a problem in modern JavaScript due to the introduction of <code>let</code> and <code>const</code>.</p> <p>In the following code, each time around the loop, a new function <code>inner</code> is created, which closes over <code>i</code>. But because <code>var i</code> is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of <code>i</code> (3) is printed, three times.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function foo() { var result = [] for (var i = 0; i &lt; 3; i++) { result.push(function inner() { console.log(i) } ) } return result } const result = foo() // The following will print `3`, three times... for (var i = 0; i &lt; 3; i++) { result[i]() }</code></pre> </div> </div> </p> <h2>Final points:</h2> <ul> <li>Whenever a function is declared in JavaScript closure is created.</li> <li>Returning a <code>function</code> from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.</li> <li>Whenever you use <code>eval()</code> inside a function, a closure is used. The text you <code>eval</code> can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using <code>eval('var foo = …')</code>.</li> <li>When you use <code>new Function(…)</code> (the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" rel="noreferrer">Function constructor</a>) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.</li> <li>A closure in JavaScript is like keeping a reference (<strong>NOT</strong> a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.</li> <li>A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.</li> <li>A new set of local variables is created every time a function is called.</li> </ul> <h2>Links</h2> <ul> <li>Douglas Crockford's simulated <a href="http://www.crockford.com/javascript/private.html" rel="noreferrer">private attributes and private methods</a> for an object, using closures.</li> <li>A great explanation of how closures can <a href="https://www.codeproject.com/Articles/12231/Memory-Leakage-in-Internet-Explorer-revisited" rel="noreferrer">cause memory leaks in IE</a> if you are not careful.</li> <li>MDN documentation on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures" rel="noreferrer">JavaScript Closures</a>.</li> </ul>
<h1>The simplest, shortest, most-easy-to-understand answer:</h1> <p>A closure is a block of code where each line can reference the same set of variables with the same variable names.</p> <p>If &quot;this&quot; means something different than it does somewhere else, then you know it is two different closures.</p>
13,626
<p>We're working on a very large .NET WinForms composite application - not CAB, but a similar home grown framework. We're running in a Citrix and RDP environment running on Windows Server 2003. </p> <p>We're starting to run into random and difficult to reproduct "Error creating window handle" error that seems to be an old fashion handle leak in our application. We're making heavy use of 3rd Party controls (Janus GridEX, Infralution VirtualTree, and .NET Magic docking) and we do a lot of dynamic loading and rendering of content based on metadata in our database.</p> <p>There's a lot of info on Google about this error, but not a lot of solid guidance about how to avoid issues in this area.</p> <p>Does the stackoverflow community have any good guidance for me for building handle-friendly winforms apps?</p>
<p>I have tracked down a lot of issues with UIs not unloading as expected in WinForms. </p> <p>Here are some general hints:</p> <ul> <li>alot of the time, a control will stay in use because controls events are not properly removed (the tooltip provider caused us really large issues here) or the controls are not properly Disposed. </li> <li>use 'using' blocks around all modal dialogs to ensure that they are Disposed</li> <li>there are some control properties that will force the creation of the window handle before it is necessary (for example setting the ReadOnly property of a TextBox control will force the control to be realized)</li> <li>use a tool like the <a href="http://memprofiler.com/Default.aspx" rel="noreferrer">.Net Memory profiler</a> to get counts of the classes that are created. Newer versions of this tool will also track GDI and USER objects.</li> <li>try to minimize your use of Win API calls (or other DllImport calls). If you do need to use interop, try to wrap these calls in such a way that the using/Dispose pattern will work correctly.</li> </ul>
<p>I ran into the same .Net runtime error but my solution was different. </p> <p><strong>My Scenario:</strong> From a popup Dialog that returned a DialogResult, the user would click a button to send an email message. I added a thread so the UI didn't lock up while generating the report in the background. This scenario ended up getting that unusual error message.</p> <p><strong>The code that resulted in problem:</strong> The problem with this code is that the thread immediately starts and returns which results in the DialogResult being returned which disposes the dialog before the thread can properly grab the values from the fields.</p> <pre><code>private void Dialog_SendEmailSummary_Button_Click(object sender, EventArgs e) { SendSummaryEmail(); DialogResult = DialogResult.OK; } private void SendSummaryEmail() { var t = new Thread(() =&gt; SendSummaryThread(Textbox_Subject.Text, Textbox_Body.Text, Checkbox_IncludeDetails.Checked)); t.Start(); } private void SendSummaryThread(string subject, string comment, bool includeTestNames) { // ... Create and send the email. } </code></pre> <p><strong>The fix for this scenario:</strong> The fix is to grab and store the values before passing them into the method which creates the thread. </p> <pre><code>private void Dialog_SendEmailSummary_Button_Click(object sender, EventArgs e) { SendSummaryEmail(Textbox_Subject.Text, Textbox_Body.Text, Checkbox_IncludeDetails.Checked); DialogResult = DialogResult.OK; } private void SendSummaryEmail(string subject, string comment, bool includeTestNames) { var t = new Thread(() =&gt; SendSummaryThread(subject, comment, includeTestNames)); t.Start(); } private void SendSummaryThread(string subject, string comment, bool includeTestNames) { // ... Create and send the email. } </code></pre>
11,455
<p>It seems with the built in friendly routing library in .NET MVC, it would allow us to do something like this.</p> <p>In case it's not obvious what I want to with the built in stuff in .NET MVC, I want to a url starting with www to be automatically redirected to a non-www url using the MVC framework.</p>
<p>There are a number of ways to do the 301 redirect from the www to the not-www. I prefer to keep this redirection logic at the ASP.NET level (i.e. in my app) in some projects, but others require better performing things, like IIS7 url rewriting.</p> <p>It was <a href="http://forums.asp.net/t/1324018.aspx" rel="nofollow noreferrer">discussed on the ASP.NET forums</a> and I chose to use a WwwFilter on each controller. This has worked for me, no issues.</p>
<p>try to add this into your <strong><em>Global.asax</em></strong> :</p> <pre><code>if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://YourSite.com")) { HttpContext.Current.Response.Status = "301 Moved Permanently"; HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://YourSite.com","http://www.YourSite.com")); } </code></pre> <p><strong>it works and tested.</strong></p>
37,471
<p>Short version is in the title.</p> <p>Long version: I am working on a program for scientific optimization using Java. The workload of the program can be divided into parallel and serial phases -- parallel phases meaning that highly parallelizable work is being performed. To speed up the program (it runs for hours/days) I create a number of threads equal to the number of CPU cores on the machine I'm using -- typically 4 or 8 -- and divide the work between them. I then start these threads and join() them before proceeding to a serial phase.</p> <p>So far so good. What's bothering me is that the CPU utilization and speedup of the parallel phases is nowhere near the "theoretical maximum" -- e.g. if I have 4 cores, I expect to see somewhere between 350-400% "utilization" (as reported by top) but instead it bounces around between 180 and about 310. Using only a single thread, I get 100% CPU utilization.</p> <p>The only reasons I know of for threads not to run at full speed are: -blocking due to I/O -blocking due to synchronization</p> <p>No I/O whatsoever is going on in my parallel threads, nor any synchronization -- the only data structures shared by the threads are read-only, and are either basic types or (non-concurrent) collections. So I'm looking for other explanations. One possibility would be that several threads are repeatedly blocking for garbage collection, but that would only seem to make sense in a situation with memory pressure, and I am allocating well above the required maximum heap space. </p> <p>Any suggestions would be appreciated.</p> <p><b>Update:</b> Just in case anyone is curious, after some more investigation I tweaked the code for general performance and am seeing better utilization, even though nothing I changed has to do with synchronization. However, some of the changes should have resulted in fewer new heap allocations in particular I got rid of some use of <b>iterators</b> and <b>termporary boxed numbers</b> (The CERN "Colt" library for high-performance Java computing was useful here: it provides collections like IntArrayList, DoubleArrayList etc for basic types.). So I think garbage collection was probably the culprit. </p>
<p>All graphics operations run on a single thread in swing. If they are rendering to the screen they will effectively be contending for access to this thread.</p> <p>If you are running on Windows, all graphics operations run on a single thread no matter what. Other operating systems have similar limitations.</p> <p>It's actually fairly difficult to get the proper granularity of threaded workers sometimes, and sometimes it's easy to make them too big or too small, which will typically give you less than 100% usage of all cores.</p> <p>If you're not rendering much gui, the most likely culprit is that you're contending more than you think for some shared resource. This is easily seen with profiler tools like jprofiler. Some VM's like bea's jrockit can even tell you this straight out of the box.</p> <p>This is one of those places where you dont want to act on guesswork. Get a profiler!</p>
<p>You try to use the full CPU capability for your calculations but the OS itself uses resources as well. So be aware that the OS will block some of your execution in order to satisfy its needs.</p>
43,196
<p>We have a web application that was implemented using GWT. What it presents is fetched from a Jboss/Seam server using the remoting mechanism, and this works fine. However, the application is now extended to support sessions and users. The Seam GWT service doesn't seem to provide a way to let me log in such that Seam can return restricted data back to the GWT application, and so it looks to me that I will have to wrap the GWT application in facelets.</p> <p>It is not obvious to me that a login using the Seam session mechanism will help me get correct data into the GWT application however, so my question is whether I will be lucky and it will just work, or if I need to do some client side magic, server side magic or if my perception of missing login functionality in the Seam GWT service actually is wrong.</p> <p>Bonus points to anyone that can provide me with a complete example showing something similar.</p>
<p>It turns out that things are "just working" as I hoped. By using Seam's Identity and login mechanism, I can access the current logged in user via <code>Identity.instance().getUsername();</code> in the service code that gets requests from the GWT portion of the application.</p> <p>I tried to put a <code>@Restrict</code> annotation on the service, but this did not appear to work, however this is not something that is not needed as long as I can provide results to the GWT application based on the logged in user.</p>
<p>How about this complete GWT app on google code -- <a href="http://code.google.com/p/tocollege-net/" rel="nofollow noreferrer">http://code.google.com/p/tocollege-net/</a> ?</p>
13,177