Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm running the following query in Hypersonic DB (HSQLDB): ``` SELECT (CASE foo WHEN 'a' THEN 'bar' WHEN 'b' THEN 'biz' .... ELSE 'fin' END ) FROM MyTable LIMIT 1 ``` When the number of "WHEN" clauses exceeds about 1000, I get a Java `StackOverflowError` thrown by the JDBC driver in `org.hsqldb.jdbc.Util.sqlE...
You should never get anywhere near 1000 terms in a `CASE` statement. Long before that, you should put the other values into a separate table and pick them by joining. ``` INSERT INTO MappingTable (foo, string) VALUES ('a', 'bar'), ('b', 'biz'), ... SELECT COALESCE(m.string, 'fin') FROM MyTable t LEFT OUTER JOIN Map...
Eliminate the CASE statement entirely. Make a table using those 1000 values, then just do an inner join to that table.
How to get more than 1000 items in HSQLDB in CASE WHEN statement?
[ "", "sql", "hsqldb", "stack-overflow", "" ]
I have been using com.sun.org.apache.xpath.internal.XPathAPI for some time and it seems to work ok. Recently I tried to use the TPTP profiler in Eclipse but it could not find the XPathAPI class. I haven't figured this problem yet but it did make me wonder whether I should be using a class in an 'internal' package? Sho...
All classes under the com.sun package are internal implementation details. You should never reference them directly. The base for xPath in the JDK is [javax.xml.xpath](http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/xpath/package-frame.html).
Use the `XPathFactory.newInstance()` method in the `javax.xml.path` package. I think this was introduced in Java 1.5. If you have to revert to Java 1.4 or earlier, I think you have to use the `com.sun` packages, which is never really a good idea (but sometimes unavoidable)
Which XPathAPI should I use in Java 1.5?
[ "", "java", "xpath", "xpath-api", "" ]
I have multiple setTimeout functions like this: ``` function bigtomedium(visiblespan) { visiblespan.removeClass('big').addClass('medium'); setTimeout(function(){ mediumtosmall(visiblespan);},150); }; function mediumtosmall(visiblespan) { visiblespan.removeClass('medium').addClass(...
Not sure if you are already aware of this but, clearTimeout accepts a timeoutID that is previously returned from a call to setTimeout. Therefore you need to assign this timeout id to a variable that remains in scope for when you need to cancel it. Then pass it to the clearTimeout call when you need to stop the loop. ...
Probably the best way to handle this is to use setInterval() instead of setTimeout. Like setTimeout, setInterval returns an integer, which can be passed to clearInterval() to cancel the processing. an example would be (warning, I've not tested this at all): ``` function animateSizes( jQueryElement ) { if( jQueryEle...
clearTimeout on multiple setTimeout
[ "", "javascript", "jquery", "" ]
How can I "hide" parts of a class so that whoever is using the libary does not have to include headers for all the types used in my class. Ie take the MainWindow class below, ho can I have it so when compiled in a static/dynamic libary, whoever is useing the libary does NOT have to include windows.h, ie HWND, CRITICAL\...
You can hide parts of a class using the so-called "cheshire cat", "letter/envelope", or "pimpl" technique (which are, all, different names for the same technique): ``` class MainWindow { private: //opaque data class ImplementationDetails; ImplementationDetails* m_data; public: ... declare your public m...
As you mentioned in your question, using an abstract interface is your best option. Your DLL should have factory methods for creating/destroying instances of your concrete class. I didn't quite get your point about the downside of this.
C++ DLL: Not exposing the entire class
[ "", "c++", "" ]
Very direct question, i need to know if its possible and maybe where to start reading about that. Im a programmer with zero experience in windows servers and a client is asking if we can deliver in their windows boxes(and no they wont let us use any kind of virtualization in them). Thanks guys, i know its not 100% pro...
Yes, it's very easy. Just run the ISAPI installer from the PHP websiite.
Yes you can. I don't think there is anything different about the setup.
Is there any way to run both PHP and ASP in the same server running IIS?
[ "", "php", "iis", "" ]
**EDIT:** Oops - as rightly pointed out, there'd be no way to know whether the constructor for the class in question is sensitive to when or how many times it is called, or whether the object's state is changed during the method, so it would have to be created from scratch each time. Ignore the Dictionary and just cons...
How should the C# compiler know that it's "the same" dictionary every time? You explicitly create a new dictionary every time. C# does not support static local variables, so you have to use a field. There's nothing wrong with that, even if no other method uses the field. It would be bad if the C# compiler did things l...
Short answer: no. Slightly longer answer: I believe it will cache the result of creating a delegate from a lambda expression which doesn't capture anything (including "this") but that's a pretty special case. Correct way to change your code: declare a private static readonly variable for the dictionary. ``` private ...
C# compiler and caching of local variables
[ "", "c#", "optimization", "compiler-construction", "" ]
I am writing this java program to find all the prime numbers up to num using the Sieve of Eratosthenes, but when I try to compile, it says I can't use a long var as an array index, and it expects an int var in its place. But I'll be working with large numbers, so I can't use int. What can I do? ``` import java.util.*;...
I'm not sure why your code would compile to begin with. You're not supposed to use [] in an array list to access members. An arraylist is merely a list that is internally stored in an array. You have to use the list get operation (which would still be O(1)). Writing numlist[index] means that you have an array of objec...
Realize that with a 32-bit signed int index to a long[] you're addressing 16GB of RAM. If you're really serious about getting to big primes with the sieve, you're not going to get away with several things in your current impl: * ArrayList of boxed longs * Using [] like Uri mentions * Not systematically paging to disk
Using a long as ArrayList index in java
[ "", "java", "arraylist", "" ]
Is that .NET related? It appears to be a pointer of some sort, what is the difference? Edit: I actually know it is the XOR operator, but look at this example from [this page](https://learn.microsoft.com/en-us/previous-versions/ms379600(v=vs.80)). ``` void objectCollection() { using namespace System::Collections;...
I'm assuming that you're looking at constructs of the form: ``` Foo ^bar = gcnew Foo(); ``` You're right, in .NET it is a pointer-"like" type and is part of C++/CLI, not but not standard ISO C++. It's a reference to a garbage-collected, managed .NET object as opposed to a regular, unmanaged C++ object. As the other...
In C++, that is the [XOR](http://en.wikipedia.org/wiki/Xor) operator.
I see many examples of C++ with the use of "Foo ^ bar" - what is "^"?
[ "", "c++", "c++-cli", "" ]
I'm creating an API for a module and after I created several methods inside my classes, I asked myself this question. Right now, and as an example, I'm doing this: ``` public Company GetMonitoredCompany( String companyName ) { ... } public List<Company> GetMonitoredCompanies( ) { ... } ``` But I realize that for sev...
Use the shortest, simplest name that clearly shows the methods purpose. And be consistent within your project. In this example, if there are no other considerations, I would use the name: > GetMonitoredCompanies Because it's shorter and clearer. (I would also return a read-only ICollection or IEnumerable unless you...
It's up to you. But I recommend you to have the same convention for whole project... I prefer the first way (GetMonitoredCompanies)
When to use Plural vs Collection word on Methods
[ "", "c#", "naming-conventions", "design-patterns", "" ]
I have a quick little application and wanted to give a try to develop using TDD. I've never used TDD and actually didn't even know what it was until I found ASP.NET-MVC. (My first MVC app had unit tests, but they were brittle, way coupled, took too much up keep, and were abandoned -- I've come to learn unit tests != TD...
One solution is to not have the constructor do the work: ``` public class PurchaseOrder { public PurchaseOrder(string newNumber, string newLine) { NewNumber = newNumber; NewLine = newLine; } // ... } ``` Then testing is easy and isolated - you're not testing `GetNewNumber` and `GetNewL...
Instead of making the setters public, make them internal and then make your test assembly InternalsVisibleTo in your main project. That way, your tests can see your internal members, but no-one else can. In you main project, put something like this; ``` [assembly: InternalsVisibleTo( "UnitTests" )] ``` Where UnitTes...
TDD: Help with writing Testable Class
[ "", "c#", "asp.net-mvc", "unit-testing", "tdd", "" ]
``` typedef void (FunctionSet::* Function)(); class MyFunctionSet : public FunctionSet { protected: void addFunctions() { addFunction(Function(&MyFunctionSet::function1)); } void function1() { // Do something. } }; ``` The addFunction method adds the function to a list in the ...
Looks like you assign a member function pointer to a function of the derived class to a member function pointer to a function of the base class. Well, that's forbidden, because it opens up a hole in the type-system. It comes at a surprise (at least for me, the first time i heard that). Read [this answer](https://stacko...
Can you explain what you're trying to achieve by doing this? This seems like a fairly bad design, can't you have an abstract class ("c++ interface") such as "Computable" that has a pure virtual function1, subclass Computable for each implementation, and then have MyFunctionSet maintain a set of Computable? Is there a...
Can I simplify this?
[ "", "c++", "reference", "polymorphism", "function-pointers", "" ]
I was looking at C# collection initializers and found the implementation to be very pragmatic but also very unlike anything else in C# I am able to create code like this: ``` using System; using System.Collections; class Program { static void Main() { Test test = new Test { 1, 2, 3 }; } } class ...
Your observation is spot on - in fact, it mirrors one made by Mads Torgersen, a Microsoft C# Language PM. Mads made a post in October 2006 on this subject titled *[What Is a Collection?](http://blogs.msdn.com/madst/archive/2006/10/10/What-is-a-collection_3F00_.aspx)* in which he wrote: > Admitted, we blew it in the f...
I thought about this too, and the answer which satisfies me the most is that ICollection has many methods other than Add, such as: Clear, Contains, CopyTo, and Remove. Removing elements or clearing has nothing to do with being able to support the object initializer syntax, all you need is an Add(). If the framework wa...
Why do C# collection initializers work this way?
[ "", "c#", "collections", "" ]
First check out this code. I seems like it should work for me, but it doesn't! (surprise!) Anyway, this is what I tried first: ``` SELECT Status as status, Address as ip, PCName as pc_name, (Numbers.Phone = 'CPU/' + PCName) as cpu_contact, (Numbers.Phone = 'PC/' + PCName) as pc_contact, (Numbers.Phone = 'LOGIN/' + PC...
You could use a `GROUP BY` and `SUM` to collapse the rows: ``` SELECT Status as status, Address as ip, PCName as pc_name, cast(sum(case when (Numbers.Phone = 'CPU/' + PCName) then 1 else 0 end) as bit) as cpu_contact, cast(sum(case when (Numbers.Phone = 'PC/' + PCName) then 1 else 0 end)) as bit) as pc_c...
You need to use Case/When for the comparisons. In this case, I am hardcoding a 1 or 0, but T-SQL will convert the hard coded numbers to int. If you want boolean (bit), you'll need to convert that manually, like this... ``` Convert(Bit, Case When Numbers.Phone = 'CPU/' + PCName Then 1 Else 0 End) as cpu_contact, Conver...
How do I make a boolean calculated field in TSQL and join on that calculated field?
[ "", "sql", "sql-server", "t-sql", "" ]
So I am trying to serve large files via a PHP script, they are not in a web accessible directory, so this is the best way I can figure to provide access to them. The only way I could think of off the bat to serve this file is by loading it into memory (fopen, fread, ect.), setting the header data to the proper MIME ty...
You don't need to read the whole thing - just enter a loop reading it in, say, 32Kb chunks and sending it as output. Better yet, use [fpassthru](http://php.net/fpassthru) which does much the same thing for you.... ``` $name = 'mybigfile.zip'; $fp = fopen($name, 'rb'); // send the right headers header("Content-Type: a...
The best way to send big files with php is the `X-Sendfile` header. It allows the webserver to serve files much faster through zero-copy mechanisms like `sendfile(2)`. It is supported by lighttpd and apache with a [plugin](http://tn123.ath.cx/mod_xsendfile/). Example: ``` $file = "/absolute/path/to/file"; // can be p...
Serving large files with PHP
[ "", "php", "apache", "" ]
I need to prevent user from selecting text (select all or select a portion of text) in the browser Mozilla Firefox, using java script. I have done this using Internet Explorer, but it seems doesn't work with Mozilla. Any hints? URL? Sample? TIA. EDIT: Actually, this ridiculous problem was requested by our client. A...
There is no way to fully protect content you publish, short of DRM schemes which are not widespread enough to be useful for a website. But to prevent simple copy-and-paste there are several approaches, each of which is very annoying to your users. A simple way would be to cover the text with another element, such as a...
Render the text to an image if you really want to prevent people from copy-pasting it. Javascript tricks can always be disabled and/or worked around. Of course the best way to prevent people from copying text is to not show it at all - they might read it and retype! ;-)
Preventing Selection / Copy to Clipboard in Firefox
[ "", "javascript", "firefox", "" ]
I'm writing a log collection / analysis application in Python and I need to write a "rules engine" to match and act on log messages. It needs to feature: * Regular expression matching for the message itself * Arithmetic comparisons for message severity/priority * Boolean operators I envision An example rule would pr...
Do not invent yet another rules language. Either use Python or use some other existing, already debugged and working language like BPEL. Just write your rules in Python, import them and execute them. Life is simpler, far easier to debug, and you've actually solved the actual log-reading problem without creating anoth...
You might also want to look at [PyKE](http://pyke.sourceforge.net/logic_programming/index.html).
Implementing a "rules engine" in Python
[ "", "python", "parsing", "rules", "" ]
I have a function (for ease, I'll just use count()) that I want to apply to maybe 4-5 different variables. Right now, I am doing this: ``` $a = count($a); $b = count($b); $c = count($c); $d = count($d); ``` Is there a better way? I know arrays can use the array\_map function, but I want the values to remain as separa...
I know you said you don't want the values to be in an array, but how about just creating an array specifically for looping through the values? i.e.: ``` $arr = Array($a, $b, $c, $d); foreach ($arr as &$var) { $var = count($var); } ``` I'm not sure if that really is much tidier than the original way, though.
If you have a bunch of repeating variables to collect data your code is poorly designed and should just be using an array to store the values, instead of dozens of variables. So perhaps you want something like: ``` $totals = array("Visa"=>0,"Mastercard"=>0,"Discover"=>0,"AmericanExpress"=>0); ``` then you simply add ...
PHP: Apply a function to multiple variables without using an array
[ "", "php", "arrays", "list", "array-map", "" ]
I would like to determine what the *alphabet* for a given locale is, preferably based on the browser Accept-Language header values. Anyone know how to do this, using a library if necessary ?
take a look at [LocaleData.getExemplarSet][1] for example for english this returns abcdefghijklmnopqrstuvwxyz [1]: <http://icu-project.org/apiref/icu4j/com/ibm/icu/util/LocaleData.html#getExemplarSet(com.ibm.icu.util.ULocale>, int)
This is an English answer written in Århus. Yesterday, I heard some Germans say 'Blödheit, à propos, ist dumm'. However, one of them wore a shirt that said 'I know the difference between 文字 and الْعَرَبيّة'. What's the answer to your question for this text? Is it allowed? Isn't this an English text?
How can I determine what the alphabet for a locale is in java?
[ "", "java", "locale", "character-encoding", "" ]
I was 'forced' to add `myLocalVar = null;` statement into finally clause just before leaving method. Reason is to help GC. I was told I will get SMS's during night when server crashes next time, so I better did it :-). I think this is pointless, as myLocalVar is scoped to method, and will be 'lost' as soon as method e...
There was an old piece of Sun documentation, *[Java Platform Performance](https://web.archive.org/web/20120626144027/http://java.sun.com:80/docs/books/performance/1st_edition/html/JPAppGC.fm.html)* (link sadly now broken, and I haven't been able to find a new one), which described a situation where nulling a local vari...
The Java GC is supposed to be "sound" but is not necessarily immediately "complete". In other words, it is designed so that it would never eliminate objects that are still accessible by at least one path (and thus cause a dangling reference). It is not necessarily immediately complete since it might take time until it ...
Does it help GC to null local variables in Java
[ "", "java", "variables", "garbage-collection", "null", "local", "" ]
I have an ASP.NET MVC project containing an AdminController class and giving me URls like these: > <http://example.com/admin/AddCustomer> > > <http://examle.com/Admin/ListCustomers> I want to configure the server/app so that URIs containing **/Admin** are only accessible from the 192.168.0.0/24 network (i.e. our LAN)...
I know this is an old question, but I needed to have this functionality today so I implemented it and thought about posting it here. Using the IPList class from here (<http://www.codeproject.com/KB/IP/ipnumbers.aspx>) **The filter attribute FilterIPAttribute.cs:** ``` using System; using System.Collections.Generic; ...
You should have access to the `UserHostAddress` in the Request object in your controller to do the restriction on. I'd suggest that you may want to extend the `AuthorizeAttribute` and add your `IP` address restrictions on it so that you can simply decorate any methods or controllers that need this protection.
Restrict access to a specific controller by IP address in ASP.NET MVC Beta
[ "", "c#", "asp.net-mvc", "security", "web-config", "authorization", "" ]
Java is supposed to be "write once, run anywhere" and it really can be, but in some cases it turns into "write once, debug everywhere". What are the most common reasons for problems when moving a Java application from one platform to another? What are un-common but interesting reasons?
* Don't make assumptions about the case (in)sensitivity of the file system * Don't make assumptions about the path or directory separator * Don't make assumptions about the line terminator * Don't use the default platform encoding unless you're really, really sure you mean to * Don't start "cmd.exe" etc (I know, it sou...
Few from UI area: * Incorrect ordering of buttons like OK/Cancel * Using absolute layouts * Different accelerator keys * Different sizes/rendering of fonts * Expecing certain keys to be present (Windows key, Meta key) (These are not Java specific though)
What Issues prevent Java applications from working on multiple platforms?
[ "", "java", "cross-platform", "" ]
I admit, I don't know too much about javascript, mostly I just "steal and modify" from Javascript.com and Dynamic Drive. I've run across a few scripts that call two .js files ``` <script type="text/javascript" src="lib/prototype.js"> </script> <script type="text/javascript" src="src/aptabs.js"> </script> ``` an...
It's actually better performance wise to have them both in the same file- Depending on how your site is architected. The principle is to reduce the number of http requests, as each one carries some overhead. That said, that's something best left to the very end of production. During development it's easier to have eve...
It's often good to separate code with different concerns. Those two files might come from different places. Say prototype is upgraded and you want the new goodness. Then you can just replace the prototype.js file on your server rather than editing your huge file and do the surgery on it. EDIT: It's also "nicer" for th...
The same script using two js files?
[ "", "javascript", "external", "" ]
In PHP you have the create\_function() function which creates a unique named lambda function like this: ``` $myFunction = create_function('$foo', 'return $foo;'); $myFunction('bar'); //Returns bar ``` Is this actually any better (apart from being more easy) then just doing: ``` do{ $myFunction = 'createdFunction_'....
On my understanding of the relevant docs,[1] they both do the same thing, create\_function() just comes up with a unique function name for you. To address some other comments on this question: > create\_function can be assigned to a variable making the function accessible to other parts of your code, whereas eval is ...
Using eval() will clutter the global function list, create\_function() will not, apart from that there's no big difference. *However*, both methods require writing the function body inside a PHP string which is error-prone and if you were working on my project I would order you to just declare a helper function using t...
PHP's create_function() versus just using eval()
[ "", "php", "eval", "create-function", "" ]
The following code demonstrates a weird problem I have in a Turbo C++ Explorer project. One of the three stack objects in D::D() is not destroyed after going out of scope. This only happens if compiled in release mode, the auto\_ptrs a\_ and b\_ are of different types and the exception thrown doesn't inherit from std:...
This appears to be a compiler bug. I just ran the same sample in VS2008SP1 and got the expected output.
For whatever it's worth, GCC 3.4.6 does the expected thing: ``` $ g++ main.cpp $ a.out C::C() C::C() C::~C() C::~C() caught exception ```
Why is the destructor ignored in this code?
[ "", "c++", "destructor", "c++builder", "" ]
Ok, I've read the Stack Overflow question ['What does it mean to "program to an interface"'](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) and understand it. I understand the benefit of using interfaces (at least I think I do). However, I'm having a little bit of a problem app...
You might want to take a look at [ASP.NET/Microsoft Membership](http://msdn.microsoft.com/en-us/library/tw292whz.aspx). From your description it sounds like you have users with different Roles (doctor, broker, etc).
"Programming to an interface" means designing a set of methods and properties which are the public "signature" of the functionality or service the class will provide. You declare it as an interface and then implement it in a class which implements the interface. Then to replace the class, any other class that impleme...
Programming to an interface - Use them for a security class?
[ "", "c#", "asp.net", "interface", "" ]
I recently upgraded my server running CentOS 5.0 to a quad-core CPU from a dual-core CPU. Do I need a recompile to make use of the added cores? PostgreSQL was installed by compiling from source. EDIT: The upgrade was from an Intel Xeon 5130 to an Intel Xeon 5345.
No, you will not need to recompile for PostgreSQL to take advantage of the additional cores. What will happen is that the Linux scheduler will now be able to select two or more (up to four) postgresql threads/processes to run all at the same time, basically they are working in parallel rather than having to wait on ea...
If it's the same architecture, I don't think a recompile should be needed. If it's a different architecture (x86 vs x86\_64 vs amd64, etc.), then you will have to recompile.
PostgreSQL recompile needed after upgrading to a quad-core CPU?
[ "", "sql", "linux", "database", "postgresql", "64-bit", "" ]
I need to do user validation of a date field, it should be in the format *yyyyMMdd* and should not be more than one year in the future. How would I go about doing this? Currently I only have a crude regexp which is insufficient. ``` function VerifyDate(source, args) { var regexp = /^([1-2]{1}[0-9]{1})\d{2}([0][1-9...
Take the regex to check the format only. You can stay simple: ``` ^(\d{4})(\d{2})(\d{2})$ ``` Then parse the date and check the range: ``` function VerifyDate(source, args) { args.IsValid = false; var regexp = /^(\d{4})(\d{2})(\d{2})$/; var daysInMonth = function (y, m) {return 32-new Date(y, m, 32).getDate();...
new Date() don't throw an exception if month or day is out of range. It uses the internal MakeDay to calculate a date (see [ECMAScript Language Specification](http://www.ecma-international.org/publications/standards/Ecma-262.htm) section 15.9.3.1 and 15.9.1.13). To make sure that the date is valid in the function below...
Verify a date in JavaScript
[ "", "asp.net", "javascript", "validation", "date", "" ]
I have a pretty good understanding of Javascript, except that I can't figure out a nice way to set the "this" variable. Consider: ``` var myFunction = function(){ alert(this.foo_variable); } var someObj = document.body; //using body as example object someObj.foo_variable = "hi"; //set foo_variable so it alerts v...
There are two methods defined for all functions in JavaScript, [`call()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), and [`apply()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply). The function syntax looks like: ``...
I think you're looking for [`call`](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call): ``` myFunction.call(obj, arg1, arg2, ...); ``` This calls `myFunction` with `this` set to `obj`. There is also the slightly different method [`apply`](https://developer.mozilla.org/en/JavaScript/R...
Set "this" variable easily?
[ "", "javascript", "variables", "scope", "this", "" ]
I have two strings: the first's value is "catdog" and the second's is "got". I'm trying to find a regex that tells me if the letters for "got" are in "catdog". I'm particularly looking to avoid the case where there are duplicate letters. For example, I know "got" is a match, however "gott" is not a match because there...
You're using the wrong tool for the job. This is not something regular expressions are capable of handling easily. Fortunately, it's relatively easy to do this without regular expressions. You just count up the number of occurrences of each letter within both strings, and compare the counts between the two strings - if...
Previous suggestions have already been made that perhaps regex isn't the best way to do this and I agree, however, your accepted answer is a little verbose considering what you're trying to achieve and that is test to see if a set of letters is the subset of another set of letters. Consider the following code which ac...
regular expression for finding parts of a string within another
[ "", "c#", "regex", "" ]
I was asking a related question but messed the title up and no-one would understand it. Since I am able now to ask the question more precisely, I decided to reformulate it in a new question and close the old one. Sorry for that. So what I want to do is passing data (my custom user's nickname as stored in the db) to th...
My guess would be that the Controller's base constructor is not filling in the User, but that it is only known later when the ControllerContext is set for the Controller. You should check this in the documentation about the lifecycle of an MVC application, (the one [here](http://www.techtribe.com/viewBlogEntry.html?blo...
The answer to this problem is actually quite simple. I can't execute the code from within the constructor for reasons pointed out by Raimond, but I can do it outside the constructor. So what I did was overriding onActionExecuting() in the base controller class (I created a custom Attribute for it, but just overriding ...
Why is User (as in User.Identity.Name) null in my abstract base controller?
[ "", "c#", "asp.net-mvc", "controller", "user-controls", "httpcontext", "" ]
I need to extract all the images from a PDF file on my server. I don't want the PDF pages, only the images at their original size and resolution. How could I do this with Perl, PHP or any other UNIX based app (which I would invoke with the exec function from PHP)?
[pdfimages](http://linuxcommand.org/man_pages/pdfimages1.html) does just that. It's is part of the poppler-utils and xpdf-utils packages. From the manpage: > Pdfimages saves images from a Portable Document Format (PDF) file as Portable Pixmap (PPM), Portable Bitmap (PBM), or JPEG files. > > Pdfimages reads the PDF fi...
With regards to Perl, have you checked [CPAN](http://search.cpan.org)? * [PDF::GetImages](http://search.cpan.org/search?query=PDF-GetImages&mode=module) - get images from pdf document * [PDF::OCR](http://search.cpan.org/search?query=PDF-OCR&mode=module) - get ocr and images out of a pdf file * [PDF::OCR2](http://searc...
How can I extract images from a PDF file?
[ "", "php", "perl", "pdf", "" ]
I am trying to add enhancements to a 4 year old VC++ 6.0 program. The debug build runs from the command line but not in the debugger: it crashes with an access violation inside printf(). If I skip the printf, then it crashes in malloc() (called from within fopen()) and I can't skip over that. This means I cannot run i...
You can use [`_CrtSetDbgFlag()`](http://msdn.microsoft.com/en-us/library/5at7yxcs(VS.71).aspx) to enable a bunch of useful heap debugging techniques. There's a host of other [CRT debugging functions](http://msdn.microsoft.com/en-us/library/1666sb98(VS.71).aspx) available that should help you track down where your probl...
When run from the debugger, a different heap is used; this is referred to as the *debug heap*. This has different behaviour from the heap used outside the debugger, and is there to help you catch problems like this one. Note that the Win32 "debug heap" is distinct from the VC++ "debug heap"; both are intended to do mo...
VC++ 6.0 access violation when run in debugger
[ "", "c++", "debugging", "visual-c++-6", "access-violation", "" ]
I am using the `String.Split()` method in C#. How can I put the resulting `string[]` into an `ArrayList` or `Stack`?
You can initialize a `List<T>` with an array (or any other object that implements `IEnumerable`). You should prefer the strongly typed `List<T>` over `ArrayList`. ``` var myList = new List<string>(myString.Split(',')); ```
If you want a re-usable method, you could write an extension method. ``` public static ArrayList ToArrayList(this IEnumerable enumerable) { var list = new ArrayList; for ( var cur in enumerable ) { list.Add(cur); } return list; } public static Stack ToStack(this IEnumerable enumerable) { return new St...
Put result of String.Split() into ArrayList or Stack
[ "", "c#", "arrays", "collections", "split", "arraylist", "" ]
I find myself attached to a project to integerate an interpreter into an existing application. The language to be interpreted is a derivative of Lisp, with application-specific builtins. Individual 'programs' will be run batch-style in the application. I'm surprised that over the years I've written a couple of compile...
Short answer: The fundamental reading list for a lisp interpreter is SICP. I would not at all call it overkill, if you feel you are overqualified for the first parts of the book jump to chapter 4 and start interpreting away (although I feel this would be a loss since chapters 1-3 really are that good!). Add LISP in S...
Yes on SICP. I've done this task several times and here's what I'd do if I were you: Design your memory model first. You'll want a GC system of some kind. It's WAAAAY easier to do this first than to bolt it on later. Design your data structures. In my implementations, I've had a basic cons box with a number of base ...
References Needed for Implementing an Interpreter in C/C++
[ "", "c++", "lisp", "interpreter", "" ]
Could you please explain me, what is the different between API functions `AllocConsole` and `AttachConsole(-1)` ? I mean if `AttachConsole` gets `ATTACH_PARENT_PROCESS(DWORD)-1`.
Well, the fundamental difference is: * `AllocConsole()` will create a new console (and attach to it) * `AttachConsole( ATTACH_PARENT_PROCESS /* -1 */)` will not create a new console, it will attach to the existing console of the parent process. In the first case you get a whole new console window, in the second case,...
I don't think there's a function called `CreateConsole`, but there's [`AllocConsole`](http://msdn.microsoft.com/en-us/library/ms681944%28VS.85%29.aspx). Assuming that's what you meant, I think the difference is that `AttachConsole(ATTACH_PARENT_PROCESS)` can [return `ERROR_INVALID_HANDLE`](http://msdn.microsoft.com/en...
What is the different between API functions AllocConsole and AttachConsole(-1)?
[ "", "c#", ".net", "winapi", "console", "" ]
How do you get the [logical xor](http://en.wikipedia.org/wiki/Exclusive_or) of two variables in Python? For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or an empty string): ``` str1 = raw_input("Enter string one:") str2 = raw_input...
If you're already normalizing the inputs to booleans, then != is xor. ``` bool(a) != bool(b) ```
You can always use the definition of xor to compute it from other logical operations: ``` (a and not b) or (not a and b) ``` But this is a little too verbose for me, and isn't particularly clear at first glance. Another way to do it is: ``` bool(a) ^ bool(b) ``` The xor operator on two booleans is logical xor (unli...
How do you get the logical xor of two variables in Python?
[ "", "python", "logical-operators", "" ]
I'm using boost for several C++ projects. I recently made a upgrade (1.33.1 to 1.36, soon to 1.37), since then I cannot run any debug-builds anymore. To be sure that no other project issues remain, I've created a minimum test-project, which only includes boost.thread, and uses it to start one method. The release build...
So you are using the *pre-built* libraries from BoostPro? If so, your environment might somehow be slightly different to the one they were built in (TR1 feature pack or not, etc). Perhaps best to try [building Boost yourself](http://www.boost.org/doc/libs/1_37_0/more/getting_started/windows.html#or-build-binaries-from-...
It's a [Side-by-Side](http://blogs.msdn.com/rchiodo/archive/2007/04/09/the-next-level-of-dll-hell-sxs.aspx) (SxS) issue – simply copying the DLLs is not enough anymore. Regarding your specific problem concerning the Debug build, see: [Running vc2008 debug builds on non-dev machines](https://stackoverflow.com/questions...
Cannot execute program if using boost (C++) libraries in debug-version on WinXP
[ "", "c++", "windows", "dll", "boost", "side-by-side", "" ]
Other than the Java language itself, you have to learn the java framework. Similiar to how you have to learn the .net framework in addition to the language (C#/VB). How important is it to know unix? Or rather, what unix areas should one focus on? Seeing as many people run java based applications (desktop/web) on unix...
The answer as read from Sun marketing material is that Java is cross platform, so you don't. The practical answer is that you need to know enough to get your own application up and running on the platform where you plan to use it. Getting to know Apache or Tomcat configuration helps if you're working with web developm...
Really, you don't need unix skills directly for writing java-based applications. However, if you want to develop java-based applications on unix boxes and deploy there, you want a good working understanding of how to operate and administer a unix box. But for the areas you mention (directory traversing, creating files...
When learning Java, how important is it to know Unix well?
[ "", "java", "unix", "" ]
I have a javascript function (class) that takes a function reference as one paremter. ``` function MyClass ( callBack ) { if (typeof callBack !== 'function') throw "You didn't pass me a function!" } ``` For reasons I won't go in to here, I need to append something to the function by enclosing it in an anonymous...
Function objects don't provide methods to modify them. Therefore, what you want to do is impossible the way you want to do it. It's the same thing Jon Skeet likes to point out about Java: Objects are not really passed by reference, but instead a pointer to them is passed by value. That means that changing the value of ...
As Javascript uses lexical scoping on variables the following is possible: ``` var modifiableCallback=function() { alert('A'); }; function ModifyCallbackClass(callback) { modifiableCallback=function() { callback(); alert('B'); }; } function body_onload() { var myClass=new ModifyCallbackClass(modifiableC...
Extend Javascript Function passed as parameter
[ "", "javascript", "" ]
I'm calling a WebService exposed by Oracle that accepts an input of an ItemID and returns to me the corresponding Item Number. I want to grab the Item Number that has been returned out of the XML contained in the response. The XML looks like this: ``` <env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelop...
I'd personally use LINQ to XML, because I find that easier to deal with than XPath, particularly when namespaces are involved. You'd do something like: ``` XNamespace ns0 = "http://dev1/MyWebService1.wsdl"; String result = doc.Descendants(ns0 + "result").First().Value; ``` Note that `doc` here is expected to be an [...
fwiw you can cheat the namespace issue with an xpath like this: `//*[local-name()='result']`
What is a good way to find a specific value in an XML document using C#?
[ "", "c#", "xml", "xpath", "searching-xml", "" ]
I am working on some schema changes to an existing database. I backed up the database to get a dev copy, and have made my changes. I will be creating a single roll script to migrate the changes on the production machine in a single transaction. Is there a best practice for creating a rollback script encase a deployme...
That's basically it, I don't think there's much to add, aside from what your approach. This is how we do it in our company, we developers are responsible for creating the script and the rollback script, and we are responsible for leaving the DB in the same state it was before the initial changes are applied. Then the D...
You are missing the fifth step * Drop new constraints and indexes * Alter tables to remove new columns * Drop added tables * Commit transaction * **Test the hell out of the script before running it in production** A more efficient approach is to register the changes as they happen like [RoR](http://wiki.rubyonrails.o...
Best way to create a SQL Server rollback script?
[ "", "sql", "sql-server-2005", "t-sql", "rollback", "" ]
Here is my issue. I have an array containing the name of cities that I need to lookup the weather for. So I'm looping through each city and performing an AJAX request to retrieve the weather. ``` var LOCATION = 'http://www.google.com/ig/api?weather='; $( document ).ready( function() { for( var cityIdx = 0; cityId...
I suspect that your problem is similar to the example at <http://ejohn.org/apps/learn/>. The index variable cityIdx is updated in the closure you create as the for loop is processed, so by the time your function on success is run cityIdx will point to the last element in the array. The solution is to use an evaluated a...
Since Javascript uses functions for closure, I found the simplest way for me was to just wrap the contents of the for loop in an inline function that copies the current city name to a variable it will always have access to. ``` $(document).ready(function() { for (var cityIdx = 0; cityIdx < cities.length; cityIdx++...
Iterating through an array while performing a request for each entry
[ "", "javascript", "jquery", "ajax", "" ]
This isn't quite as straight forward as one may think. I'm using a plugin called [jQuery MultiSelect](http://abeautifulsite.net/notebook.php?article=62 "jQuery MultiSelect") and multiple <select> options using XSLT as follows: ``` <xsl:for-each select="RootField"> <select id="{RootField}" multiple="multiple" size="3...
I'd not heard the 'Halloween problem' tag before, but Robert may be correct. The nodelist returned from getElementsByTagName is dynamic i.e. adding or removing, in this case selects, will change the nodelist after it has been created. try ``` //hoping for magic here $('select').multiSelect(); ``` or ``` $('select...
Sounds like a Halloween problem (<http://blogs.msdn.com/mikechampion/archive/2006/07/20/672208.aspx>) in multiSelect, but since I don't know multiSelect I can't say for sure.
Iterating Over <select> Using jQuery + Multi Select
[ "", "javascript", "jquery", "multi-select", "" ]
How do you do "inline functions" in C#? I don't think I understand the concept. Are they like anonymous methods? Like lambda functions? **Note**: The answers almost entirely deal with the ability to [inline functions](http://en.wikipedia.org/wiki/Inline_expansion), i.e. "a manual or compiler optimization that replaces...
Finally in .NET 4.5, the CLR allows one to hint/suggest1 method inlining using [`MethodImplOptions.AggressiveInlining`](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions%28v=VS.110%29.aspx) value. It is also available in the Mono's trunk (committed today). ``` // The full attrib...
Inline methods are simply a compiler optimization where the code of a function is rolled into the caller. There's no mechanism by which to do this in C#, and they're to be used sparingly in languages where they are supported -- if you don't know why they should be used somewhere, they shouldn't be. Edit: To clarify, ...
Inline functions in C#?
[ "", "c#", "optimization", "inline", "" ]
I understand the best way to count the number of rows in an SQL table is count(\*) (or equivalently count(PrimaryKey)). 1. Is this O(1)? 2. If not, why not? Why not just implement a counter and return it for this specific query? Is it because this query is not a common use case? If the answers vary according to SQL ...
In *some* RDBM's this is O(1) (most notably MySQL), put AFAIK it is generally frowned upon and considered an "ugly performance hack". The reasons is that if you have transactions (which every real RDBM should have), the total number of rows in the table might or might not be equal to the total number *you can see from ...
No this is not a common use case. Most row counts I have seen have some where clause involved. The main reason this is not implemented though is the row counter would be a cause of contention in a multi user environment. Every time a row was inserted or deleted the counter would need updating effectively locking the w...
Count rows in an SQL table in O(1)
[ "", "sql", "performance", "count", "" ]
I have a partially nfilled array of objects, and when I iterate through them I tried to check to see whether the selected object is `null` before I do other stuff with it. However, even the act of checking if it is `null` seem to through a `NullPointerException`. `array.length` will include all `null` elements as well....
You have more going on than you said. I ran the following expanded test from your example: ``` public class test { public static void main(String[] args) { Object[][] someArray = new Object[5][]; someArray[0] = new Object[10]; someArray[1] = null; someArray[2] = new Object[1]; ...
It does not. See below. The program you posted runs as supposed. ``` C:\oreyes\samples\java\arrays>type ArrayNullTest.java public class ArrayNullTest { public static void main( String [] args ) { Object[][] someArray = new Object[5][]; for (int i=0; i<=someArray.length-1; i++) { ...
How to check if array element is null to avoid NullPointerException in Java
[ "", "java", "arrays", "exception", "nullpointerexception", "" ]
I'm rolling my own logger class, and want to represent the heirarchy of logs as the app moves through different phases: ``` log start loading loaded 400 values processing couldn't process var "x" ``` etc. In C++ (yes I know), I'd use RAII classlets that pushed themselves on the log stack whe...
You can get the behavior you are asking about if you use the [using](http://msdn.microsoft.com/en-us/library/yh598w02(VS.80).aspx) statement with an IDisposable-class. Do something like this: ``` public class LogContext: IDisposable { private readonly Logger _logger; private readonly string _context; public Lo...
OffTopic: If you want "the logger syntax to be as unobtrusive " to the client code as possible, you might want to have a look at Aspect Oriented Programming once your logger is finished. But maybe you should take a short less painful route and use any of the great loggers available (log4Net, NLog, System.Trace or even ...
Replicating C++'s RAII in C#
[ "", "c#", "logging", "raii", "" ]
In Python, properties are used instead of the Java-style getters and setters. So one rarely sees `get...` or `set...` methods in the public interfaces of classes. But, in cases where a property is not appropriate, one might still end up with methods that behave like getters or setters. Now for my questions: Should the...
I think shorter is better, so I tend to prefer the latter. But what's important is to be consistent within your project: don't mix the two methods. If you jump into someone else's project, keep what the other developers chose initially.
You won't ever lose the chance to make your property behave like a getter/setter later by using [descriptors](https://web.archive.org/web/20081216014119/http://users.rcn.com/python/download/Descriptor.htm). If you want to change a property to be read-only, you can also replace it with a getter method with the same name...
Should I use get_/set_ prefixes in Python method names?
[ "", "python", "coding-style", "" ]
I've been extensively using smart pointers (boost::shared\_ptr to be exact) in my projects for the last two years. I understand and appreciate their benefits and I generally like them a lot. But the more I use them, the more I miss the deterministic behavior of C++ with regarding to memory management and RAII that I se...
## Problem Summary There are two competing concerns in this question. 1. Life-cycle management of `Subsystem`s, allowing their removal at the right time. 2. Clients of `Subsystem`s need to know that the `Subsystem` they are using is valid. ## Handling #1 `System` owns the `Subsystem`s and should manage their life-c...
This is do-able with proper use of the `weak_ptr` class. In fact, you are already quite close to having a good solution. You are right that you cannot be expected to "out-think" your client programmers, nor should you expect that they will always follow the "rules" of your API (as I'm sure you are already aware). So, t...
A Question On Smart Pointers and Their Inevitable Indeterminism
[ "", "c++", "shared-ptr", "raii", "object-lifetime", "" ]
[This question](https://stackoverflow.com/questions/417265/what-does-sign-mean-in-django) originally asked (wrongly) what does "|" mean in Python, when the actual question was about Django. That question had a wonderful answer by Triptych I want to preserve.
In Python, the `'|'` operator is defined by default on integer types and set types. If the two operands are integers, then it will perform a [bitwise or](http://en.wikipedia.org/wiki/Bitwise_operation#OR), which is a mathematical operation. If the two operands are `set` types, the `'|'` operator will return the union...
Bitwise OR
What does the “|” sign mean in Python?
[ "", "python", "syntax-rules", "" ]
Looking for an implementation for C++ of a function like .NET's String.Format. Obviously there is printf and it's varieties, but I'm looking for something that is positional as in: > String.Format("Hi there {0}. You are > {1} years old. How does it feel to be > {1}?", name, age); This is needed because we're going to...
Lots of good recommendations above that would work in most situations. In my case, I ultimately wanted to load strings from a resource, AND keep the string resources as close to .NET String.Format as I could, so I rolled my own. After looking at some of the implementations above for ideas, the resulting implementation ...
Look at the [boost format library.](http://www.boost.org/doc/libs/1_37_0/libs/format/index.html)
String.Format for C++
[ "", "c++", "localization", "string.format", "printf", "" ]
I have the following code (adapted from an example given in [Dive Into Python](http://diveintopython.net/file_handling/file_objects.html#d0e14928)) that reads the entire contents of a file into a buffer. ``` buffer = "" try: file = open(postFileName, 'rU') try: # Read the entire POST log file into a b...
I find that finally blocks are often overused. The file close (and a few other similar patterns) are so important that Python 3.0 will have a **with** statement just to cover this base in a slightly less obscure way. * Do I need an except with a finally? That hits on the confusing nature of this specific example, a...
I disagree with the other answers mentioning unifying the try / except / finally blocks. That would change the behaviour, as you wouldn't want the finally block to try to close the file if the open failed. The split blocks are correct here (though it may be better using the new "`with open(filename,'rU') as f`" syntax ...
How do you test a file.read() error in Python?
[ "", "python", "file-io", "error-handling", "" ]
What I want to do is trigger a function from an extension/GM Script once a page in FireFox reloads/refreshes... Picture this: 1. I goto a webpage that asks for a username and password. 2. My code populates these values and submits the credentials 3. The webpage reloads and brings up a page asking me to enter a pre-de...
*I've updated my answer to reflect your updated question below.* As [rjk](https://stackoverflow.com/questions/432925/actions-on-page-reload-refresh-in-javascript#432941) mentioned, you can use the `onbeforeunload` event to perform an action when the page refreshes. Here is a solution that should work with some potent...
I do not think there is any way of preserving you JavaScript through refreshing the page in browser - it then loads it all again... Maybe you can start with `window.onbeforeunload` to overload default function of reload button and use AJAX to reload some main div...
Actions on page reload/refresh in JavaScript
[ "", "javascript", "" ]
Is there a shortcut to add an event method for a control? If I have a button, I want to add the Click method without having to type it out or switch to design view. EDIT: Seriously! When i did this in VB I had a drop down list of all the controls and their events. Is that so hard to do for C#?
Winforms? Webforms? What? One option is to (after initialization) hook the event your self - intellisense supplies the event name, and [Tab][Tab] creates the method stub - i.e. ``` public MyForm() { InitializeComponent() someButton.Click += (press [tab][tab] now) } ``` and it does the rest... likewise in web...
Have you looked into creating a snippet? Here is a snippet I use to create anonymous methods that hook up to an event. ``` <?xml version="1.0" encoding="utf-8" ?> <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"> <CodeSnippet Format="1.0.0"> <Header> <Title>anon...
Create event method for control shortcut - Visual Studio
[ "", "c#", "visual-studio-2008", "" ]
I just want to send SMS from my web application in PHP. Can anyone tell me how to do this? What all things I need to do for this?
I don't know if this applies to you, but what I have done many times to save myself the money is ask the user in his profile what his carrier is, then tried matching it with [`this list`](http://en.wikipedia.org/wiki/List_of_carriers_providing_SMS_transit). Essentially, many/most carriers have an email address connecte...
Your main option for sending SMS messages is using an existing SMS provider. In my experience (which is extensive with SMS messaging web applications), you will often find that negotiating with different providers is the best way to get the best deal for your application. Different providers often offer different serv...
SMS from web application
[ "", "php", "sms", "" ]
What is the correct way to separate between `F1` and i.e. `CTRL`+`F1` respective `SHIFT`-`CTRL`+`F1` within an KeyListener registered behind i.e. a JButton? ``` public void keyPressed(KeyEvent event) { int key = event.getKeyCode(); logger.debug("KeyBoard pressed char(" + event.getKeyChar() + ") code (" + key ...
The Solution lies in the parent of KeyEvent (InputEvent) 1. Use the isAltDown,isControlDown,isShiftDown methods or 2. Use the getModifiers method
`KeyEvent`s are probably a bit low-level when dealing with a Swing widget. Instead go through `InputMap` and `ActionMap`.
Java: handling combined keyboard input
[ "", "java", "event-handling", "keyboard", "" ]
How can I set a parameter of a sub-report? I have successfully hooked myself up to the SubreportProcessing event, I can find the correct sub-report through e.ReportPath, and I can add datasources through e.DataSources.Add. But I find no way of adding report parameters?? I have found people suggesting to add them to th...
After looking and looking, I have come to the conclusion that setting the parameters of a sub-report, in code, is not possible. Unless you do something fancy like start editing the xml of the report definition before you load it or something like that. (But if someone else should know that I am wrong, please do answer...
It does work but it sure is persnickety. First thing I recommend is to develop your reports as .rdl. Much easier to test the reports this way. You can also get the subreport parameters set up and tested as rdl, making sure each parameter of the subreport is also defined as a parameter of the parent report. Once you ge...
Microsoft Reporting: Setting subreport parameters in code
[ "", "c#", "reporting-services", "parameters", "reporting", "subreport", "" ]
Is there anyway I can create a not in clause like I would have in SQL Server in *Linq to Entities*?
If you are using an in-memory collection as your filter, it's probably best to use the negation of Contains(). Note that this can fail if the list is too long, in which case you will need to choose another strategy (see below for using a strategy for a fully DB-oriented query). ``` var exceptionList = new List<stri...
Try: ``` from p in db.Products where !theBadCategories.Contains(p.Category) select p; ``` What's the SQL query you want to translate into a Linq query?
"NOT IN" clause in LINQ to Entities
[ "", "c#", "linq-to-entities", "" ]
Ok, this may be a dumb question but here goes. I noticed something the other day when I was playing around with different HTML to PDF converters in PHP. One I tried (dompdf) took forever to run on my HTML. Eventually it ran out of memory and ended but while it was still running, none of my other PHP scripts were respon...
did you had open sessions for each of the scripts?:) they might reuse the same sesion and that blocks until the session is freed by the last request...so they basically wait for each other to complete(in your case the long-running pdf generator). This only applies if you use the same browser. Tip, not sure why you wan...
It could be that all the scripts you tried are running in the same application pool. (At least, that's what it's called in IIS.) However, another explanation is that some browsers will queue requests over a single connection. This has caused me some confusion in the past. If your web browser is waiting for a response ...
PHP/Apache blocking on each request?
[ "", "php", "apache", "" ]
So say I have a `products` table with a list of products, and one of the fields is `price`. This table also has an `id` field. When someone makes a purchase I insert a row into another table called `purchases`. This table also has a field called `price` and a `productid` field that maps to the products table `id` field...
Sure. In my normal practice I'd just be sending the price as part of the insert, but if you truly need to extract it from the product table at that point, you can do it with a subselect, like: ``` INSERT INTO `purchase` SET `product_id` = $whatever, `price` = ( SELECT `price` FROM `product` WHERE `id` = $w...
``` INSERT INTO purchases ( price ,productid ,add your other columns here ) SELECT price ,id ,add your other columns here FROM products WHERE add your selection criteria here ```
Is it possible to take a value from a row in one table in my MySQL database and insert into another table in the same database?
[ "", "sql", "mysql", "" ]
I was wondering if there are any times where it's advantageous to use an IEnumerator over a foreach loop for iterating through a collection? For example, is there any time where it would be better to use either of the following code samples over the other? ``` IEnumerator<MyClass> classesEnum = myClasses.GetEnumerator...
First, note that one big difference in your example (between `foreach` and `GetEnumerator`) is that `foreach` guarantees to call `Dispose()` on the iterator if the iterator is `IDisposable`. This is important for many iterators (which might be consuming an external data feed, for example). Actually, there are cases wh...
According to the [C# language spec](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx): > A foreach statement of the form ``` foreach (V v in x) embedded-statement ``` > is then expanded to: ``` { E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { ...
When should I use IEnumerator for looping in c#?
[ "", "c#", "iterator", "ienumerable", "loops", "" ]
What is the most efficient Javascript/AJAX toolkit?
Choose the library that makes the most sense to you idiomatically. The differences in efficiency are going to become less and less important as two things happen. 1. [Browsers are getting much better at interpreting Javascript.](http://ejohn.org/blog/javascript-performance-rundown/) 2. [Most major Javascript librarie...
jQuery seems pretty popular at the moment, and is lightweight. * <http://jquery.com/> Their API is well constructed and designed, and the resulting code tends to be very concise. Some may find it TOO concise - matter of taste. On larger projects I sometimes end up using YUI - it's a lot more heavyweight, but for a l...
Most efficient javascript/AJAX toolkit?
[ "", "javascript", "ajax", "" ]
I am writing a simple web app using Linq to Sql as my datalayer as I like Linq2Sql very much. I have been reading a bit about DDD and TDD lately and wanted to give it a shot. First and foremost it strikes me that Linq2Sql and DDD don't go along too great. My other problem is finding tests, I actually find it very hard...
Test Case discovery is more of an art than a science. However simple guidelines include: * Code that you know to be frail / weak / likely to break * Follow the user scenario (what your user will be doing) and see how it will touch your code (often this means Debugging it, other times profiling, and other times it simp...
Well, going by the standard interpretation of TDD is that the tests *drive* your development. So, in essence you start with the test. It will fail, and you will write code until that test passes. So it's kind of driven by your requirements, however you go about gathering those. You decide what your app/feature needs to...
TDD, What are your techniques for finding good tests?
[ "", "c#", "linq-to-sql", "tdd", "domain-driven-design", "" ]
I have a JAR file for authorization. I need it for each of my WAR files. All the WAR files are packaged in an EAR file. Do I have to repeat this common JAR in every WAR, or is there a structure for common libraries? So my example looks something like this... ``` big.ear - META-INF - MANIFEST.MF - applicatio...
The standard way is to put the JARs at the root of your EAR and reference them in the `Class-Path` attribute of the WARs' `META-INF/MANIFEST.MF`. See [this article](http://java.sun.com/j2ee/verified/packaging.html). Check your container's documentation to make sure it is supported.
It’s in the JEE5 spec, chapter EE 8.2.1: > A .ear file may contain a directory that contains libraries packaged > in JAR files. The library-directory element of the .ear file’s > deployment descriptor contains the name of this directory. If a > library-directory element isn’t specified, or if the .ear file does > not ...
Do common JARs have to be repeated across WARs in an EAR?
[ "", "java", "jakarta-ee", "enterprise-library", "" ]
I've been working with web start for a couple years now and have experience with signing the jars and what not. I am taking my first attempt at deploying a RCP app with web start and though I have in fact signed all of the jars with the same certificate I keep getting this error: 'jar resources in jnlp are not signed b...
When I had similar problems after checking the jars it turned out that some 3rd party jar was signed by someone else. You should create a separate jnlp file for the jars signed by the other certificate and read this jnlp from your jnlp file: ``` <resources> ... <extension name="other" href="other.jnlp"/> </resour...
The following script lists serial number of the RSA certificate in each jar in /some/lib directory and helps to find jars that are signed by the wrong certificate: ``` for f in $( find /some/lib -type f -name '*.jar' ) do serial=$( unzip -p $f 'META-INF/*.RSA' | openssl pkcs7 -inform der -print -noou...
jar resources in jnlp are not signed by the same certificate
[ "", "java", "rcp", "java-web-start", "jnlp", "" ]
I would like to be able to match a string literal with the option of escaped quotations. For instance, I'd like to be able to search "this is a 'test with escaped\' values' ok" and have it properly recognize the backslash as an escape character. I've tried solutions like the following: ``` import re regexc = re.compil...
I think this will work: ``` import re regexc = re.compile(r"(?:^|[^\\])'(([^\\']|\\'|\\\\)*)'") def check(test, base, target): match = regexc.search(base) assert match is not None, test+": regex didn't match for "+base assert match.group(1) == target, test+": "+target+" not found in "+base print "test...
## re\_single\_quote = r"`'[^'\\]*(?:\\.[^'\\]*)*'"` First note that MizardX's answer is 100% accurate. I'd just like to add some additional recommendations regarding efficiency. Secondly, I'd like to note that this problem was solved and optimized long ago - See: [Mastering Regular Expressions (3rd Edition)](https://...
Regex for managing escaped characters for items like string literals
[ "", "python", "regex", "" ]
I use the following code to create countdowns in Javascript. n is the number of times to repeat, freq is the number of milliseconds to wait before executing, funN is a function to call on each iteration (typically a function that updates part of the DOM) and funDone is the function to call when the countdown is complet...
I'd create an object that receives a counter and receives a function pointer to execute, something akin to the following pseudo code: ``` TimedIteration = function(interval, iterations, methodToRun, completedMethod){ var counter = iterations; var timerElapsed = methodToRun; //Link to timedMethod() method var c...
This is basically the same idea as @balabaster, but it is tested, uses prototype, and has a little more flexible interface. ``` var CountDownTimer = function(callback,n,interval) { this.initialize(callback,n,interval); } CountDownTimer.prototype = { _times : 0, _interval: 1000, _callback: null, ...
Best way to have event occur n times?
[ "", "javascript", "" ]
Could you suggest an efficient way to identify a unique user with JavaScript (e.g. calculate a hash to send to the server-side)? EDIT: The point is that I can't "intrude" into the browser (e.g. send cookies). And IPs are also not the option. And it has to be a client-side solution (therefore JavaScript).
A common solution to this problem is to calculate a unique ID on the server side, then push a cookie to the browser containing that ID (checking, first, to see whether that cookie has already been defined for the current browser). Advertising networks use that technique fairly heavily to gather demographic information...
I upvoted Brian's answer but I'd like to add that the problem is identifying a unique user. Insisting that it be done in Javascript - which is stateless beyond the page level unless there is participation at the server level - just isn't a fruitful approach.
Identifying unique hits with JavaScript
[ "", "javascript", "unique", "hit", "" ]
[Problem 2b](http://sqlzoo.net/2b.htm) goes as follows: > 2b. For each subject show the first year that the prize was awarded. > > > nobel(yr, subject, winner) My solution was this: `SELECT DISTINCT subject, yr FROM nobel ORDER BY yr ASC;` Why isn't this working?
Your answer gets a row for every distinct combination of subject and year. The correct answer GROUPS BY the subject, and gets the MIN year per subject. Enough of a clue?
You could do it a different way without using group by or min ``` select distinct subject, yr from nobel x where yr <= all (select yr from nobel y where y.subject = x.subject) ``` but its definitely more work.
Why can't I get the right answer in this SQLzoo tutorial?
[ "", "sql", "mysql-5.0", "" ]
I have a very large app, 1.5 million lines of C++, which is currently MFC based using the Document/View architecture. The application includes a lot of 3d vector graphics, spreadsheets, and very many dialogs and Windows. Within the constraints of the DVA it is fairly well written, in that there is no significant progra...
The short answer is that it is feasible, don't use java, and that it will be a considerable amount of work. A good few years ago (around the time of IE5) I was asked by a client to answer a similar question to this one. The application in question was a well structured three tier desktop application. The upshot of th...
Before considering to convert the MFC application to a web application, I suggest you to read "[Avoiding The Uncanny Valley of User Interface](https://blog.codinghorror.com/avoiding-the-uncanny-valley-of-user-interface/)" from Jeff Atwood. > If you're considering or actively building Ajax/RIA applications, you should ...
Is it feasible to convert a desktop based MFC C++ application to a web app
[ "", "c++", "mfc", "refactoring", "" ]
Why do we need to create custom exceptions in `.NET?`
Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this: ``` try {} catch (Exception ex) {} ``` This catches *all* exceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for e...
I did a lengthy blog post on this subject recently: <https://learn.microsoft.com/en-us/archive/blogs/jaredpar/custom-exceptions-when-should-you-create-them> The crux of it comes down to: Only create a custom exception if one of the following are true 1. You actually expect someone to handle it. 2. You want to log in...
Why Create Custom Exceptions?
[ "", "c#", ".net", "exception", "" ]
I need to display something such as below. ## Type A 1. Type A Item 1 2. Type A Item 2 3. Type A Item 3 ## Type B 1. Type B Item 1 2. Type B Item 2 3. Type B Item 3 ## Type C 1. Type C Item 1 2. Type C Item 2 3. Type C Item 3 All of the data comes from a dataset with columns 'Type' and 'ItemName'. Now an easy so...
Instead of creating a repeater for each type, how about a nested repeater? <http://www.codeproject.com/KB/aspnet/AspNetNestedRepeaters.aspx> Try that out. You still will need more than one repeater, but in this case it'd only be two that you need, and you wouldn't have to make one for each type (as you were fearing) ...
Ok, I just came up with a solution. Though it is pretty dirty. I created a global variable to track the headers. The variable is a list of strings. OnItemDatabind I check if the header item is in the global list. If the item doesn't exist, I add it to the list and display the header. Otherwise, the header item is emp...
Repeater for display sets
[ "", "c#", "asp.net", "repeater", "" ]
How to detect IIS version using C#? Update: I meant from a winapp (actually the scenario is developing a custom installer that wants to check the version of the installed IIS to call the appropriate api's)
You can get this information from the `SERVER_SOFTWARE` variable. It will return the following: `Microsoft-IIS/5.0 (Windows 2000)` `Microsoft-IIS/5.1 (Windows XP)` `Microsoft-IIS/6.0 (Windows 2003 Server)` etc. If you're using ASP.NET, you can get this string via ``` Request.ServerVariables["SERVER_SOFTWARE"]; ...
Found the answer here: [link text](http://forums.iis.net/p/1162404/1923867.aspx#1923867) The fileVersion method dosesn't work on Windows 2008, the inetserv exe is somewhere else I guess. ``` public Version GetIisVersion() { using (RegistryKey componentsKey = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\In...
How to detect IIS version using C#?
[ "", "c#", "iis", "" ]
I realised this might be relatively niche, but maybe that's why this is good to ask anyway. I'm looking at a hardware multiple input recording console (such as the Alesis IO 26) to take in an Adat lightpipe 8 channel input to do signal processing. As I have yet to acquire the device and need to work out whether this is...
Multi-channel audio is supposed to be possible in Java depending on the version of Java you are running, the platform you are running on, and the type of soundcard you are running. See the excellent [Java Audio Faq](http://www.jsresources.org/faq_audio.html) For more details. I've never been able to use this reliably a...
I have implemented something similar with Terratec cards cascaded to 32 inputs, the only library at the time was Jsyn. Its a really good library once you get to know it. http://www.softsynth.com/jsyn I am not sure if there is anything else that can help.
How to sample multi-channel sound input in Java
[ "", "java", "audio-recording", "javasound", "" ]
I got the code of a former employee. There are many calls to methods like: ``` foo(val,...); ``` where ``` void foo(String s,...) { ... } ``` and val is an int. Of course, I get an error. As a workaround I pass ""+val to foo. I wonder if there is a better way.
depending on the different types that are supposed to be passed as parameter, you could either accept an object and call .toString() ``` void foo(Object o){ String s=o.toString(); ... } ``` or overload foo for specific types ``` void foo(String s) { ... } void foo(int i){ foo(Integer.toString(i); } ```
String.valueOf(val) is much faster.
Automatic .toString() when calling a method?
[ "", "java", "" ]
In a similar vain to the c# extension topic on SO It would be great if we could pull together a whole host of useful jQuery function extensions. **Please Note the idea is to have short snippets of code not full blown well known plugins or ui widgets**
``` // Allows chainable logging // USAGE: $('#someDiv').hide().log('div hidden').addClass('someClass'); // Demo : http://jsbin.com/odeke jQuery.log = jQuery.fn.log = function (msg) { if ( window.console && window.console.log ) { console.log("%s: %o", msg, this); } return this; }; ```
you can use this to see if a selector exists. ``` if($.exists('#mydiv')) { } $.exists = function(selector) { return ($(selector).length); } ```
Post your short extension functions goodies for jQuery
[ "", "javascript", "jquery", "jquery-plugins", "" ]
Does any one know a good way to do remote procedure calls in windows (non .net) environmental? I cant find much information on how to do it and the msdn only has the .net version. . Edit: Thanks for the answers so far. What i need it for is to communicate with a service on the same computer which will send progress...
If you are only interested in talking between processes on the same machine, [boost::interprocess](http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html) is a cool way of getting a channel for them to talk through. More windows specific solutions is a [shared memory mapped file](http://msdn.microsoft.com/en-...
[DCOM](http://en.wikipedia.org/wiki/Distributed_Component_Object_Model) is has a remote procedure call mechanism based on DCE RPC. If you build your system as a COM component or put a COM wrapper over the API you want to expose you could use this. Beyond that, you might want to expand on your question with some more in...
remote procedure calls
[ "", "c++", "windows", "rpc", "" ]
I'm trying to effectively build a functional test suite for an applet, and I'm trying to find a good framework for it. In the past, when I wanted to design a test suite that would serve as both functional and load testing on an application, it has always been a web-based application, or at least some kind of service-b...
Have a look at [FEST Swing](http://docs.codehaus.org/display/FEST/Swing+Module). It makes it easy to drive and test Swing GUIs. It supports applets.
We have had a big success testing applets using QuickTest Professional ([wikipedia link](http://en.wikipedia.org/wiki/HP_QuickTest_Professional)). We tested the applet both in its natural environment (browser) and using a specially built "cradle" which takes over the browser part and embed the applet in a JFrame (so we...
What is the best mechanism for testing applets?
[ "", "java", "testing", "applet", "automated-tests", "integration-testing", "" ]
If I have three classes, A, B, C. A and B are friends (bidirectionally). Also, B and C are friends (bidirectionally). A has a pointer to B and B has a pointer to C. Why can't A access C's private data through the pointer? Just to clarify: This is a pure theoretical C++ language question, not a design advice question.
### Friendship in C++ is not transitive: John is a friend of mine and he can use my wireless connection any time (I trust him). John's friend Tim though is a waster and though John is my friend I do not include Tim as a friend, and thus I don't let him use my wireless connection. ### Friendship is NOT inherited Al...
Friendship in C++ is not transitive: ``` (A is friend of B) and (B is friend of C) does not mean (A is friend of C) ``` Also, friendship is not symmetric. ``` (A is friend of B) does not mean (B is friend of A) ``` You have to explicitly state that A is a friend of C to be able to access C's private stuff from with...
Friend scope in C++
[ "", "c++", "friend", "" ]
Is it possible to have Python save the `.pyc` files to a separate folder location that is in `sys.path`? ``` /code foo.py foo.pyc bar.py bar.pyc ``` To: ``` /code foo.py bar.py /code_compiled foo.pyc bar.pyc ``` I would like this because I feel it'd be more organized. Thanks for any help...
**Update:** In Python 3.8 `-X pycache_prefix=PATH` command-line option enables writing `.pyc` files to a parallel tree rooted at the given directory instead of to the code tree. See [`$PYTHONPYCACHEPREFIX` envvar](https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPYCACHEPREFIX)credits: [@RobertT' answer](https...
*In the dark and ancient days of 2003, PEP 304 came forth to challenge this problem. Its patch was found wanting. Environment variable platform dependencies and version skews ripped it to shreds and left its bits scattered across the wastelands.* *After years of suffering, a new challenger rose in the last days of 200...
Way to have compiled python files in a separate folder?
[ "", "python", "file", "compiled", "" ]
I need to invoke tesseract OCR (its an open source library in C++ that does Optical Character Recognition) from a Java Application Server. Right now its easy enough to run the executable using Runtime.exec(). The basic logic would be 1. Save image that is currently held in memory to file (a .tif) 2. pass in the image ...
It's hard to say whether it would be worth it. If you assume that if done in-process via JNI, the OCR code can directly access the image data without having to write it to a file, then it would certainly eliminate any disk I/O constraints there. I'd recommend going with the simpler approach and only undertaking the JN...
If you do pursue your own wrapper, I recommend you check out [JNA](https://github.com/twall/jna/). It will allow you to call most "native" libraries writing only Java code, and will give you more help than does raw JNI to do it safely. JNA is available for most platforms.
Invoking via command line versus JNI
[ "", "java", "java-native-interface", "ocr", "tesseract", "" ]
Here are two questions related to modifying the data source for strongly typed dataset connection string. When my app is deployed, a light weight database ( in the form of Microsoft Access) is deployed to the Application Data folder. I have a strongly typed dataset that is wrapped around that. So the question is how t...
When you deploy an Windows Forms application you could have an app.config file. yourproject.exe gives you a yourproject.exe.config file, which is the app.config file.
Instead of modifying .config file, you might be better off adding a new connection string property at runtime and using the TableAdapterManager. Please read more at: <http://rajmsdn.wordpress.com/2009/12/09/strongly-typed-dataset-connection-string/>
Modifying the Data Source for the Strongly Typed Dataset connection string
[ "", "c#", "configuration", "strongly-typed-dataset", "" ]
I have a statistics page which has a meta refresh tag on it. ``` <meta http-equiv="refresh" content="10" /> ``` How do I stop it forcing a refresh of the images in the page too? I've tried setting Cache control but the browser (IE7) still refreshes the 50+ images in the page. ``` Response.Cache.AppendCacheExtension(...
I solved this issue by using javascript to manually refresh the page rather than the meta tag. This stopped the browser refreshing all the images on every reload, but still forced the browser to refresh the ASPX page itself. ``` <script> setTimeout('document.location=document.location',10000) </script> ```
Maybe your IE is set to not cache images? How do you generate the images? Do they contain some kind of no-cache header?
How to force caching of image with meta refresh?
[ "", "c#", "asp.net", "html", "caching", "" ]
I was just reading over [this thread](https://stackoverflow.com/questions/186338/why-is-requireonce-so-bad-to-use) where the pros and cons of using `include_once` and `require_once` were being debated. From that discussion (particularly [Ambush Commander's answer](https://stackoverflow.com/questions/186338/why-is-requi...
That would depend somewhat on whether it was more work to parse several small files or to parse one big one. If you require files on an as-needed basis (not saying you necessarily *should* do things that way ) then presumably for some execution paths there would be considerably less compilation required than if all you...
There is a problem with Apache/PHP on Windows which causes the application to be extremely slow when loading or even touching too many files (page which loads approx. 50-100 files may spend few seconds only with file business). This problem appears both with including/requiring and working with files (fopen, file\_get\...
Rolling and packing PHP scripts
[ "", "php", "optimization", "" ]
In the following code I want to replace every occurrence of `"U.S.A"` with `"united states of America"` and every occurrence of `"uk"` with `"united kingdom"` in a string, but it does not seem to work. How do I fix it? ``` class Program { static void Main(string[] args) { string s = "th...
For simple replacements, you don't need Regular expressions: ``` string s = "the U.S.A love UK"; s = s.Replace("U.S.A", "United States of America").Replace("UK", "United Kingdom"); ```
Well, look at the search pattern in your regex. The `^` has a specific meaning. (as do the `.` but they won't actually fail in this case, but they aren't doing what you think they are)
Why is the regex replace method not working?
[ "", "c#", "regex", "" ]
Short of inserting a try/catch block in each worker thread method, is there a way to deal with unhandled, non-ui thread, exceptions in Windows Forms? `Thread.GetDomain().UnhandledException` works great for catching the error, but by then it's too late to do anything about it (besides log it). After control passes out ...
If you want to do something about the error before it hits UnhandledException, then you need a try/catch in the thread method. You should at least handle exceptions like FileNotFoundException here, where you can do something intelligent about it. If all else fails, you can use UnhandledException to cleanly handle anyt...
Thread.GetDomain().UnhandledException devolves to [AppDomain.UnhandledException](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx), which ordinarily would be the same domain for all threads in your application - in other words, you only have to hook this event once, not once per thread. ...
Unhandled, non-ui thread, exceptions in Windows Forms
[ "", "c#", ".net", "winforms", "multithreading", "" ]
Assume I have a form ``` class SampleClass(forms.Form): name = forms.CharField(max_length=30) age = forms.IntegerField() django_hacker = forms.BooleanField(required=False) ``` Is there a way for me to define css classes on each field such that I can then use jQuery based on class in my rendered page? I w...
Answered my own question. *Sigh* <http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs> I didn't realize it was passed into the widget constructor.
Yet another solution that doesn't require changes in python code and so is better for designers and one-off presentational changes: [django-widget-tweaks](https://github.com/kmike/django-widget-tweaks). Hope somebody will find it useful.
Define css class in django Forms
[ "", "python", "django", "django-forms", "" ]
Should I make my own framework by wrapping up the STL classes and/or Boost libraries so that if I need to change the implementation of the string, vectors, lists, etc. or I need to write functions that MFC, other other libraries or even other platforms would need to use their format, I can easily mutate them to meet th...
It seems to me like there won't be a lot of benefit to this; in my experience, the *point* of using these frameworks is so that you don't go reinventing the wheel. If you find that you need to write a new string class or a new vector class, you should think really hard about it, and make sure you're not just doing some...
"Am I reinventing the wheel too much?" - yes. Don't do it.
Should I make my own framework?
[ "", "c++", "frameworks", "interface", "portability", "" ]
How do you convert a number to a string showing dollars and cents? ``` eg: 123.45 => '$123.45' 123.456 => '$123.46' 123 => '$123.00' .13 => '$0.13' .1 => '$0.10' 0 => '$0.00' ```
PHP also has [money\_format()](http://php.net/money_format). Here's an example: ``` echo money_format('$%i', 3.4); // echos '$3.40' ``` This function actually has tons of options, go to the documentation I linked to to see them. Note: money\_format is undefined in Windows. --- UPDATE: Via the PHP manual: <https:/...
If you just want something simple: ``` '$' . number_format($money, 2); ``` [number\_format()](http://php.net/number_format)
How do I format a number to a dollar amount in PHP
[ "", "php", "formatting", "currency", "" ]
I have a generic class ``` public MyClass<TContext, T> where TContext : DataContext ``` that effectively acts on an instance of another ``` public class MyOtherClass<T> : IEnumerable<T> ``` I want to enforce that the `TContext` has a `Table<T>`. Is there a clean way to enforce this?
Are you wanting to verify that TContext has a member which is a Table<T>? If so, the only way to do that is to define an interface for this contract and alter your generic constraints ``` interface IMyTable<T> { Table<T> Table; } public MyClass<TContext,T> where TContext : DataContext,IMyTable<T> ``` **EDIT** Jas...
I think JaredPar had the right idea the first time around. ``` interface IMyTable<T> { Table<T> TheTable {get;} } public class MyClass<TContext,T> where TContext : DataContext,IMyTable<T> { //silly implementation provided to support the later example: public TContext Source {get;set;} public List<T> GetThe...
Generic enforcement
[ "", "c#", ".net", "linq-to-sql", "generics", "datacontext", "" ]
What are some of the ways you have implemented models in the Zend Framework? I have seen the basic `class User extends Zend_Db_Table_Abstract` and then putting calls to that in your controllers: `$foo = new User;` `$foo->fetchAll()` but what about more sophisticated uses? The Quickstart section of the documentation...
I personally subclass both `Zend_Db_Table_Abstract` and `Zend_Db_Table_Row_Abstract`. The main difference between my code and yours is that explicitly treat the subclass of `Zend_Db_Table_Abstract` as a "table" and `Zend_Db_Table_Row_Abstract` as "row". Very rarely do I see direct calls to select objects, SQL, or the b...
I worked for Zend and did quite a bit of work on the Zend\_Db\_Table component. Zend Framework doesn't give a lot of guidance on the concept of a "Model" with respect to the Domain Model pattern. There's no base class for a Model because the Model encapsulates some part of business logic specific to your application. ...
Models in the Zend Framework
[ "", "php", "model-view-controller", "zend-framework", "model", "" ]
I've been working on optimizing a query and have ran into a situation that's making me question how I've always used SQL's OR operator. (SQL Server 2000 also) I have a query where the conditional (WHERE) clause looks something like this: ``` WHERE (Column1 = @Param1 or Column1 LIKE @Param1 + '%') AND (@Param2 = '' OR...
"OR only evaluates expressions until it find a TRUE result" It only has to, but that's not your problem (actually this is what was saving you in your original case). Your two queries are not really equivalent. I'm thinking you have `NULL`s in Column2 which will never cause `(Column2 LIKE ISNULL(@Param2, '') + '%')` t...
OR is not all-encompassing, especially as it's in parentheses. What you have in a larger since is: `WHERE X AND Y`. That fact that X and Y are themselves boolean expressions that make use of an OR is not important: they are evaluated separately and then results are fed to the AND operator. [edit]: Reading again, I m...
SQL 'Or' operator. How does it work in the following scenario?
[ "", "sql", "sql-server", "null", "three-valued-logic", "" ]
> **Possible Duplicate:** > [Converting XML to JSON using Python?](https://stackoverflow.com/questions/191536/converting-xml-to-json-using-python) I'm doing some work on App Engine and I need to convert an XML document being retrieved from a remote server into an equivalent JSON object. I'm using `xml.dom.minidom` ...
Soviut's advice for lxml objectify is good. With a specially subclassed simplejson, you can turn an lxml objectify result into json. ``` import simplejson as json import lxml class objectJSONEncoder(json.JSONEncoder): """A specialized JSON encoder that can handle simple lxml objectify types >>> from lxml impo...
[xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this ["standard"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is [Expat](http://docs.python.org/library/pyexpat.html)-based, so i...
How to convert XML to JSON in Python?
[ "", "python", "xml", "json", "" ]
Lets say that I have a header user control in a master page, and want to change a property of the user control depending on what content page is loaded inside of the master page. How might I go about this? Thanks!
You can use two methods. The first is by using `Page.Master.FindControl('controlID')`. Then you can cast it to the type of your user control. The second method is by adding a `<%@ MasterType VirtualPath="">` OR `<%@ MasterType TypeName=""%>` tag to your aspx page. In the `VirtualPath` add the virtual path to the master...
first find the user control in the masterpage as below.Then find the control you need to access their property. ``` UserControl uch = Page.Master.FindControl("ucHeader1") as UserControl; PlaceHolder phProxylist= ucHeader1.FindControl("phProxy") as PlaceHolder; DropDownList ddlproxylist1 = ucHeader1.FindControl("ddlPro...
How to access a user control in a masterpage from a content page?
[ "", "c#", "asp.net", "user-controls", "master-pages", "" ]
I am in a situation where I would like to accept a LOT of log events controlled by me - notably the logging agent I am preparing for slf4j - and then analyze them interactively. I am not as such interested in a facility that presents formatted log files, but one that can accept log events as objects and allow me to so...
You might implement a adapter for logback to send log4j events to a log4j receiver. This would enable you to use chainsaw. Or build an adapter which receives logback network events and exposes them for log4j.
Take a look at [splunk](http://www.splunk.com/), it doesn't do the specific things that you are looking for, but maybe it can help you achieve the end goal.
Recommendations of a high volume log event viewer in a Java environment
[ "", "java", "logging", "" ]
If you are developing a memory intensive application in C++ on Windows, do you opt to write your own custom memory manager to allocate memory from virtual address space or do you allow CRT to take control and do the memory management for you ? I am especially concerned about the fragmentation caused by the allocation a...
I think your best bet is to not implement one until profiles **prove** that the CRT is fragmenting memory in a way that damages the performance of your application. CRT, core OS, and STL guys spend a lot of time thinking about memory management. There's a good chance that your code will perform quite fine under existi...
Although most of you indicate that you shouldn't write your own memory manager, it could still be useful if: * you have a specific requirement or situation in which you are sure you can write a faster version * you want to write you own memory-overwrite logic (to help in debugging) * you want to keep track of the plac...
Memory management in memory intensive application
[ "", "c++", "windows", "optimization", "memory-management", "" ]
What libraries, extensions etc. would be required to render a portion of a PDF document to an image file? Most PHP PDF libraries that I have found center around creating PDF documents, but is there a simple way to render a document to an image format suitable for web use? Our environment is a LAMP stack.
You need [`ImageMagick`](https://www.php.net/imagick) and [`GhostScript`](https://www.ghostscript.com/download.html) ``` <?php $im = new imagick('file.pdf[0]'); $im->setImageFormat('jpg'); header('Content-Type: image/jpeg'); echo $im; ?> ``` The `[0]` means `page 1`.
For those who don't have ImageMagick for whatever reason, GD functions will also work, in conjunction with GhostScript. Run the ghostscript command with `exec()` to convert a PDF to JPG, and manipulate the resulting file with `imagecreatefromjpeg()`. Run the ghostscript command: ``` exec('gs -dSAFER -dBATCH -sDEVICE=...
How do I convert a PDF document to a preview image in PHP?
[ "", "php", "image", "pdf", "lamp", "" ]
does jquery have any plugin that prevents entering any input to a textbox that doesnt match a regexp pattern. for example , i have a textbox for entering payment amount, i want user t be able to enter only numebers and . in the textbox, all other input wont have any effect on the textbox.. thanks
[jquery-keyfilter plugin](http://code.google.com/p/jquery-keyfilter/) - does what is needed.
[Masked Input Plugin](http://digitalbush.com/projects/masked-input-plugin/) ``` jQuery(function($){ $("#paymentAmount").mask("9999.99"); }); ```
jquery plugin for preventing entering any input not matching a regexp
[ "", "javascript", "jquery", "jquery-plugins", "" ]
I have a bunch of Python modules in a directory, all being a derivate class. I need a "runner" script that, for each module, instantiate the class that is inside it (the actual class name can be built by the module file name) and than call the "go" method on each of them. I don't know how many modules are there, but I...
``` def run_all(path): import glob, os print "Exploring %s" % path for filename in glob.glob(path + "/*.py"): # modulename = "bot_paperino" modulename = os.path.splitext(os.path.split(filename)[-1])[0] # classname = "Paperino" classname = modulename.split("bot_")[-1].capitali...
You could use [`__import__()`](http://docs.python.org/library/functions.html#__import__) to load each module, use [`dir()`](http://docs.python.org/library/functions.html#dir) to find all objects in each module, find all objects which are classes, instantiate them, and run the `go()` method: ``` import types for module...
Best way to create a "runner" script in Python?
[ "", "python", "metaprogramming", "" ]
I need to create an out-of-process COM server (.exe) in C# that will be accessed by multiple other processes on the same box. The component has to be a single process because it will cache the information it provides to its consumers in memory. Note: the processes that will access my COM Server are mostly Matlab proce...
One option is [serviced components](http://msdn.microsoft.com/en-us/library/3x7357ez(VS.80).aspx) - i.e. host it in COM+ as the shell exe. See also the [howto here](http://msdn.microsoft.com/en-us/library/ty17dz7h(VS.80).aspx).
We too had some issues many years ago with regasm and running the COM class as a Local EXE Server. This is a bit of a hack and I'd welcome any suggestions to make it more elegant. It was implemented for a project back in the .NET 1.0 days and has not been touched since then! Basically it performs a regasm style of re...
Create Out-Of-Process COM in C#/.Net?
[ "", "c#", "com", "" ]