input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
C#: Refactoring a Reynolds number calculator <p>I'm trying to learn some C# over the weekend and am following the 15 exercises found here: <a href="http://www.jobsnake.com/seek/articles/index.cgi?openarticle&8533" rel="nofollow">http://www.jobsnake.com/seek/articles/index.cgi?openarticle&8533</a></p>
<p>Yesterday I asked a similar question for the Fibonacci sequence and received some great responses which introduced me to elements of C# which I'd not encountered before:
<a href="http://stackoverflow.com/questions/406446/refactoring-fibonacci-algorithm">http://stackoverflow.com/questions/406446/refactoring-fibonacci-algorithm</a></p>
<p>Today I would like to see how a C# Jedi would refactor the following code:</p>
<pre><code>static string Reynolds(int d, int v, int rho, int mu)
{
int number = (d*v*rho) / mu;
if (number < 2100) return "Laminar Flow";
else if (number < 2100 && number < 4000) return "Transient Flow";
else return "Turbulent Flow";
}
</code></pre>
<p>So more simple than yesterday, but is there any nice way to deal with the multiple conditionals?</p>
<p>Regards,</p>
<p>Chris</p>
| <p>I think there is an error in your code but I made an assumption. Your second "if" would never evaluate tree as number < 2000 already makes the first branch true.</p>
<p>I would create an ENUM:</p>
<pre><code>enum FlowType
{
Laminar
, Transient
, Turbulent
};
static FlowType Reynolds(int d, int v, int rho, int mu)
{
int n = (d*v*rho) / mu;
if(n < 2000)
{
return FlowType.Laminar;
}
else if(n < 4000)
{
return FlowType.Transient;
}
else
{
return FlowType.Turbulent;
}
}
</code></pre>
|
Regular expression to parse an array of JSON objects? <p>I'm trying to parse an array of JSON objects into an array of strings in C#. I can extract the array from the JSON object, but I can't split the array string into an array of individual objects.</p>
<p>What I have is this test string:</p>
<pre><code>string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
</code></pre>
<p>Right now I'm using the following regular expressions right now to split the items into individual objects. For now they're 2 separate regular expressions until I fix the problem with the second one:</p>
<pre><code>Regex arrayFinder = new Regex(@"\{items:\[(?<items>[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?<items>\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
</code></pre>
<p>The <code>arrayFinder</code> regex works the way I'd expect it but, for reasons I don't understand, the <code>arrayParser</code> regex doesn't work at all. All I want it to do is split the individual items into their own strings so I get a list like this:</p>
<blockquote>
<p><code>{id:0,name:"Lorem Ipsum"}</code><br />
<code>{id:1,name:"Lorem Ipsum"}</code><br />
<code>{id:2,name:"Lorem Ipsum"}</code> </p>
</blockquote>
<p>Whether this list is a <code>string[]</code> array or a <code>Group</code> or <code>Match</code> collection doesn't matter, but I'm stumped as to how to get the objects split. Using the <code>arrayParser</code> and the <code>json</code> string declared above, I've tried this code which I assumed would work with no luck:</p>
<pre><code>string json = "{items:[{id:0,name:\"Lorem Ipsum\"},{id:1,name"
+ ":\"Lorem Ipsum\"},{id:2,name:\"Lorem Ipsum\"}]}";
Regex arrayFinder = new Regex(@"\{items:\[(?<items>[^\]]*)\]\}"
, RegexOptions.ExplicitCapture);
Regex arrayParser = new Regex(@"((?<items>\{[^\}]\}),?)+"
, RegexOptions.ExplicitCapture);
string array = arrayFinder.Match(json).Groups["items"].Value;
// At this point the 'array' variable contains:
// {id:0,name:"Lorem Ipsum"},{id:1,name:"Lorem Ipsum"},{id:2,name:"Lorem Ipsum"}
// I would have expected one of these 2 lines to return
// the array of matches I'm looking for
CaptureCollection c = arrayParser.Match(array).Captures;
GroupCollection g = arrayParser.Match(array).Groups;
</code></pre>
<p>Can anybody see what it is I'm doing wrong? I'm totally stuck on this.</p>
| <p>Balanced parentheses are literally a textbook example of a language that cannot be processed with regular expressions. JSON is essentially balanced parentheses plus a bunch of other stuff, with the braces replaced by parens. In the <a href="http://en.wikipedia.org/wiki/Chomsky_hierarchy">hierarchy of formal languages</a>, JSON is a context-free language. Regular expressions can't parse context-free languages.</p>
<p>Some systems offer extensions to regular expressions that kinda-sorta handle balanced expressions. However they're all ugly hacks, they're all unportable, and they're all ultimately the wrong tool for the job.</p>
<p>In professional work, you would almost always use an existing JSON parser. If you want to roll your own for educational purposes then I'd suggest starting with a simple arithmetic grammar that supports + - * / ( ). (JSON has some escaping rules which, while not complex, will make your first attempt harder than it needs to be.) Basically, you'll need to:</p>
<ol>
<li>Decompose the language into an alphabet of symbols</li>
<li>Write a context-free grammar in terms of those symbols thatrecognizes the language</li>
<li>Convert the grammar into Chomsky normal form, or near enough to make step 5 easy</li>
<li>Write a lexer that converts raw text into your input alphabet</li>
<li>Write a recursive descent parser that takes your lexer's output, parses it, and produces some kind of output</li>
</ol>
<p>This is a typical third-year CS assignment at just about any university. </p>
<p>The next step is to find out how complex a JSON string you need to trigger a stack overflow in your recursive parser. Then look at the other types of parsers that can be written, and you'll understand why anyone who has to parse a context-free language in the real world uses a tool like yacc or antlr instead of writing a parser by hand.</p>
<p>If that's more learning than you were looking for then you should feel free to go use an off-the-shelf JSON parser, satisified that you learned something important and useful: the limits of regular expressions.</p>
|
Stack, Static, and Heap in C++ <p>I've searched, but I've not understood very well these three concepts. When do I have to use dynamic allocation (in the heap) and what's its real advantage? What are the problems of static and stack? Could I write an entire application without allocating variables in the heap? </p>
<p>I heard that others languages incorporate a "garbage collector" so you don't have to worry about memory. What does the garbage collector do? </p>
<p>What could you do manipulating the memory by yourself that you couldn't do using this garbage collector?</p>
<p>Once someone said to me that with this declaration:</p>
<pre><code>int * asafe=new int;
</code></pre>
<p>I have a "pointer to a pointer". What does it mean? It is different of:</p>
<pre><code>asafe=new int;
</code></pre>
<p>?</p>
| <p><a href="http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap">A similar question</a> was asked, but it didn't ask about statics.</p>
<h2>Summary of what static, heap, and stack memory are:</h2>
<ul>
<li><p>A static variable is basically a global variable, even if you cannot access it globally. Usually there is an address for it that is in the executable itself. There is only one copy for the entire program. No matter how many times you go into a function call (or class) (and in how many threads!) the variable is referring to the same memory location.</p></li>
<li><p>The heap is a bunch of memory that can be used dynamically. If you want 4kb for an object then the dynamic allocator will look through its list of free space in the heap, pick out a 4kb chunk, and give it to you. Generally, the dynamic memory allocator (malloc, new, et c.) starts at the end of memory and works backwards.</p></li>
<li><p>Explaining how a stack grows and shrinks is a bit outside the scope of this answer, but suffice to say you always add and remove from the end only. Stacks usually start high and grow down to lower addresses. You run out of memory when the stack meets the dynamic allocator somewhere in the middle (but refer to physical versus virtual memory and fragmentation). Multiple threads will require multiple stacks (the process generally reserves a minimum size for the stack).</p></li>
</ul>
<h2>When you would want to use each one:</h2>
<ul>
<li><p>Statics/globals are useful for memory that you know you will always need and you know that you don't ever want to deallocate. (By the way, embedded environments may be thought of as having only static memory... the stack and heap are part of a known address space shared by a third memory type: the program code. Programs will often do dynamic allocation out of their static memory when they need things like linked lists. But regardless, the static memory itself (the buffer) is not itself "allocated", but rather other objects are allocated out of the memory held by the buffer for this purpose. You can do this in non-embedded as well, and console games will frequently eschew the built in dynamic memory mechanisms in favor of tightly controlling the allocation process by using buffers of preset sizes for all allocations.)</p></li>
<li><p>Stack variables are useful for when you know that as long as the function is in scope (on the stack somewhere), you will want the variables to remain. Stacks are nice for variables that you need for the code where they are located, but which isn't needed outside that code. They are also really nice for when you are accessing a resource, like a file, and want the resource to automatically go away when you leave that code.</p></li>
<li><p>Heap allocations (dynamically allocated memory) is useful when you want to be more flexible than the above. Frequently, a function gets called to respond to an event (the user clicks the "create box" button). The proper response may require allocating a new object (a new Box object) that should stick around long after the function is exited, so it can't be on the stack. But you don't know how many boxes you would want at the start of the program, so it can't be a static.</p></li>
</ul>
<h2>Garbage Collection</h2>
<p>I've heard a lot lately about how great Garbage Collectors are, so maybe a bit of a dissenting voice would be helpful.</p>
<p>Garbage Collection is a wonderful mechanism for when performance is not a huge issue. I hear GCs are getting better and more sophisticated, but the fact is, you may be forced to accept a performance penalty (depending upon use case). And if you're lazy, it still may not work properly. At the best of times, Garbage Collectors realize that your memory goes away when it realizes that there are no more references to it (see <a href="http://en.wikipedia.org/wiki/Reference_counting">reference counting</a>). But, if you have an object that refers to itself (possibly by referring to another object which refers back), then reference counting alone will not indicate that the memory can be deleted. In this case, the GC needs to look at the entire reference soup and figure out if there are any islands that are only referred to by themselves. Offhand, I'd guess that to be an O(n^2) operation, but whatever it is, it can get bad if you are at all concerned with performance. (Edit: Martin B <a href="http://www.hpl.hp.com/personal/Hans_Boehm/gc/complexity.html">points out</a> that it is O(n) for reasonably efficient algorithms. That is still O(n) too much if you are concerned with performance and can deallocate in constant time without garbage collection.)</p>
<p>Personally, when I hear people say that C++ doesn't have garbage collection, my mind tags that as a feature of C++, but I'm probably in the minority. Probably the hardest thing for people to learn about programming in C and C++ are pointers and how to correctly handle their dynamic memory allocations. Some other languages, like Python, would be horrible without GC, so I think it comes down to what you want out of a language. If you want dependable performance, then C++ without garbage collection is the only thing this side of Fortran that I can think of. If you want ease of use and training wheels (to save you from crashing without requiring that you learn "proper" memory management), pick something with a GC. Even if you know how to manage memory well, it will save you time which you can spend optimizing other code. There really isn't much of a performance penalty anymore, but if you really need dependable performance (and the ability to know exactly what is going on, when, under the covers) then I'd stick with C++. There is a reason that every major game engine that I've ever heard of is in C++ (if not C or assembly). Python, et al are fine for scripting, but not the main game engine. </p>
|
Catch MainLoop exceptions and displaying them in MessageDialogs <p>I have a wxPython application that relies on an external config file. I want provide friendly message dialogs that show up if there are any config errors. I've tried to make this work by wrapping my app.MainLoop() call in a try/except statement.</p>
<p>The code below works for the init code in my MainWindow frame class, but doesn't catch any exceptions that occur within the MainLoop. How can I catch these exceptions as well?</p>
<pre><code>if __name__ == '__main__':
app = MyApp(0)
try:
MainWindow(None, -1, 'My Cool App')
app.MainLoop()
except ConfigParser.Error, error_message:
messagebox = wx.MessageDialog(None, error_message, 'Configuration Error', wx.OK | wx.ICON_ERROR)
messagebox.ShowModal()
</code></pre>
<p>I've read some mention of an OnExceptionInMainLoop method that can be overridden in the wx.App class, but the source I read must be out of date (2004) since wx.App no longer seems to have a method by that name.</p>
<p><strong>EDIT:</strong></p>
<p>I need to be able to catch unhandled exceptions during my mainloop so that I can further handle them and display them in error dialogs, not pass silently, and not terminate the app.</p>
<p>The sys.excepthook solution is too low level and doesn't play nice with the wxPython mainloop thread. While the link to the other answer does the same try/except wrapping around the mainloop which doesn't work due, once again, to wxPython spawning a different thread for the app/ui.</p>
| <p>Don't know if this will work for a wxPython application, but in the sys module you can overwrite the excepthook attribute, which is a function called with 3 arguments, <code>(type, value, traceback)</code>, when an uncaugth exception is caught. You can install your own function in there that handles only the exceptions you want, and call the original function for all the others.</p>
<p>Consult: <a href="http://docs.python.org/library/sys.html#sys.excepthook" rel="nofollow" title="sys module">http://docs.python.org/library/sys.html#sys.excepthook</a></p>
|
What is the difference between Swing and AWT? <p>Can someone please explain me what's the difference between Swing and AWT?</p>
<p>Are there any cases where AWT is more useful/advised to use than swing or vice-versa?</p>
| <p>AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.</p>
<p>Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, checkboxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it. Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a "pluggable look and feel" that can make it look more or less like how the native windows and widgets would look).</p>
<p>These are vastly different approaches to GUI toolkits and have a lot of consequences. A full answer to your question would try to explore all of those. :) Here are a couple:</p>
<p>AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those toolkits can do. Advanced or newer AWT widgets that might exist on one platform might not be supported on another. Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform. People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.</p>
<p>Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view. Swing itself handles your widgets' layout and stacking. Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.</p>
<p>Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT. This made Swing unfortunately slow to catch on. However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals. Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets. Some will say it took far too long to get to this point, but most will say that it is well worth it.</p>
<p>Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.</p>
|
Mass Memory Default directory <p>in my application i want to support both mass memory and memory card. but is the defualt drive name for mass memory "F:" ?</p>
<p>or it might change . and how could i know if it changes ?!?</p>
<p>Note : Lang is C# , windows application , Mobile series :S60</p>
<p>thnx</p>
| <p>I think you mean Mass Storage Device? There is no default drive letter, and the user can always change them. It's best not to rely on the drive letter that the device will be assigned, and instead pop up a list of possible devices (see Google's picasa as an exmample)</p>
|
IOCP, Cross platform libraries? <p>I've recently bumped into something called IOCP on the windows platform, to be more precise: Input/Output Control Ports. This seems to be <i>the</i> most efficient way to code your server software when it needs to hold thousands of users concurrently.
(Correct me if I'm wrong, but thread-per-socket, polling, and asynchronous callbacks (thread on every callback) are not efficient enough.)</p>
<p>I am wondering if there are any 3rd party libraries available that implement this concept. I know the win32 api supplies us with CreateIoCompletionPort, FreeBSD has kqueue and linux in general can use /dev/epoll that works somewhat similarly... But isn't there a crossplatform library (such as boost::thread) that handles this stuff for me?</p>
| <p>Have you looked at boost::asio?
I'm not sure if it has all this functionality yet, but I believe that's one of the things it's intended for.</p>
|
Generating WordML Reports Using Templates and XPath using ASP.Net <p>I need to know how we can Generate WordML Reports Using Templates and XPath using ASP.Net.
What are its advantages.</p>
<p>A Simple How To Tutorial is what I require.</p>
| <blockquote>
<p>I need to know how we can Generate WordML Reports Using Templates and XPath using ASP.Net. ... A Simple How To Tutorial is what I require.</p>
</blockquote>
<p>Create (using Word) a document in WordML format which you'll use as a template.</p>
<p>Look at your WordML template: see that it's in XML format. Have Microsoft's WordML reference documentation, so that you understand what it means and how to modify it.</p>
<p>Define XPath expressions which identify the locations in your template which you want to modify (where "modify" probably means "insert data at run time").</p>
<p>At runtime use an API like <a href="http://www.google.com/search?hl=en&q=c%23+xpath" rel="nofollow">http://www.google.com/search?hl=en&q=c%23+xpath</a></p>
<blockquote>
<p>What are its advantages.</p>
</blockquote>
<p>Its advantages over what alternative?</p>
<p>The <strong>benefit</strong> is that the output is a Word document, whose content is based on a template plus modifications made at runtime.</p>
|
How to structure a Java EE system? How is the term application and thus the content of an EAR defined? <p>I am in the process of designing a build system and the directory structure for a large software system developed with Java EE 5. The build system will be implemented using ant.</p>
<p>We have multiple different services, which are grouped thematically. Each service offers either a web service or EJBs. Each service runs on a dedicated application server cluster. Thus, we have multiple clusters and some of these clusters can be grouped logically by topics.</p>
<p>I did read generic definitions and examples, but I am still confused about the Java EE terminology:</p>
<ul>
<li>What is a Java EE application? And thus, what is the content of an EAR file?</li>
<li>What is a Java EE Project? (the term is used by Netbeans as well as in the Java Blueprints Guidelines Project Conventions for Enterprise Applications)</li>
</ul>
<p>Do I have to put all EJB and WAR-module-package-files into one single EAR, so that this single EAR contains our complete system?</p>
<p>Or do I put each group of services into one EAR, despite the fact that these services are only grouped logically but not technically?</p>
<p>Or do I assemble a separate EAR for each service, i.e. most often only containing a single EJB jar file and sometimes and EJB and a WAR file?</p>
<p>Or do I dismiss the concept of applications and merely build EJB and WAR files, so that I have exactly one deployment file for each application server cluster?</p>
<p>I guess, my main question is: What are the advantages of packaging EAR files?</p>
<p>As I see it at the moment, there is only the need for EAR-EJB and WAR files and additionally the concept of nested subproject in the ant-build-system and the directory structure of our source?</p>
<p>Edit: Thanks a lot for the answers! It seems to me that an application packaged into an ear is a rather atomic subsystem. So I guess, that I will have a nested subproject-structure (only logical, visible only to the build system and in the directory structure of the source) and a rather large amount of EARs, each of those containing mostly only one ejb-jar and/or war module and implementing a single service (which is deployed on a single application server cluster).</p>
| <p>Lots of questions here.</p>
<p>Java EE projects are either EAR or WAR deployments that use Java EE technology. If you have a WAR with JSPs and JDBC access of a relational database, that's a Java EE project. The original intent was that EAR files were "enterprise", and that meant EJBs. An EAR file an contain EJBs, WARs, JARs, the whole enchilada.</p>
<p>Thinking in terms of services are a little different. I think deployment deserves careful consideration, because components that are packaged together must be brought down and up together if any maintenance has to be done.</p>
<p>So think carefully about how you package your services. It's not an all or none blanket answer, IMO. You should look at what your services are doing and how they might be used together to decide how they should be packaged and deployed.</p>
|
Remove whitespace before a field using AWK <p>(<em>Almost exact duplicate of <a href="http://stackoverflow.com/questions/408469/keeping-original-format-post-passing-through-awk">http://stackoverflow.com/questions/408469/keeping-original-format-post-passing-through-awk</a> submitted by same person.</em>)</p>
<p>I have a simple question pertaining to <b>g</b>awk, illustrated below:</p>
<pre><code> 1 int blah (void)
2 {
3 if (foo) {
4 printf ("blah\n");
5 }
6 return 0;
7 }
</code></pre>
<p>Using the following gawk code - using gensub() to maintain original formatting:</p>
<pre><code> gawk '{ print gensub($1, "\t", 1) }' ./sample_code.out
int blah (void)
{
if (foo) {
printf ("blah\n");
}
return 0;
}
</code></pre>
<p>How can I use <b>g</b>awk or awk (maybe with regular expressions) to remove previous whitespace before field $1 <b>(^ )</b></p>
<p>Illustrated below:</p>
<pre><code> int blah (void)
{
if (foo) {
printf ("blah\n");
}
return 0;
}
</code></pre>
<p>Kind regards in advance</p>
| <pre><code>awk '{sub(/^[ \t]+/, ""); print}'
</code></pre>
<p>This is from the famous awk 1 liners list, can be found here: <a href="http://student.northpark.edu/pemente/awk/awk1line.txt" rel="nofollow">http://student.northpark.edu/pemente/awk/awk1line.txt</a></p>
|
Accessing a Class that is NOT declared in App_Code in ASP.NET <p>I sometimes define Business Logic classes to "help" my ASPX code-behind classes. It makes the most sense to me to include them both in the code-behind file since they work together. However, I'd occasionally like to access the Business Logic classes from higher level classes defined in App_Code but they aren't automatically accessible outside of the file.</p>
<p>Thus, the question: it is easy to access classes defined in App_Code but how do I access classes defined elsewhere?</p>
<p>UPDATE: One other thing, the ASPX page class and the App_Code class are in the same namespace - that isn't the issue.</p>
<p>NOTE: I have taken the advice of those who have responded (thanks guys) and am refactoring to make class access easier. However, I don't think the question is actually answered yet (in the case of an ASP.NET Website project). I don't <em>need</em> the answer any more but, if someone could clarify what makes classes visible when they are outside of App_Code, it may well help someone else (or even me, down the road).</p>
| <p>Make sure you place your classes in a sensible namespace.</p>
<p>Place 'using' keyword in code behind files you would like to access them.</p>
<p>Or <%@ import if you are using them in inline code.</p>
<p>Put the dll that contains your classes in the /bin folder.</p>
<p>TBH I prefer to keep the separate library project in the same solution and have project reference in the Web probject. VS handles building and placing the dll for you.</p>
|
Which license can I release stand-alone (exe, dmg) shoes-applications under? <p>If I create an application, using <a href="http://shoooes.net/" rel="nofollow">Shoes</a>, would I have to license it under a open source license, or can I use it for closed-source/propietary stuff? The framework consists of a lot of moving parts, so it's not entirely clear to me.</p>
<p>EDIT: The reason why I'm asking, is because of the notes <a href="http://hackety.org/2008/06/19/stampingExesAndDmgs.html" rel="nofollow">at this page</a>:</p>
<blockquote>
<p>Since both anal_pe and XPwn are GPL, Iâm afraid this extension must be GPL as well. The rest of Shoes is MIT. Which is okay I guess since the packager isnât really needed to run Shoes apps.</p>
</blockquote>
<p>I assume that it doesn't affect the final product that the packager is GPL'ed, but I just wanted an opinion about that, other than my own guesswork.</p>
| <p>Shoes is distributed under an MIT license:</p>
<pre><code>Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
</code></pre>
<p>You should be able to use pretty much any license, even a closed source/proprietary license.</p>
<p>You're not linking against the packager, merely <em>using</em> it, so your app shouldn't fall under the requirements of the GPL.</p>
|
What do you write in your log book? <p>Everywhere I've worked, programmers carry about a ruled A4 hard-back note book. To avoid attracting attention, I dutifully carry one also, and once or twice in every meeting I nod sagely and pretend to write down something interesting. Occasionally people leave theirs unattended and I sneak a look. Mostly they seem to be writing a complete narrative of everything they do in the order it happened. Some fill book after book with tiny scrawl like the Kevin Spacey character in 'Seven'.</p>
<p>I can't seem to organize these books like everyone else. Almost all of the paper I generate I throw away, so I work with loose sheets. The things which need preserving end up in design docs or a wiki. TODOs are best tracked as Post-Its on my monitor. Browser bookmarks take care of most day-to-day info about 3rd party tools, and so on. </p>
<p>Could anyone who has an effective log book system please share?</p>
| <blockquote>
<p>Day 417. </p>
<p>Still here. We have no source code.</p>
<p>We lost the last of Joel's 12 tests two days ago.</p>
<p>I can not get out.</p>
<p>The end comes.</p>
<p>Management failures.</p>
<p>Management failures in the deep.</p>
<p>They are coming.</p>
</blockquote>
|
Anybody using .netTiers? <p>I'm considering adopting .nettiers for a new project as it seems to provide a lot of functionality I could use.</p>
<p>Is anybody using it in anger (I'm getting the feeling it hasn't got the following it once had) and if so, what are your perceptions of it?</p>
<p>Also, I can't find any comparative performance metrics against things like SubSonic. Anybody have any strong feelings about its performance and scalability?</p>
<p>Many thanks</p>
<p>Tony</p>
| <p>Look at <a href="http://forums.subsonicproject.com/forums/p/340/1517.aspx" rel="nofollow">this</a>. It provides you with a good X vs Y comparison between the two of them.</p>
<p>A Key point that i always revise when selecting a framework to work with is:</p>
<p><strong>Will this Simplify, Make me more Productive</strong>, if you answer "Yes of course" to this, it doesnt matter what other benchmarks say, even if it's 10% slower in running than SubSonic or even faster, you should go with the framework you develop the fastest and most that you are the most comfy in.</p>
|
How to vectorize with gcc? <p>The v4 series of the <code>gcc</code> compiler can automatically vectorize loops using the <a href="http://en.wikipedia.org/wiki/SIMD" rel="nofollow">SIMD</a> processor on some modern CPUs, such as the AMD Athlon or Intel Pentium/Core chips. How is this done?</p>
| <p>This page offers details on getting gcc to automatically vectorize
loops, including a few examples:</p>
<p><a href="http://gcc.gnu.org/projects/tree-ssa/vectorization.html">http://gcc.gnu.org/projects/tree-ssa/vectorization.html</a></p>
<p>In summary, the following options will work for x86 chips with SSE2,
giving a log of loops that have been vectorized:</p>
<pre><code>gcc -O2 -ftree-vectorize -msse2 -ftree-vectorizer-verbose=5
</code></pre>
<p>Note that -msse is also a possibility, but it will only vectorize loops
using floats, not doubles or ints.</p>
|
Sorting and Grouping Nested Lists in Python <p>I have the following data structure (a list of lists)</p>
<pre><code>[
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
<p>I would like to be able to</p>
<ol>
<li><p>Use a function to reorder the list so that I can group by each item in the list. For example I'd like to be able to group by the second column (so that all the 21's are together) </p></li>
<li><p>Use a function to only display certain values from each inner list. For example i'd like to reduce this list to only contain the 4th field value of '2somename' </p></li>
</ol>
<p>so the list would look like this </p>
<pre><code>[
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
</code></pre>
| <p>For the first question, the first thing you should do is sort the list by the second field:</p>
<pre><code>x = [
['4', '21', '1', '14', '2008-10-24 15:42:58'],
['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['5', '21', '3', '19', '2008-10-24 15:45:45'],
['6', '21', '1', '1somename', '2008-10-24 15:45:49'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
]
from operator import itemgetter
x.sort(key=itemgetter(1))
</code></pre>
<p>Then you can use itertools' groupby function:</p>
<pre><code>from itertools import groupby
y = groupby(x, itemgetter(1))
</code></pre>
<p>Now y is an iterator containing tuples of (element, item iterator). It's more confusing to explain these tuples than it is to show code:</p>
<pre><code>for elt, items in groupby(x, itemgetter(1)):
print(elt, items)
for i in items:
print(i)
</code></pre>
<p>Which prints:</p>
<pre><code>21 <itertools._grouper object at 0x511a0>
['4', '21', '1', '14', '2008-10-24 15:42:58']
['5', '21', '3', '19', '2008-10-24 15:45:45']
['6', '21', '1', '1somename', '2008-10-24 15:45:49']
22 <itertools._grouper object at 0x51170>
['3', '22', '4', '2somename', '2008-10-24 15:22:03']
['7', '22', '3', '2somename', '2008-10-24 15:45:51']
</code></pre>
<p>For the second part, you should use list comprehensions as mentioned already here:</p>
<pre><code>from pprint import pprint as pp
pp([y for y in x if y[3] == '2somename'])
</code></pre>
<p>Which prints:</p>
<pre><code>[['3', '22', '4', '2somename', '2008-10-24 15:22:03'],
['7', '22', '3', '2somename', '2008-10-24 15:45:51']]
</code></pre>
|
Running an OpenID organization <p>I wrote an application recently, which relies on OpenID for authentication. A lot of web applications these days are moving to OpenID, insofar that they <em>already</em> have userid/password authentication scheme, and OpenID is just an add-on. Since my application is a new one, I decided that it makes no sense to program separate authentication mechanism based on userid/password, when I can rely on OpenID for all the authentication altogether.</p>
<p>But sure as hell, once I presented the application to a customer, she asked "well, how do we create user accounts, and reset their passwords"? Conceptually, she didn't want to make the users create their own OpenID if they don't already have one.</p>
<p>I kind-of had a pre-made response to that, which was: "You can always run your own OpenID server". I guess I didn't put too much thought into this answer though, since many implementations of OpenID server are pretty raw and need a lot of work before they could be run in production.</p>
<p>So, my question is: does anyone here have an experience of running private OpenID server purely for authenticating of her own users. Here are the features I'm looking for it to support out of the box:</p>
<ul>
<li>Ability to bulk-load user accounts</li>
<li>Self-served password resets through verification email</li>
<li>Administrative features (lock/unlock/disable accounts, troubleshoot, etc)</li>
<li>Presentable look</li>
</ul>
| <p>This doesn't directly answer their question, but how many folks are on the internet and don't have an account with Yahoo, Flickr, AIM, WordPress, Myspace, Google, or MSN? They're all OpenID providers.</p>
<p>I'd argue that for the tiny % of the 'net population who uses none of those services, just point them to Vidoop or MyOpenID and let them get an account with someone who already has a secure infrastructure.</p>
|
Auto-vectorizing vs. vectorized code by hand <p>Is it better in some sense to vectorize code by hand, using explicit pragmas or to rely on or use auto-vectorization? For optimum performance using auto-vectorization, one would have to monitor the compiler output to ensure that loops are being vectorized or modify them until they are vectorizable. </p>
<p>With hand coding, one is certain that the desired instructions are being emitted, but now the code is likely not portable (either to other architectures or other compilers).</p>
| <p>Auto vectorization never worked out well for me. To me it seems like auto-vectorization only works for very trivial loops at the moment.</p>
<p>I use the pragma/intrinsic approach and take a look at the assembly. If the compiler generates bad code (like spilling SSE registes onto the stack or adding redundant moves) I use inline assembler for the whole loop body.</p>
<p>Portability is btw not a problem. Often you start with a C/C++ loop and optimize it using intrinsics. Just keep the old loop and use it as a unit-test / fallback for your SIMD implementation. Also it's always wise to be able to remove all SIMD code from a project via a compile-time define. Debugging an application is <em>much</em> easier that way. The same define can be used for cross-compilation.</p>
|
Protecting your images, CSS and Javascript files from being used by external sites with Apache? <p>I came across a site that demonstrated a Javascript library and it asked that you please not link to the Javascript file directly from your site. That's a reasonable request. In fact, it wouldn't have occurred to me to do that instead of hosting it myself but I guess will try and save on bandwidth any way they can.</p>
<p>This got me thinking: does Apache (in a shared hosting environment) come with any simple means of either preventing this or at least making it a little more difficult by looking at the HTTP_REFERRER or the likes? Or perhaps even just ensuring you have a PHP session?</p>
| <p>Using an htaccess file you can do this.</p>
<p>Simply create a .htaccess file in the directory of the files you wish to protect with the following inside it:</p>
<pre><code>RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com(/)?.*$ [NC]
</code></pre>
<p>For more information and some other things you can do to prevent hot linking at the web server level see <a href="http://www.devpapers.com/article/242" rel="nofollow">Dev Papers article on Preventing Hotlinking</a></p>
|
Can you lock on a generic dictionary? <p>Or should you always create some other lock object?</p>
| <p>Yes, cast it to an IDictionary and lock on <code>.SyncRoot</code>:</p>
<pre><code>Generic.Dictionary<int, int> dic = new Generic.Dictionary<int, int>();
lock (((IDictionary)dic).SyncRoot)
{
// code
}
</code></pre>
<p>Thanks to this <a href="http://en.csharp-online.net/CSharp_Generics_Recipes%E2%80%94Replacing_the_Hashtable_with_Its_Generic_Counterpart">source</a> for the info.</p>
<p>Of course a thread-safe dictionary would be nice, too, as others have suggested.</p>
|
What is Java written in? <p>What language is Sun's <code>JVM</code> written in?</p>
| <p>Sun actually has multiple JVMs. The <a href="http://OpenJDK.Java.Net/groups/hotspot/">HotSpot JVM</a> is written largely in C++, because HotSpot is heavily based on the <a href="http://Strongtalk.Org/">Animorphic Smalltalk VM</a> which is <a href="http://Code.Google.Com/p/strongtalk/source/browse/#svn/trunk/vm">written in C++</a>.</p>
<p>More interesting than HotSpot is IMHO the <a href="http://Research.Sun.Com/projects/maxine/">Maxine Research VM</a>, which is <a href="http://Kenai.Com/projects/maxine/sources/maxine/show">written (almost) completely in Java</a>.</p>
|
mySQL stored procedure with .NET connector problem <p>I've seen other topics that deal with this error but none that seem to correspond to my situation.</p>
<p>First of all, my code works completely fine when i run it locally.</p>
<p>But when i upload it to the server, i get the error:</p>
<p>Parameter '?PuserName' not found in the collection.</p>
<p>Here is the C# code:</p>
<pre><code>public DataSet GetEmployeeByUsername(string username)
{
string proc = "schema.GetEmployeeByUsername";
MySqlParameter[] args = new MySqlParameter[1];
args[0] = new MySqlParameter("?PuserName", MySqlDbType.VarChar);
args[0].Value = username;
return SQLDatasetCall(args, proc);
}
protected DataSet SQLDatasetCall(MySqlParameter[] sqlparams, string call)
{
string myConString = ConfigurationManager.AppSettings["mySql"];
MySqlConnection MyConnection = new MySqlConnection(myConString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
MyConnection.Open();
MySqlCommand command = new MySqlCommand(call, MyConnection);
command.CommandType = CommandType.StoredProcedure;
if (sqlparams != null)
{
foreach (MySqlParameter param in sqlparams)
{
command.Parameters.Add(param);
}
}
DataSet ds = new DataSet();
adapter.SelectCommand = command;
adapter.Fill(ds);
adapter.Dispose();
MyConnection.Close();
return ds;
}
</code></pre>
<p>SQL code:</p>
<pre><code>delimiter |
create procedure GetEmployeeByUsername(in PuserName varchar(45))
begin
select id,
firstName,
lastName,
phone,
address1,
address2,
city,
state,
zip,
username,
password,
emptypeid
from schema.tblemployees
where
username=PuserName;
end |
delimiter;
</code></pre>
| <p>turned out microsoft Visual Web Developer wasn't correctly ftp-ing my files during the "publish" method. i downloaded filezilla and ftp-ed the files again and it worked....</p>
|
Printing named parameters <p>Archaelus suggested in <a href="http://stackoverflow.com/questions/383407/what-are-some-interesting-projects-to-solve-in-erlang-for-learning-purposes#383456">this post</a> that writing a new format routine to handle named parameters may be a good learning exercise. So, in the spirit of learning the language I wrote a formatting routine which handles named parameters.</p>
<p><br /><br />
<strong>An Example:</strong></p>
<pre><code>1> fout:format("hello ~s{name}, ~p{one}, ~p{two}, ~p{three}~n",[{one,1},{three,3},{name,"Mike"},{two,2}]).
hello Mike, 1, 2, 3
ok
</code></pre>
<p><br /><br /></p>
<p><strong>The Benchmark:</strong></p>
<pre><code>1> timer:tc(fout,benchmark_format_overhead,["hello ~s{name}, ~p{one}, ~p{two}, ~p{three}~n",[{one,1},{name,"Mike"},{three,3},{two,2}],100000]).
{421000,true}
= 4.21us per call
</code></pre>
<p>Although I suspect that much of this overhead is due to looping, as a calling the function with one loop yields a response in < 1us.</p>
<pre><code>1> timer:tc(fout,benchmark_format_overhead,["hello ~s{name}, ~p{one}, ~p{two}, ~p{three}~n",[{one,1},{name,"Mike"},{three,3},{two,2}],1]).
{1,true}
</code></pre>
<p>If there is a better way of benchmarking in erlang, please let me know.</p>
<p><br /><br />
<strong>The Code:</strong>
(which has been revised in accordance with Doug's suggestion)</p>
<pre><code>-module(fout).
-export([format/2,benchmark_format_overhead/3]).
benchmark_format_overhead(_,_,0)->
true;
benchmark_format_overhead(OString,OList,Loops) ->
{FString,FNames}=parse_string(OString,ONames),
benchmark_format_overhead(OString,OList,Loops-1).
format(OString,ONames) ->
{FString,FNames}=parse_string(OString,ONames),
io:format(FString,FNames).
parse_string(FormatString,Names) ->
{F,N}=parse_format(FormatString),
{F,substitute_names(N,Names)}.
parse_format(FS) ->
parse_format(FS,"",[],"").
parse_format("",FormatString,ParamList,"")->
{lists:reverse(FormatString),lists:reverse(ParamList)};
parse_format([${|FS],FormatString,ParamList,"")->
parse_name(FS,FormatString,ParamList,"");
parse_format([$}|_FS],FormatString,_,_) ->
throw({'unmatched } found',lists:reverse(FormatString)});
parse_format([C|FS],FormatString,ParamList,"") ->
parse_format(FS,[C|FormatString],ParamList,"").
parse_name([$}|FS],FormatString,ParamList,ParamName) ->
parse_format(FS,FormatString,[list_to_atom(lists:reverse(ParamName))|ParamList],"");
parse_name([${|_FS],FormatString,_,_) ->
throw({'additional { found',lists:reverse(FormatString)});
parse_name([C|FS],FormatString,ParamList,ParamName) ->
parse_name(FS,FormatString,ParamList,[C|ParamName]).
substitute_names(Positioned,Values) ->
lists:map(fun(CN)->
case lists:keysearch(CN,1,Values) of
false ->
throw({'named parameter not found',CN,Values});
{_,{_,V}} ->
V
end end,
Positioned).
</code></pre>
<p>As this was a learning exercise, I was hoping that those more experienced with erlang could give me tips on how to improve my code.</p>
<p>Cheers,
Mike</p>
| <p>Without comment on the algorithm, or on use of appropriate library functions... </p>
<p>I would have expected to see more use of pattern matching and recursion; for example parse_character (no longer folded) might be replaced with something like:</p>
<pre><code>parse_in_format ([], FmtStr, ParmStrs, ParmName) -> {FmtStr, ParmStrs};
parse_in_format ([${ | Vr], FmtStr, ParmStrs, ParmName) -> parse_in_name (Vr, FmtStr, ParmStrs, ParmName);
parse_in_format ([$} | Vr], FmtStr, ParmStrs, ParmName) -> throw() % etc.
parse_in_format ([V | Vr], FmtStr, ParmStrs, ParmName) -> parse_in_format (Vr, [V | FmtStr], ParmStrs, ParmName).
parse_in_name ([], FmtStr, ParmStrs, ParmName) -> throw() % etc.
parse_in_name ([$} | Vr], FmtStr, ParmStrs, ParmName) -> parse_in_format (Vr, FmtStr, [list_to_atom(lists:reverse(ParmName))|ParmStrs], "");
parse_in_name ([${ | Vr], FmtStr, ParmStrs, ParmName) -> throw() % etc.
parse_in_name ([V | Vr], FmtStr, ParmStrs, ParmName) -> parse_in_name (Vr, FmtStr, ParmStrs, [V | ParmName]).
</code></pre>
<p>Kicked off with a </p>
<pre><code>parse_in_format (FormatStr, [], [], "");
</code></pre>
|
Using Reflection To Instantiate 'Builder Pattern' (Joshua Bloch) <p>When attempting to use Joshua Bloch's "Builder Pattern" [Item 2 in <em>Effective Java Second Edition</em>] with reflection [<strong>object = constructors[index].newInstance(constructorParameterValues);</strong>] the following exception occurs:</p>
<p>java.lang.IllegalAccessException: Class info.soaj.core.util.SjUtilReflection can not access a member of class info.soaj.core.attribute.SjAttributesForThrowable with modifiers "private"</p>
<p>Note: This has been resolved. The accessible (private) constructor was being discarded and a non-accessible (override = false) was being attempted. Bottom Line: Programmer Error </p>
<p>An example Builder Class follows: </p>
<pre><code>package info.soaj.core.attribute;
import info.soaj.core.attribute.internal.SjAttributesForStronglyTypedWrappers;
import info.soaj.core.internal.string.SjPopulatedClassName;
import info.soaj.core.internal.string.SjPopulatedMethodName;
import info.soaj.core.util.internal.SjUtilThrowable;
import java.io.Serializable;
/**
* <p>
* The "Builder" pattern as documented by Joshua Bloch ("Effective Java" -
* Second Edition) is utilized to handle the variable number of required and
* optional parameters.
* </p>
*
* <p style="font-family:Verdana; font-size:10px; font-style:italic"> Copyright
* (c) 2006 - 2008 by Global Technology Consulting Group, Inc. at <a
* href="http://gtcGroup.com">gtcGroup.com </a>. </p>
*
* @author MarvinToll@gtcGroup.com
* @since v. 1.0
*/
public class SjAttributesExample implements Serializable {
/** UID */
private static final long serialVersionUID = 1L;
/** The name of class throwing the exception. */
protected final SjPopulatedClassName classname;
/** The name of method throwing the exception. */
protected final SjPopulatedMethodName methodname;
/**
* Suppresses logging; default is <code>false</code>.
*/
protected final boolean suppressLoggingOnly;
/**
* Constructor - private
*
* @param builderThrowable
*/
private SjAttributesExample(final BuilderThrowable builderThrowable) {
this.classname = builderThrowable.classname;
this.methodname = builderThrowable.methodname;
this.suppressLoggingOnly = builderThrowable.suppressLoggingOnly;
}
/**
* This static member immutable class is used to implement the builder
* pattern.
*
* @author MarvinToll@gtcGroup.com
* @since v. 1.0
*/
public static class BuilderThrowable {
/** Class name. */
private static final String CLASS_NAME = BuilderThrowable.class
.getName();
// Required attributes.
/** The name of class throwing the exception. */
protected final SjPopulatedClassName classname;
/** The name of method throwing the exception. */
protected final SjPopulatedMethodName methodname;
// Optional attributes.
/** Prevents action from occurring. Default is false. */
protected boolean suppressLoggingOnly = false;
/**
* Constructor
*
* @param classname
* @param methodname
*/
public BuilderThrowable(final String classname, final String methodname) {
super();
final String Method_Name = "BuilderThrowable";
// What happens when handling an exception throws an exception?
try {
this.classname = new SjPopulatedClassName(classname,
new SjAttributesForStronglyTypedWrappers(CLASS_NAME,
Method_Name));
this.methodname = new SjPopulatedMethodName(methodname,
new SjAttributesForStronglyTypedWrappers(CLASS_NAME,
Method_Name));
} catch (final RuntimeException e) {
// Log the contextual details.
SjUtilThrowable.logExceptionOccuredWhileThrowingException(
CLASS_NAME, Method_Name, e);
throw e;
}
return;
}
/**
* This method sets a flag to suppress logging.
*
* @param isLoggingSuppressed
* @return BuilderThrowable
*/
public BuilderThrowable suppressLoggingOnly(
final boolean isLoggingSuppressed) {
this.suppressLoggingOnly = isLoggingSuppressed;
return this;
}
/**
* This method is used for instantiating this class.
*
* @return SjAttributesForThrowable
*/
@SuppressWarnings("synthetic-access")
public SjAttributesExample build() {
return new SjAttributesExample(this);
}
}
/**
* This method returns an attribute.
*
* @return String - Returns the <code>classname</code> attribute.
*/
public String getClassname() {
return this.classname.getString();
}
/**
* This method returns an attribute.
*
* @return String - Returns the <code>methodname</code> attribute.
*/
public String getMethodname() {
return this.methodname.getString();
}
/**
* This method returns an attribute.
*
* @return boolean - Returns the <code>suppressLoggingOnly</code> attribute.
*/
public boolean isLoggingSuppressed() {
return this.suppressLoggingOnly;
}
}
</code></pre>
| <p>Note: This has been resolved. The accessible (private) constructor was being discarded and a non-accessible (override = false) was being attempted. Bottom Line: Programmer Error </p>
|
Linking page title block to home - best practises? <p>I do most if not all my sites to have the page title block (generally a styled h1 on my pages) to link back to the home page. </p>
<p>Should this be linked on the first page, i.e. the home page? I read that this shouldn't be linked, but one thing I do when I go to a page for the first time is mouseover the title to check the status bar to see if it will send me home. </p>
<p>What I'm asking is best practises for this... should the home page's title link back to itself for future reference for the user?</p>
| <p>See sites such as facebook - the facebook logo always links to the homepage.</p>
<p>It's a strong convention, and I try to utilize it where ever practicable.</p>
|
Ruby Basics <p>What is the best online resource for learning the ruby language? Preferably intermediate and advanced topics.</p>
| <p>For start with the language:</p>
<ul>
<li><a href="http://www.ruby-lang.org/en/documentation/" rel="nofollow">Ruby Documentation</a></li>
<li>Why's Poignant Guide To Ruby (offline since August 2009)
<ul>
<li><a href="http://www.scribd.com/doc/8545174/Whys-Poignant-Guide-to-Ruby" rel="nofollow">Mirror 1</a> (Scribd)</li>
<li><a href="http://www.ember.co.nz/resources/whys-poignant-guide-to-ruby/" rel="nofollow">Mirror 2</a> (PDF Version)</li>
<li><a href="http://mislav.uniqpath.com/poignant-guide/" rel="nofollow">Mirror 3</a> (HTML Version)</li>
</ul></li>
<li><a href="http://www.ruby-doc.org/docs/ProgrammingRuby/" rel="nofollow">Programming Ruby</a></li>
<li><a href="http://www.sapphiresteel.com/The-Book-Of-Ruby" rel="nofollow">The Book Of Ruby</a></li>
<li><a href="http://tryruby.hobix.com/" rel="nofollow">Ruby online interpreter</a></li>
</ul>
<p>And if you'll use Rails, these screencasts are excellent:</p>
<ul>
<li><a href="http://rubyonrails.org/screencasts" rel="nofollow">Ruby on Rails Screencasts</a></li>
<li><a href="http://railscasts.com/" rel="nofollow">Railscasts.com</a></li>
</ul>
|
Table per Concrete Class Hierarchy in Hibernate <p>I have the following Hibernate Mapping, which has to be mapped using the Table per Concrete Class Hierarchy:</p>
<pre><code><hibernate-mapping package='dao'>
<meta attribute='class-description'></meta>
<class name='PropertyDAO'>
<id name='id' column='id_property'>
<generator class='assigned'/>
</id>
<property name='address' column='address' type='string'/>
<union-subclass name='HouseDAO' table='house'>
<property name='noOfRooms' column='noOfRooms'/>
<property name='totalArea' column='totalArea'/>
<property name='price' column='price'/>
</union-subclass>
<union-subclass name='LandDAO' table='land'>
<property name='area' column='area'/>
<property name='unitPrice' column='unitPrice'/>
</union-subclass>
</class>
</hibernate-mapping>
</code></pre>
<p>Which means in the database i have only 2 tables : </p>
<ul>
<li>house (id_property(PK), address, noOfRooms, totalArea, price)</li>
<li>land (id_property(PK), address, area, unitPrice)</li>
</ul>
<p>As far as I understood, in this case the ids need to be generated explicitly before calling .save(), so my question is: How can I create a strategy for the automatically generation of the ids, so that the ids from the concrete class form a continuous domain when joined.</p>
| <p>IMHO your model in the DB is wrong as you have redundant information across multiple tables which are related. </p>
<p>Table per concrete class is an inheritance model which gives problems at runtime as you can have the situation where one updates the address of Land but not of House while they're the same (semantically). I.o.w.: drop this model and introduce table-per-subclass, so you have a property base table with id and address and two separated tables with a PK which is an FK to the pk of property base, one is house with the house specific fields, the other is land with the land specific fields. </p>
<p>That will give you the smallest number of problems as it's the way to convert inheritance between entity types to relational tables (see Nijssen/Halpin's books about NIAM/ORM)</p>
|
Can I change the thickness of the border of a window with MFC? <p>Normally, the thickness of a window is 4 pixels, which can be retrieved by GetSystemMetrics method. Can I change its value, for example 2 pixels?</p>
<p>Thank you very much!</p>
| <p>Simple answer: No. Not for a specific window.</p>
<p>Complicated answer: The border is drawn as part of the "non-client" region of the window. This is all handled (under the hood) by the default processing (i.e. DefWindowProc), along with the caption, minimize, maximize buttons, etc. You can override this by handling the WM_NCPAINT message. You'll then be responsible for drawing the entire non-client area of your window. You'll also want to handle the WM_NCCALCSIZE message, so that Windows knows how much of the remaining space to give to your client area.</p>
<p>Alternatively, you can set the border style of your window to none. This will allow Windows to draw the caption for you, although it'll probably look slightly different. Unfortunately, by doing this, you lose the drag-to-resize functionality. For that, you'll need to handle the WM_NCHITTEST message.</p>
|
How can I make a button like 'Digg it' for my website? <p>I've got a blogging site hosted on Windows Sever, ASP.Net 3.5, ASP.Net AJAX, SQL Server in background.</p>
<p>I want to give bloggers a button like 'digg-it' which they can put on their blogs for the readers to click to thumb-up the post if they like it.</p>
<p>I know I'll be using Javascript to do that. What can I do to: -</p>
<ol>
<li>Retrieve code from my website which will display the current count of the thumb-up.</li>
<li>Increase the count on my website if the user thumbs up something.</li>
</ol>
<p>Since most of these blogs are on blogger.com/wordpress.com, the plugin code will be embedded in the blog theme. I guess I will be using the URL of the blog post as the unique id. My problem is how to get my site and javascript that's on blogger.com talking.</p>
<p>Your help will be appreciated.</p>
<p>Thanks</p>
| <p>You can look into using SCRIPT callbacks loading JSON data instead of using XmlHttpRequest to get around the crossdomain issues.</p>
<pre><code>function dynScript(url){
var script=document.createElement('script');
script.src=url;
script.type="text/javascript";
document.getElementsByTagName('head')[0].appendChild(script);
}
function handleYourData(json) {
// Do something with your response data if you need to, like alter
// dom.
}
function thumbUp(postId) {
dynScript('http://yourdomain.com/path/to/thumbHandler?callback=handleYourData&thumbs=up&postId=' + postId);
}
function thumbDown(postId) {
dynScript('http://yourdomain.com/path/to/thumbHandler?callback=handleYourData&thumbs=down&postId=' + postId);
}
</code></pre>
<p>You can use it like this in your HTML.</p>
<pre><code><a onClick="thumbUp(521);">Thumb up</a> | <a onClick="thumbDown(521);">Thumb Down</a>
</code></pre>
<p>Your <code>thumbHandler</code> code would have to output JSON with <code>handleYourData()</code> wrapped around it so that your callback will be called with the JSON data as the argument.</p>
|
How to trace a NullPointerException in a chain of getters <p>If I get a NullPointerException in a call like this:</p>
<pre><code>someObject.getSomething().getSomethingElse().
getAnotherThing().getYetAnotherObject().getValue();
</code></pre>
<p>I get a rather useless exception text like:</p>
<pre><code>Exception in thread "main" java.lang.NullPointerException
at package.SomeClass.someMethod(SomeClass.java:12)
</code></pre>
<p>I find it rather hard to find out wich call actually returend null, often finding myself refactoring the code to something like this:</p>
<pre><code>Foo ret1 = someObject.getSomething();
Bar ret2 = ret1.getSomethingElse();
Baz ret3 = ret2.getAnotherThing();
Bam ret4 = ret3.getYetAnotherOject();
int ret5 = ret4.getValue();
</code></pre>
<p>and then waiting for a more descriptive NullPointerException that tells me which line to look for.</p>
<p>Some of you might argue that concatening getters is bad style and should be avoided anyway, but my Question is: Can I find the bug without changing the code? </p>
<p>Hint: I'm using eclipse and I know what a debugger is, but I can't figuere out how to apply it to the problem.</p>
<p><strong>My conclusion on the answers:</strong><br />
Some answers told me that I should not chain getters one after another, some answers showed my how to debug my code if I disobayed that advice.</p>
<p>I've accepted an answer that taught me excactly when to chain getters:</p>
<ul>
<li>If they cannot return null, chain them as long as you like. No need for checking != null, no need to worry about NullPointerExceptions (<em>be warned that chaining still vialotes the law of demeter, but I can live with that</em>)</li>
<li>If they may return null, don't ever, never ever chain them, and perform a check for null values on each one that may return null</li>
</ul>
<p>This makes any good advice on actual debugging useless.</p>
| <p>The answer depends on how you view (the contract of) your getters. If they may return <code>null</code> you should really check the return value each time. If the getter should not return <code>null</code>, the getter should contain a check and throw an exception (<code>IllegalStateException</code>?) instead of returning <code>null</code>, that you promised never to return. The stacktrace will point you to the exact getter. You could even put the unexpected state your getter found in the exception message.</p>
|
"#include" a text file in a C program as a char[] <p>Is there a way to include an entire text file as a string in a C program at compile-time?</p>
<p>something like:</p>
<ul>
<li><p>file.txt:</p>
<pre><code>This is
a little
text file
</code></pre></li>
<li><p>main.c:</p>
<pre><code>#include <stdio.h>
int main(void) {
#blackmagicinclude("file.txt", content)
/*
equiv: char[] content = "This is\na little\ntext file";
*/
printf("%s", content);
}
</code></pre></li>
</ul>
<p>obtaining a little program that prints on stdout "This is
a little
text file"</p>
<p>At the moment I used an hackish python script, but it's butt-ugly and limited to only one variable name, can you tell me another way to do it?</p>
| <p>I'd suggest using (unix util)<a href="http://www.manpagez.com/man/1/xxd/">xxd</a> for this.
you can use it like so</p>
<pre><code>$ echo hello world > a
$ xxd -i a
</code></pre>
<p>outputs:</p>
<pre><code>unsigned char a[] = {
0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x0a
};
unsigned int a_len = 12;
</code></pre>
|
What is involved in open sourcing proprietary software? <p>My primary motivation for asking this question is <a href="http://stackoverflow.uservoice.com/pages/general/suggestions/29462-make-your-software-open-source" rel="nofollow">this uservoice suggestion</a>. Jeff declined the ticket to make the SO software open source saying that it will take more time.</p>
<p>I've seen this before in various other pieces of software that have gone from proprietary to open source. So, my question is: <strong>why does it seem to take so long to make software open source?</strong> To me, it seems pretty simple: put your code on sourceforge and google code and be done with it. But there's obviously something that I'm missing in the whole process.</p>
<p>(And before anyone gets the impression that I'm trying to be critical of Jeff or anyone else that delays open sourcing their software, I'm not. I just want to get an understanding of the process for open sourcing stuff and its costs.)</p>
| <p>Usually it requires all contributors to agree, for some projects that means you have to ask quite a few people if its ok to open their code too.</p>
<p>For other projects, it requires the libraries you've used to be either open source, or taken out of the project where you've used them. IIRC Sun said they couldn't <a href="http://www.infoworld.com/article/06/06/27/79685_HNsunopensourcejava_1.html" rel="nofollow">open Java</a> for so long because they used some 3rd party code that couldn't be opened.</p>
|
How do I select individual words of a camelized word in IntelliJ IDEA <p>What is the shortcut in IntelliJ IDEA to move across or select individual words of a camelized word? Lets say I have aLongMultiWordVariableName, I want to be able to move the cursor to each word for editing or select parts of the variable.</p>
<p>Eclipse has a shortcut to do this <kbd>Ctrl</kbd>+<kbd>←</kbd>/<kbd>→</kbd> for move and <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>←</kbd>/<kbd>→</kbd> for selection.</p>
| <p>IDEA has the same keystrokes as Eclipse for camel-case words, but you have to have the CamelHumps option turned on (it's in Settings -> Editor -> General -> Smart Keys -> Use "CamelHumps" words )</p>
|
Do you usually set the default value before or set it in the else? <p>Which one of the following do you do:</p>
<pre><code>var = true;
if (...) var = false;
</code></pre>
<p>Or</p>
<pre><code>if (...) var = false;
else var = true;
</code></pre>
<p>Is there a reason you pick on or the other?</p>
<p>I'm working on the premise that nothing else is happening to var. The next line of code might be something like:</p>
<pre><code>if (var) { ... }
</code></pre>
| <p>how about var = { ...} directly since it's boolean ?</p>
|
Subversion Repository on Linux Dev <p>What's the best practice for setting up a subversion repository on a linux development machine. External users need to be able to access a specific repository, but nothing else on the machine. I know one answer is to set up a dedicated repository, but I'm looking for a single machine solution: location of repositories, accounts, backup procedures.</p>
| <p>One of the popular access methods to Subversion is via Apache module. You can set put different rights at the directory level to control access. See <a href="http://svnbook.red-bean.com/en/1.5/svn.serverconfig.choosing.html" rel="nofollow">Choosing a Server Configuration</a> and <a href="http://svnbook.red-bean.com/en/1.5/svn.serverconfig.httpd.html" rel="nofollow">httpd, the Apache HTTP Server</a>. For authentication, I recommend using external authentication source like Microsoft AD via <a href="http://sourceforge.net/projects/mod-auth-sspi/" rel="nofollow"><code>mod_auth_sspi</code></a>.</p>
<p>If you need to mix and match rights, see my answer for <a href="http://stackoverflow.com/questions/335039/how-can-i-make-only-some-folders-show-up-for-certain-developers-with-svn#336312">How can I make only some folders show up for certain developers with SVN</a>.</p>
|
Use HTTP Keep-Alive for server to communicate to client <p>Recently in an interview I was asked how I would approach an online chat client application. I went through the standard "polling" solution but was cut off because the interviewer was looking for the "HTTP 1.1 keep-alive" method. Having used HTTP for quite a while and remembering that the whole point was to be "stateless", this never occurred to me (also, not to mention that the keep-alive is not consistently implemented).</p>
<p>My question is, is it possible for a web server to broadcast and/or send information to a client when the "keep-alive" header has been set?</p>
| <p>Keep-alive simply holds a TCP socket open, so each time you poll, you save the overhead of the TCP setup/teardown packets--but you still have to poll.</p>
<p>However, "long polling" is a strategy for the web server to broadcast notifications to the client. Essentially, the client issues a GET request, but instead of immediately responding, the web server waits until they have a notification to send, at which point they respond to the GET request. This eliminates any need for packets to go across the wire for polling purposes, and keeps the connection stateless, which as you correctly mention is one of the purposes of the protocol.</p>
|
Understanding IEquatable <p>If i want to compare objects and they implement the IEquatable<> interface, i have a few questions:</p>
<ol>
<li>Why do i have to override Equals(object ) if i have to implements Equals<></li>
<li>can i use == and != once i implement IEquatable ?</li>
</ol>
| <p>Regarding #1:</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/ms131187.aspx">MSDN:</a></p>
<blockquote>
<p>If you implement <code>IEquatable<T></code>, you should also override the
base class implementations of
<code>Object::Equals(Object)</code> and
<code>GetHashCode()</code> so that their behavior is
consistent with that of the
<code>IEquatable<T>::Equals</code>
method. If you do override
<code>Object::Equals(Object)</code>, your
overridden implementation is also
called in calls to the static
<code>Equals(System.Object, System.Object)</code>
method on your class. This ensures
that all invocations of the <code>Equals()</code>
method return consistent results.</p>
</blockquote>
<p>2)
No, these do plain reference comparisons and do not use the Equals method.</p>
|
How to create a series of dates in Cocoa for a week <p>I am current writing an application and need to show the current days of the week.</p>
<p>So, for the coming week I need to generate the follow dates.</p>
<p>Monday, 5 January 2009
Tuesday, 6 January 2009
Wednesday, 7 January 2009
Thursday, 8 January 2009
Friday, 9 January 2009</p>
<p>I have already coded the application to generate five dates from the current date. The problem I have is finding a method to create Monday through to Friday on the current week.</p>
<p>I am running OS X 10.5 and am using the Cocoa environment.</p>
| <p>Look at <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/Reference/NSCalendar.html" rel="nofollow">NSCalendar</a> and <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Classes/NSDateComponents_Class/Reference/Reference.html" rel="nofollow">NSDateComponents</a>.</p>
<p>If you haven't, you should read <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html" rel="nofollow">Dates and Times Programming Topics for Cocoa</a> for more info/help.</p>
|
Why does FogBugz require that the DEP is turned off? <p>I am really wondering why FogBugz when installed locally insists that <a href="http://support.microsoft.com/default.aspx/kb/875352" rel="nofollow">DEP</a> is turned off? </p>
| <p>FogBugz 6 (and earlier) requires that Data Execution Prevention (DEP) be disabled on versions of Windows that have DEP, <strong>because of a third-party COM component</strong> that we use for parsing email. We will fix this in the next major release of FogBugz: FogBugz will no longer use this third-party component (in fact, the next version of FogBugz will not use <em>any</em> COM components).</p>
|
Enterprise Library Unity vs Other IoC Containers <p>What's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor, Spring.Net, Autofac ..)?</p>
| <p>I am preparing a presentation for a usergroup. As such I just went through a bunch of them. Namely: AutoFac, MEF, Ninject, Spring.Net, StructureMap, Unity, and Windsor.</p>
<p>I wanted to show off the 90% case (constructor injection, which is mainly what people use an IOC for anyway).
<a href="https://cid-b0ed6c076f2f2bfe.skydrive.live.com/self.aspx/Public/IocDemo.zip">You can check out the solution here (VS2008)</a></p>
<p>As such, there are a few key differences:</p>
<ul>
<li>Initialization</li>
<li>Object retrieval</li>
</ul>
<p>Each of them have other features as well (some have AOP, and better gizmos, but generally all I want an IOC to do is create and retrieve objects for me)</p>
<p>Note: the differences between the different libraries object retrieval can be negated by using the CommonServiceLocator: <a href="http://www.codeplex.com/CommonServiceLocator">http://www.codeplex.com/CommonServiceLocator</a></p>
<p>That leaves us with initialization, which is done in two ways: via code or via XML configuration (app.config/web.config/custom.config). Some support both, some support only one. I should note: some use attributes to help the IoC along.</p>
<p>So here is my assessment of the differences:</p>
<h3><a href="http://ninject.org/">Ninject</a></h3>
<p>Code initialization only (with attributes). I hope you like lambdas. Initialization code looks like this:</p>
<pre><code> IKernel kernel = new StandardKernel(
new InlineModule(
x => x.Bind<ICustomerRepository>().To<CustomerRepository>(),
x => x.Bind<ICustomerService>().To<CustomerService>(),
x => x.Bind<Form1>().ToSelf()
));
</code></pre>
<h3><a href="http://structuremap.sourceforge.net/">StructureMap</a></h3>
<p>Initialization code or XML or Attributes. v2.5 is also very lambda'y. All in all, this is one of my favorites. Some very interesting ideas around how StructureMap uses Attributes.</p>
<pre><code>ObjectFactory.Initialize(x =>
{
x.UseDefaultStructureMapConfigFile = false;
x.ForRequestedType<ICustomerRepository>()
.TheDefaultIsConcreteType<CustomerRepository>()
.CacheBy(InstanceScope.Singleton);
x.ForRequestedType<ICustomerService>()
.TheDefaultIsConcreteType<CustomerService>()
.CacheBy(InstanceScope.Singleton);
x.ForConcreteType<Form1>();
});
</code></pre>
<h3><a href="http://codeplex.com/unity">Unity</a></h3>
<p>Initialization code and XML. Nice library, but XML configuration is a pain in the butt. Great library for Microsoft or the highway shops.
Code initialization is easy:</p>
<pre><code> container.RegisterType<ICustomerRepository, CustomerRepository>()
.RegisterType<ICustomerService, CustomerService>();
</code></pre>
<h3><a href="http://www.springframework.net/">Spring.NET</a></h3>
<p>XML only as near as I can tell. But for functionality Spring.Net does everything under the sun that an IoC can do. But because the only way to unitize is through XML it is generally avoided by .net shops. Although, many .net/Java shop use Spring.Net because of the similarity between the .net version of Spring.Net and the Java Spring project. </p>
<p><strong>Note</strong>: Configuration in the code is now possible with the introduction of <a href="http://www.springframework.net/codeconfig/">Spring.NET CodeConfig</a>.</p>
<h3><a href="http://www.castleproject.org/container/index.html">Windsor</a></h3>
<p>XML and code. Like Spring.Net, Windsor will do anything you could want it to do. Windsor is probably one of the most popular IoC containers around.</p>
<pre><code>IWindsorContainer container = new WindsorContainer();
container.AddComponentWithLifestyle<ICustomerRepository, CustomerRepository>("CustomerRepository", LifestyleType.Singleton);
container.AddComponentWithLifestyle<ICustomerService, CustomerService>("CustomerService",LifestyleType.Singleton);
container.AddComponent<Form1>("Form1");
</code></pre>
<h3><a href="http://code.google.com/p/autofac/">Autofac</a></h3>
<p>Can mix both XML and code (with v1.2). Nice simple IoC library. Seems to do the basics with not much fuss. Supports nested containers with local scoping of components and a well-defined life-time management.</p>
<p>Here is how you initialize it:</p>
<pre><code>var builder = new ContainerBuilder();
builder.Register<CustomerRepository>()
.As<ICustomerRepository>()
.ContainerScoped();
builder.Register<CustomerService>()
.As<ICustomerService>()
.ContainerScoped();
builder.Register<Form1>();
</code></pre>
<hr>
<p>If I had to choose today: I would probably go with StructureMap. It has the best support for C# 3.0 language features, and the most flexibility in initialization.</p>
<p><strong>Note</strong>: Chris Brandsma turned his original answer into a <a href="http://elegantcode.com/2009/01/07/ioc-libraries-compared/">blog post</a>.</p>
|
How can I parse dates and convert time zones in Perl? <p>I've used the <a href="http://perldoc.perl.org/functions/localtime.html">localtime</a> function in Perl to get the current date and time but need to parse in existing dates. I have a GMT date in the following format: "20090103 12:00" I'd like to parse it into a date object I can work with and then convert the GMT time/date into my current time zone which is currently Eastern Standard Time. So I'd like to convert "20090103 12:00" to "20090103 7:00" any info on how to do this would be greatly appreciated.</p>
| <p>Because the Perl built in date handling interfaces are kind of clunky and you wind up passing around a half dozen variables, the better way is to use either <a href="http://search.cpan.org/perldoc?DateTime">DateTime</a> or <a href="http://search.cpan.org/perldoc?Time::Piece">Time::Piece</a>. DateTime is the all-singing, all-dancing Perl date object, and you'll probably eventually want to use it, but Time::Piece is simpler and perfectly adequate to this task, has the advantage of shipping with 5.10 and the technique is basically the same for both.</p>
<p>Here's the simple, flexible way using Time::Piece and <a href="http://opengroup.org/onlinepubs/007908799/xsh/strftime.html">strptime</a>.</p>
<pre><code>#!/usr/bin/perl
use 5.10.0;
use strict;
use warnings;
use Time::Piece;
# Read the date from the command line.
my $date = shift;
# Parse the date using strptime(), which uses strftime() formats.
my $time = Time::Piece->strptime($date, "%Y%m%d %H:%M");
# Here it is, parsed but still in GMT.
say $time->datetime;
# Get your local time zone offset and add it to the time.
$time += $time->localtime->tzoffset;
# And here it is localized.
say $time->datetime;
</code></pre>
<p>And here's the by-hand way, for contrast.</p>
<p>Since the format is fixed, a regular expression will do just fine, but if the format changes you'll have to tweak the regex.</p>
<pre><code>my($year, $mon, $day, $hour, $min) =
$date =~ /^(\d{4}) (\d{2}) (\d{2})\ (\d{2}):(\d{2})$/x;
</code></pre>
<p>Then convert it to Unix epoch time (seconds since Jan 1st, 1970)</p>
<pre><code>use Time::Local;
# Note that all the internal Perl date handling functions take month
# from 0 and the year starting at 1900. Blame C (or blame Larry for
# parroting C).
my $time = timegm(0, $min, $hour, $day, $mon - 1, $year - 1900);
</code></pre>
<p>And then back to your local time.</p>
<pre><code>(undef, $min, $hour, $day, $mon, $year) = localtime($time);
my $local_date = sprintf "%d%02d%02d %02d:%02d\n",
$year + 1900, $mon + 1, $day, $hour, $min;
</code></pre>
|
How do I retrieve a Django model class dynamically? <p>Without having the full module path of a Django model, is it possible to do something like:</p>
<pre><code>model = 'User' [in Django namespace]
model.objects.all()
</code></pre>
<p>...as opposed to:</p>
<pre><code>User.objects.all().
</code></pre>
<p>EDIT: I am trying to make this call based on command-line input. Is it possible to avoid the import statement, e.g., </p>
<pre><code>model = django.authx.models.User
</code></pre>
<p>Without Django returning the error:</p>
<pre><code>"global name django is not defined."
</code></pre>
| <p>I think you're looking for this:</p>
<pre><code>from django.db.models.loading import get_model
model = get_model('app_name', 'model_name')
</code></pre>
<p>There are other methods, of course, but this is the way I'd handle it if you don't know what models file you need to import into your namespace. (Note there's really no way to safely get a model without first knowing what app it belongs to. Look at the source code to loading.py if you want to test your luck at iterating over all the apps' models.)</p>
<p><strong>Update:</strong> According to Django's <a href="https://docs.djangoproject.com/en/dev/internals/deprecation/#deprecation-removed-in-1-9" rel="nofollow">deprecation timeline</a>, <code>django.db.models.loading</code> has been deprecated in Django 1.7 and will be removed in Django 1.9. As pointed out in <a href="http://stackoverflow.com/a/28380435/996114">Alasdair's answer</a>, a new API for dynamically loading models was added to Django 1.7.</p>
|
Possible to call Oracle FUNCTION from .Net using Enterprise Library? <p>I have the following Oracle function:</p>
<pre><code>function get_job_no return number is
V_job_no number;
begin
select appwork.tlm_corphier_job.nextval into V_job_no from dual;
return V_job_no;
end get_job_no;
</code></pre>
<p>PLEASE NOTE:<br />
1) This is a FUNCTION, not a procedure<br />
2) This is returning a NUMBER, not a VARCHAR<br />
3) I happen to be using System.Data.OracleClient rather than Oracle.DataAccess.Client (due to another issue I was having) but a solution with either would be fine. </p>
<p>I am trying to call this from VB.Net using the MS enterprise library like so:</p>
<pre><code>Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports System.Data.OracleClient
Public Function GetNextJobNumber() As Object
Dim db As Database = DatabaseFactory.CreateDatabase()
Dim myresult As Object = Nothing
Using cmd As DbCommand = db.GetStoredProcCommand("CORPHIER_PKG.get_job_no")
Dim retval As New Data.OracleClient.OracleParameter("retval", GetType(System.Data.OracleClient.OracleNumber))
retval.Direction = ParameterDirection.ReturnValue
cmd.Parameters.Add(retval)
db.ExecuteNonQuery(cmd)
myresult = retval.Value
End Using
Return myresult
End Function
</code></pre>
<p>I get the following error:</p>
<p>System.InvalidCastException: Failed to convert parameter value from a RuntimeType to a Decimal. ---> System.InvalidCastException: Object must implement IConvertible.
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Data.OracleClient.OracleParameter.CoerceValue(Object value, MetaType destinationType)
--- End of inner exception stack trace ---
at System.Data.OracleClient.OracleParameter.CoerceValue(Object value, MetaType destinationType)
at System.Data.OracleClient.OracleParameter.SetCoercedValueInternal(Object value, MetaType metaType)
at System.Data.OracleClient.OracleParameterBinding.PrepareForBind(OracleConnection connection, Int32& offset)
at System.Data.OracleClient.OracleCommand.Execute(OciStatementHandle statementHandle, CommandBehavior behavior, Boolean needRowid, OciRowidDescriptor& rowidDescriptor, ArrayList& resultParameterOrdinals)
at System.Data.OracleClient.OracleCommand.ExecuteNonQueryInternal(Boolean needRowid, OciRowidDescriptor& rowidDescriptor)
at System.Data.OracleClient.OracleCommand.ExecuteNonQuery()
at Microsoft.Practices.EnterpriseLibrary.Data.Database.DoExecuteNonQuery(DbCommand command)
at Microsoft.Practices.EnterpriseLibrary.Data.Database.ExecuteNonQuery(DbCommand command)</p>
| <p>Ok, this seems to work:</p>
<pre><code>Public Function GetNextJobNumber() As Object
Dim db As Database = DatabaseFactory.CreateDatabase()
Using cmd As DbCommand = db.GetStoredProcCommand("CORPHIER_PKG.get_job_no")
db.AddParameter(cmd, "retval", DbType.Int32, 0, ParameterDirection.ReturnValue, True, 0, 0, String.Empty, DataRowVersion.Current, Convert.DBNull)
db.ExecuteNonQuery(cmd)
Return db.GetParameterValue(cmd, "retval")
End Using
End Function
</code></pre>
|
RewriteRule but keep the subdomain <p>I would like to redirect the following as an example:</p>
<pre><code>A.olddomain.com.au/blah.html > A.newdomain.com/blah.html
B.olddomain.com.au/blah.html > B.newdomain.com/blah.html
</code></pre>
<p>Essentially, I have a variable number of subdomains and I only want to change the domain name itself on the redirect.</p>
<p>Any clues or suggestions to try out?</p>
<p>Thanks.</p>
| <p>This should work for the HTTP case</p>
<pre><code>RewriteCond %{HTTP_HOST} (.*)\.olddomain\.com\.au
RewriteRule (.*) http://%1.newdomain.com/$1
</code></pre>
<p>If you use both HTTP and HTTPS you'd have to use two set of rules, one for HTTP and the other for HTTPS</p>
<pre><code>RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} (.*)\.olddomain\.com\.au
RewriteRule (.*) https://%1.newdomain.com/$1
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} (.*)\.olddomain\.com\.au
RewriteRule (.*) http://%1.newdomain.com/$1
</code></pre>
|
How do I skip items when tabbing without using tabindex? <p>Is there a good way, in a javascript onfocus() handler, to trampoline the focus to the next item in the tab order, without having to manually enter the ID of the item that should be next?</p>
<p>I built an HTML date picker in Django/jQuery. It's a line edit followed by a calendar icon that pops up a calendar. I want to be able to tab from the line edit to the next input, skipping the link for the calendar icon. I mean for it to be a generalized widget, so I can't hardcode the id of whatever is next and call .focus(). I know I could set tabindex attributes on everything, but that's more manual than I'd like. Also, iirc, that wouldn't prevent it from taking the focus, it would just put it at the end of the tab order.</p>
| <p>Set tabindex = "-1" for that control and browser will skip that control from tabbing.</p>
|
TDD - How much do you test? <p>I'm working on a new project and I'm using the repository pattern, I have my repository that pulls the data from the database and a "service" class which uses the repository and does all the business logic.</p>
<p>something similar to the following;</p>
<pre><code>public class UserRepository : IUserRepository
{
public IQueryable<User> GetUsers()
{
// do stuff
}
}
public class UserService
{
public IList<User> GetUserById
{
var rep = new UserRepository();
var users = rep.GetUsers();
// do business logic
return users.ToList();
}
}
</code></pre>
<p>Would you test both the UserService and the UserRepository or do you think testing just the Service would suffice? I figure since the service is using the repository it should be fun, but it does kill code coverage.</p>
| <p>You should test them both, because it's possible that someday there will be other clients of UserRepository than UserService, and those clients may use UserRepository differently than UserService.</p>
|
FormsAuthentication.SignOut() does not log the user out <p>Smashed my head against this a bit too long. How do I prevent a user from browsing a site's pages after they have been logged out using FormsAuthentication.SignOut? I would expect this to do it:</p>
<pre><code>FormsAuthentication.SignOut();
Session.Abandon();
FormsAuthentication.RedirectToLoginPage();
</code></pre>
<p>But it doesn't. If I type in a URL directly, I can still browse to the page. I haven't used roll-your-own security in a while so I forget why this doesn't work.</p>
| <p>Users can still browse your website because cookies are not cleared when you call <code>FormsAuthentication.SignOut()</code> and they are authenticated on every new request. In MS documentation is says that cookie will be cleared but they don't, bug?
Its exactly the same with <code>Session.Abandon()</code>, cookie is still there.</p>
<p>You should change your code to this:</p>
<pre><code>FormsAuthentication.SignOut();
Session.Abandon();
// clear authentication cookie
HttpCookie cookie1 = new HttpCookie(FormsAuthentication.FormsCookieName, "");
cookie1.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie1);
// clear session cookie (not necessary for your current problem but i would recommend you do it anyway)
SessionStateSection sessionStateSection = (SessionStateSection)WebConfigurationManager.GetSection("system.web/sessionState");
HttpCookie cookie2 = new HttpCookie(sessionStateSection.CookieName, "");
cookie2.Expires = DateTime.Now.AddYears(-1);
Response.Cookies.Add(cookie2);
FormsAuthentication.RedirectToLoginPage();
</code></pre>
<p><code>HttpCookie</code> is in the <code>System.Web</code> namespace. <a href="https://msdn.microsoft.com/en-us/library/system.web.httpcookie(v=vs.110).aspx" rel="nofollow">MSDN Reference</a>.</p>
|
Combine paths in Java <p>Is there a Java equivalent for <a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx"><code>System.IO.Path.Combine()</code></a> in C#/.NET? Or any code to accomplish this?</p>
<p>This static method combines one or more strings into a path.</p>
| <p>Rather than keeping everything string-based, you should use a class which is designed to represent a file system path.</p>
<p>If you're using Java 7 or Java 8, you should strongly consider using <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html"><code>java.nio.file.Path</code></a>; <code>Path.resolve</code> can be used to combine one path with another, or with a string. The <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/Paths.html"><code>Paths</code></a> helper class is useful too. For example:</p>
<pre><code>Path path = Paths.get("foo", "bar", "baz.txt");
</code></pre>
<p>If you need to cater for pre-Java-7 environments, you can use <a href="http://java.sun.com/javase/6/docs/api/java/io/File.html"><code>java.io.File</code></a>, like this:</p>
<pre><code>File baseDirectory = new File("foo");
File subDirectory = new File(baseDirectory, "bar");
File fileInDirectory = new File(subDirectory, "baz.txt");
</code></pre>
<p>If you want it back as a string later, you can call <code>getPath()</code>. Indeed, if you really wanted to mimic <code>Path.Combine</code>, you could just write something like:</p>
<pre><code>public static String combine(String path1, String path2)
{
File file1 = new File(path1);
File file2 = new File(file1, path2);
return file2.getPath();
}
</code></pre>
|
Problem compiling gnustep-gui-0.16.0 undefined reference to png_sizeof <p>I'm trying to compile GNUstep on a linux box but gnustep-gui-0.16.0 package is failing. I downloaded GNUstep Startup stable 0.20.1 (<a href="http://wwwmain.gnustep.org/resources/downloads.php" rel="nofollow">http://wwwmain.gnustep.org/resources/downloads.php</a>)and follow instructions about how to compile (./configure && make). I'm getting this error:</p>
<p><code>libgnustep-gui.so: undefined reference to 'png_sizeof'</code></p>
<p>I have compiled latest libpng (1.2.34) and I can see that png_sizeof is defined as macro. However, I'm not quite sure how to fix the gnustep-gui-0.16.0 build. I tried to pass the include/lib directory where libpng is installed to configure build but nothing seems to help.</p>
<p>I have quite up to date linux box but using gcc 3.3 (upgrade is not an option - but this should not be a problem).</p>
<p>Full error:</p>
<pre><code>Making all for tool set_show_service...
Compiling file set_show_service.m ...
Linking tool set_show_service ...
../Source/./obj/libgnustep-gui.so: undefined reference to `png_sizeof'
collect2: ld returned 1 exit status
gmake[3]: *** [obj/set_show_service] Error 1
gmake[2]: *** [set_show_service.all.tool.variables] Error 2
gmake[1]: *** [internal-all] Error 2
gmake[1]: Leaving directory `/home/bla/local/src/gnustep-startup-0.22.0/build/gnustep-gui-0.16.0'
gmake[3]: *** [obj/set_show_service] Error 1
gmake[2]: *** [set_show_service.all.tool.variables] Error 2
gmake[1]: *** [internal-all] Error 2
</code></pre>
<p>Any suggestions?
Thanks</p>
| <p>Note that you can run <code>make messages=yes</code> to let GNUstep-make be more verbose about what it is doing.</p>
|
Best practices/algorithm/approach for implementing temporary transaction password for banking/financial website <p>What are the best practices for implementing temporary transaction password feature for website?</p>
<p>For e.g in banking/finance scenarios like
- While transfering funds from one account to another, a transaction password is required
- While commiting a trade, a transaction password is required
- etc.</p>
<p>The password should be temporary and time based i.e. this password should not work after x minutes has elapsed.</p>
<p>What algorithm would you recommend?
Do you suggest keeping track of used passwords i.e. store used password in some store?</p>
<p>Some website use a OneTimePassword device. Apart from this please feel to highlight any other strategy you think may be appropriate.</p>
<p>Any other thoughts/suggestions/algorithm welcome.</p>
<p>Edit: Based on question from 'lassevk'</p>
<ol>
<li>The password would be communicated by email/phone/sms.</li>
<li>There is no third site involved.</li>
</ol>
<p>I require this for additional level of security for critical points in the application.
This may also be called as "AuthenticationCode". </p>
| <p><strong>Edit after updated question</strong>:</p>
<p>Well, one way would be to simply store it in the session variable, that would make it forcibly go away whenever the service is restarted.</p>
<p>Additionally you would need to have a timer on it, basically you store expiration time+password somewhere, and whenever you check the password, if the expired time is in the past, you don't have a password and just clear it.</p>
<p>If you encapsulate this away in some base code that not only checks if the right password is given, then it would need to be able to answer both <em>yes</em>, <em>no</em>, and <em>no password stored</em> so that you can give the appropriate message to the user.</p>
<p><hr /></p>
<p>A couple of questions:</p>
<ul>
<li>How would you communicate the temporary password to the user? SMS?</li>
<li>Is the password for the same site, or is it created for another, linked, site? (ie. your bank main site generates or gets hold of the password, and you use that to log on or authorize the transaction on another, related, site?)</li>
</ul>
<p>If the answers are:</p>
<ul>
<li>Via the website</li>
<li>No, same site</li>
</ul>
<p>Then what's the point? What are you hoping to gain from this? What are the specific criteria or goal for implementing this feature?</p>
|
How to to send and retrieve data from flickr flickr.test.echo method using JQuery Ajax REST? <p>I want to display whatever the response of flickr.test.echo was on the page using rest (jquery ajax - because thats what im using)</p>
<p>I need to supply an api_key</p>
<hr>
<p>The REST Endpoint URL is <a href="http://api.flickr.com/services/rest/" rel="nofollow">http://api.flickr.com/services/rest/</a></p>
<p>To request the flickr.test.echo service, invoke like this:</p>
<p><a href="http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value" rel="nofollow">http://api.flickr.com/services/rest/?method=flickr.test.echo&name=value</a></p>
<p>By default, REST requests will send a REST response.</p>
<p>To return the response in REST format, send a parameter "format" in the request with a value of "rest". When using the REST request method, the response defaults to REST.</p>
<p>A method call returns this:</p>
<p>
[xml-payload-here]
</p>
<p>If an error occurs, the following is returned:</p>
<p>
</p>
<p>I got that from here <a href="http://www.flickr.com/services/api/request.rest.html" rel="nofollow">http://www.flickr.com/services/api/request.rest.html</a></p>
<hr>
<p>This is the method I'm interested in <a href="http://www.flickr.com/services/api/flickr.test.echo.html" rel="nofollow">http://www.flickr.com/services/api/flickr.test.echo.html</a></p>
<p>please help.</p>
| <p>I'm not sure how you're going to retrieve their data with Ajax, since Ajax doesn't work cross-domain.</p>
<p>Have you seen their $.getJSON demo?
<a href="http://docs.jquery.com/Ajax/jQuery.getJSON" rel="nofollow">http://docs.jquery.com/Ajax/jQuery.getJSON</a></p>
<p>It lets you specify a callback and returns json wrapped as a parameter inside an automatically generated function. It works cross-domain as well.</p>
|
Image Uploading in ASP.NET with C# <p>I created 2 pages: page1.aspx and page2.aspx. I defined 5 fileuploader controls in page 2 but I want to save Page1.aspx on save button.</p>
<p>Actually, the page contains a Back Button in which I store all Uploading file in a string object and it populate on Page1.aspx as a session.</p>
<p>How can I save a file on server?</p>
| <p>Here are some links which can help you out with this:</p>
<p>1) <a href="http://www.codeproject.com/KB/aspnet/multiuploads.aspx" rel="nofollow">http://www.codeproject.com/KB/aspnet/multiuploads.aspx</a></p>
<p>2) <a href="http://www.dotnetcurry.com/ShowArticle.aspx?ID=68&AspxAutoDetectCookieSupport=1" rel="nofollow">http://www.dotnetcurry.com/ShowArticle.aspx?ID=68&AspxAutoDetectCookieSupport=1</a></p>
<p>3) <a href="http://www.asp.net/Learn/videos/video-252.aspx" rel="nofollow">http://www.asp.net/Learn/videos/video-252.aspx</a></p>
<p>Also couple of things to remember, the user associated with ASP.net account should have sufficient permissions on the server folder on which you are uploading the file to and the maximum size of the file is 4MB by default but you could change that using the web.config httpRuntime configuration changes.</p>
<p>Hope this would help,</p>
<p>Jomit</p>
|
SQL Delete (Suspended in activity monitor) <p>I have a table containing hundreds of entries and I am trying to delete a small range. It is taking a long time, in fact it is not being executed.</p>
<p>I monitored the query from the activity monitor and its status is "Suspended"</p>
<p>Is there anyone knows what may cause this problem?</p>
| <p>What's the SQL you're running? Any triggers on the table, or any cascaded deletes to tables that have triggers on? Anything in the "Blocked By" column or Wait Type?</p>
<p>Try executing the following in management studio (on the database in question):</p>
<pre><code>dbcc checkdb
dbcc checkcatalog
</code></pre>
|
ORM and SOA in the .NET world <p>From my experience the major ORM frameworks for .NET (<a href="http://nhforge.org" rel="nofollow">NHibernate</a>, <a href="http://msdn.microsoft.com/en-us/library/bb425822.aspx" rel="nofollow">LinqToSql</a>, <a href="http://msdn.microsoft.com/en-us/library/aa697427%28VS.80%29.aspx" rel="nofollow">Entity Framework</a>) work best when they keep track of loaded objects. This works fine for simple client-server applications, but when using three- or more tier architecture with Web Services in a Service Oriented Archtitecture, this is not possible. Eventually, by writing a lot of code to do the tracking yourself it could be done, but isn't ORM supposed to simplify DB access? </p>
<p>Is the idea to use ORM in service oriented architecture good at all? </p>
| <p><a href="http://www.llblgen.com" rel="nofollow">LLBLGen Pro</a> has change tracking inside the entities. This means that you can fetch a graph from the database using prefetch paths (so one query per graph node) and serialize it over the wire to the client, change it there, send it back and directly save the graph as all change tracking is inside the entities (and is serialized inside the XML as compact custom elements). </p>
<p>Disclaimer: I'm the lead developer of llblgen pro.</p>
|
IE prompts for password when saving an excel file <p>File is sent to the client using Response.writefile and content diposition as inline. When user chooses to Save As, they are asked to authenticate with IIS again even though Anonymous access in enabled</p>
| <p>At a guess, I'd suggest looking at the ownership of the Excel file. Presumably it would need to be readable and writable by the IUSR.</p>
|
Testing tools for Django Project <p>Can anyone please suggest some good testing tools for a Django project? </p>
<p>I need to test the different use case scenarios, unit-testing, as well as load-testing for my project. Are there any good standard testing suites available?<br>
Any other suggestion(s) for the testing process is greatly appreciated.</p>
<p>I use Django, postgresql on Ubuntu server if this information is necessary.</p>
| <p>This article about <a href="http://docs.djangoproject.com/en/dev/topics/testing/">Django Testing</a> should be a good starting point.</p>
|
NHibernate.Search with Lucene.NET without using DB? <p>Could I use NHibernate.Search only with luceneâs index without database? Because I would like to store all data only in my luceneâs index, but I really like features in NHibernate.Search.</p>
| <p>Not really, as they are tightly coupled. The point of the NHSearch/Lucene.NET/NHibernate integration is that you can do a full text search, but the results returned are domain entities, i.e. from the database.</p>
<p>So, without storing them in the database, there would be no way for NHSearch to inflate the domain objects it finds in the Lucence index.</p>
<p>One other approach would be to look at one of the document databases such as Raven.</p>
|
Best way to work with an array of pointers in Objective-C? <p>I'm trying to mimic the following Java code:</p>
<pre><code>int[][] multi; // DIMENSIONS ARE UNKNOWN AT CREATION TIME
// LATER ON...
multi = new int[10][];
multi[5] = new int[20];
multi[5][11] = 66;
// LATER ON...
multi = null; // PROPER WAY OF FREEING EVERYTHING
</code></pre>
<p>I've came out with the following Objective-C version:</p>
<pre><code>int* *multi;
//
multi = malloc(10 * sizeof(int*));
multi[5] = (int *) malloc(20 * sizeof(int));
multi[5][11] = 66;
//
free(multi[5]);
free(multi);
</code></pre>
<p>So first, I'd like to hear if it's the best way to go. And mostly: I can't find a way to free memory in some "automatic" fashion, i.e. the following code is causing run-time exceptions on the IPhone:</p>
<pre><code>for (int i = 0; i < 10; i++)
{
if (multi[i] != NULL) free(multi[i]);
}
</code></pre>
| <p>Free doesn't zero out the memory address in the pointer, it just invalidates it. So, if you're running this loop more than once, you will get exceptions when you try to free memory that has already been invalidated. You can use an NSPointerArray or wrap your integers in objects and use an NSMutableArray for your purposes, but if you just want to use what you have, and you're running the loop more than once, you will have to do something like:</p>
<pre><code>int **multi;
multi = calloc(10, sizeof(int*));
multi[5] = calloc(20, sizeof(int));
//
multi[5][11] = 66;
//
for( int i = 0; i < 10; i++ ) {
if( multi[i] ) {
free(multi[i]);
multi[i] = NULL;
}
}
//
free(multi);
</code></pre>
<p>This way if the loop is run more than once, you won't fail. Also, I use calloc instead of malloc because it will set all the pointers to NULL and integers to 0. The first parameter is the size of the array you want (in your case) and the second parameter is the size of the type (so no multiplication is required).</p>
|
Excel VBA: Is there any way to format chart axes through VBA only? <p>I have to make column charts in Excel using VBA only (no user input). I wanted to format the labels of the x-axis so that the alignment for every label becomes -270 degrees. (This can be done manually by changing the "Custom angle" property in the "Alignment" tab of the "Format Axis" Dialog.) I have tried recording a macro for this but Excel does not seem to be recording the alignment step. Does anybody know how to do this with VBA only?</p>
| <p>If you are using Excel 2007, try using an earlier version because 2007's macro recorder is a bit crippled.</p>
<p>This is what I got:</p>
<pre><code>ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.Axes(xlCategory).Select
Selection.TickLabels.Orientation = xlUpward
</code></pre>
|
Registering object _instances_ instead of _types_ with .NET remoting? <p>There's something I'm just not getting about .NET remoting. Well, two things actually:</p>
<ol>
<li><p>Why is the emphasis back on classes that inherit from MarshalByRef instead of interfaces ala the original COM style (which I liked)?</p></li>
<li><p>Why is it that .NET remoting always forces you to effectively create some sort of object pool instead of allowing you to associate specific <em>instances</em> with a URL?</p></li>
</ol>
<p>Server code:</p>
<pre><code>RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingTypes.Server), "MyURL", WellKnownObjectMode.Singleton);
</code></pre>
<p>Client code:</p>
<pre><code>RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemotingTypes.Server), "MyURL", WellKnownObjectMode.Singleton);
</code></pre>
<p>But suppose I want to create the "Server" instance myself and then just bind it to an endpoint?</p>
<pre><code>RemotingTypes.Server myInstance = new RemotingTypes.Server();
</code></pre>
<p>What now? How can I associate "myInstance" with the URL "MyURL" ?</p>
| <p>The problem with Nickd's answer: I wanted to know how to associate an already created instance with a URL, rather than how to get .NET remoting to do this for me (some instance that I have created that does not have a default constructor, for example).</p>
<p>I was hoping there'd be some epic response explaining the "philosophy" behind .NET remoting, and why it's inextricably coupled to the type system...</p>
<p>What I've concluded instead is simply that:
a) It's because .NET remoting sucks. Don't use it
b) Use <a href="http://social.msdn.microsoft.com/content/en-us/msft/netframework/wcf/GettingStarted" rel="nofollow">WCF</a> instead</p>
|
Start program on usb hardware plugin <p>Is there a way to detect when a specific device is plugged into a usb port, what I would like to happen is when I plug my laptop into my docking station it run up several apps to account for my different keyboard, mouse and monitors. Specifically I have an issue with some software for my G15 keyboard stopping media player closing properly.</p>
<p>Hopefully in .NET but if not any suggestions appreciated.</p>
| <p>Try using <a href="http://www.icsharpcode.net/OpenSource/SharpUSBLib/default.aspx" rel="nofollow">SharpUSBLib</a>. It's a C# wrapper around the libusb project.</p>
<p>I'm pasting a code sample below (included in the download - just tried it myself). It seems simple enough and I think it will provide you with quite lot of info on devices connected to your laptop via USB.</p>
<pre><code> foreach (Bus bus in Bus.Busses)
{
Console.WriteLine(bus);
foreach (Descriptor descriptor in bus.Descriptors)
{
Console.WriteLine("\t" + descriptor);
try
{
using (Device device = descriptor.OpenDevice())
{
Console.WriteLine("\t\t Product: " + device.Product);
Console.WriteLine("\t\tManufacturer: " + device.Manufacturer);
Console.WriteLine();
}
}
catch (UsbException e)
{
Console.WriteLine("Got Exception : " + e);
}
}
}
</code></pre>
|
Excel VBA: Which OLE/OCX control to use to display a chart in a form? <p>I have to display a column chart in a user form in VBA. Exporting the chart to GIF and importing in a picture box works; but I cannot use it because the chart needs to be modified based on options chosen by the user from the same form. I have been searching and people have commented that default OLE/OCX controls provided by MS may be used. I cannot find an ActiveX which may do the trick. Does somebody know which controls to use and how to use them?</p>
| <p>Just use Microsoft Chart, it's the same engine as Microsoft Excel.</p>
<p>Assuming you're using Excel 2003 ... the control is called "Microsoft Office Chart 11.0"</p>
<p>If you have Excel 2007, Microsoft did not ship the chart control. But you can still <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=7287252C-402E-4F72-97A5-E0FD290D4B76&displaylang=en" rel="nofollow">download Microsoft Office Chart 11.0</a>. It's in a file called OWC11.EXE.</p>
<p>Then, in the VBA editor, when your VBA UserForm is showing, right click on the toolbox and choose "Additional Controls" and then check "Microsoft Office Chart 11.0" from the list that appears.</p>
|
Configuration of BIND DNS server, I'm lost <p>I hope you'll forgive me for thinking that configuring a DNS server would be easy. It turns out it is quite hard... especially if you never did it before.</p>
<p>To recap a little, I previously asked if someone could recommend a personal DNS server for Windows XP for use in a development project.</p>
<p>My basic wish is to host a DNS server that represents the following lookup table:</p>
<pre><code> Address | IP
------------------+--------------
*.devdomain1.dev | 192.168.10.2
*.devdomain2.dev | 192.168.10.2
</code></pre>
<p>Do you know how to setup this in BIND 9? Or maybe there is an easier solution that I've overlooked. I know I could add the individual subdomains in my HOSTS file but since we have a lot of subdomains which has to be maintained on several dev machines I would rather have a simple wildcard setup.</p>
| <p>A zone file like this should suffice (on my system this would be in /etc/bind/zones/devdomain2.dev.hosts)</p>
<pre><code>devdomain2.dev. IN SOA localhost. johannesh.devdomain2.dev. (
1102522753
10800
3600
604800
38400
)
devdomain2.dev. IN NS localhost.
*.devdomain2.dev. IN A 192.168.10.2
</code></pre>
<p>Then my /etc/bind/named.conf.local would reference this as follows</p>
<pre><code>zone "devdomain2.dev" {
type master;
file "/etc/bind/zones/devdomain2.dev.hosts";
};
</code></pre>
<p>(Note you could adapt this just wildcard .dev domain entirely, or set up another zone for devdomain1)</p>
|
Sharepoint: Is there some OOB way to delete provision files? <p>I'm using OOB functionality to upload files to sharepoint. I'm using <code><module</code>> tags and feature which wraps all data. (it is described <a href="http://msdn.microsoft.com/en-us/library/ms441170.aspx" rel="nofollow">here</a>)</p>
<p>Here is example of module in my elements.xml file:</p>
<pre><code><Module Name="SampleImages" Url="Style Library/Images/SampleImages" Path="Images" RootWebOnly="TRUE">
<File IgnoreIfAlreadyExists="TRUE" Name="example.jpg" Url ="example.jpg" Type="GhostableInLibrary" />
</Module>
</code></pre>
<p>The only problem is that when I deactivate feature uploaded files are not removed. Currently I use feature receiver which removes theese files, since I wasn't able to find any other solution.</p>
<p>So do I miss something or this is the only way how I can get rid of files uploaded in this manner?</p>
| <p>I believe the way you are doing it is the only way.</p>
|
C#: How to remove namespace information from XML elements <p>How can I remove the "xmlns:..." namespace information from each XML element in C#?</p>
| <p>Zombiesheep's cautionary answer notwithstanding, my solution is to wash the xml with an xslt transform to do this.</p>
<p><strong>wash.xsl:</strong></p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="no" encoding="UTF-8"/>
<xsl:template match="/|comment()|processing-instruction()">
<xsl:copy>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="*">
<xsl:element name="{local-name()}">
<xsl:apply-templates select="@*|node()"/>
</xsl:element>
</xsl:template>
<xsl:template match="@*">
<xsl:attribute name="{local-name()}">
<xsl:value-of select="."/>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
</code></pre>
|
How do i auto-populate fields in django? <p>I have a model Question with a field called <strong>userid</strong>, before one ask a question, one needs to login, i want when saving to capture the user ID of the currently logged-in user and assign it to the userid of the Question model.</p>
<p>Please note am not showing the userid on my form i.e. in the Question model i have declared the userid as follows;</p>
<p>class Question(models.Model):
...
userid=models.ForeignKey(User, editable=false)
...</p>
<p>How do i assign logged-in user ID to the Question model <strong>userid</strong>?</p>
| <p>Your code may look like this:</p>
<pre><code>from django.contrib.auth.decorators import login_required
class QuestionForm(forms.ModelForm):
class Meta:
model = Question
@login_required
def ask(request):
form = QuestionForm(request.POST)
if form.is_valid():
question = form.save(False)
question.userid = request.user
question.save()
#...
</code></pre>
|
Which is the maximum number of Windows concurrent tcp/ip connections? <p>In .NET I have already tried the configuration below successfully:</p>
<pre><code> <system.net>
<connectionManagement>
<add address="*" maxconnection="100"/>
</connectionManagement>
</system.net>
</code></pre>
<p>Using 100 concurrent HttpWebRequest they answered almost simultaneously (less than a second).</p>
<p>I wonder why some people wrote in some forums that Windows XP and Windows Server 2008 limits this number to 15 or 20. They are right?</p>
| <p>The client versions of Windows are restricted in the number of half-open connections. The 10 limit for XP is well known, Vista has other limits depending on the version (e.g. Home Basic has a limit of 2, Ultimate has 25). You can Google "Patch for Event ID 4226" to alleviate these limits. Post Vista SP2 the behavior is <a href="http://support.microsoft.com/kb/969710">configurable through a registry key</a>.</p>
<p>Windows Server can handle several tens of thousands concurrent inbound connections given enough resources.</p>
<p>Depending on your server version, you have to change some default parameters to allow this many connections see <a href="http://blogs.msdn.com/david.wang/archive/2006/04/12/HOWTO-Maximize-the-Number-of-Concurrent-Connections-to-IIS6.aspx">this guide</a>. </p>
<p>The author reports having seen 50.000+ concurrent connections to IIS6 on WS03SP1 x64 with 4GB RAM.</p>
|
When I run the rake:db migrate command I get an error "Uninitialized constant CreateArticles" <p>I created a model ruby script/generate model Article (simple enuff)</p>
<p>Here is the migration file create_articles.rb:</p>
<pre><code>def self.up
create_table :articles do |t|
t.column :user_id, :integer
t.column :title, :string
t.column :synopsis, :text, :limit => 1000
t.column :body, :text, :limit => 20000
t.column :published, :boolean, :default => false
t.column :created_at, :datetime
t.column :updated_at, :datetime
t.column :published_at, :datetime
t.column :category_id, :integer
end
def self.down
drop_table :articles
end
end
</code></pre>
<p>When I run the rake:db migrate command I receive an error rake aborted! "Uninitialized constant CreateArticles." </p>
<p>Does anyone know why this error keeps happening? </p>
| <p>Be sure that your file name and class name say the same thing(except the class name is camel cased).The contents of your migration file should look something like this, simplified them a bit too:</p>
<pre><code>#20090106022023_create_articles.rb
class CreateArticles < ActiveRecord::Migration
def self.up
create_table :articles do |t|
t.belongs_to :user, :category
t.string :title
t.text :synopsis, :limit => 1000
t.text :body, :limit => 20000
t.boolean :published, :default => false
t.datetime :published_at
t.timestamps
end
end
def self.down
drop_table :articles
end
end
</code></pre>
|
moodle file.php returns a blank 0 bytes file <p>For some reason one installation of Moodle 1.9.3+ has a problem that file.php returns a blank 0 byte file sometimes, even the apache log shows 0 bytes were returned. Another moodle installation works OK with the same htm files.</p>
<p>What could be causing this? Problematic files are just usual htm files - bug occurs with links like this:</p>
<p><a href="http://server/file.php/164/moddata/scorm/4/data/msg.htm" rel="nofollow">http://server/file.php/164/moddata/scorm/4/data/msg.htm</a> </p>
<p>(The problematic moodle was upgraded from 1.8 version earlier)</p>
| <p>A completely blank response may indicate a PHP error; check the PHP error log.</p>
|
Visual Studio web user control events only show up in design mode? <p>Calling all Visual Studio gurus â when I'm working on a .ascx or .aspx file in a c# web project, the <strong>events</strong> do not show up in the properties panel unless I switch into the design view from the code view. Is this an intentional functionality of Visual Studio? Both VS2005 and VS2008 seem to work this way.</p>
<p>And is there any way to get the events to show up in the properties panel all the time?</p>
| <p>I don't know if that's the way VS is 'intended to work, but yes that's a limitation. In case you've noticed sometimes clicking on the control and pressing F4 (or clicking on the properties tab) fails to load the properties for the correct control, and then you gotta select it from the list.</p>
<p><em>Sigh</em></p>
<p>That apart, if you make a usercontrol of your own, and give it an event, that event will not show up in the properties tab when you put it on a page. You'll have to capture it manually in the Page_Init event (like demonstrated by fallen888). </p>
<p>These days I don't bother with going to the properties tab to see an event. You can just as well type the event's name in the mark-up and then write it in the code-behind file.</p>
|
Fastest way to "jump back" to a file in TextMate? <p>Often, when I am reading code or debugging, I want the ability to quickly jump around files. I especially want to "go back" to where I was. I know about "Command+T", "Command+Shift+T", and, bookmarks. But, I cannot figure out a way to jump around files quickly.</p>
<p>UPDATE: I do not think I my question was clear enough judging by two answers given. Specifically, I am looking for a way to "jump back" to where I was in a file. I know how to navigate in TextMate (in general). I want to know if TextMate has a "jump back" key binding.</p>
| <p>It's subtle.</p>
<p>The command-T thing has the files listed in Most Recently Used order.
So, you can go command-T return to get back to your last file real quick. At first I couldn't find it either.</p>
<p>I don't think there's a go to last edit location as there is in, say, IDEA/RubyMine.</p>
|
What is the point of www in web urls? <p>I've been trying to collect analytics for my website and realized that Google analytics was not setup to capture data for visitors to www.example.com (it was only setup for example.com). I noticed that many sites will redirect me to www.example.com when I type only example.com. However, stackoverflow does exactly the opposite (redirects www.stackoverflow.com to just stackoverflow.com).</p>
<p>So, I've decided that in order to get accurate analytics, I should have my web server redirect all users to either www.example.com, or example.com. Is there a reason to do one or the other? Is it purely personal preference? What's the deal with www? I never type it in when I type domains in my browser.</p>
| <p>History lesson.</p>
<p>There was a time when the Web did not dominate the Internet. An organisation with a domain (e.g. my university, aston.ac.uk) would typically have several hostnames set up for various services: gopher.aston.ac.uk, news.aston.ac.uk, ftp.aston.ac.uk. They were just the obvious names for accessing those services.</p>
<p>When HTTP came along, the convention became to give the web server the hostname "www". The convention was so widespread, that some people came to believe that the "www" part actually told the client what protocol to use.</p>
<p>That convention remains popular today, and it does make some amount of sense. However it's not technically required.</p>
<p>I think Slashdot was one of the first web sites to decide to use a www-less URL. Their head man Rob Malda refers to "TCWWW" - "The Cursed WWW" - when press articles include "www" in his URL. I guess that for a site like Slashdot which is primarily a web site to a strong degree, "www" in the URL is redundant.</p>
<p>You may choose whichever you like as the canonical address. But do be consistent. Redirecting from other forms to the canonical form is good practice.</p>
|
What is the right way to initialize a non-empty static collection in C# 2.0? <p>I want to initialize a static collection within my C# class - something like this:</p>
<pre><code>public class Foo {
private static readonly ICollection<string> g_collection = ???
}
</code></pre>
<p>I'm not sure of the right way to do this; in Java I might do something like:</p>
<pre><code>private static final Collection<String> g_collection = Arrays.asList("A", "B");
</code></pre>
<p>is there a similar construct in C# 2.0? </p>
<p>I know in later versions of C#/.NET you can do collection initializers (<a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx">http://msdn.microsoft.com/en-us/library/bb384062.aspx</a>), but migration isn't an option for our system at the moment.</p>
<p>To clarify my original question - I'm looking for a way to succinctly declare a simple static collection, such as a simple constant collection of strings. The static-initializer-style way is also really good to know for collections of more complex objects.</p>
<p>Thanks!</p>
| <p>If I fully understand your question, it seems some others have missed the point, you're looking to create a static collection in a similar manner to Java in that you can declare and populate in a single line of code without having to create a dedicated method to do this (as per some of the other suggestions). This can be done using an array literal (written over two lines to prevent scrolling):</p>
<pre><code>private static readonly ICollection<string> Strings =
new string[] { "Hello", "World" };
</code></pre>
<p>This both declares and populates the new readonly collection with the item list in one go. Works in 2.0 and 3.5, I tested it just to be doubly sure.</p>
<p>In 3.5 though you can use type inference so you no longer need to use the string[] array which removes even more keystrokes:</p>
<pre><code>private static readonly ICollection<string> Strings =
new[] { "Hello", "World" };
</code></pre>
<p>Notice the missing "string" type in the second line line. String is automatically inferred from the contents of the array initializer.</p>
<p>If you want to populate it as a list, just change up the new string[] for new List a la:</p>
<pre><code>private static readonly ICollection<string> Strings =
new List<string>() { "Hello", "World" };
</code></pre>
<p>Of course, because your type is IEnumerable rather than a specific implementation, if you want to access methods specific to List< string> such as .ForEach(), you will need to convert it to List:</p>
<pre><code>((List<string>)Strings).ForEach(Console.WriteLine);
</code></pre>
<p>But it's a small price to pay for migratability [is that a word?].</p>
|
Optimising if statements by reordering <p>I remember reading once that the order of the members of an evaluation is important.
Such as</p>
<pre><code>if (null == myClass)
</code></pre>
<p>is better (faster?) then</p>
<pre><code>if (myClass == null)
</code></pre>
<p>is this the case?
If so could someone explain how and why?
If the answer requires a language then aim towards c#.<br/>
Thanks</p>
| <p>No, it is not faster. This is a relic from the old C days, it avoided doing bugs like</p>
<pre><code>if(myClass = null) /* accident, sets myClass to null instead of comparing */
</code></pre>
<p>so you would always have the constant at the left:</p>
<pre><code>if(null = myClass) /* throws an error at compile time */
</code></pre>
<p>However it makes no sense to do this in C# I believe..</p>
|
Visual Studio on a Mac <p>My job is currently based on Visual Studio (ASP.NET).<br/>
Looking for experiences using Visual Studio on a Mac.<br/>
Does it work?</p>
| <p>In a word, <strong>yes</strong>.</p>
<p>I use a Mac Mini 1.67 GHz machine with 2GB of RAM. That's not an impressive box, but performance under WinXP is excellent. I have used VS2005, VS2008, MySQL Server, Sql Server Express, and dozens of little utilities.</p>
<p>The only issues I've ever had were when I used a hotkey (ex: F10) that was assigned to something like Expose in the mac. So I would hit F10 and instead of stepping over, it would bring up the weather widget. Workaround was to reassign those keys on the Mac (i.e., reassign to Shift+F10).</p>
<p><em>Edit:</em></p>
<p>I see others report having sluggish performance. You may want to get an extra drive and keep your Virtual Drive there. I've been doing that for a long time, and that may be the reason for good performance under XP. <a href="http://www.codinghorror.com/blog/archives/000714.html">Jeff Atwood has a blog entry about this topic.</a></p>
|
How to programmatically select an item in a WPF TreeView? <p>How is it possible to programmatically select an item in a WPF <code>TreeView</code>? The <code>ItemsControl</code> model seems to prevent it.</p>
| <p>For those who are still looking for the right solution to this problem here is the one below. I found this one in the comments to the Code Project article âWPF TreeView Selectionâ <a href="http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx" rel="nofollow">http://www.codeproject.com/KB/WPF/TreeView_SelectionWPF.aspx</a> by DaWanderer.
It was posted by Kenrae on Nov 25 2008. This worked great for me. Thanks Kenrae!</p>
<h2>Here is his post:</h2>
<p>Instead of walking the tree, have your own data object have the IsSelected property (and I recommend the IsExpanded property too). Define a style for the TreeViewItems of the tree using the ItemContainerStyle property on the TreeView that binds those properties from the TreeViewItem to your data objects. Something like this:</p>
<pre><code><Style x:Key="LibraryTreeViewItemStyle"
TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected"
Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="FontWeight"
Value="Normal" />
<Style.Triggers>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="FontWeight"
Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
<TreeView ItemsSource="{Binding Path=YourCollection}"
ItemContainerStyle="{StaticResource LibraryTreeViewItemStyle}"
ItemTemplate={StaticResource YourHierarchicalDataTemplate}/>
</code></pre>
|
Ribbon UI Control for WinForms <p>Is there a Ribbon UI Control available in VS 2008? Will it be available if i have office 2007 installed on the development and deployment machines?</p>
<p><br />
EDIT: I would imagine that Microsoft would include the Ribbon UI control in VS 2008 as this is the way the UI of office is going to be moving forward also for the sake of consistency in Windows applications</p>
| <p>Yes - it was included as part of the Visual Studio 2008 Service Pack 1 - at least for C++/MFC support anyhow.</p>
<p>See this <a href="http://stackoverflow.com/questions/33909/ribbon-toolbar-and-visual-studio-2008-service-pack-1">similar question</a> for more info.</p>
|
How to compose `not` with a function of arbitrary arity? <p>When I have some function of type like</p>
<pre><code>f :: (Ord a) => a -> a -> Bool
f a b = a > b
</code></pre>
<p>I should like make function which wrap this function with not.</p>
<p>e.g. make function like this</p>
<pre><code>g :: (Ord a) => a -> a -> Bool
g a b = not $ f a b
</code></pre>
<p>I can make combinator like</p>
<pre><code>n f = (\a -> \b -> not $ f a b)
</code></pre>
<p>But I don't know how.</p>
<pre><code>*Main> let n f = (\a -> \b -> not $ f a b)
n :: (t -> t1 -> Bool) -> t -> t1 -> Bool
Main> :t n f
n f :: (Ord t) => t -> t -> Bool
*Main> let g = n f
g :: () -> () -> Bool
</code></pre>
<p>What am I doing wrong?</p>
<p>And bonus question how I can do this for function with more and lest parameters e.g.</p>
<pre><code>t -> Bool
t -> t1 -> Bool
t -> t1 -> t2 -> Bool
t -> t1 -> t2 -> t3 -> Bool
</code></pre>
| <p>Unless you want to go hacking around with typeclasses, which is better left for thought experiments and proof of concept, you just don't generalize to multiple arguments. Don't try.</p>
<p>As for your main question, this is most elegantly solved with Conal Elliott's <em>semantic editor combinators</em>. A semantic editor combinator is a function with a type like:</p>
<pre><code>(a -> b) -> F(a) -> F(b)
</code></pre>
<p>Where F(x) is some expression involving x. There are also "contravariant" editor combinators which take a <code>(b -> a)</code> instead. Intuitively, an editor combinator selects a part of some larger value to operate on. The one you need is called <code>result</code>:</p>
<pre><code>result = (.)
</code></pre>
<p>Look at the type of the expression you're trying to operate on:</p>
<pre><code>a -> a -> Bool
</code></pre>
<p>The result (codomain) of this type is a -> Bool, and the result of <em>that</em> type is Bool, and that's what you're trying to apply <code>not</code> to. So to apply <code>not</code> to the result of the result of a function <code>f</code>, you write:</p>
<pre><code>(result.result) not f
</code></pre>
<p>This beautifully generalizes. Here are a few more combinators:</p>
<pre><code>argument = flip (.) -- contravariant
first f (a,b) = (f a, b)
second f (a,b) = (a, f b)
left f (Left x) = Left (f x)
left f (Right x) = Right x
...
</code></pre>
<p>So if you have a value <code>x</code> of type:</p>
<pre><code>Int -> Either (String -> (Int, Bool)) [Int]
</code></pre>
<p>And you want to apply <code>not</code> to the Bool, you just spell out the path to get there:</p>
<pre><code>(result.left.result.second) not x
</code></pre>
<p>Oh, and if you've gotten to Functors yet, you'll notice that <code>fmap</code> is an editor combinator. In fact, the above can be spelled:</p>
<pre><code>(fmap.left.fmap.fmap) not x
</code></pre>
<p>But I think it's clearer to use the expanded names.</p>
<p>Enjoy.</p>
|
How can I prevent/detect an underflow in a Postgresql calculation that uses EXP() <p>I am receiving a value out of range: underflow error from pgsql, in a query that uses the EXP(x) function. What values of x trigger this? How do I prevent or detect it?</p>
| <p>The function exp is called the exponential function, and its inverse is the natural logarithm, or logarithm to base e. The number e is also commonly defined as the base of the natural logarithm</p>
<p>In other words, exp(x) and e^x are the same function. However, since e is a transcendental number, and therefore irrational, its value cannot be given exactly.</p>
<p>The Numerical value of e truncated to 10 decimal places is 2.71828â1828</p>
<p>So, the function exp(x) is technically valid for all values of x, but practically speaking, you can limit them. For example, if you limit them to +/- 700 you should cover all cases covering the range </p>
<pre><code>exp(700) = 1.01423205 Ã 10^304
exp(-700) = 9.85967654 Ã 10^-305
</code></pre>
<p>More than that depends on your application</p>
|
Is there a good Java networking library? <p>I'm currently searching for a Java networking library. What I want to do is sending XML, JSON or other serialized messages from a client to another client and/or client to server.</p>
<p>My first attempt was to create an POJO for each message, plus a MessageWriter for sending and a MessageReader for receiving it. Plus socket and error handling. Which is quite a lot of error prone work.</p>
<p>What I'm looking for is a a higher level library which abstracts from sockets. Furthermore it should supports something like code generation for the messages.</p>
<p>Google's Protocol Buffers (<a href="http://code.google.com/apis/protocolbuffers/">http://code.google.com/apis/protocolbuffers/</a>) looks promising. But are there alternatives? The emphasis is not on speed or security (at the moment), it is just supposed to work reliable and with a low amount of implementation time.</p>
| <p>You have several options depending on how abstracted from raw sockets you want to get. Once you depart from socket level programming, you're pretty much into <em>remoting</em> territory,</p>
<ul>
<li>Standard Remoting Options for Java: RMI or JMS</li>
<li>Implement JMX Mbeans in each client and the servers and use JMX remoting to invoke message passing operations.</li>
<li>If you think you might want to use multicast, I would definitely check <a href="http://www.jgroups.org/javagroupsnew/docs/index.html" rel="nofollow">JGroups</a>.</li>
<li>If you're looking to create your own protocol but want to use some existing building blocks, check out <a href="http://commons.apache.org/proper/commons-net/" rel="nofollow">Jakarta Commons Net</a>. The <strong>HttpClient</strong> referenced in Answer #1 has been incorporated into this package.</li>
<li>There are also some interesting proprietary messaging systems that have the added virtue of supporting multiple platforms/languages such as <a href="http://www.spread.org" rel="nofollow">Spread</a> and <a href="http://www.freedesktop.org/wiki/Software/dbus" rel="nofollow">DBus</a>.</li>
<li>Can't enumerate remoting options without mentioning WebServices.... but.... <strong>blech!</strong></li>
</ul>
<p>I am not completely sure what you mean by <em>code generation for the messages</em>. Can you elaborate ?</p>
|
How should I import highly formatted data from Excel to a database? <p>What is the best way to import highly formatted data from Excel to SQL server.
Basically I have 250+ Excel files that have been exported from a reporting tool in a format that our business users would prefer. This is a 3rd party tool that can not export data in any other format. I need to "scrub" these files on a monthly basis and import them into a database. I want to use SQL Server 2005</p>
<p>File formats look like this:</p>
<pre><code> Report Name
Report Description
MTH/DEC/2003 MTH/JAN/2004 MTH/FEB/2004
Data Type Data Type Data Type
Grouping 1 1900 1700 2800
Grouping 2 1500 900 1300
Detail 300 500 1000
Detail 1100 200 200
Detail 100 200 100
</code></pre>
| <p>you could write a simple parser application. there are many api that will handle reading excel files.</p>
<p>I have written one in java and it only took a day or two.</p>
<p><a href="http://jexcelapi.sourceforge.net/" rel="nofollow">here</a> is one api.</p>
<p>Good Luck</p>
<p>EDIT: Forgot to mention we will also need a sql api such as <a href="http://www.microsoft.com/sqlserver/2005/en/us/java-database-connectivity.aspx" rel="nofollow">JDBC</a>. Again we use JDBC for the majority of our applications and works great.</p>
|
Able Commerce POS Data Merge <p>We are building an AbleCommerce 7 web store and trying to integrate it with an existing point-of-sale system. The product inventory will be shared between a phyical store and a web store so we will need to periodically update quantity on hand for each product to keep the POS and the web store as close to in synch as possible to avoid over selling product in either location. The POS system does have an scheduled export that will run every hour.</p>
<p>My question is, has anyone had any experience with synchronizing data with an Able Commerce 7 web store and would you have any advice on an approach?</p>
<p>Here are the approaches that we are currently considering:</p>
<ol>
<li>Grab exported product data from the POS system and determine which products need to be updated. Make calls to a custom-built web service residing on the server with AbleCommerce to call AbleCommerce APIs and update the web store appropriately.</li>
<li>Able Commerce does have a Data Port utility that can import/export web store data via the Able Commerce XML format. This would provide all of the merging logic but there doesn't appear to be a way to programmatically kick off the merge process. Their utility is a compiled Windows application. There is no command-line interface that we are aware of. The Data Port utility calls an ASHX handler on the server.</li>
<li>Take an approach similar to #1 above but attempt to use the Data Port ASHX handler to update the products instead of using our own custom web service. Currently there is no documentation for interfacing with the ASHX handler that we are aware of.</li>
</ol>
<p>Thanks,
Brian</p>
| <p>I've done this with POS software. It wasn't AbleCommerce, but retail sales and POS software is generic enough (no vendor wants to tell prospects that "you need to operate differently") that it might work.</p>
<p>Sales -> Inventory </p>
<p>Figure out how to tap into the Data Port for near-real-time sales info. I fed this to a Message-Queue-By-DBMS-Table mechanism that was polled and flushed every 30 seconds to update inventory. There are several threads here that discuss MQ via dbms tables.</p>
<p>Inventory -> Sales</p>
<p>Usually there is a little more slack here - otherwise you get into interesting issues about QC inspection failures, in-transit, quantity validation at receiving, etc. But however it's done, you will have a mechanism for events occurring as new on-hand inventory becomes available. Just do the reverse of the first process. A QOH change event causes a message to be queued for a near-real-time polling app to update the POS.</p>
<p>I actually used a single queue table in MSSQL with a column for messagetype and XML for the message payload.</p>
<p>It ends up being simpler than the description might sound. Let me know if you want info offline.</p>
|
Are Apache Ant Javadocs Included in the Eclipse Plugin? <p>I was trying to add Ant libraries to a project in eclipse, and I used the ones that were part of eclipse's plugins folder. When I tried to associate them with Javadocs, I couldn't locate them in the plugin folder. I searched for them online, and I found <a href="http://ant.apache.org/manual/api/index.html" rel="nofollow">this page</a>, in which they say the docs are not provided online because they are part of every distribution. So where can I find the docs in the distribution that came bundled in Eclipse?</p>
| <p>The ant javadocs may or may not be included with eclipse, depending on which version you have. <strong>Edit: Anyway, it's better not to depend on the version bundled with the IDE.</strong> Otherwise everyone who works on the project will have to use the same version of the IDE, and eclipse automatic updates can break your project.</p>
<ul>
<li>Download the <a href="http://ant.apache.org/bindownload.cgi" rel="nofollow">ant binary distribution</a> and <a href="http://ant.apache.org/srcdownload.cgi" rel="nofollow">ant source distribution</a></li>
<li>Take the eclipse ant distribution out of your project and replace it with the binary jars (extracted from the zip).</li>
<li>In the eclipse java build path window attach the source zip to the binary jars. (Click the plus, double click "Source attachment" and select the source zip. You'll be able view the source if you want, and the javadoc will appear in the appropriate views.</li>
</ul>
|
exchange powershell : parsing an array boolean value <p>In my output, I get</p>
<p>@{ActiveSyncEnabled=False}</p>
<p>how do I parse this so that it just says "False"?</p>
<p>the output is coming from this line of code: </p>
<pre><code> $pda = get-casmailbox -Anr $user.displayname | select activesyncenabled
</code></pre>
| <p>To access the value directly:</p>
<p>(get-casmailbox -Anr $user.displayname).activesyncenabled </p>
<p>You can skip anr and use the identity member:</p>
<p>Get-CASMailbox $user.Identity</p>
<p>To get all activesyncenabled enabled mailboxes:</p>
<p>get-casmailbox -resultSize unlimited -filter {activesyncenabled -eq $true}</p>
|
python "'NoneType' object has no attribute 'encode'" <p>I wrote this tiny Python snippet that scrapes a feed and prints it out. When I run the code, something in the feed triggers the error message you see here as my question. Here's the complete console output on error:</p>
<pre><code>> Traceback (most recent call last):
> File "/home/vijay/ffour/ffour5.py",
> line 20, in <module>
> myfeed() File "/home/vijay/ffour/ffour5.py", line
> 15, in myfeed
> sys.stdout.write(entry["title"]).encode('utf-8')
> AttributeError: 'NoneType' object has
> no attribute 'encode'
</code></pre>
| <blockquote>
<pre><code>> sys.stdout.write(entry["title"]).encode('utf-8')
</code></pre>
</blockquote>
<p>This is the culprit. You probably mean:</p>
<pre><code>sys.stdout.write(entry["title"].encode('utf-8'))
</code></pre>
<p>(Notice the position of the last closing bracket.)</p>
|
LINQ sorting anonymous types? <p>How do I do sorting when generating anonymous types in linq to sql?</p>
<p>Ex:</p>
<pre><code>from e in linq0
order by User descending /* ??? */
select new
{
Id = e.Id,
CommentText = e.CommentText,
UserId = e.UserId,
User = (e.User.FirstName + " " + e.User.LastName).Trim()),
Date = string.Format("{0:d}", e.Date)
}
</code></pre>
| <p>If you're using LINQ to Objects, I'd do this:</p>
<pre><code>var query = from e in linq0
select new
{
Id = e.Id,
CommentText = e.CommentText,
UserId = e.UserId,
User = (e.User.FirstName + " " + e.User.LastName).Trim()),
Date = e.Date.ToString("d")
} into anon
orderby anon.User descending
select anon;
</code></pre>
<p>That way the string concatenation only has to be done once.</p>
<p>I don't know what that would do in LINQ to SQL though...</p>
|
WPF DataGrid Sync Column Widths <p>I've got two WPF Toolkit <code>DataGrids</code>, I'd like so that when the user resizes the first column in the first grid, it resizes the first column in the second grid. I've tried binding the width of the <code>DataGridColumn</code> in the second grid to the appropriate column in the first grid, but it doesn't work. I'd prefer to use all xaml, but I'm fine with using code behind as well.</p>
<pre><code><tk:DataGrid Width="100" Height="100">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn x:Name="Column1" Width="50"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
<tk:DataGrid Width="100" Height="100">
<tk:DataGrid.Columns>
<tk:DataGridTextColumn x:Name="Column1Copy" Width="{Binding Path=ActualWidth, ElementName=Column1}"/>
</tk:DataGrid.Columns>
</tk:DataGrid>
</code></pre>
<p>I also tried binding to <code>Width</code> instead of <code>ActualWidth</code>, but neither works.</p>
<p>Any help is greatly appreciated.</p>
| <p>Well, I don't think that it is possible using straight XAML, but I still feel like it should because <code>DataGridColumn</code> does derive from <code>DependencyObject</code>. I did find a way to do it programatically though. I'm not thrilled about it, but it works:</p>
<pre><code>DataGridColumn.WidthProperty.AddValueChanged(upperCol, delegate
{
if (changing) return;
changing = true;
mainCol.Width = upperCol.Width;
changing = false;
});
DataGridColumn.WidthProperty.AddValueChanged(mainCol, delegate
{
if (changing) return;
changing = true;
upperCol.Width = mainCol.Width;
changing = false;
});
public static void AddValueChanged(this DependencyProperty property, object sourceObject, EventHandler handler)
{
DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(property, property.OwnerType);
dpd.AddValueChanged(sourceObject, handler);
}
</code></pre>
|
Rails: Creating an HTML Snippet with a Variable? <p>I have a submit button that is a block of HTML code because of styling and images to make it look better. (I stole most of it from Wufoo).</p>
<p>This is one every form in the application and I was wondering if there is a cleaner way to do this. Something like a partial or helper? </p>
<p>The name of the button "Submit" or "Add Contact" needs to be a variable.</p>
<h1>snippet</h1>
Add Contact #variable text
Back
<br><br>* Required
| <p>consider partials (<a href="http://api.rubyonrails.org/classes/ActionView/Partials.html" rel="nofollow">http://api.rubyonrails.org/classes/ActionView/Partials.html</a>)</p>
|
How do you set up solution configuration specific config files? <p>I have a web service that needs different settings for different environments (debug, test, prod). What's the easiest way to setup separate config files for these different environments? Everything I find on the web tells me how to use configuration manager to retrieve settings, but not how to find particular settings based on the current build configuration.</p>
| <p>I find having several config files for each environment works well. ie:</p>
<ul>
<li>config\local.endpoints.xml</li>
<li>config\ dev.endpoints.xml</li>
<li>config\ test.endpoints.xml</li>
<li>config\ staging.endpoints.xml</li>
<li>config\ prod.endpoints.xml</li>
</ul>
<p>I then link to a "master" version of this using the built in configSource attribute within the web.config or app.config such as</p>
<pre><code><appSettings configSource="config\endpoints.xml"/>
</code></pre>
<p>I would then use the build process or deploy process to copy the the correct configuration for the environment down to the name that the web.config is expecting.</p>
<p>Each environment is clearly labelled and controlled, without the need of messy placeholders.</p>
|
Javascript HAML editor <p>Does anyone know of a Javascript based <a href="http://haml.hamptoncatlin.com/" rel="nofollow">HAML</a> editor out there? I'm looking for for something like <a href="http://tinymce.moxiecode.com/" rel="nofollow">TinyMCE</a> that just understands HAML (so it does indenting and highlighting correctly)</p>
<p>I'm thinking of using an editor like this for a dynamic website I'm building.</p>
<p><strong>Clarification</strong>
The site I am building allows the users to define layouts(in the rails sense) and css. So finer grain control than textile and markdown is required, I know I can include raw html in markdown but haml is so much prettier. </p>
| <p>HAML was designed as a more elegant way to define page structure; It was not intended to be used for formatting text, like what you're asking it to do.</p>
<p>In this case, you're probably better off using something like <a href="http://daringfireball.net/projects/markdown/" rel="nofollow">Markdown</a> or <a href="http://www.textism.com/tools/textile/" rel="nofollow">Textile</a>. Both of these already have WYSIWYGs (<a href="http://wmd-editor.com/" rel="nofollow">for Markdown</a>, <a href="http://slateinfo.blogs.wvu.edu/plugins/textile_editor_helper" rel="nofollow">for Textile</a> (<a href="http://github.com/felttippin/textile-editor-helper/tree/master" rel="nofollow">forked version</a>)), and Haml's got built-in filters to convert it into HTML.</p>
<p>e.g.:</p>
<pre><code>#content
:markdown
@post.body
</code></pre>
<p>(Haml's wonderful space-indentation will even be preserved on output!)</p>
|
How to Test Standard HTML Forms <p>What tools are best for lightweight testing of HTML forms? My particular use is <strong>very light:</strong> no multithreading issues nor elaborate test scripts: just fill in a form with particular values and let <strong>me</strong> click submit.</p>
<p>A Firefox plugin would be fine...</p>
| <p>Have you looked at <a href="http://seleniumhq.org/">Selenium IDE</a> or does this not fit the light weightness?</p>
<p>It is a Firefox plugin and although it does use scripts, it can record and playback with little effort.</p>
|
Why am I suddenly getting Missing Template errors with edge Rails (2.3)? <p>After freezing edge rails, all my controller examples are failing with
MissingTemplate errors.
e.g., "Missing template attachments/create.erb in view path app/views"</p>
<p>Trying to actually render the views gives me the same error.</p>
<p>I noticed I can fix most of them by using respond_to but I usually
never use it. I almost always only need to respond to one format in
one action so I omit respond_to and let Rails figure out which file to
render.</p>
<p>Does Rails suddenly require respond_to blocks in every action as of 2.3?</p>
| <p>Just found this, which answers my question:</p>
<p><a href="http://rails.lighthouseapp.com/projects/8994/tickets/1590-xhrs-require-explicit-respond_to" rel="nofollow">http://rails.lighthouseapp.com/projects/8994/tickets/1590-xhrs-require-explicit-respond_to</a></p>
|
Change Tracking Structure <p>We are looking to implement Optimistic locking in our WCF/WPF application. So far the best way I've come up with doing this is to implement a generic Optimistic which will store a copy of the original and any changes (so it will store two copies: the original and modified) of any value object that can be modified. Is this the best way of doing it?</p>
<p>For example: a UserVO will be wrapped by the generic as a Optimistic. When a change is made to the Optimistic, the change will be made to the modified copy stored in the Optimistic while the original also stored in the Optimistic will remain intact. The main issue seems to be that it will use up twice the space and hence bandwidth.</p>
<p>Thanks</p>
<p><strong>EDIT</strong> The solution needs to be database independent, and it would be useful to be able to specify an conflict resolution policy per value object. (eg. A user object might try and merge if the updated rows weren't changed, but a transaction object would always require user intervention).</p>
| <p>If you are using SQL server you can use a timestamp column. The timestamp column is changed anytime a row is modified. Essentially when your updating the DB you can check if the timestamp column is the same as when the client first got the data, if so no one has modified the data. </p>
<h1>Edit</h1>
<p>If you want to minimize the bandwidth, you could emulate the timestamp concept by adding a version number on each object. So for example:</p>
<ol>
<li>Client 1 requests object, sever returns Object V1</li>
<li>Client 2 requests object, server returns Object v2</li>
<li>Client 1 modifies object sending it back to server as V1</li>
<li>Server compares the version and see's v1=v1 so it commits the change</li>
<li>Server increments the version of the object so now its v2</li>
<li>Client 2 modifis object sending it back to server as v1</li>
<li>Server compares the version and see's v1!=v2 so it performs whatever your policy is</li>
</ol>
<p>For configuring your policy, you could define in a configuration a specific object that will handle Policy failures depending on the type of root object. You could whip up a IOptomisticCheckFailurePolicy interface, and you could probally use one of the DI libraries like structure map to create the object when you need it (Although you could just as easily load it up using reflection)</p>
|
Best method of Instantiating an XMLHttpRequest object <p>What is the best method for creating an <a href="http://en.wikipedia.org/wiki/XMLHttpRequest">XMLHttpRequest</a> object?</p>
<p>It should work in all capable browsers.</p>
| <p>For a library-less solution, you can emulate Prototype's use of <code>Try.these</code> fairly easily:</p>
<pre><code>function newAjax() {
try { return new XMLHttpRequest(); } catch(){}
try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch(){}
try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch(){}
try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch(){}
try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch(){}
return false;
}
</code></pre>
|
ExtJS: AJAX Links in Grid in Tab in Window <p>I am working on my first project using ExtJS.</p>
<p>I have a Data Grid sitting inside a Tab that is inside a Window.</p>
<p>I want to add a link or button to the each element of the grid (I am using extended elements at the moment with HTML content through the RowExpander) that will make an AJAX call and open another tab.</p>
| <p>If you are looking to add the link to the grid itself, you can specify another column in your ColumnModel and apply a renderer to the column. The function of the renderer is to return formatted content to be applied to that cell, which can be tailored according to the value of the dataIndex of the column (you should have a dataIndex, even if it is a duplicate of another column), and the record of that row.</p>
<pre><code>function myRenderer(value,meta,record,rowIndex,colIndex,store){
// Do something here
}
</code></pre>
<p>Your link might have a click event to call a method, opening another tab</p>
<pre><code>function myClickEvent(value1, value2){
var myTabs = Ext.getCmp('myTabPanel');
myTabs.add(// code for new tab);
}
</code></pre>
<p>If you're adding the links to your expanded area, within the RowExpander, then you'll have to write the rendering into the Template you're using for your expanded content area.</p>
|
Generate XML documentation for private members <p>Is there a way to generate XML documentation for private members? Be default it only generates it for public members, which is correct for published code but not for code only used within a company.</p>
| <p>Try using <a href="http://www.roland-weigelt.de/ghostdoc/" rel="nofollow">GhostDoc</a>.</p>
|
.NET Class Refactoring Dilemma <p>So I'm refactoring a legacy codebase I've inherited, and in the process I found a static class that encapsulates the logic for launching 3rd party applications. It essentially looks like this (shortened for brevity to only show one application):</p>
<pre><code>using System.IO;
using System.Configuration;
public static class ExternalApplications
{
public string App1Path
{
get
{
if(null == thisApp1Path)
thisApp1Path = Configuration.AppSettings.Get("App1Path");
return thisApp1Path;
}
}
private string thisApp1Path = null;
public bool App1Exists()
{
if(string.IsNullOrEmpty(App1Path))
throw new ConfigurationException("App1Path not specified.");
return File.Exists(App1Path);
}
public void ExecuteApp1(string args)
{
// Code to launch the application.
}
}
</code></pre>
<p>It's a nice attempt to separate the external applications from the rest of the code, but it occurs to me that this could have been refactored further. What I have in mind is something like this:</p>
<pre><code>using System.IO;
public abstract class ExternalApplicationBase
{
protected ExternalApplicationBase()
{
InitializeFromConfiguration();
}
public string Path { get; protected set; }
public bool Exists()
{
if(string.IsNullOrEmpty(this.Path))
throw new ConfigurationException("Path not specified.");
return File.Exists(this.Path);
}
public virtual void Execute(string args)
{
// Implementation to launch the application
}
protected abstract InitializeFromConfiguration();
}
public class App1 : ExternalApplicationBase
{
protected virtual void InitializeFromConfiguration()
{
// Implementation to initialize this application from
// the application's configuration file.
}
}
public class App2 : ExternalApplicationBase
{
protected virtual void InitializeFromConfiguration()
{
// Implementation to initialize this application from
// the application's configuration file.
}
}
</code></pre>
<p>My concerns are as follows:</p>
<ol>
<li><p>A class, interface, or other construct may already exist that does this, and I just haven't stumbled across it.</p></li>
<li><p>It may be overkill for what I want to do. Note, however, that the application uses at least three separate 3rd party applications that I have identified so far (and more are almost certain to pop up). </p></li>
<li><p>I'm not entirely comfortable with the name of the base class. It seems fuzzy, and not very informative (but I couldn't think of much better, given that Application is already well defined, reserved by the Framework, and would create a gross level of confusion were I to use it).</p></li>
<li><p>The idea is that I want to be able to keep the application configuration data (it's path and executable name) in the App.Config file, and check for its existence when my application starts up; when my software needs to launch the software, I want to do it through a single method call, and not have the code building command lines and trying to launch the software manually (as it currently does).</p></li>
</ol>
<p>So I'm sending out a request for help, guidance, and suggestions. Anything you can profer is greatly appreciated.</p>
<p>P.S. I'm asking this here because I work, as I frequently do, as a sole developer at my firm; I don't have anyone else to bounce these ideas off of. You guys have tons of experience with this stuff, and it would be foolish of me not to ask for your advice, so I hope you'll all bear with me. Thanks in advance!</p>
| <p>Here is another way of refactoring this:</p>
<pre><code>using System.IO;
public class ExternalApplication
{
public ExternalApplication(string path)
{
this.Path = path;
}
public string Path { get; protected set; }
public bool Exists()
{
if(string.IsNullOrEmpty(this.Path))
throw new ConfigurationException("Path not specified.");
return File.Exists(this.Path);
}
public void Execute(string args)
{
// Implementation to launch the application
}
}
public class AppFactory
{
public ExternalApplication App1()
{
// Implementation to initialize this application from
// the application's configuration file.
}
public ExternalApplication App2()
{
// Implementation to initialize this application from
// the application's configuration file.
}
public ExternalApplication AppFromKey(string key)
{
// get from somewhere
}
}
</code></pre>
<p>In this case, you have a single type <code>ExternalApplication</code> and a factory that has methods the return a properly configured application for you. </p>
|
How do you find out what users really want? <p>I've read somewhere (I forget the source, sorry - I think the MS Office developer's blog?), that when you do a survey of users asking them about what features they would like to see in your software/website, they will more often than not say that they want every little thing, whereas collected metrics show that in the end, most people don't use 99% of these features. The general message from the blog post was that you shouldn't ask people what they use, you should track it for yourself.</p>
<p>This leads to an unfortunate chicken-and-egg situation when trying to figure out what new feature to add next. Without the feature already in place, I can't measure how much it's actually being used. With finite (and severely stretched) resources, I also can't afford to add all the features and then remove the unused ones.</p>
<p><strong>How do you find out what will be useful to your users?</strong> If a survey is the only option, do you have to structure your questions in certain ways (eg: don't show a list of possible features, since that would be leading them on)?</p>
| <p>Contrary to popular belief, you <em>don't</em> ask them. Well, you don't listen to them when they <em>tell</em> you what they want. You watch them while they use what they have right now. If they don't have anything, you listen to them enough to give them a prototype, then you watch them use that. How a person actually <em>uses</em> software tells you a lot more than what they actually say they want. Watch what they do to find out what they really need.</p>
|
Flash security: problem loading Flash 8 AS2 modules into Flash 6 AS1 module <p>I have an old program written in Actionscript 1, compiled in Flash 6. It loads 10 other modules, of which 3 are written in Actionscript 2, compiled in Flash 8. The original program is embedded into an html and works perfectly when the html file is run on a webserver. But if I just drag the html file to my browser, the 3 AS2 modules will not load. Or, more accurately, they do load but I can't access their functions.
All the modules are compiled with "local playback security=access local files only".
I am using Flash CS3 to compile all the modules.
Without rewriting the main loading module to AS2, is there anything I can do to solve this?
Thanks</p>
| <p>The rules of Flash's security model get kind of arcane, but it seems you're up against a cross-scripting restriction. One option might be to work around it, for example by installing Apache (or whatever) and accessing the content via <code>http://localhost...</code> rather than <code>file://...</code>. However, the security issue can probably be addressed too.</p>
<p>First you might want to check out <a href="http://www.adobe.com/devnet/flash/articles/fplayer8_security_05.html" rel="nofollow">this article</a>, and particularly the chart partway down that page, which lays out the ground rules for when one SWF is allowed to access the functions of another. As indicated in the chart, the easiest way to make all accesses work is to get all the contents functioning in the "local trusted" sandbox. How to do that is covered part-way down <a href="http://www.adobe.com/devnet/flash/articles/fplayer8_security_04.html" rel="nofollow">page 4</a> of the same article.</p>
|
How do I make Tomcat stop caching my servlet responses? <p>I'm learning Servlets programming, using Apache Tomcat 6 on a Ubuntu 8.10 machine, and I'm running with a very annoying issue -- apparently, related to caching.</p>
<p>This is what I'm doing: I write a servlet, put it in a nice directory structure and deploy it using the Tomcat Web Application Manager. It works as expected. Then I edit the servlet, recompile and try to access it again, but Tomcat keeps returning the same old version. Reloading the Application or even restarting the server does not work. The only thing that works is "Undeploying" the Application, then deploying it all over again. </p>
<p>I have to do this every single time I make any small change on my code. It sucks.</p>
<p>I'm sure there is a way around this, but I couldn't find the answer anywhere on the web (and I did search a lot). I would really appreciate any help. Thanks!</p>
| <p>The advice from Adeel Ansari is flawed: you should never modify CATALINA_HOME/conf/context.xml with webapp-specific configuration. That's what your-webapp/META-INF/context.xml is for.</p>
<p>You should also never specify the "docBase" attribute of <Context>.
You should also never specify the "path" attribute of <Context>.</p>
<p>The OP has several options:</p>
<ol>
<li><p>Use the manager to reload the web app (undeploy/redeploy should not be necessary: a simple reload should work)
( <a href="http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Reload_An_Existing_Application" rel="nofollow">http://tomcat.apache.org/tomcat-6.0-doc/manager-howto.html#Reload_An_Existing_Application</a> )</p></li>
<li><p>Set the element in META-INF/context.xml to have reloadable="true"
( <a href="http://tomcat.apache.org/tomcat-6.0-doc/config/context.html" rel="nofollow">http://tomcat.apache.org/tomcat-6.0-doc/config/context.html</a> )</p></li>
</ol>
<p>With all due respect to SO, if you need help with Tomcat, join the users' mailing list and get some real answers.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.