Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there a difference between using `exit()` or just `return` statements in `main()`? Personally I favor the `return` statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the `main()` function, having `re...
Actually, there *is* a difference, but it's subtle. It has more implications for C++, but the differences are important. When I call `return` in `main()`, destructors will be called for my locally scoped objects. If I call `exit()`, **no destructor will be called for my locally scoped objects!** Re-read that. `exit()`...
Another difference: `exit` is a Standard Library function so you need to include headers and link with the standard library. To illustrate (in C++), this is a valid program: ``` int main() { return 0; } ``` but to use `exit` you'll need an include: ``` #include <stdlib.h> int main() { exit(EXIT_SUCCESS); } ``` Plus...
return statement vs exit() in main()
[ "", "c++", "c", "return", "exit", "" ]
as I usually don't do the up front design of my models in Django projects I end up modifying the models a lot and thus deleting my test database every time (because "syncdb" won't ever alter the tables automatically for you). Below lies my workflow and I'd like to hear about yours. Any thoughts welcome.. 1. Modify the...
Steps 2 & 3 can be done in one step: ``` manage.py reset appname ``` Step 4 is most easily managed, from my understanding, by using [fixtures](http://www.djangoproject.com/documentation/models/fixtures/)
This is a job for Django's fixtures. They are convenient because they are database independent and the test harness (and manage.py) have built-in support for them. To use them: 1. Set up your data in your app (call it "foo") using the admin tool 2. Create a fixtures directory in your "foo" app directory 3. Type...
Django workflow when modifying models frequently?
[ "", "python", "django", "django-models", "workflow", "django-syncdb", "" ]
I'm pulling a list of items from one table, on the basis of their being included in another table, like this: ``` select fruit.id, fruit.name from fruit, fruit_rating where fruit_rating.fruit_id=fruit.id group by fruit.name; ``` That works fine -- it basically produces a list of all the fruit that has been rated by s...
``` ... WHERE fruit_rating.fruit_id=fruit.id and fruit.id not in (select fruit_rating.fruit_id from fruit_rating where fruit_rating.user_id = 10) ```
I read this differently from Cowan, and agree with Noah... Find all fruit where: - User 10 did not rate it - Atleast one other user did rate it However, in my experience using NOT IN can be quite slow. So, I generally prefer to filter using LEFT JOIN in the same way as Cowan. Here are a few different options, though ...
SQL query to exclude items on the basis of one value
[ "", "sql", "mysql", "" ]
I am working on a site, and everything is working in my local environment as well as on a test server I have here and everything works fine. *but* when I upload it to my host, nothing seems to work!? The Asp.Net javascript validators fire, but any and all of the jquery is not working? I even put in a simple ``` $("#t...
my host did not default to have .js in their MIME types, so I had to add it in: ``` extension: .js application/x-javascript ```
You could always let Google do your work for you: ``` <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> </head> ``` One pleasant side-effect is that you'll save a little bandwidth, and because many sites now use Google's AJAX API, many users will a...
jQuery not working on my host?
[ "", "asp.net", "javascript", "jquery", "hosting", "" ]
Has anyone had issues with the contents of an isolated storage directory go missing or not update properly after a click once automated deployment?
I believe you can find your answer on this post - [ClickOnce and Isolated Storage](https://stackoverflow.com/questions/202013/clickonce-and-isolatedstorage#227218).
If the version of your application changes (I am uncertain exactly which version number it is) then new deployment creates a new folder for storage. There are 2 ways in which isolated storage stores the data: 1. Isolation by user and assembly 2. Isolation by user, domain and assembly In both cases, when the assembly ...
Clickonce & Isolated Storage
[ "", "c#", ".net", "clickonce", "" ]
Is iterating through the vector using an iterator and copying to a list the most optimal method of copying. Any recommendations?
Why would you iterate and not use the standard copy algorithm? ``` std::copy( vector.begin(), vector.end(), std::back_inserter( list ) ); ```
If you're making a new list, you can take advantage of a constructor that takes begin and end iterators: ``` std::list<SomeType> myList(v.begin(), v.end()); ``` Kasprzol's answer is perfect if you have an existing list you want to append to.
Best way to copy a vector to a list in STL?
[ "", "c++", "stl", "" ]
I have a C++ memory management doubt, that's (obviously) related to references and pointers. Suppose I have a class `Class` with a method `my_method`: ``` OtherClass& Class::my_method( ... ) { OtherClass* other_object = new OtherClass( ... ); return *other_object; } ``` Meanwhile in a nearby piece of code: `...
It's fairly obvious that you want to return a new object to the caller that you do not need to keep any reference to. For this purpose, the simplest thing to do is to return the object by value. ``` OtherClass Class::my_method( ... ) { return OtherClass( ... ); } ``` Then in the calling code you can construct the...
Yes that will lead to a memory leak. What you'll do is, in the return statement, dereference the new object you created. The compiler will invoke the assignment operator as part of the returning and copy the CONTENTS of your new object to the object it's assigned to in the calling method. The new object will be left ...
Will this lead to a memory leak in C++?
[ "", "c++", "pointers", "memory-leaks", "reference", "memory-management", "" ]
When I try to make a very large boolean array using Java, such as: ``` boolean[] isPrime1 = new boolean[600851475144]; ``` I get a possible loss of precision error? Is it too big?
To store 600 *billion* bits, you need an absolute minimum address space of 75 *gigabytes*! Good luck with that! Even worse, the Java spec doesn't specify that a `boolean` array will use a single bit of memory for each element - it could ([and in some cases does](http://eblog.chrononsystems.com/hidden-evils-of-javas-by...
Consider using a [BitSet](http://java.sun.com/j2se/1.4.2/docs/api/java/util/BitSet.html).
How do you make REALLY large boolean arrays using Java?
[ "", "java", "boolean", "" ]
So for a while I've been using XslCompiledTransform because that's what Microsoft tells me I need to use as XslTransform is deprecated. Recently I had to use it with a transform that has nearly 100,000 lines (generated xsl - of course). When I used my application I was shocked to see an OOM pop up. No matter what I did...
ok, so now i think, maybe this is more 'microsoft being microsoft'... on a hunch i changed the target platform back to "Any CPU", closed ALL my visual studio instances open and reopened my project... i then cleaned, recompiled, and reran and i am again getting the OOM... i then set the target platform back to x86 and ...
well... programming in the windows world is always a mystery... i thank you both for your answers however today - while trying to replicate the problem (after being gone for around 14 hrs) the issue has disappeared entirely... the only thing i did differently was to set the compiler to be x86 instead of x64 and now t...
XslCompiledTransform vs. XslTransform and how about an OOM for good measure?
[ "", "c#", "xslt", "xslcompiledtransform", "" ]
How can I redirect the user from one page to another using jQuery or pure JavaScript?
## One does not simply redirect using jQuery jQuery is not necessary, and [**`window.location.replace(...)`**](https://developer.mozilla.org/en-US/docs/Web/API/Location/replace) will best simulate an HTTP redirect. `window.location.replace(...)` is better than using `window.location.href`, because `replace()` does no...
**WARNING:** This answer has merely been provided as a possible solution; it is obviously *not* the best solution, as it requires jQuery. Instead, prefer the pure JavaScript solution. ``` $(location).prop('href', 'http://stackoverflow.com') ```
How do I redirect to another webpage?
[ "", "javascript", "jquery", "redirect", "" ]
In Python, I can do: ``` list = ['a', 'b', 'c'] ', '.join(list) # 'a, b, c' ``` However, if I have a list of objects and try to do the same thing: ``` class Obj: def __str__(self): return 'name' list = [Obj(), Obj(), Obj()] ', '.join(list) ``` I get the following error: ``` Traceback (most recent c...
You could use a list comprehension or a generator expression instead: ``` ', '.join([str(x) for x in list]) # list comprehension ', '.join(str(x) for x in list) # generator expression ```
The built-in string constructor will automatically call `obj.__str__`: ``` ''.join(map(str,list)) ```
string.join(list) on object array rather than string array
[ "", "python", "string", "list", "" ]
What is the most efficient to fill a ComboBox with all the registered file types in Windows? I want the full file type, not just the extension. I'm using VB 9 (VS2008).
All the file types are stored in the registry under the HKEY\_CLASS\_ROOT, which you could obtain using the Framework's [Registry class](http://msdn.microsoft.com/en-us/library/microsoft.win32.registry.aspx). Here's c# code to perform the task: ``` using Microsoft.Win32; public class FileAssoc { public string Ex...
I agree with Joel, that's going to be a lot of entries and trying to find something in a combobox list of hundreds of items is going to end up as a really poor user experience. Other than that, the only way to get this information is to go through the registry, as Mitch says but it won't be simple code. What are you t...
What is the most efficient way to get fill a ComboBox with all the registered file types (not just extensions)
[ "", "c#", "file", "combobox", "registry", "" ]
I have a string object "with multiple characters and even special characters" I am trying to use ``` UTF8Encoding utf8 = new UTF8Encoding(); ASCIIEncoding ascii = new ASCIIEncoding(); ``` objects in order to convert that string to ascii. May I ask someone to bring some light to this simple task, that is hunting my ...
This was in response to your other question, that looks like it's been deleted....the point still stands. Looks like a [classic Unicode to ASCII issue](http://www.joelonsoftware.com/articles/Unicode.html). The trick would be to find *where* it's happening. .NET works fine with Unicode, assuming [it's told it's Unicod...
I was able to figure it out. In case someone wants to know below the code that worked for me: ``` ASCIIEncoding ascii = new ASCIIEncoding(); byte[] byteArray = Encoding.UTF8.GetBytes(sOriginal); byte[] asciiArray = Encoding.Convert(Encoding.UTF8, Encoding.ASCII, byteArray); string finalString = ascii.GetString(asciiAr...
How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?
[ "", "c#", "encoding", "utf-8", "ascii", "transliteration", "" ]
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves th...
It depends if you want a quick fix or a rigorous fix. A quick fix would be just to use one lock object in all cases. e.g. `private readonly object _lock = new object();` And then just lock on that. However, depending on your situation, that may impact performance more than you can accept. I.e. your code would becom...
Take the Processing lock in method A and the WaitingQueue lock in method B (in other words, make it look like the first block of code). That way, you always take the locks in the same order and you'll never deadlock.
How to prevent deadlocks in the following C# code?
[ "", "c#", ".net", "multithreading", "deadlock", "" ]
Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods? ``` TestClass = function(){ var privateField = "hello"; this.nonProtoHello = function(){alert(privateField)}; }; TestClass.prototype.prototypeHello = function(){alert(privateField)}; ``` Th...
No, there's no way to do it. That would essentially be scoping in reverse. Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined. Methods defined on a prototype are not defined within the scope of the constructor, and will not...
# Update: With ES6, there is a better way: Long story short, you can use the new `Symbol` to create private fields. Here's a great description: <https://curiosity-driven.org/private-properties-in-javascript> Example: ``` var Person = (function() { // Only Person can access nameSymbol var nameSymbol = Symbo...
Accessing private member variables from prototype-defined functions
[ "", "javascript", "private-members", "" ]
The keyword `protected` grants access to classes in the same package and subclasses (<http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html>). Now, every class has `java.lang.Object` as superclass (<http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Object.html>). Hence I conclude that every class may...
You can only access protected members of a type in a different package if the compile-time type of the expression you're referencing it through is either your own class or a subclass. (Where "your" class is the class containing the code.) Your own class has to be a subclass of the type which originally declares the met...
When you said "`((Object) this).clone()`", you accessed your own object via its superclass Object. You performed a widening conversion to an Object. The code then attempts to call clone on Object. But, as you've noted, clone is a protected method, meaning that only if your object was in the same package of java.lang w...
How are java.lang.Object's protected methods protected from subclasses?
[ "", "java", "object", "protected", "access-modifiers", "" ]
I'm learning JavaScript and while browsing through the jQuery library I see `:` (colon) being used a lot. What is this used for in JavaScript? ``` // Return an array of filtered elements (r) // and the modified expression string (t) return { r: r, t: t }; ```
``` var o = { r: 'some value', t: 'some other value' }; ``` is functionally equivalent to ``` var o = new Object(); o.r = 'some value'; o.t = 'some other value'; ```
And also, a colon can be used to label a statement. for example ``` var i = 100, j = 100; outerloop: while(i>0) { while(j>0) { j++ if(j>50) { break outerloop; } } i++ } ```
What does ':' (colon) do in JavaScript?
[ "", "javascript", "" ]
The following throws an `InvalidCastException`. ``` IEnumerable<int> list = new List<int>() { 1 }; IEnumerable<long> castedList = list.Cast<long>(); Console.WriteLine(castedList.First()); ``` Why? I'm using Visual Studio 2008 SP1.
That's very odd! There's a blog post [here](http://blogs.msdn.com/ed_maurer/archive/2008/02/16/breaking-change-in-linq-queries-using-explicitly-typed-range-variables.aspx) that describes how the behaviour of `Cast<T>()` was changed between .NET 3.5 and .NET 3.5 SP1, but it still doesn't explain the InvalidCastException...
Enumerable.Cast method is defined as following: ``` public static IEnumerable<TResult> Cast<TResult>( this IEnumerable source ) ``` And there is no information about initial type of IEnumerable's items, so I think each of your ints is initially converted to System.Object via boxing and then it's tried to be unbox...
Puzzling Enumerable.Cast InvalidCastException
[ "", "c#", ".net", "exception", "" ]
I have done the following code in JavaScript to put focus on the particular element (branch1 is a element), ``` document.location.href="#branch1"; ``` But as I am also using jQuery in my web app, so I want to do the above code in jQuery. I have tried but don't know why its not working, ``` $("#branch1").focus(); ```...
Check [jQuery.ScrollTo](https://github.com/flesler/jquery.scrollTo), I think that's the behavior that you want, check the [demo](http://demos.flesler.com/jquery/scrollTo/).
For my problem this code worked, I had to navigate to an anchor tag on page load : ``` $(window).scrollTop($('a#captchaAnchor').position().top); ``` For that matter you can use this on any element, not just an anchor tag.
How to scroll to an element in jQuery?
[ "", "javascript", "jquery", "html", "focus", "" ]
I am currently working on a [Flot](http://code.google.com/p/flot/) graph, the [API](http://flot.googlecode.com/svn/trunk/API.txt) which seems pretty powerful overall, although examples of advanced use are not widely documented. The API suggests there are ways to set hoverable on the graph, not that I am sure what exac...
Have a look at [this flot example](http://www.flotcharts.org/flot/examples/interacting/) which demonstrates tooltips for plot points on the chart. (Make sure you select the **Enable tooltip** checkbox.)
There is also a simple tooltip plugin for it, you can find it [here](https://github.com/krzysu/flot.tooltip) And I also add some feature to the plugin, you can find it on github. <https://github.com/skeleton9/flot.tooltip>
Any examples of Flot with floating tooltips?
[ "", "javascript", "jquery", "jquery-events", "flot", "graphing", "" ]
I'm working on an asp.net-mvc application. The linq data context is being passed into my service objects by structure map. I've got is set to have a scope of hybrid. This all works just fine. ``` protected override void configure() { ForRequestedType<AetherDataContext>() .TheDefaultIs(() => new AetherDataC...
This is almost an exact copy of the question I asked 2 days ago: [Session containing items implementing IDisposable](https://stackoverflow.com/questions/498095/session-containing-items-implementing-idisposable) InstanceScope.Hybrid just stores the object inside HttpContext.Current.Items if it exists or ThreadLocal sto...
Ok so the latest version of StructureMap [(2.3.5)](http://codebetter.com/blogs/jeremy.miller/archive/2009/02/01/structuremap-2-5-3-is-released-and-the-future-of-structuremap.aspx) has a useful little method called ``` HttpContextBuildPolicy.DisposeAndClearAll(); ``` > Cleanup convenience methods on HttpContext and Th...
StructureMap InstanceScope.Hybrid and IDisposable
[ "", "c#", "asp.net-mvc", "linq", "inversion-of-control", "structuremap", "" ]
I have some logic, which defines and uses some user-defined types, like these: ``` class Word { System.Drawing.Font font; //a System type string text; } class Canvass { System.Drawing.Graphics graphics; //another, related System type ... and other data members ... //a method whose implementation combines th...
First, I wonder if the entire scenario isn't a little artificial; are you really going to **need** this level of abstraction? Perhaps subscribe to [YAGNI](http://en.wikipedia.org/wiki/You_Ain't_Gonna_Need_It)? Why does your `MyGraphics` only work with a `MyFont`? Can it work with an `IFont`? That would be a better use...
You're effectively saying "I know better than the compiler - I know that it's bound to be an instance of `MyFont`." At that point you've got `MyFont` and `MyGraphics` being tightly coupled again, which reduces the point of the interface a bit. Should `MyGraphics` work with any `IFont`, or only a `MyFont`? If you can m...
Is it possible to avoid a downcast?
[ "", "c#", "polymorphism", "downcast", "" ]
Using LINQ to SQL ``` db.Products.Where(c => c.ID == 1).Skip(1).Take(1).ToList(); ``` executes ``` SELECT [t1].[ID], [t1].[CategoryID], [t1].[Name], [t1].[Price], [t1].[Descripti n], [t1].[IsFeatured], [t1].[IsActive] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [t0].[ID], [t0].[CategoryID], [t0].[Name , [t0].[Pric...
I think its because the category is in memory. You are asking it, implicitly, to get the products of the category. This implicit request for data is for filled, and then in memory (where the category is at this point) the query is executed. I'm thinking its equivalent to : ``` var cat = db.Categories.Where(c => c.ID ...
have you tried: ``` var cat = db.Categories.Where(c => c.ID == 1); var prod = cat.Products.Where(c => c.ID == 1).Skip(1).Take(1).ToList(); ```
Querying against LINQ to SQL relationships
[ "", "asp.net", "sql", "linq", "linq-to-sql", "" ]
I'd like to parse status.dat file for nagios3 and output as xml with a python script. The xml part is the easy one but how do I go about parsing the file? Use multi line regex? It's possible the file will be large as many hosts and services are monitored, will loading the whole file in memory be wise? I only need to ...
Nagiosity does exactly what you want: <http://code.google.com/p/nagiosity/>
Pfft, get yerself mk\_livestatus. <http://mathias-kettner.de/checkmk_livestatus.html>
How to parse nagios status.dat file?
[ "", "python", "parsing", "nagios", "" ]
We started a Web Project in Eclipse 3.2 a ways back and we've since upgraded to Eclipse 3.4 but now the Project has the error: "This project needs to migrate WTP metadata" We've tried right-clicking and doing the "quick-fix" which is in fact to Migrate WTP Metadata. Unfortunately nothing happens and the error remains...
The above solution works fine but it creeps up again and again. An easier solution is to right click on the concerned project in Eclipse and choose Validate.
For me, none of these worked. The solution for me was deleting the following file while Eclipse was stopped: ``` /workspace/.metadata/.plugins/org.eclipse.core.resources/.projects/myprojectname/.markers ```
Eclipse error: This project needs to migrate WTP metadata
[ "", "java", "eclipse", "eclipse-wtp", "" ]
How do I get a random [`decimal.Decimal`](https://docs.python.org/3.6/library/decimal.html#decimal-objects) instance? It appears that the random module only returns floats which are a pita to convert to Decimals.
What's "a random decimal"? Decimals have arbitrary precision, so generating a number with as much randomness as you can hold in a Decimal would take the entire memory of your machine to store. You have to know how many decimal digits of precision you want in your random number, at which point it's easy to just grab an...
From the [standard library reference](http://docs.python.org/dev/3.0/library/decimal.html) : To create a Decimal from a float, first convert it to a string. This serves as an explicit reminder of the details of the conversion (including representation error). ``` >>> import random, decimal >>> decimal.Decimal(str(ran...
random Decimal in python
[ "", "python", "random", "decimal", "" ]
What's the disadvantage of choosing a large value for max when creating a varchar or varbinary column? I'm using MS SQL but I assume this would be relevant to other dbs as well. Thanks
That depends on whether it is ever reasonable to store a large amount of data in the particular column. If you declare a column that would never properly store much data (i.e. an employee first name as a VARCHAR(1000)), you end up with a variety of problems 1. Many if not most client APIs (i.e. ODBC drivers, JDBC dri...
Depends on the RDBMS. IIRC, MySql allocates a 2 byte overhead for varchars > 255 characters (to track the varchar length). MSSQL <= 2000 would allow you to allocate a row size > 8060 bytes, but would fail if you tried to INSERT or UPDATE a row that actually exceeded 8060 bytes. SQL 2005[1] allows the insert, but will a...
Disadvantage of choosing large MAX value for varchar or varbinary
[ "", "sql", "sql-server", "types", "varchar", "" ]
I'm writing a simplistic game to learn get some more C++ experience, and I have an idea where I feel polymorphism *almost* works, but doesn't. In this game, the `Party` moves fairly linearly through a `Map`, but can occasionally encounter a `Fork` in the road. A fork is (basically) an `std::vector<location*>`.Originall...
All problems can be solved by adding a level of indirection. I would use your suggested variant, and decouple Location from Party by allowing getNext to accept an object that resolves directional choices. Here is an example (untested): ``` class Location; class IDirectionChooser { public: virtual bool ShouldIGoThi...
You should use polymorphism as long as it makes sense and simplifies your design. You shouldn't use it just because it exists and has a fancy name. If it does make your design simpler, then it's worth the coupling. Correctness and simplicity should be the ultimate goal of every design decision.
Is Polymorphism worth an increase in coupling?
[ "", "c++", "polymorphism", "coupling", "" ]
Today I had to fix some older VB.NET 1.0 code which is using threads. The problem was with updating UI elements from the worker thread instead of the UI-thread. It took me some time to find out that I can use assertions with InvokeRequired to find the problem. Besides the above mentioned concurrent modification proble...
This could be a *massive* list - read Joe Duffy's excellent "[Concurrent Programming On Windows](https://rads.stackoverflow.com/amzn/click/com/032143482X)" for much more detail. This is pretty much a brain dump... * Try to avoid calling into significant chunks of code while you own a lock * Avoid locking on references...
I'm not sure how well this will help for the particular application you're working with, but here are two approaches borrowed from functional programming for writing multithreaded code: **Immutable objects** If you need to share state between threads, the state should be immutable. If one thread needs to make a chang...
How to write safe/correct multi-threaded code in .NET?
[ "", "c#", ".net", "vb.net", "multithreading", "" ]
Basically I want to do this: ``` public interface A { void a(); } public interface B { void b(); } public class SomeClass { public SomeClass(<A&B> e) { // Note the type here e.a(); e.b(); } } ``` What I did on the commented line is obviously illegal. I know I can just require the passe...
You can do it with generics enabled. For example, to accept an instance of some class that implements both CharSequence and Appendable: ``` public <T extends CharSequence & Appendable> void someMethod(T param) { ... } ```
Depending on the design, you can do one of the following: 1. Make A : B or B : A. 2. Make an interface C : A, B. Either way you'll want to have contract that includes both a() and b().
Can you require multiple types at once?
[ "", "java", "inheritance", "types", "interface", "" ]
I'm learning Java (and OOP) and although it might irrelevant for where I'm at right now, I was wondering if SO could share some common pitfalls or good design practices.
One important thing to remember is that static methods cannot be overridden by a subclass. References to a static method in your code essentially tie it to that implementation. When using instance methods, behavior can be varied based on the type of the instance. You can take advantage of polymorphism. Static methods a...
I don't think any of the answers get to the heart of the OO reason of when to choose one or the other. Sure, use an instance method when you need to deal with instance members, but you could make all of your members public and then code a static method that takes in an instance of the class as an argument. Hello C. Yo...
Is there a rule of thumb for when to code a static method vs an instance method?
[ "", "java", "oop", "class-design", "" ]
I found a couple of ways to handle recursion in Smarty, mostly based on including templates into themselves, which seems like ridiculous waste of resources. I found one solution, by Messju over at Smarty that seemed to be just right - but it is not supported and fails in the latest version of smarty :( For people aski...
"In order to understand recursion, you must first understand recursion..." Just kidding. This should do what you want: ``` <?php /* * Smarty plugin * ————————————————————- * File: function.recurse_array.php * Type: function * Name: recurse_array * Purpose: prints out elements of an array recursively * ——...
With Smarty 3, this can be done using {function}. The following code will produce the required ouput. ``` {function name=printList} <ul> {foreach $items as $item} <li> <h1>{$item['headline']}</h1> <p>{$item['body']}</p> {if $item['children']} {call name=printList items=$item...
What is the best way to handle recursion in smarty?
[ "", "php", "templates", "recursion", "smarty", "" ]
I am trying to generate a key using the .net 2.0 PasswordDeriveBytes class. ``` PasswordDeriveBytes pdb = new PasswordDeriveBytes("blahblahblah",null); byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }; byte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 128, iv); ``` The code throws "CryptographicException: I...
According to MSDN: *"If the keySize parameter is set to 0 bits, the default key size for the specified algorithm is used."* [MSDN PasswordDeriveBytes.CryptDeriveKey Method](http://msdn.microsoft.com/en-us/library/system.security.cryptography.passwordderivebytes.cryptderivekey.aspx) ``` PasswordDeriveBytes pdb = new ...
TripleDES has a key length of 192 bits try: ``` byte[] key = pdb.CryptDeriveKey("TripleDES", "SHA1", 192, iv); ``` Try [this link](http://msdn.microsoft.com/en-us/library/system.security.cryptography.passwordderivebytes.aspx) for example code
Deriving a crypto key from a password
[ "", "c#", "asp.net", "" ]
I am quite a heavy user of wxWidgets, partly because of licensing reasons. * How do you see the future of wxWidgets in prospect of the [recent announcement](http://www.qtsoftware.com/about/licensing) of Qt now being released under LGPL? * Do you think wxwidget is still a good technical choice for new projects ? Or wou...
For those of us who are drawn to wxWidgets because it is the cross-platform library that uses native controls for proper look and feel the licensing change of Qt has little to no consequences. **Edit:** Regarding > Qt not having native controls but native drawing functions let me quote the [wxWidgets wiki page comp...
I'm currently using pyqt at work and I find myself totally satisfied. You have better documentation (IMHO), better event managing (signal-slot pattern is somehow more powerful than the old simple-callback style), and importing your custom widget in a graphical designer like qt-designer is far easier. As far as I can te...
Qt being now released under LGPL, would you recommend it over wxWidgets?
[ "", "python", "qt", "wxpython", "wxwidgets", "" ]
I talked to the Team Lead at Snap-On Tools once, and she told they used an "implementation of JavaScript" for their server-side coding. It's been a while, but I was thinking, WTF is she talking about? Are there interpreters for JavaScript besides those implemented in browsers? **How can you create a program or code, e...
JavaScript does not have to be run in a browser if you use an ECMAScript engine. Actually, both [SpiderMonkey](http://www.mozilla.org/js/spidermonkey/) and [Rhino](http://www.mozilla.org/rhino/) are [ECMAScript engines](http://en.wikipedia.org/wiki/List_of_ECMAScript_engines). Flash's ActionScript is another ECMAScrip...
List of JS interpreters that I know of, that can run standalone or embedded with other code: * [Google's V8](http://code.google.com/p/v8/) (C++) * [Jint](http://jint.codeplex.com/) (.NET) * [Microsoft's JScript](http://msdn.microsoft.com/en-us/library/hbxc2t98.aspx) (.NET), old * [JavaScript ScriptEngine in Java 6](ht...
Browserless JavaScript
[ "", "javascript", "" ]
What do the following mean in an sql sytax: 1. (+) after a condition eg: "WHERE table1.col1 = table2.col2 (+) 2. What does /\* \*/ after select signify , i vaguely remember it being a suggestion to the optimizer, but where can i find more reference on this eg: select /\* \*/ ...
1. The `(+)` means an outer join syntax for SQL on Oracle. 2. The `/*` alter the SELECT means a comment. In Oracle if the comments starts with `/*+` (A plus after the comment token, means a hint, for instance `/*+ORDERED*/`
If we are talking oracle then the `(+)` is an outer join and `/* some stuff */` is a comment. If the comment is of the form `/*+ hint* */` then the comment is probably a hint. [google on oracle hints](http://www.google.co.uk/search?source=ig&hl=en&rlz=1G1GGLQ_ENUK243&q=oracle+hint&meta=lr%3D)
SQL syntax question
[ "", "sql", "oracle", "" ]
in my code i would like boost::shared\_ptr not to call delete but call ptr->deleteMe() instead. Also i have a few C styled functions that return a ptr. Can i make it call lib\_freeXYZ(ptr); instead of trying to delete?
Or how about using the stl to provide the wrapper functor - Doug T. description but without the custom caller. ``` boost::shared_ptr<T> ptr( new T, std::mem_fun_ref(&T::deleteMe) ); boost::shared_ptr<S> ptr( new S, std::ptr_fun(lib_freeXYZ) ); ```
You can give the shared\_ptr template a custom deleter function which has the signature ``` void Deleter( T* ptr); ``` for a boost::shared\_ptr So for Deleter you would do ``` boost::shared_ptr<T> ptrToT( new T, Deleter ); ``` then in the body of Deleter: ``` void Deleter( T* ptr); { ptr->delete...
make shared_ptr not use delete
[ "", "c++", "boost", "" ]
How can I work with Novell eDirectory services in J2SE? Will JNDI work with eDirectory? What are some resources I can use to learn about whatever library or libraries you suggest? I just want to play around with retrieving information via LDAP for right now, and if I get things working the way I want, I will probably ...
JNDI should work with eDirectory.....
try; <http://developer.novell.com/wiki/index.php/Jldap> and <http://developer.novell.com/wiki/index.php/Novell_LDAP_Extended_Library> Used it successfully with OpenLDAP and should suffice for eDirectory as well.
How can I work with Novell eDirectory services in J2SE?
[ "", "ldap", "java", "edirectory", "" ]
Is there a parser/library which is able to read an HTML document into a DOM tree using Java? I'd like to use the standard `DOM/Xpath` API that Java provides. Most libraries seem have custom API's to solve this task. Furthermore the conversion HTML to XML-DOM seems unsupported by the most of the available parsers. Any...
[JTidy](http://jtidy.sourceforge.net/), either by processing the stream to XHTML then using your favourite DOM implementation to re-parse, or using parseDOM if the limited DOM imp that gives you is enough. Alternatively [Neko](http://nekohtml.sourceforge.net/).
Since HTML files are generally problematic, you'll need to first clean them up using a parser/scanner. I've used JTidy but never happily. NekoHTML works okay, but any of these tools are always just making a best guess of what is intended. You're effectively asking to let a program alter a document's markup until it con...
Reading HTML file to DOM tree using Java
[ "", "java", "html", "dom", "parsing", "" ]
Are there any standalone type conversion libraries? I have a data storage system that only understands bytes/strings, but I can tag metadata such as the type to be converted to. I could hack up some naive system of type converters, as every other application has done before me, or I could hopefully use a standalone l...
Flatland does this well. <http://discorporate.us/projects/flatland/>
You've got two options, either use the [struct](http://docs.python.org/library/struct.html#module-struct) or [pickle](http://docs.python.org/library/pickle.html#module-pickle) modules. With struct you specify a format and it compacts your data to byte array. This is useful for working with C structures or writing to n...
Is there a standalone Python type conversion library?
[ "", "python", "type-conversion", "" ]
We are migrating to a new server running Windows 2003 and IIS 6. When my PHP code runs, it has a warning on a particular line (which I'm expecting at the moment but will fix shortly). However, when it hits the warning, it immediately halts processing and returns a 500 error in the HTTP header. Normally, I would expect ...
Figured out the issue. `log_errors` in php.ini was set to `On`, but `error_log` was unset. This was causing PHP to stop everything. After setting `display_errors` to `on`, the warnings now display so I can see where things are breaking in the output. This thread was helpful: <http://forums.iis.net/p/1146102/1856222.as...
I don't know about IIS or FastCGI, but afaik php has no such option. You can however set `error_reporting` (in your `php.ini`) to ``` E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR ``` to make warnings go away.
PHP warnings cause script to halt on IIS running FastCGI
[ "", "php", "iis-6", "windows-server-2003", "fastcgi", "" ]
I have a class that has a vector of another class objects as a member. In many functions of this class I have to do same operation on all the objects in the vector: ``` class Small { public: void foo(); void bar(int x); // and many more functions }; class Big { public: void foo() { fo...
Well you can rewrite the for loops to use iterators and more of the STL like this: ``` void foo() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::foo)); } void bar() { std::for_each(VectorOfSmalls.begin(), VectorOfSmalls.end(), std::mem_fun(&Small::bar)); } ``` beyond that,...
If you're using the std library, you should take a look at [for\_each](http://www.sgi.com/tech/stl/for_each.html). You mention that using function pointers in C++ might not be a good idea, but -- allowing your worry is speed -- you have to see if this is even a performance bottleneck area you're in, before worrying.
Iterating over vector and calling functions
[ "", "c++", "stl", "foreach", "iteration", "" ]
How can I use BOOST\_FOREACH efficiently (number-of-character/readability-wise) with a boost::ptr\_map? Kristo demonstrated in his [answer](https://stackoverflow.com/questions/461507/how-to-use-boostforeach-with-a-boostptrmap#461908) that it is possible to use BOOST\_FOREACH with a ptr\_map, but it does not really sav...
As STL style containers, the pointer containers have a `value_type` typedef that you can use: ``` #include <boost/ptr_container/ptr_map.hpp> #include <boost/foreach.hpp> int main() { typedef boost::ptr_map<int, int> int_map; int_map mymap; BOOST_FOREACH(int_map::value_type p, mymap) { } } ``` I ...
I just ran into the same problem today. Unfortunately, Daniel's suggestion will not work with a constant reference to a map. In my case, the ptr\_map was a member of a class, and I wanted to loop through it in a const member function. Borrowing Daniel's example, this is what I had to do in my case: ``` #include "boost...
How to use BOOST_FOREACH with a boost::ptr_map?
[ "", "c++", "boost", "" ]
Following the discussions here on SO I already read several times the remark that mutable structs are “evil” (like in the answer to this [question](https://stackoverflow.com/questions/292676/is-there-a-workaround-for-overloading-the-assignment-operator-in-c)). What's the actual problem with mutability and structs in C...
Structs are value types which means they are copied when they are passed around. So if you change a copy you are changing only that copy, not the original and not any other copies which might be around. If your struct is immutable then all automatic copies resulting from being passed by value will be the same. If yo...
Where to start ;-p [Eric Lippert's blog](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/mutating-readonly-structs) is always good for a quote: > This is yet another reason why mutable > value types are evil. Try to always > make value types immutable. First, you tend to lose changes quite easily... for ...
Why are mutable structs “evil”?
[ "", "c#", "struct", "immutability", "mutable", "" ]
I want to create a static class in PHP and have it behave like it does in C#, so 1. Constructor is automatically called on the first call to the class 2. No instantiation required Something of this sort... ``` static class Hello { private static $greeting = 'Hello'; private __construct() { $greeting...
You can have static classes in PHP but they don't call the constructor automatically (if you try and call `self::__construct()` you'll get an error). Therefore you'd have to create an `initialize()` function and call it in each method: ``` <?php class Hello { private static $greeting = 'Hello'; private stati...
In addition to Greg's answer, I would recommend to set the constructor private so that it is impossible to instantiate the class. So in my humble opinion this is a more complete example based on Greg's one: ``` <?php class Hello { /** * Construct won't be called inside this class and is uncallable from ...
Is it possible to create static classes in PHP (like in C#)?
[ "", "php", "design-patterns", "oop", "static", "" ]
Hi there im using Linq for check if two user fields correspond for an unique user register in SQL Table, for example UID : userID PIN : passID so fields have to be from a single user, i was trying this: ``` public bool AutentificacionUsuario(string userID , string password passID) { USER _userID = _db.U...
``` var usr = db.Users.From(uid => uid.dsiglas == userID && uid.codigousuario == passID).FirstOrDefault(); if(usr != null) //Authenticate user here ``` or ``` var usr = (from u in db.Users where u.dsiglas == userID && uid.codigousuario == passID select u).FirstOrDefault() if(usr ...
You need to use a Where clause to select the user. I'm unsure if LINQ-2-SQL is what I've been using, but I would have done it like this: ``` USER u = ( from u in _db.USER where u.uid == userID && u.pwd == password select u ).FirstOrDefault() ``` I hope that code is correct, I don't have access to intellisense on a...
Using LINQ2Sql for Validate Users
[ "", ".net", "sql", "linq", "linq-to-sql", "lambda", "" ]
Several colleagues and I are faced with an architectural decision that has serious performance implications: our product includes a UI-driven schema builder that lets non-programmers build their own data types for a web app. Currently, it builds properly normalized schemas behind the scenes and includes some complex lo...
> The normalized schemas have hit > performance bottlenecks in the past, > and a major refactoring has been > scheduled. One of the groups of > developers wants to store every > property of the data types in a > separate table, so that changes to the > data types will never require schema > altering. (A single property...
What you describe doesn't resemble what I call normalization. It's more like hyperabstraction - trying to find some abstraction level from which everything else can be derived. Like "Object" in javascript. If you take it to its logical conclusion, you could get by with two tables; one table for every Object, with a col...
The dangers of hyper-normalization?
[ "", "sql", "database-design", "architecture", "" ]
I have the following line of code in a link on my webpage: ``` <a href="javascript:$('#comment_form').toggle('normal')" title="Comment on this post"> ``` This produces a link that should pop open a hidden form. It works on Safari, but in Firefox, I just get an almost-empty page with nothing but the following text: `...
For the love of... ``` <script type='text/javascript'> jQuery(function($){ # Document ready, access $ as jQuery in this scope $("a#comment").click(function(){ # bind a click event on the A like with ID='comment' $('#comment_form').toggleClass('normal'); # Toggle the class on the ID comment form ...
Try: ``` <a href="javascript:void($('#comment_form').toggle('normal'))" title="Comment on this post"> ``` Containing the script inside a `void()` will suppress the browser from displaying the result of the execution. --- **Update** I directly answered the original question, with the solution that would take the le...
Why does the call to this jQuery function fail in Firefox?
[ "", "javascript", "jquery", "firefox", "" ]
I'm trying to strip all punctuation out of a string using a simple regular expression and the php preg\_replace function, although I get the following error: > Compilation failed: POSIX named classes are supported only within a class at offset 0 I guess this means I can't use POSIX named classes outside of a class at...
The [`preg_*` functions](http://docs.php.net/manual/en/ref.pcre.php) expect [Perl compatible regular expressions](http://en.wikipedia.org/wiki/Perl_Compatible_Regular_Expressions) with delimiters. So try this: ``` preg_replace('/[[:punct:]]/', ' ', $string) ```
**NOTE: The `g` modifier is not needed with PHP's `PCRE` implementation!** In addition to [Gumbo's answer](https://stackoverflow.com/questions/475159/php-regex-what-is-class-at-offset-0#475170), use the `g` modifier to replace *all* occurances of punctuation: ``` preg_replace('/[[:punct:]]/g', ' ', $string) // ...
PHP regex: what is "class at offset 0"?
[ "", "php", "regex", "" ]
I have to perform 3 operations in a windows app as a Transaction. These are not SQL operation otherwise i'd have used TransactionScope. The first operation is to log some value in a db, 2nd is to move an e mail to a pst and 3rd one is to move email to another mailbox. If any if these operation fails,I want other operat...
You could roll your own ResourceManager and use [System.Transactions](http://msdn.microsoft.com/en-us/library/system.transactions.aspx) to help you handle the transactions. <http://www.codeguru.com/csharp/.net/net_data/sortinganditerating/article.php/c10993__1/> Depending on the complexity though, and how often you'l...
Not unless your e-mail backend supports DTC, in which case you can use `TransactionScope`; note that `TransactionScope` is not limited just to SQL-providers; some middleware tools support it, and there is even a `TransactionScope`-based provided for .NET objects (not **any** object - only those written using the librar...
Transaction for .net operations
[ "", "c#", "transactions", "" ]
I have a problem which I think is related to forward declarations, but perhaps not. Here is the relevant code: A.h ``` #ifndef A_H_ #define A_H_ #include "B.h" class A { private: B b; public: A() : b(*this) {} void bar() {} }; #endif /*A_H_*/ ``` B.h ``` #ifndef B_H_ #defin...
You've got a circular reference, so you need to separate B.h. Try something like: B.h: ``` #ifndef B_H_ #define B_H_ // don't include A.h here! class A; class B { private: A& a; public: B(A& a) : a(a) {} void foo(); }; #endif /*B_H_*/ ``` B.cpp: ``` #include "B.h" #include "A.h" void ...
The line `#include<file.h>` will just replace the line with the content of `file.h`. So when the computer tries to compile your `main.cpp`, it will pull everything together, which looks like the following. At the place you want to use A::bar(), it has not been defined. ``` // result from #include "A.h" #ifndef A_H_ #...
C++ Forward Declaration Problem when calling Method
[ "", "c++", "compiler-construction", "declaration", "" ]
As you probably know, Derek Sivers is the guy who created CD Baby and eventually sold it for some big bucks. He wrote it in PHP originally and then down the road set about rewriting it in Rails. His troubles are the stuff of legend: [**7 reasons I switched back to PHP after 2 years on Rails**](http://www.oreillynet.co...
Re-writing an existing site is almost always a bad idea. It's hard to put your heart into retreading an old wheel. I worked on a rewrite of a site from CGIs to a Java app server and saw several programmers quit because of it. For one, they preferred their old way of doing things and did not want to learn Java. Secondly...
Austin Ziegler wrote an interesting response to that article: [On Derek Siver’s Return to PHP…](http://www.halostatue.ca/2007/09/23/on-derek-sivers-return-to-php%E2%80%A6/) The gist of it is: > 1. Derek chose the technology for the wrong reasons. He chose it partially > based on the hype of Rails, but he > env...
Should I heed Derek Sivers' warnings about migrating from PHP to Rails?
[ "", "php", "ruby-on-rails", "comparison", "" ]
If I understand this correctly: Current CPU developing companies like AMD and Intel have their own API codes (the assembly language) as what they see as the 2G language on top of the Machine code (1G language) Would it be possible or desirable (performance or otherwise) to have a CPU that would perform IL handling at...
A similar technology does exist for Java - ARM do a range of CPUs that can do this, they call it their "Jazelle" technology. However, the operations represented by .net IL opcodes are only well-defined in combination with the type information held on the stack, not on their own. This is a major difference from Java by...
You seem a bit confused about how CPU's work. Assembly is not a separate language from machine code. It is simply a different (textual) representation of it. Assembly code is simply a sequential listing of instructions to be executed. And machine code is exactly the same thing. Every instruction supported by the CPU h...
Would there be any point in designing a CPU that could handle IL directly?
[ "", "c#", "performance", "compiler-construction", "cpu", "cpu-architecture", "" ]
I'm iterating through a HashMap (see [my earlier question](https://stackoverflow.com/questions/448122/how-do-i-use-a-foreach-loop-in-java-to-loop-through-the-values-in-a-hashmap) for more detail) and building a string consisting of the data contained in the Map. For each item, I will have a new line, but for the very l...
Change your thought process from "append a line break all but the last time" to "prepend a line break all but the first time": ``` boolean first = true; StringBuilder builder = new StringBuilder(); for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) { if (first) { first = false; } else { ...
one method (with apologies to Jon Skeet for borrowing part of his Java code): ``` StringBuilder result = new StringBuilder(); string newline = ""; for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) { result.append(newline) .append(entry.key()) .append(": ") .append(entry.value()); ...
How do I append a newline character for all lines except the last one?
[ "", "java", "foreach", "newline", "" ]
What is the scope of variables in javascript? Do they have the same scope inside as opposed to outside a function? Or does it even matter? Also, where are the variables stored if they are defined globally?
## TLDR JavaScript has lexical (also called static) scoping and closures. This means you can tell the scope of an identifier by looking at the source code. The four scopes are: 1. Global - visible by everything 2. Function - visible within a function (and its sub-functions and blocks) 3. Block - visible within a blo...
Javascript uses scope chains to establish the scope for a given function. There is typically one global scope, and each function defined has its own nested scope. Any function defined within another function has a local scope which is linked to the outer function. It's always the position in the source that defines the...
What is the scope of variables in JavaScript?
[ "", "javascript", "function", "variables", "scope", "var", "" ]
If there is truly a 'best' way, what *is* the best way to ship a python app and ensure people can't (easily) reverse engineer your algorithms/security/work in general? If there isn't a 'best' way, what are the different options available? Background: I love coding in Python and would love to release more apps with it...
Security through obscurity *never* works. If you must use a proprietary license, enforce it through the law, not half-baked obfuscation attempts. If you're worried about them learning your security (e.g. cryptography) algorithm, the same applies. Real, useful, security algorithms (like AES) are secure even though the ...
Even if you use a compiled language like C# or Java, people can perform reverse engineering if they are motivated and technically competent. Obfuscation is not a reliable protection against this. You can add prohibition against reverse-engineering to your end-user license agreement for your software. Most proprietary ...
Python Applications: Can You Secure Your Code Somehow?
[ "", "python", "security", "reverse-engineering", "" ]
I have an text that consists of information enclosed by a certain pattern. The only thing I know is the pattern: "${template.start}" and ${template.end} To keep it simple I will substitute ${template.start} and ${template.end} with "a" in the example. So one entry in the text would be: ``` aINFORMATIONHEREa ``` I do...
Simply use non-greedy expressions, namely: ``` a(.*?)a ```
You need to match something like: ``` a[^a]*a ```
Using an asterisk in a RegExp to extract data that is enclosed by a certain pattern
[ "", "c++", "regex", "qt4", "" ]
In Python, I've got a list of dictionaries that looks like this: ``` matchings = [ {'id': 'someid1', 'domain': 'somedomain1.com'}, {'id': 'someid2', 'domain': 'somedomain2.com'}, {'id': 'someid3', 'domain': 'somedomain3.com'} ] ``` and, I have a variable: ``` the_id = 'someid3' ``` What's the most effic...
You can use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` domains = [matching['domain'] for matching in matchings if matching['id'] == the_id] ``` Which follows the format standard format of: ``` resulting_list = [item_to_return for item in items if condition] `...
I'd restructure `matchings`. ``` from collections import defaultdict matchings_ix= defaultdict(list) for m in matchings: matchings_ix[m['id']].append( m ) ``` Now the most efficient lookup is ``` matchings_ix[ d ] ```
What's the most efficient way to access sibling dictionary value in a Python dict?
[ "", "python", "loops", "dictionary", "list-comprehension", "" ]
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked. I currently capture the onunload event of the window. How can i accomplish this? ``` window....
Why do you want to do this? We can probably help you come up with a different design that doesn't require this if you tell us what you're trying to do. However, to answer your question: it's not possible to catch that event in all cases. You cannot prevent the user from closing the browser or guarantee that your code ...
If I understood correctly, your question is about a browser **dialog**, not the main browser **window**. To answer your question, you probably cannot distinguish between the Cancel button and the X button of a browser **dialog**. They'll both end up just returning a `false`. If you need this level of control, you shou...
Prevent a user from closing a browser window using "X"?
[ "", "asp.net", "javascript", "html", "" ]
Having the hours and minutes, is there any easier or better way to set it into a Calendar object than: ``` calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), hour, minute); ```
From [here](http://www.java2s.com/Code/JavaAPI/java.util/Calendarsetintfieldintvalue.htm): ``` calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); ```
Use [set(int field, int value)](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html#set-int-int-). The first parameter is the field number for HOUR/MINUTE/SECOND.
How do you set the time and only the time in a calendar in Java?
[ "", "java", "date", "calendar", "hour", "minute", "" ]
What is the most efficient way of testing an input string whether it contains a numeric value (or conversely Not A Number)? I guess I can use `Double.Parse` or a regex (see below) but I was wondering if there is some built in way to do this, such as javascript's `NaN()` or `IsNumeric()` (was that VB, I can't remember?)...
This doesn't have the regex overhead ``` double myNum = 0; String testVar = "Not A Number"; if (Double.TryParse(testVar, out myNum)) { // it is a number } else { // it is not a number } ``` Incidentally, all of the standard data types, with the glaring exception of GUIDs, support TryParse. **update** secretwe...
I prefer something like this, it lets you decide what [`NumberStyle`](http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx) to test for. ``` public static Boolean IsNumeric(String input, NumberStyles numberStyle) { Double temp; Boolean result = Double.TryParse(input, numberStyle, Cult...
What is the C# equivalent of NaN or IsNumeric?
[ "", "c#", "parsing", "" ]
Today, I have seen some legacy code. In the destructor there is a statement like "`delete this`". I think, this call will be recursive. Why it is working? I made some quick search on Y!, I found that if there is a need to restrict the user to create the stack object, we can make destructor private and provide an inter...
"delete this" is commonly used for ref counted objects. For a ref counted object the decision of when to delete is usually placed on the object itself. Here is an example of what a Release method would look like [1]. ``` int MyRefCountedObject::Release() { _refCount--; if ( 0 == _refCount ) { delete this; ...
### `delete this` is valid in C++11 It is valid to call `delete this` in a destructor. The [C++ FAQ](https://isocpp.org/wiki/faq/freestore-mgmt#delete-this) has an entry about that. The restrictions of [C++11 [basic.life] p5](https://timsong-cpp.github.io/cppwp/n3337/basic.life#5) do not apply to objects under destruc...
What is the use of "delete this"?
[ "", "c++", "memory-management", "destructor", "self-destruction", "" ]
stripslashes() ? That's lame and so 4.0. What's the 5.0 counterpart of mysqli::real\_escape\_string that strips all slashes added for SQL queries? Got some other questions: 1. Tried to update a record and added a single quote in a text field, turns out phpMyAdmin escapes the string with single quotes instead of slash...
If you don't want to go with PDO, and you are using mysqli, you should be using prepared statements, so you don't have to worry about escaping quotes with things like mysql\_real\_escape\_string\_i\_mean\_it\_this\_time. More specifically, you can call [mysqli->prepare](http://ca.php.net/manual/en/mysqli.prepare.php) ...
Use [PDO](http://php.net/pdo) instead of any of the `mysql[i]`/`pgsql`/... extensions. If you're just looking to reverse the damage done by magic quotes, though, `stripslashes()` is exactly what you're looking for.
The counterpart of mysqli::real_escape_string?
[ "", "php", "mysql", "mysqli", "" ]
I've been told not to use `for...in` with arrays in JavaScript. Why not?
The reason is that one construct: ``` var a = []; // Create a new empty array. a[5] = 5; // Perfectly legal JavaScript that resizes the array. for (var i = 0; i < a.length; i++) { // Iterate over numeric indexes from 0 to 5, as everyone expects. console.log(a[i]); } /* Will display: undefined undefin...
The `for-in` statement by itself is not a "bad practice", however it can be *mis-used*, for example, to *iterate* over arrays or array-like objects. The purpose of the `for-in` statement is to *enumerate* over object properties. This statement will go up in the prototype chain, also enumerating over *inherited* proper...
Why is using "for...in" for array iteration a bad idea?
[ "", "javascript", "arrays", "loops", "for-loop", "iteration", "" ]
I've been doing a lot of research on how best to write "correct" network code in C#. I've seen a number of examples using the "using" statement of C#, and I think this is a good approach, however i've seen inconsistent use of it with various expressions. For instance, suppose I have some code like this: ``` TcpClien...
Generally, objects should internally handle multiple `Dispose()` calls, and only do the main code once; so a stream getting `Dispose()`d multiple times is not usually a problem. Personally, I would use lots of `using` there; note that you don't need to indent/nest, though (unless different levels have different life-ti...
If an object supports IDisposable, it's best to put it in a using {} block because the dispose method gets called automatically for you. This also makes for less code on your part. It is important to note the using a 'using' doesn't handle any exceptions. YOu still have to do that if you want to handle any errors. Once...
C# network programming and resource usage
[ "", "c#", ".net", "network-programming", "using-statement", "" ]
I wrote some CSS in my HTML code to create rollover buttons. Then i tried to run it with IE 7 and surprise! it doesn't run. In fact it shows both the button and underlying rollover. How can i get around IE's inability to cache background images? Preferably using CSS but javascript 'will' be tried. Sample CSS: ``` #M...
Well firstly you are giving conflicting instructions ... ``` background: url("img/menu.png") top left no-repeat; background-position: -123px 0; ``` ... the background is already positioned using shorthand. I assume that your regular and hover states both share the same image, so why not do both with shorthand? Remov...
Image rollover issue comes mainly because of downloading image every time on hovering a link or tab. This flicker is caused by the delay when the primary image is removed and the rollover image is loaded (even though they are technically the same image, Internet Explorer prefers to treat them separately). check it...
CSS rollover problems with Internet Explorer 7
[ "", "javascript", "css", "internet-explorer", "" ]
This code compiles: ``` private static void Main(string[] args) { bool? fred = true; if (fred == true) Console.WriteLine("fred is true"); else if (fred == false) Console.WriteLine("fred is false"); else Console.WriteLine("fred is null"); } ``` This code does *not* compile. ``` priva...
There's no implicit conversion from `Nullable<bool>` to `bool`. There *is* an implicit conversion from `bool` to `Nullable<bool>` and that's what happens (in language terms) to each of the bool constants in the first version. The `bool operator==(Nullable<bool>, Nullable<bool>` operator is then applied. (This isn't qui...
Because fred is not a boolean. it is a struct, which has a boolean property called IsNull, or HasValue, or whatever... The object named fred is the complex composite object containing a boolean and a value, not a primitive boolean itself... Below, for example is how a Nullable Int could be implemented. The generic Nul...
Why do nullable bools not allow if(nullable) but do allow if(nullable == true)?
[ "", "c#", ".net", "nullable", "" ]
I have a generator and I would like to know if I can use it without having to worry about StopIteration , and I would like to use it without the **`for item in generator`** . I would like to use it with a while statement for example ( or other constructs ). How could I do that ?
Use this to wrap your generator: ``` class GeneratorWrap(object): def __init__(self, generator): self.generator = generator def __iter__(self): return self def next(self): for o in self.generator: return o raise StopIteration # If you don't car...
built-in function > next(iterator[, default]) > Retrieve the next item from the iterator by calling its `__next__()` method. If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised. In Python 2.5 and older: ``` raiseStopIteration = object() def next(iterator, default=rai...
is there an alternative way of calling next on python generators?
[ "", "python", "language-features", "" ]
What is the difference between Object Literals and Array Literals in JavaScript? I know it has something to do with the length method but i don't fully understand it.
[Mozilla.org](https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Core_Language_Features#Literals) has very good explanation of the different literals with examples. > **Array Literals** > > An array literal is a list of zero or > more expressions, each of which > represents an array element, enclosed > in squa...
The difference is the way they're indexed. Objects have name, value pairs which are not ordered. In some browsers the order you added values will be the order you get when you traverse the object but not in all. The name is usually a string. Arrays are numerically indexed and the order is totally reliable
JavaScript Object Literals & Array Literals
[ "", "javascript", "" ]
Say we've got: ``` struct IsEven { bool operator() (int i) { return i % 2 == 0; } }; ``` Then: ``` vector<int> V; // fill with ints vector<int>::iterator new_end = remove_if(V.begin(), V.end(), IsEven()); V.erase(new_end, V.end()); ``` works fine (it leaves `V` with only the odd integers). But it seems that the ...
It sounds like you want to use `partition()` to partition the vector into groups of odd values at the start and even values at the end. `partition()` will return an iterator to the first element of the second grouping. As for the WTF, I'm not sure why you would expect a remove operation to preserve the elements you wa...
I suppose the point is that the function is called `remove_if` for a reason. It removes elements. It doesn't move them or select them. After you've called remove\_if, you're no longer guaranteed that the elements you removed exist. All you're guaranteed is that the elements between `first` and `new_last` do not contain...
How to use the "removed" elements after std::remove_if
[ "", "c++", "stl", "" ]
What is the difference between using [the `delete` operator](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/delete) on the array element as opposed to using [the `Array.splice` method](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice)? For example: ```...
`delete` will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined: ``` > myArray = ['a', 'b', 'c', 'd'] ["a", "b", "c", "d"] > delete myArray[0] true > myArray[0] undefined ``` Note that it is not in fact set to the value `undefined`, rath...
# Array.remove() Method **John Resig**, creator of jQuery created a very handy `Array.remove` method that I always use it in my projects. ``` // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ...
Deleting array elements in JavaScript - delete vs splice
[ "", "javascript", "arrays", "element", "delete-operator", "array-splice", "" ]
Given `[1,2,3,4,5]`, how can I do something like ``` 1/1, 1/2, 1/3,1/4,1/5, ...., 3/1,3/2,3/3,3/4,3/5,.... 5/1,5/2,5/3,5/4,5/5 ``` I would like to store all the results, find the minimum, and return the two numbers used to find the minimum. So in the case I've described above I would like to return `(1,5)`. So basic...
You can do this using [list comprehensions](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and [min()](http://docs.python.org/library/functions.html) (Python 3.0 code): ``` >>> nums = [1,2,3,4,5] >>> [(x,y) for x in nums for y in nums] [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), ...
If I'm correct in thinking that you want to find the minimum value of a function for all possible pairs of 2 elements from a list... ``` l = [1,2,3,4,5] def f(i,j): return i+j # Prints min value of f(i,j) along with i and j print min( (f(i,j),i,j) for i in l for j in l) ```
Python: For each list element apply a function across the list
[ "", "python", "algorithm", "list", "list-comprehension", "" ]
Is there a standard way to associate version string with a Python package in such way that I could do the following? ``` import foo print(foo.version) ``` I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings are specified in `setup.py` already. Alternative sol...
Not directly an answer to your question, but you should consider naming it `__version__`, not `version`. This is almost a quasi-standard. Many modules in the standard library use `__version__`, and this is also used in [lots](http://www.google.com/codesearch?as_q=__version__&btnG=Search+Code&hl=en&as_lang=python&as_li...
I use a single `_version.py` file as the "once cannonical place" to store version information: 1. It provides a `__version__` attribute. 2. It provides the standard metadata version. Therefore it will be detected by `pkg_resources` or other tools that parse the package metadata (EGG-INFO and/or PKG-INFO, PEP 0345). 3....
Standard way to embed version into Python package?
[ "", "python", "setuptools", "setup.py", "python-packaging", "" ]
I have a website which uses PHP and HTML pages, I want to create a session which stores a username from the login page. But the login pages are php and the next pages are html. Is this a problem or can I just add a small statement of php into the html page saying ``` <?PHP session_start(); $_session['loginid']=$_pos...
If you have access to your apache configuration, or a simple .htaccess file, you can tell Apache to handle php code inside of an .html file. You can do this by creating an **.htaccess** file (remember the . (dot) as the first character in that filename) on the document root of the site (probably public\_html/) and putt...
You are trying to share a PHP session variable with a page that is of type text/html. As you suggested you must make the HTML page a PHP page for this to work and add a little snippet of PHP somewhere to display the user name. Change your HTML page to PHP. At the top of the page add something like this: ``` <?php s...
PHP sessions with HTML
[ "", "php", "html", "session", "" ]
I will participate a modeling competition, which spends three days. I need a language which is fast and designed for modeling, such as to 2D/3D models. I have considered these languages: 1. Python 2. Sage Which languages would you use?
You should use the language that you know best and that has good-enough tools for the task at hand. Depending on when the competition is you may have no time to learn a new language/environment.
have a look at <http://www.processing.org/> -- it is a programming language (similar to java) and IDE especially developed for simulation and data visualization. given that it was developed in a teaching context, it will be easy to use and will give you great results in no time -- i have seen amazing applications (e,g,...
Most suitable language(s) for simulations in modeling?
[ "", "python", "sage", "" ]
I have an element in my document that has a background color and image set through a regular CSS rule. When a certain event happens, I want to animate that item, highlighting it (I'm using Scriptaculous, but this question applies to any framework that'll do the same). ``` new Effect.Highlight(elHighlight, { startcolo...
Chances are you're not setting the style on the correct element. It's probably being set somewhere up the line in a parent node. ``` elHighlight.style.backgroundColor = ""; elHighlight.style.backgroundImage = ""; ``` You can also remove *all* the default styling by calling: ``` elHighlight.style.cssText = ""; ``` I...
Try `elHighlight.style.removeProperty('background-color')` `elHighlight.style.removeProperty('background-image')`
How can I undo the setting of element.style properties?
[ "", "javascript", "css", "animation", "" ]
I'm attempting to capture the output of `fputcsv()` in order to use `gzwrite()` to actually write to a tab-delimited file. Basically, I'm querying a database and I want to put these rows into a gzipped CSV file and I'd rather use `fputcsv()` than actually append `"\t"` and `"\n"` everywhere. Can I somehow do this with ...
Maybe I'm misunderstanding the question but [`fputcsv()`](http://www.php.net/fputcsv) operates on a file handle, which is what gzopen returns, so you can do this: ``` $results = get_data_from_db(); $fp = gzopen($file_name, 'w'); if($fp) { foreach ($results as $row) { fputcsv($fp, $row); } gzclose($...
As read on [php.net](http://www.php.net/manual/en/function.fputcsv.php#74118), you could try this little trick: ``` <?php // output up to 5MB is kept in memory, if it becomes bigger // it will automatically be written to a temporary file $csv = fopen('php://temp/maxmemory:'. (5*1024*1024), 'r+'); fputcsv($csv, array(...
Capturing file output in PHP (fputcsv)
[ "", "php", "" ]
First of all,I'm not into web programming. I bumped into django and read a bit about models. I was intrigued by the following code ( from djangoproject.com ) : ``` class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): ...
Yes, first\_name and last\_name are class variables. They define fields that will be created in a database table. There is a Person table that has first\_name and last\_name columns, so it makes sense for them to be at Class level at this point. For more on models, see: <http://docs.djangoproject.com/en/dev/topics/db/...
The essence of your question is "how come these class variables (which I assign Field objects to) suddenly become instance variables (which I assign data to) in Django's ORM"? The answer to that is the magic of Python [metaclasses](http://docs.python.org/reference/datamodel.html). A metaclass allows you to hook into a...
How do Django model fields work?
[ "", "python", "django", "django-models", "" ]
Just wanted opinions on a design question. If you have a C++ class than owns other objects, would you use smart pointers to achieve this? ``` class Example { public: // ... private: boost::scoped_ptr<Owned> data; }; ``` The 'Owned' object can't be stored by value because it may change through the lifetime of th...
It's a good idea. It helps simplify your code, and ensure that when you do change the Owned object during the lifetime of the object, the previous one gets destroyed properly. You have to remember that scoped\_ptr is noncopyable, though, which makes your class noncopyable by default until/unless you add your own copy ...
scoped\_ptr is very good for this purpose. But one has to understand its semantics. You can group smart pointers using two major properties: * Copyable: A smart pointer can be copied: The copy and the original share ownership. * Movable: A smart pointer can be moved: The move-result will have ownership, the original w...
C++ using scoped_ptr as a member variable
[ "", "c++", "oop", "smart-pointers", "" ]
Why would someone use numeric(12, 0) datatype for a simple integer ID column? If you have a reason why this is better than int or bigint I would like to hear it. We are not doing any math on this column, it is simply an ID used for foreign key linking. I am compiling a list of programming errors and performance issue...
Perhaps they're used to working with Oracle? All numeric types including ints are normalized to a standard single representation among all platforms.
There are many reasons to use numeric - for example - financial data and other stuffs which need to be accurate to certain decimal places. However for the example you cited above, a simple int would have done. Perhaps sloppy programmers working who didn't know how to to design a database ?
Is there any reason for numeric rather than int in T-SQL?
[ "", "sql", "database", "oracle", "t-sql", "types", "" ]
My friend is working on a project in which he needs to get some digital signals into a computer to display/manipulate them. So I advised him to insert those signals into a USB port due to it's popularity (because the device (which outputs the signals) and the program used for display and manipulation should both be de...
There is a great article here: [USB hardware/software integration](http://www.codeproject.com/KB/system/HIDAche.aspx "USB hardware/software integration") that describes the process in full.
Get a [Labjack](http://www.labjack.com/) or one of the [Phidgets](http://www.phidgets.com/). (I've used the former several times, not the latter) They're fairly inexpensive and both have Java driver support, among other things. (like LabView drivers)
How to load digital signals from a USB port into memory?
[ "", "c++", "usb", "driver", "" ]
I want to execute an SQL query like: ``` select 'tb1'.'f1','tb1'.'f2','tb2'.'f1' from 'tb1','tb2'; ``` Now the problem is that i want to put it into an array in PHP like: ``` $result['tb1']['f1'], $result['tb1']['f2'], $result['tb2']['f1']... ``` Any idea how to achieve the above? Afaik there is no function which d...
You'll need to select the data as you are already doing, and then loop over it getting it into the format required, and because the fields have the same names, its easiest to use aliases or they'll just overwrite each other in the returned data (but you could use mysql\_fetch\_row instead, which returns a numerically i...
Since you say you can't specify column aliases, and you can't know the fields of the query beforehand, I'd suggest a solution using [`mysql_fetch_field()`](http://php.net/manual/en/function.mysql-fetch-field.php) to get metadata information: ``` <?php mysql_connect('localhost', 'username', 'password'); mysql_select_db...
Place multiple similar fields in multi-dimensional array - php mysql
[ "", "php", "mysql", "" ]
I am returning a List from my WCF method. In my client code, it's return type shows as MyObject[]. I have to either use MyObject[], or IList, or IEnumerable... ``` WCFClient myClient = new WCFClient(); MyObject[] list = myClient.GetMyStuff(); or IList<MyObject> list = myClient.GetMyStuff(); or IEnumerable...
You can specify that you want to use a generic list instead of an array by clicking the advanced button when you add a reference, or you can right click on the service reference and choose configure to change it in place. The reason is that WCF serializes Generic lists as arrays to send across the wire. The configurat...
When you use `svcutil.exe` to create you client code you need to tell it how to resolve certain references that are not available to it. This is how you would do it for `List<T>`: ``` svcutil /o:YourService.cs /ct:System.Collections.Generic.List`1 http://example.com/mex ```
Why does WCF return myObject[] instead of List<T> like I was expecting?
[ "", "c#", "wcf", "collections", "" ]
after a bit speedtracing I found a piece of code (called very very often) which converts values of one enum to values of another enum, like this: ``` public Enum2 ConvertToEnum2(Enum1 enum1) { switch(enum1) { case Enum1.One: return Enum2.One; break; case Enum1.Two: return E...
A dictionary definitely would not be faster. If the enums in the Enum1 are sequential then an array of Enum2 would likely be faster (but that could be marginal). IF the Enum1 is close to sequential so that the array isn't too spares it may still be useful approach. For an enum with the [Flags] attribute then the swit...
Are you sure that it's a botteneck? I found that many profilers report incorrect time percentages for small methods. In my computer I can execute 100 millons conversions between enums with 10 elements in 1.7 seconds using a switch (Anthony's answer is 10 time faster).
Performance of enum conversion
[ "", "c#", "performance", "enums", "" ]
Can someone please explain what the "&" does in the following: ``` class TEST { } $abc =& new TEST(); ``` I know it is by reference. But can someone illustrate why and when I would need such a thing? Or point me to a url where this is explained well. I am unable to grasp the concept. Thank you very much.
As I understand it, you're not asking about PHP references in general, but about the `$foo =& new Bar();` construction idiom. This is only seen in PHP4 as the usual `$foo = new Bar()` stores a *copy* of the object. This generally goes unnoticed unless the class stored a reference to $this in the constructor. When call...
Firstly, you don't really need to use it if you are using PHP 5, in PHP 5 all objects are passed by reference by default. Secondly, when you assign an object to a variable name, either by creation, passing in a parameter, or setting a variable value, you are either doing so by reference or value. Passing by reference...
Php By Reference
[ "", "php", "reference", "" ]
I have a page that is accessed via a URL like this: <http://power-coder.net/Test/something.php?id=3#Page1> I know how to access the id parameter using $\_GET, however is there a way for me to access the #Page1 part? I have looked at the $\_SERVER array and the REQUEST\_URI ends at ?id=3. I know that I could also cha...
No, there isn't a way. The fragment part (the label after #) is not transmitted to the server. The browser retrieve the document <http://power-coder.net/Test/something.php?id=3> and then go to the correct anchor (if there is one) in the document.
The relevant text from [the specs](http://www.faqs.org/rfcs/rfc2396.html): > 4.1. Fragment Identifier > > When a URI reference is used to perform a retrieval action on the > identified resource, the optional fragment identifier, separated from > the URI by a crosshatch ("#") character, consists of additional > referen...
Is it possible to access anchors in a querystring via PHP?
[ "", "php", "url", "query-string", "anchor", "" ]
Consider these examples using `print` in Python: ``` >>> for i in range(4): print('.') . . . . >>> print('.', '.', '.', '.') . . . . ``` Either a newline or a space is added between each value. How can I avoid that, so that the output is `....` instead? In other words, how can I "append" strings to the standard outpu...
In Python 3, you can use the `sep=` and `end=` parameters of the [`print`](https://docs.python.org/library/functions.html#print) function: To not add a newline to the end of the string: ``` print('.', end='') ``` To not add a space between all the function arguments you want to print: ``` print('a', 'b', 'c', sep='...
For Python 2 and earlier, it should be as simple as described in *[Re: How does one print without a CR?](http://legacy.python.org/search/hypermail/python-1992/0115.html)* by [Guido van Rossum](https://en.wikipedia.org/wiki/Guido_van_Rossum) (paraphrased): > Is it possible to print something, but not automatically have...
How to print without a newline or space
[ "", "python", "trailing-newline", "" ]
I've got data in SQL Server 2005 that contains HTML tags and I'd like to strip all that out, leaving just the text between the tags. Ideally also replacing things like `&lt;` with `<`, etc. Is there an easy way to do this or has someone already got some sample T-SQL code? I don't have the ability to add extended stor...
There is a UDF that will do that described here: [User Defined Function to Strip HTML](http://blog.sqlauthority.com/2007/06/16/sql-server-udf-user-defined-function-to-strip-html-parse-html-no-regular-expression/) ``` CREATE FUNCTION [dbo].[udf_StripHTML] (@HTMLText VARCHAR(MAX)) RETURNS VARCHAR(MAX) AS BEGIN DECL...
Derived from @Goner Doug answer, with a few things updated: - using REPLACE where possible - conversion of predefined entities like `&eacute;` (I chose the ones I needed :-) - some conversion of list tags `<ul> and <li>` ``` ALTER FUNCTION [dbo].[udf_StripHTML] --by Patrick Honorez --- www.idevlop.com --inspired...
How to strip HTML tags from a string in SQL Server?
[ "", "html", "sql", "sql-server", "string", "sql-server-2005", "" ]
I am running into quite an annoying issue while trying to deserialise a specific XML document using XmlSerializer.Deserialize() method. Basically, I have a strongly typed XSD with an element of type double. When trying to deserialise the element for a specific XML document, I get the usual "System.FormatException: Inp...
You can specify the default value like ``` [XmlElement] [System.ComponentModel.DefaultValueAttribute(0.0)] public double AverageSpeed { ... } ``` /edit: ok, strange beaviour here. Whatever I set as value in the Attribute it's always the fields value: ``` private double averageSpeed = 2.0; ``` But no...
Check out MSDN documentation on DefaultValueAttribute: <http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx> > **Note:** A DefaultValueAttribute will not cause a member to be > automatically initialized with the > attribute's value. You must set the > initial value in your code. I...
Error deserialising XML document with strongly typed XSD
[ "", "c#", "xml", "xsd", "serialization", "" ]
I have a huge bunch of XML files with the following structure: ``` <Stuff1> <Content>someContent</name> <type>someType</type> </Stuff1> <Stuff2> <Content>someContent</name> <type>someType</type> </Stuff2> <Stuff3> <Content>someContent</name> <type>someType</type> </Stuff3> ... ... ``` I need to change the...
The XML you have provided shows that someone completely misses the point of XML. Instead of having ``` <stuff1> <content/> </stuff1> ``` You should have:/ ``` <stuff id="1"> <content/> </stuff> ``` Now you would be able to traverse the document using Xpath (ie, //stuff[id='1']/content/) The names of nodes s...
(1.) The [XmlElement / XmlNode].Name property is read-only. (2.) The XML structure used in the question is crude and could be improved. (3.) Regardless, here is a code solution to the given question: ``` String sampleXml = "<doc>"+ "<Stuff1>"+ "<Content>someContent</Content>"+ "<type>someType</type...
Change the node names in an XML file using C#
[ "", "c#", "xml", "" ]
I have been working with PostgreSQL, playing around with Wikipedia's millions of hyperlinks and such, for 2 years now. I either do my thing directly by sending SQL commands, or I write a client side script in python to manage a million queries when this cannot be done productively (efficiently and effectively) manually...
Since you already known python, PL/Python should be something to look at. And you sound like you write SQL for your database queries, so PL/SQL is a natural extension of that. PL/SQL feels like SQL, just with all the stuff that you would expect from SQL anyway, like variables for whole rows and the usual control struc...
Why can't you run your Python on the database server? That has the fewest complexities -- you can run the program you already have.
PostgreSQL procedural languages: to choose?
[ "", "python", "postgresql", "" ]
I've discovered this idiom recently, and I am wondering if there is something I am missing. I've never seen it used. Nearly all Java code I've worked with in the wild favors slurping data into a string or buffer, rather than something like this example (using HttpClient and XML APIs for example): ``` final LSOutpu...
From the [Javadocs](http://docs.oracle.com/javase/7/docs/api/java/io/PipedInputStream.html): > Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as...
In your example you're creating two threads to do the work that could be done by one. And introducing I/O delays into the mix. Do you have a better example? Or did I just answer your question. --- To pull some of the comments (at least my view of them) into the main response: * Concurrency introduces complexity int...
Why doesn't more Java code use PipedInputStream / PipedOutputStream?
[ "", "java", "design-patterns", "concurrency", "pipe", "" ]
The documentation of `System.Threading.Timer` says that I should keep a live reference for it to avoid it being garbage collected. But where should I do that? My `main` is very simple that I don't know where to keep the reference: ``` class Program { static void Main() { new System.Threading.Thread(myThrea...
If your Timer is an application-level object there's nothing wrong with making it a private static member of your Main class. That's what I would do, anyway.
EDIT: My original answer is rubbish. Really rubbish. I've kept it here to explain *why* it's rubbish though - it's in the comments, but they'd have been deleted with the answer. GC.KeepAlive only makes sure a reference is treated as a root until after the call. In the code at the bottom of this answer, the GC.KeepAliv...
In C#, where should I keep my timer's reference?
[ "", "c#", ".net", "garbage-collection", "reference", "timer", "" ]
K... I'm doing something obviously wrong. I have a simple page with a file input control on and a submit button. I'm trying out the new "File" ActionResult that was released with the Mvc RC... All, I want to happen is when the submit button is clicked the selected file is uploaded to the database. This all works fine....
FileResult returns the ASCII or binary contents of the file. When you say do the following: ``` <img src="<%=Model.FileContent.FileContents %>" /> ``` You are attempting to push the binary image data into the `src` attribute. That will never work, because the `src` must a URL or a path to an image. There are several...
I think it's pretty simple: the src attribute of your img tag requires an URL. What you're doing here is just putting the FileStream object in there (which implicitly calls the ToString method on that object). Your resulting html is probably something like this: ``` <img src="FileStream#1" /> ``` Did you check your h...
Mvc Release Candidate "File" ActionResult
[ "", "c#", "asp.net-mvc", "" ]
I am able to send emails using the typical C# SMTP code across Exchange 2007 as long as both the from and to addresses are within my domain. As soon as I try to send emails outside the domain I get: Exception Details: System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.1 Un...
Try #2... How about using a [Exchange Pickup Folder](http://www.msexchange.org/articles_tutorials/exchange-server-2007/management-administration/exchange-pickup-folder.html) instead? They are a faster way to send emails through Exchange because it just creates the email and drops it in the folder, no waiting to connect...
Authenticate to the exchange server. <http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.credentials.aspx> --- > DefaultNetworkCredentials returns > empty strings for username etc and > causes this exception... Here is an [example](http://aspalliance.com/867), and here is [another](http://www.system...
How do I send emails outside my domain with Exchange 2007 and c#
[ "", "c#", "smtp", "exchange-server-2007", "" ]
BACKGROUND: I have the following XUL fragment ``` <tree id="treeToChange" flex="1"> <treecols> <treecol label = "First Column" id="c1" flex="1"/> <treecol label = "Second Column" id="c2" flex="1"/> </treecols> <treechildren> <treeitem> <treerow> <treecell label="Data for Column 1"/> ...
It turns out that the element.style.color only effects the column headings, and that within firefox, the cells in a tree structure can only be affected by coding the dataview. code snippets follow: ``` // DatabaseTreeView: Create a custom nsITreeView DatabaseTreeView: function(aTableData, aColumns) { this.getCellPro...
The style property of a DOM element contains all the CSS declarations for that element. The naming scheme is slightly different (camelCaps instead of dashes), but otherwise exactly the same. ``` element.style.color = 'blue'; ``` You can read more on the style property in the [Mozilla javascript manual](http://develo...
In firefox, how to change color of text in a treecell using javascript
[ "", "javascript", "css", "firefox", "xul", "" ]
I am developing a c# GUI and was wondering if there were any (preferably free) runtime diagnostic programs available. What Im looking for is a way to monitor user interactions with my GUI and what functions are called when. Preferably I do not want to add stacks of debug code as this has the potential to change the be...
[EQATEC profiler](http://www.eqatec.com/tools/profiler) is pretty simple to use. Free too. Started life targetting Compact Framework but since 2.00 is now geared more towards Desktop too.
I recommend [ANTS profiler](http://www.red-gate.com/Products/ants_profiler/index.htm). There is a trial available, first two weeks free.
C# runtime application Diagnostics
[ "", "c#", "runtime", "diagnostics", "" ]
I've heard of [**static\_cast operator**](http://msdn.microsoft.com/en-us/library/c36yw7x9(VS.80).aspx) Recently I've come across **static\_case**, for instance: ``` *ppv = static_case<IUnknown> ``` What does this mean?
It's a typo : **there is no static\_case**, [only static\_cast, dynamic\_cast, const\_cast and reinterpret\_cast](http://www.cplusplus.com/doc/tutorial/typecasting.html). You can see [on google](http://www.google.fr/search?rlz=1C1GGLS_frFR299FR303&sourceid=chrome&ie=UTF-8&q=c%2B%2B+static_case) that the docs where you...
There is nothing called **static\_case** in C++. There is just **static\_cast**
What is static_case operator in C++?
[ "", "c++", "" ]
How can I change values in string from 0,00 to 0.00? - only numeric values, not all chars "," to "." FROM ``` string myInputString = "<?xml version=\"1.0\"?>\n<List xmlns:Table=\"urn:www.navision.com/Formats/Table\"><Row><HostelMST>12,0000</HostelMST><PublicMST>0,0000</PublicMST><TaxiMST>0,0000</TaxiMST><ParkMST>0,00...
I strongly recommend joel.neely's regex approach or the one below: 1. Use XmlReader to read all nodes 2. Use double.TryParse with the formatter = a NumberFormatInfo that uses a comma as decimal separator, to identify numbers 3. Use XmlWriter to write a new XML 4. Use CultureInfo.InvariantCulture to write the numbers o...
Try this : ``` Regex.Replace("attrib1='12,34' attrib2='43,22'", "(\\d),(\\d)", "$1.$2") ``` **output :** attrib1='12.34' attrib2='43.22'
how to change values in string from 0,00 to 0.00
[ "", "c#", ".net", "" ]
There's no much documentation on how to deploy a Django project with [Spawning](http://pypi.python.org/pypi/Spawning/) and yet people are recommending it over apache/mod\_wsgi. [In another similar question](https://stackoverflow.com/questions/487224/reducing-django-memory-usage-low-hanging-fruit/487261#487261), other ...
I'd be interested in seeing whose seriously recommending Spawning over Apache and mod\_python or mod\_wsgi. Judging by the fact that this question is now the #4 result in Google for 'django spawning' I'd say it's very much early days. :) If you're putting anything serious into production stick to Apache/mod\_wsgi for ...
cd to your django's settings.py directory. Here is the command line to serve your django application ``` spawn --factory=spawning.django_factory.config_factory settings --port 80 ```
How to deploy Django with Spawning
[ "", "python", "django", "deployment", "spawning", "" ]