Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a large text template which needs tokenized sections replaced by other text. The tokens look something like this: ##USERNAME##. My first instinct is just to use String.Replace(), but is there a better, more efficient way or is Replace() already optimized for this? | [System.Text.RegularExpressions.Regex.Replace()](http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.replace.aspx "MSDN") is what you seek - IF your tokens are odd enough that you need a regex to find them.
[Some kind soul did some performance testing](http://blogs.msdn.com/debuggingtoolbox/ar... | The only situation in which I've had to do this is sending a templated e-mail. In .NET this is provided out of the box by the [MailDefinition class](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.maildefinition.aspx). So this is how you create a templated message:
```
MailDefinition md = new MailDef... | Best way to replace tokens in a large text template | [
"",
"c#",
".net",
""
] |
I often run into the following problem.
I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what ... | In Ruby on Rails, there's a concept of a [migration](https://edgeguides.rubyonrails.org/active_record_migrations.html) -- a quick script to change the database.
You generate a migration file, which has rules to increase the db version (such as adding a column) and rules to downgrade the version (such as removing a col... | I'm a bit old-school, in that I use source files for creating the database. There are actually 2 files - project-database.sql and project-updates.sql - the first for the schema and persistant data, and the second for modifications. Of course, both are under source control.
When the database changes, I first update the... | Is there a version control system for database structure changes? | [
"",
"sql",
"database",
"oracle",
"version-control",
""
] |
What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place! | There are a couple of things to do in order to keep your session secure:
1. Use SSL when authenticating users or performing sensitive operations.
2. Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish.
3. Have sessions tim... | One guideline is to call [session\_regenerate\_id](http://www.php.net/session_regenerate_id) every time a session's security level changes. This helps prevent session hijacking. | PHP Session Security | [
"",
"security",
"php",
""
] |
I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like `play()`, `stop()`, `pause()`, `record()` etc... Then I have workhorse classes that do the video decoding and video encoding.
I just learned about the existence o... | I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media ... | You would use a nested class to create a (small) helper class that's required to implement the main class. Or for example, to define an interface (a class with abstract methods).
In this case, the main disadvantage of nested classes is that this makes it harder to re-use them. Perhaps you'd like to use your VideoDecod... | Should I use nested classes in this case? | [
"",
"c++",
"class",
"oop",
"inner-classes",
""
] |
Suppose we have a table A:
```
itemid mark
1 5
2 3
```
and table B:
```
itemid mark
1 3
3 5
```
I want to join A\*B on A.itemid=B.itemid both right and left ways. i.e. result:
```
itemid A.mark B.mark
1 5 3
2 3 NULL
3 NULL 5
```
Is there a way to do it in one query i... | It's called a full outer join and it's not supported natively in MySQL, judging from its [docs](http://dev.mysql.com/doc/refman/4.1/en/join.html). You can work around this limitation using UNION as described in the comments to the page I linked to.
[edit] Since others posted snippets, here you go. You can see explanat... | Could do with some work but here is some sql
```
select distinct T.itemid, A.mark as "A.mark", B.mark as "B.mark"
from (select * from A union select * from B) T
left join A on T.itemid = A.itemid
left join B on T.itemid = B.itemid;
```
This relies on the left join, which returns all the rows in the orig... | Bidirectional outer join | [
"",
"sql",
"mysql",
""
] |
When using a `Zend_Form`, the only way to validate that an input is not left blank is to do
```
$element->setRequired(true);
```
If this is not set and the element is blank, it appears to me that validation is not run on the element.
If I do use `setRequired()`, the element is automatically given the standard NotEmp... | I did it this way (ZF 1.5):
```
$name = new Zend_Form_Element_Text('name');
$name->setLabel('Full Name: ')
->setRequired(true)
->addFilter('StripTags')
->addFilter('StringTrim')
->addValidator($MyNotEmpty);
```
so, the addValidator() is the interesting part. The Message is set in an "Errormessage ... | By default, setRequired(true) tells isValid() to add a NonEmpty validation *if one doesn't already exist*. Since this validation doesn't exist until isValid() is called, you can't set the message.
The easiest solution is to simply manually add a NonEmpty validation before isValid() is called and set it's message accor... | Zend Framework: setting a Zend_Form_Element form field to be required, how do I change the validator used to ensure that the element is not blank | [
"",
"php",
"zend-framework",
"validation",
""
] |
I have an NHibernate session. In this session, I am performing exactly 1 operation, which is to run this code to get a list:
```
public IList<Customer> GetCustomerByFirstName(string customerFirstName)
{
return _session.CreateCriteria(typeof(Customer))
.Add(new NHibernate.Expression.EqExpression("FirstName", custom... | I have seen this once before when one of my models was not mapped correctly (wasn't using nullable types correctly). May you please paste your model and mapping? | Always be careful with NULLable fields whenever you deal with NHibernate. If your field is NULLable in DB, make sure corresponding .NET class uses Nullable type too. Otherwise, all kinds of weird things will happen. The symptom is usually will be that NHibernate will try to update the record in DB, even though you have... | NHibernate Session.Flush() Sending Update Queries When No Update Has Occurred | [
"",
"c#",
".net",
"nhibernate",
""
] |
I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it.
Unfortunately, whilst I know the XML model fairly well in .NET, I'm uncertain what the pros and cons are of the XML models in Python.
An... | Personally, I've played with several of the built-in options on an XML-heavy project and have settled on [pulldom](http://docs.python.org/lib/module-xml.dom.pulldom.html) as the best choice for less complex documents.
Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a... | [ElementTree](http://effbot.org/zone/element-index.htm) has a nice pythony API. I think it's even shipped as part of python 2.5
It's in pure python and as I say, pretty nice, but if you wind up needing more performance, then [lxml](http://codespeak.net/lxml/) exposes the same API and uses libxml2 under the hood. You c... | XML Processing in Python | [
"",
"python",
"xml",
""
] |
I have an SQL server database that I am querying and I only want to get the information when a specific row is null. I used a where statement such as:
```
WHERE database.foobar = NULL
```
and it does not return anything. However, I know that there is at least one result because I created an instance in the database w... | Correct syntax is WHERE database.foobar IS NULL. See <http://msdn.microsoft.com/en-us/library/ms188795.aspx> for more info | Comparison to NULL will be false every time. You want to use IS NULL instead.
```
x = NULL -- always false
x <> NULL -- always false
x IS NULL -- these do what you want
x IS NOT NULL
``` | SQLServer Get Results Where Value Is Null | [
"",
"sql",
"sql-server",
"oracle",
""
] |
What is the the best JavaScript compressor available? I'm looking for a tool that:
* is easy to use
* has a high compression rate
* Produce reliable end results (doesn't mess up the code) | I recently released [UglifyJS](http://github.com/mishoo/UglifyJS), a JavaScript compressor which is written in JavaScript (runs on the NodeJS [Node.js](http://en.wikipedia.org/wiki/Nodejs) platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any `Node.js` internals). It's a lot... | Revisiting this question a few years later, [UglifyJS](http://github.com/mishoo/UglifyJS), seems to be the best option as of now.
As stated below, it runs on the NodeJS platform, but can be easily modified to run on any JavaScript engine.
--- Old answer below---
Google released [**Closure Compiler**](https://github.... | Best JavaScript compressor | [
"",
"javascript",
"compression",
""
] |
In other words, is this Singleton implementation thread safe:
```
public class Singleton
{
private static Singleton instance;
private Singleton() { }
static Singleton()
{
instance = new Singleton();
}
public static Singleton Instance
{
get { return instance; }
}
}
``` | Static constructors are guaranteed to be run only once per application domain, before any instances of a class are created or any static members are accessed. <https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors>
The implementation shown is thread safe for the init... | While all of these answers are giving the same general answer, there is one caveat.
Remember that all potential derivations of a generic class are compiled as individual types. So use caution when implementing static constructors for generic types.
```
class MyObject<T>
{
static MyObject()
{
//this co... | Is the C# static constructor thread safe? | [
"",
"c#",
"multithreading",
"singleton",
""
] |
The topic says the most of it - what is the reason for the fact that static methods can't be declared in an interface?
```
public interface ITest {
public static String test();
}
```
The code above gives me the following error (in Eclipse, at least): "Illegal modifier for the interface method ITest.test(); only p... | There are a few issues at play here. The first is the issue of declaring a static method without defining it. This is the difference between
```
public interface Foo {
public static int bar();
}
```
and
```
public interface Foo {
public static int bar() {
...
}
}
```
The first is impossible for the reason... | The reason why you can't have a static method in an interface lies in the way Java resolves static references. Java will not bother looking for an instance of a class when attempting to execute a static method. This is because static methods are not instance dependent and hence can be executed straight from the class f... | Why can't I declare static methods in an interface? | [
"",
"java",
"interface",
"methods",
"static",
""
] |
In the PHP manual, to show the syntax for functions with optional parameters, they use brackets around each set of dependent optional parameter. For example, for the [`date()`](https://php.net/date) function, the manual reads:
```
string date ( string $format [, int $timestamp = time() ] )
```
Where `$timestamp` is a... | Much like the manual, use an equals (`=`) sign in your definition of the parameters:
```
function dosomething($var1, $var2, $var3 = 'somevalue'){
// Rest of function here...
}
``` | > The default value of the argument must be a constant expression. It can't be a variable or a function call.
If you need this functionality however:
```
function foo($foo, $bar = false)
{
if(!$bar)
{
$bar = $foo;
}
}
```
Assuming `$bar` isn't expected to be a boolean of course. | How do you create optional arguments in php? | [
"",
"php",
""
] |
I need debug some old code that uses a Hashtable to store response from various threads.
I need a way to go through the entire Hashtable and print out both keys and the data in the Hastable.
How can this be done? | ```
foreach(string key in hashTable.Keys)
{
Console.WriteLine(String.Format("{0}: {1}", key, hashTable[key]));
}
``` | I like:
```
foreach(DictionaryEntry entry in hashtable)
{
Console.WriteLine(entry.Key + ":" + entry.Value);
}
``` | Print out the keys and Data of a Hashtable in C# .NET 1.1 | [
"",
"c#",
"hashtable",
".net-1.1",
""
] |
Is there anything similar to rails' scaffolding for pylons? I've been poking around google, but only found this thing called dbsprockets, which is fine, although probably way too much for my needs. What I really need is a basic CRUD that is based on the SQLAlchemy model. | The question is super old, but hell: <http://code.google.com/p/formalchemy/>
Gives you basic crud out of the box, customizable to do even relatively complex things easily, and gives you a drop-in Pylons admin app too (written and customizable with the same api, no magic). | I hear you, I've followed the Pylons mailing list for a while looking for something similar. There have been some attempts in the past (see [AdminPylon](http://adminpylon.devjavu.com/) and [Restin](http://code.google.com/p/restin/)) but none have really kept up with SQLAlchemy's rapidly developing orm api.
Since DBSpr... | Scaffolding in pylons | [
"",
"python",
"pylons",
""
] |
I am using the Photoshop's javascript API to find the fonts in a given PSD.
Given a font name returned by the API, I want to find the actual physical font file that font name corresponds to on the disc.
This is all happening in a python program running on OSX so I guess I'm looking for one of:
* Some Photoshop javas... | Unfortunately the only API that isn't deprecated is located in the ApplicationServices framework, which doesn't have a bridge support file, and thus isn't available in the bridge. If you're wanting to use ctypes, you can use ATSFontGetFileReference after looking up the ATSFontRef.
Cocoa doesn't have any native support... | open up a terminal (Applications->Utilities->Terminal) and type this in:
```
locate InsertFontHere
```
This will spit out every file that has the name you want.
Warning: there may be alot to wade through. | How can I find the full path to a font from its display name on a Mac? | [
"",
"python",
"macos",
"fonts",
"photoshop",
""
] |
I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.
if I o... | For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.
An old trick for doing obfuscated code was to use this to create if statements, such as:
```
a || b();
```
if "a" is true, "b()" would never be evaluated, so we can rewrite it... | Pretty much every language does a short circuit evaluation. Meaning the second condition is only evaluated if it's aboslutely necessary to. For this to work, most languages use the double pipe, ||, not the single one, |.
See <http://en.wikipedia.org/wiki/Short-circuit_evaluation> | if statement condition optimisation | [
"",
"php",
"language-agnostic",
"conditional-statements",
""
] |
Any good suggestions? Input will be the name of a header file and output should be a list (preferably a tree) of all files including it directly or indirectly. | If you have access to GCC/G++, then the [`-M` option](http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#Preprocessor-Options) will output the dependency list. It doesn't do any of the extra stuff that the other tools do, but since it is coming from the compiler, there is no chance that it will pick up files f... | Thanks to KeithB. I looked up the docs for cl.exe (VS2008) and found the /showIncludes flag. From the IDE, this can be set from the property page of any CPP file.
 | Tool to track #include dependencies | [
"",
"c++",
"c",
"header",
""
] |
In SQL Server how do you query a database to bring back all the tables that have a field of a specific name? | The following query will bring back a unique list of tables where `Column_Name` is equal to the column you are looking for:
```
SELECT Table_Name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE Column_Name = 'Desired_Column_Name'
GROUP BY Table_Name
``` | ```
SELECT Table_Name
FROM Information_Schema.Columns
WHERE Column_Name = 'YourFieldName'
``` | SQL query for a database scheme | [
"",
"sql",
"sql-server",
""
] |
When building projects in C++, I've found debugging linking errors to be tricky, especially when picking up other people's code. What strategies do people use for debugging and fixing linking errors? | Not sure what your level of expertise is, but here are the basics.
Below is a linker error from VS 2005 - yes, it's a giant mess if you're not familiar with it.
```
ByteComparator.obj : error LNK2019: unresolved external symbol "int __cdecl does_not_exist(void)" (?does_not_exist@@YAHXZ) referenced in function "void _... | One of the common linking errors I've run into is when a function is used differently from how it's defined. If you see such an error you should make sure that every function you use is properly declared in some .h file.
You should also make sure that all the relevant source files are compiled into the same lib file.... | Best practices for debugging linking errors | [
"",
"c++",
"visual-studio",
"gcc",
"linker",
"compilation",
""
] |
I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.
How do I specify a port number when I'm trying to connect to a database?
It would be even better if ... | After digging through the sql.el file, I found a variable that allows me to specify a port when I try to create a connection.
This option was added GNU Emacs 24.1.
> **sql-mysql-login-params**
>
> List of login parameters needed to connect to MySQL.
I added this to my Emacs init file:
```
(setq sql-mysql-login-para... | ```
(setq sql-mysql-options (list "-P <port number>"))
``` | Specify a Port Number in Emacs sql-mysql | [
"",
"sql",
"mysql",
"emacs",
""
] |
What recommendations can you give for a system which must do the following:
Load Plugins (and eventually execute them) but have 2 methods of loading these plugins:
* Load only authorized plugins
(developed by the owner of the
software)
* Load all plugins
And we need to be reasonably secure that the authorized pl... | Basically, if you're putting your code on someone else's machine, there's no absolute guarantee of security.
You can look at all kinds of security tricks, but in the end, the code is on their machine so it's out of your control.
How much do you stand to lose if the end user loads an unauthorised plugin? | > How much do you stand to lose if the end user loads an unauthorised plugin?
Admittedly this won't happen often, but when/if it does happen we lose a lot and I although I understand we will produce nothing 100% secure, I want to make it enough of a hindrance to put people off doing it.
The annoying thing about going... | .Net Dynamic Plugin Loading with Authority | [
"",
"c#",
".net",
"plugins",
"assemblies",
"dynamics-crm",
""
] |
I want a data structure that will allow querying *how many items in last **X** minutes*. An item may just be a simple identifier or a more complex data structure, preferably the timestamp of the item will be in the item, rather than stored outside (as a hash or similar, wouldn't want to have problems with multiple item... | A simple linked list can be used for this.
Basically you add new items to the end, and remove too old items from the start, it is a cheap data structure.
example-code:
```
list.push_end(new_data)
while list.head.age >= age_limit:
list.pop_head()
```
If the list will be busy enough to warrant chopping off larger... | I think that an important consideration will be the frequency of querying vs. adding/removing. If you will do frequent querying (especially if you'll have a large collection) a B-tree may be the way to go:
<http://en.wikipedia.org/wiki/B-tree>
You could have some thread go through and clean up this tree periodically ... | Aging Data Structure in C# | [
"",
"c#",
"linq",
".net-3.5",
"data-structures",
""
] |
I'm looking into writing a audio syntesizer in Java, and was wondering if anybody has any advice or good resources for writing such a program. I'm looking for info on generating raw sound waves, how to output them into a usable form (playing over speakers), as well as general theory on the topic. Thanks guys. | 1. This problem is basically about mapping functions to arrays of numbers. A language that supports first-class functions would come in really handy here.
2. Check out
<http://www.harmony-central.com/Computer/Programming> and
<http://www.developer.com/java/other/article.php/3071021> for some Java-related info.
3.... | Check out [Frinika](http://frinika.sourceforge.net/). It's a full-featured music workstation implemented in Java (open source). Using the API, you can run midi events through the synthesizer, read the raw sound output, and write it to a WAV file (see source code link below).
Additional information:
* [Frinika Develop... | Beginner Digital Synth | [
"",
"java",
"synthesizer",
""
] |
I want to start using Python for small projects but the fact that a misplaced tab or indent can throw a compile error is really getting on my nerves. Is there some type of setting to turn this off?
I'm currently using NotePad++. Is there maybe an IDE that would take care of the tabs and indenting? | > I'm currently using NotePad++. Is
> there maybe an IDE that would take
> care of the tabs and indenting?
I liked [pydev](http://pydev.sourceforge.net/) extensions of eclipse for that. | The answer is no.
At least, not until something like the following is implemented:
```
from __future__ import braces
``` | Is there a way around coding in Python without the tab, indent & whitespace criteria? | [
"",
"python",
""
] |
After reading [this question](https://stackoverflow.com/questions/28832/java-and-manually-executing-finalize), I was reminded of when I was taught Java and told never to call finalize() or run the garbage collector because "it's a big black box that you never need to worry about". Can someone boil the reasoning for thi... | The short answer: Java garbage collection is a very finely tuned tool. System.gc() is a sledge-hammer.
Java's heap is divided into different generations, each of which is collected using a different strategy. If you attach a profiler to a healthy app, you'll see that it very rarely has to run the most expensive kinds ... | As far as finalizers go:
1. They are virtually useless. They aren't guaranteed to be called in a timely fashion, or indeed, at all (if the GC never runs, neither will any finalizers). This means you generally shouldn't rely on them.
2. Finalizers are not guaranteed to be idempotent. The garbage collector takes great c... | Why do you not explicitly call finalize() or start the garbage collector? | [
"",
"java",
"garbage-collection",
""
] |
I'm trying to parse an INI file using C++. Any tips on what is the best way to achieve this? Should I use the Windows API tools for INI file processing (with which I am totally unfamiliar), an open-source solution or attempt to parse it manually? | You can use the Windows API functions, such as [GetPrivateProfileString()](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofilestring) and [GetPrivateProfileInt()](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getprivateprofileint). | If you need a cross-platform solution, try Boost's [Program Options](http://www.boost.org/doc/libs/1_36_0/doc/html/program_options.html) library. | What is the easiest way to parse an INI File in C++? | [
"",
"c++",
"winapi",
"ini",
"fileparse",
""
] |
I am prototyping some C# 3 collection filters and came across this.
I have a collection of products:
```
public class MyProduct
{
public string Name { get; set; }
public Double Price { get; set; }
public string Description { get; set; }
}
var MyProducts = new List<MyProduct>
{
new MyProd... | LINQ turns into method calls like the code you have.
In other words, there should be no difference.
However, in your two pieces of code you are not calling .ToList in the first, so the first piece of code will produce an enumerable data source, but if you call .ToList on it, the two should be the same. | As mentioned d will be `IEnumerable<MyProduct>` while f is `List<MyProduct>`
The conversion is done by the C# compiler
```
var d =
from mp in MyProducts
where mp.Price < 50d
select mp;
```
Is converted to (before compilation to IL and with generics expanded):
```
var d =
MyProducts.
Where<MyPr... | When to use an extension method with lambda over LINQtoObjects to filter a collection? | [
"",
"c#",
"linq",
".net-3.5",
"lambda",
""
] |
How can I find out which node in a tree list the context menu has been activated? For instance right-clicking a node and selecting an option from the menu.
I can't use the TreeViews' `SelectedNode` property because the node is only been right-clicked and not selected. | You can add a mouse click event to the TreeView, then select the correct node using GetNodeAt given the mouse coordinates provided by the MouseEventArgs.
```
void treeView1MouseUp(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
// Select the clicked node
treeView1.Select... | Here is my solution. Put this line into NodeMouseClick event of the TreeView:
```
((TreeView)sender).SelectedNode = e.Node;
``` | Find node clicked under context menu | [
"",
"c#",
"winforms",
"treeview",
"contextmenu",
""
] |
What does it mean when you get or create a date in UTC format in JavaScript? | A date represents a specific point in time. This point in time will be called differently in different places. As I write this, it's 00:27 on Tuesday in Germany, 23:27 on Monday in the UK and 18:27 on Monday in New York.
To take an example method: getDay returns the day of the week in the local timezone. Right now, fo... | getUTC is for converting times to Coordinated Universal Time (UTC, the acronym is ordered differently than what it stands for) which is the standard time based on the time in Greenwich, London.
The universal time is calculated using a time offset (in minutes when in JavaScript.) This offset is based on the time zone c... | What do the getUTC* methods on the date object do? | [
"",
"javascript",
"date",
"utc",
""
] |
I'm just about to make my first trip into the world of JNI (Java Native Interface) to provide file system change notifications from platform specific C/C++ code to Java. That is unless someone suggest some brilliant library for doing this that I've missed.
Being new to JNI I've managed to find much documentation on th... | I strongly dislike make because of its implicit ruleset and treatment of whitespace. Personally I would use cpp tasks (<http://ant-contrib.sourceforge.net/cpptasks/index.html>) to do my C compilation. They are not as flexible as make but they are also far less complex and it will mean you don't have to burden your deve... | As a simpler alternative to JNI, try JNA: <https://jna.dev.java.net/>, may solve this hassle for you and be simpler (assuming it can do what you want). | JNI and Java: ant calling make or make calling ant? | [
"",
"java",
"ant",
"makefile",
"java-native-interface",
"automake",
""
] |
I see many user interface control libraries for .NET, but where can I get similar stuff for win32 using simply C/C++?
Things like prettier buttons, dials, listviews, graphs, etc.
Seems every Win32 programmers' right of passage is to end up writing his own collection. :/
---
No MFC controls please. I only do pure C/... | I've used [Trolltech's Qt framework](http://trolltech.com/products/qt/) in the past and had great success with it:
In addition, it's also cross-platform, so in theory you can target Win, Mac, & Linux (provided you don't do anything platform-specific in the rest of your code, of course ;) )
Edit: I notice that you're t... | I you don't mind using the MFC libraries you should try the [Visual C++ 2008 Feature Pack](http://www.microsoft.com/downloads/details.aspx?FamilyId=D466226B-8DAB-445F-A7B4-448B326C48E7&displaylang=en) | User Interface Controls for Win32 | [
"",
"c++",
"winapi",
"user-interface",
""
] |
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:
```
public String appendWithDelimiter( String original, S... | ### Pre Java 8:
Apache's commons lang is your friend here - it provides a join method very similar to the one you refer to in Ruby:
[`StringUtils.join(java.lang.Iterable,char)`](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#join(java.lang.Iterable,%20char))
---
### ... | You could write a little join-style utility method that works on java.util.Lists
```
public static String join(List<String> list, String delim) {
StringBuilder sb = new StringBuilder();
String loopDelim = "";
for(String s : list) {
sb.append(loopDelim);
sb.append(s);
... | What's the best way to build a string of delimited items in Java? | [
"",
"java",
"string",
"algorithm",
""
] |
I need to create a backup of a SQL Server 2005 Database that's only the structure...no records, just the schema. Is there any way to do this?
EDIT: I'm trying to create a backup file to use with old processes, so a script wouldn't work for my purposes, sorry | Use a 3 step process:
1. Generate a script from the working database
2. Create a new database from that script
3. Create a backup of the new database | Why not just use SQL Management Studio to create a complete script of your database and the objects? | Backup SQL Schema Only? | [
"",
"sql",
"sql-server",
"oracle",
"sql-server-2005",
"backup",
""
] |
I need to try to lock on an object, and if its already locked just continue (after time out, or without it).
The C# lock statement is blocking. | I believe that you can use [`Monitor.TryEnter()`](http://msdn.microsoft.com/en-us/library/system.threading.monitor.tryenter%28VS.71%29.aspx).
The lock statement just translates to a `Monitor.Enter()` call and a `try catch` block. | Ed's got the right function for you. Just don't forget to call `Monitor.Exit()`. You should use a `try-finally` block to guarantee proper cleanup.
```
if (Monitor.TryEnter(someObject))
{
try
{
// use object
}
finally
{
Monitor.Exit(someObject);
}
}
``` | Is there a "try to lock, skip if timed out" operation in C#? | [
"",
"c#",
"multithreading",
"locking",
""
] |
Currently, I don't really have a good method of debugging JavaScript in Internet Explorer and [Safari](http://en.wikipedia.org/wiki/Safari_%28web_browser%29). In Firefox, you can use [Firebug's](http://en.wikipedia.org/wiki/Firebug) [logging feature](http://getfirebug.com/logging.html) and [command Line functions](http... | For Safari you need to enable the "Develop" menu via Preferences (in Safari 3.1; see [the entry in Apple's Safari development FAQ](http://developer.apple.com/internet/safari/faq.html#anchor14)) or via
```
$ defaults write com.apple.Safari IncludeDebugMenu 1
```
at the terminal in Mac OS X. Then from the Develop menu ... | [This is the Firebug Lite](http://getfirebug.com/lite.html "Firebug Lite") that @John was referring to that works on IE, Safari and Opera. | Debugging JavaScript in Internet Explorer and Safari | [
"",
"javascript",
"internet-explorer",
"safari",
""
] |
I have a medium sized application that runs as a .net web-service which I do not control,
and I want to create a loose pythonic API above it to enable easy scripting.
I wanted to know what is the best/most practical solution for using web-services in python.
Edit:
I need to consume a complex soap WS
and I have no con... | [Jython](http://www.jython.org) and [IronPython](http://www.codeplex.com/IronPython) give access to great Java & .NET SOAP libraries.
If you need CPython, [ZSI](http://pywebsvcs.sourceforge.net/) has been flaky for me, but it could be possible to use a tool like [Robin](http://robin.python-hosting.com/) to wrap a good... | If I have to expose APIs, I prefer doing it as JSON. Python has excellent support for JSON objects (JSON Objects are infact python dictionaries) | What's the best way to use web services in python? | [
"",
"python",
"web-services",
"soap",
""
] |
We have the question [is there a performance difference between `i++` and `++i` **in C**?](/q/24886)
What's the answer for C++? | [Executive Summary: Use `++i` if you don't have a specific reason to use `i++`.]
For C++, the answer is a bit more complicated.
If `i` is a simple type (not an instance of a C++ class), [then the answer given for C ("No there is no performance difference")](https://stackoverflow.com/a/24887/194894) holds, since the c... | Yes. There is.
The ++ operator may or may not be defined as a function. For primitive types (int, double, ...) the operators are built in, so the compiler will probably be able to optimize your code. But in the case of an object that defines the ++ operator things are different.
The operator++(int) function must crea... | Is there a performance difference between i++ and ++i in C++? | [
"",
"c++",
"performance",
"oop",
"post-increment",
"pre-increment",
""
] |
Using SQL Server, how do I split a string so I can access item x?
Take a string "Hello John Smith". How can I split the string by space and access the item at index 1 which should return "John"? | You may find the solution in *[SQL User Defined Function to Parse a Delimited String](http://www.codeproject.com/KB/database/SQL_UDF_to_Parse_a_String.aspx)* helpful (from [The Code Project](http://en.wikipedia.org/wiki/The_Code_Project)).
You can use this simple logic:
```
Declare @products varchar(200) = '1|20|3|34... | I don't believe SQL Server has a built-in split function, so other than a UDF, the only other answer I know is to hijack the PARSENAME function:
```
SELECT PARSENAME(REPLACE('Hello John Smith', ' ', '.'), 2)
```
PARSENAME takes a string and splits it on the period character. It takes a number as its second argument, ... | How do I split a delimited string so I can access individual items? | [
"",
"sql",
"sql-server",
"t-sql",
"split",
""
] |
I would like to compare the contents of a couple of collections in my Equals method. I have a Dictionary and an IList. Is there a built-in method to do this?
Edited:
I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the ... | [`Enumerable.SequenceEqual`](http://msdn.microsoft.com/en-us/library/bb342073.aspx)
> Determines whether two sequences are equal by comparing their elements by using a specified IEqualityComparer(T).
You can't directly compare the list & the dictionary, but you could compare the list of values from the Dictionary wit... | As others have suggested and have noted, `SequenceEqual` is order-sensitive. To solve that, you can sort the dictionary by key (which is unique, and thus the sort is always stable) and then use `SequenceEqual`. The following expression checks if two dictionaries are equal regardless of their internal order:
```
dictio... | Is there a built-in method to compare collections? | [
"",
"c#",
".net",
"collections",
""
] |
I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)
The script works fine, that is until you try and use it on files that have Unicode show-names ... | Use a subrange of `[\u0000-\uFFFF]` for what you want.
You can also use the `re.UNICODE` compile flag. [The docs](http://docs.python.org/lib/re-syntax.html) say that if `UNICODE` is set, `\w` will match the characters `[0-9_]` plus whatever is classified as alphanumeric in the Unicode character properties database.
S... | Python's re module doesn't support \p{Letter} or \X. However, the [new regex implementation on PyPI](http://pypi.python.org/pypi/regex) does. | Regex and unicode | [
"",
"python",
"regex",
"unicode",
"character-properties",
""
] |
I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.
Do you have any *best practices*, tipps or major *DO NOTs* for a starter? How did you start with Spring - big project or small tutorial-like appli... | Small tip - I've found it helpful to modularize and clearly label my Spring xml context files based on application concern. Here's an example for a web app I worked on:
* `MyProject / src / main / resources / spring /`
+ ***datasource.xml*** - My single data source bean.
+ ***persistence.xml*** - My DAOs/Repositor... | Focus first on the heart of Spring: Dependency Injection. Once you see all the ways that DI can be used, then start thinking about the more interesting pieces like AOP, Remoting, JDBC Templates etc. So my best bit of advice is let your use of Spring grow out from the core.
Best practice? If you're using the standard X... | What's your "best practice" for the first Java EE Spring project? | [
"",
"java",
"spring",
"jakarta-ee",
"aop",
""
] |
I know I need to have (although I don't know why) a `GROUP BY` clause on the end of a SQL query that uses any aggregate functions like `count`, `sum`, `avg`, etc:
```
SELECT count(userID), userName
FROM users
GROUP BY userName
```
When else would `GROUP BY` be useful, and what are the performance ramifications? | To retrieve the number of widgets from each widget category that has more than 5 widgets, you could do this:
```
SELECT WidgetCategory, count(*)
FROM Widgets
GROUP BY WidgetCategory
HAVING count(*) > 5
```
The "having" clause is something people often forget about, instead opting to retrieve all their data to the cli... | GROUP BY is similar to DISTINCT in that it groups multiple records into one.
This example, borrowed from <http://www.devguru.com/technologies/t-sql/7080.asp>, lists distinct products in the Products table.
```
SELECT Product FROM Products GROUP BY Product
Product
-------------
Desktop
Laptop
Mouse
Network Card
Hard ... | How do I use T-SQL Group By | [
"",
"sql",
"sql-server",
"group-by",
""
] |
What is the Java equivalent of PHP's `$_POST`? After searching the web for an hour, I'm still nowhere closer. | Your `HttpServletRequest` object has a `getParameter(String paramName)` method that can be used to get parameter values. <http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)> | Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.
I hope this helps you out.
```
<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
`... | Accessing post variables using Java Servlets | [
"",
"java",
"http",
"servlets",
""
] |
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object?
```
const myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;
``` | ## Updated answer
**Here's an update as of 2016 and [widespread deployment of ES5](http://kangax.github.io/compat-table/es5/) and beyond.** For IE9+ and all other modern ES5+ capable browsers, you can use [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) so... | If you know you don't have to worry about `hasOwnProperty` checks, you can use the [Object.keys()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method in this way:
```
Object.keys(myArray).length
``` | Length of a JavaScript object | [
"",
"javascript",
"object",
"javascript-objects",
""
] |
In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.
Anyway, I'm no... | In PHP you can pass a variable number of arguments to a function or method by using [`call_user_func_array`](http://www.php.net/call_user_func_array). An example for a method would be:
```
call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);
```
The function will be called with each member in the arra... | The more modern way to bind parameters dynamically is via the splat/spread operator (`...`).
Assuming:
* you have a non-empty array of values to bind to your query and
* your array values are suitably processed as string type values in the context of the query and
* your input array is called `$values`
Code for PHP5... | Variable parameter/result binding with prepared statements | [
"",
"php",
"mysql",
"mysqli",
""
] |
I'm writing a C/C++ DLL and want to export certain functions which I've done before using a .def file like this
```
LIBRARY "MyLib"
EXPORTS
Foo
Bar
```
with the code defined as this, for example:
```
int Foo(int a);
void Bar(int foo);
```
However, what if I want to declare an overloaded method of Foo() like:
`... | In the code itself, mark the functions you want to export using \_\_declspec(dllexport). For example:
```
#define DllExport __declspec(dllexport)
int DllExport Foo( int a ) {
// implementation
}
int DllExport Foo( int a, int b ) {
// implementation
}
```
If you do this, you do not need to list the functions in ... | Function overloading is a C++ feature that relies on name mangling (the cryptic function names in the linker error messages).
By writing the mangled names into the def file, I can get my test project to link and run:
```
LIBRARY "TestDLL"
EXPORTS
?Foo@@YAXH@Z
?Foo@@YAXHH@Z
```
seems to work for
```
void Foo... | Overloaded functions in C++ DLL def file | [
"",
"c++",
"c",
"dll",
""
] |
I have a column which is of type nvarchar(max). How do I find the length of the string (or the number of bytes) for the column for each row in the table? | > SELECT LEN(columnName) AS MyLength
> FROM myTable | If you want to find out the max there should be a way for you to get the schema of the table. Normally you can do something like [SHOW COLUMNS](http://dev.mysql.com/doc/refman/5.0/en/show-columns.html) in SQL or a [DESCRIBE](http://dev.mysql.com/doc/refman/5.0/en/describe.html) style command. In a mysql shell that can ... | What SQL-server function can I use to get the character or byte length of a nvarchar(max) column? | [
"",
"sql",
"sql-server",
""
] |
Currently we have a project with a standard subversion repository layout of:
./trunk
./branches
./tags
However, as we're moving down the road of OSGi and a modular project, we've ended up with:
./trunk/bundle/main
./trunk/bundle/modulea
./trunk/bundle/moduleb
./tags/bundle/main-1.0.0
./tags/bundle/main-1.0... | The Subversion book contains two sections on this:
* [Repository Layout](http://svnbook.red-bean.com/en/1.4/svn.branchmerge.maint.html#svn.branchmerge.maint.layout)
* [Planning Your Repository Organization](http://svnbook.red-bean.com/en/1.4/svn.reposadmin.planning.html#svn.reposadmin.projects.chooselayout)
A blog en... | This is very much up to personal preference, but I find the following structure suitable for large projects consisting of many modules:
```
branches
project-name
module1
branch-name
module2
possibly-another-branch-name
branch-name-on-a-higher-level-including-both-modules
module1
... | When should a multi-module project to split into separate repository trees? | [
"",
"java",
"svn",
"osgi",
""
] |
So, I know that try/catch does add some overhead and therefore isn't a good way of controlling process flow, but where does this overhead come from and what is its actual impact? | I'm not an expert in language implementations (so take this with a grain of salt), but I think one of the biggest costs is unwinding the stack and storing it for the stack trace. I suspect this happens only when the exception is thrown (but I don't know), and if so, this would be decently sized hidden cost every time a... | Three points to make here:
* Firstly, there is little or NO performance penalty in actually having try-catch blocks in your code. This should not be a consideration when trying to avoid having them in your application. The performance hit only comes into play when an exception is thrown.
* When an exception is thrown ... | What is the real overhead of try/catch in C#? | [
"",
"c#",
".net",
"performance",
"optimization",
"try-catch",
""
] |
This question is kind of an add-on to this [question](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why)
In C#, a switch case cannot fall through to other cases, this causes a compilation error. In this case I am just adding some number to the month total for the selected month and each subs... | Often times when you see the noise from a huge switch statement or many if statements that might fall into more than one block, you're trying to suppress a bad design.
Instead, what if you implemented the Specification pattern to see if something matched, and then act on it?
```
foreach(MonthSpecification spec in thi... | In C# switch statements you can fall through cases only if there is no statement for the case you want to fall through
```
switch(myVar)
{
case 1:
case 2: // Case 1 or 2 get here
break;
}
```
However if you want to fall through with a statement you must use the dreaded GOTO
```
switch(myVar)
{
... | C# switch: case not falling through to other cases limitation | [
"",
"c#",
"switch-statement",
""
] |
We have some input data that sometimes appears with   characters on the end.
The data comes in from the source system as varchar() and our attempts to cast as decimal fail b/c of these characters.
Ltrim and Rtrim don't remove the characters, so we're forced to do something like:
```
UPDATE myTable
SET myColumn =... | [This page](http://www.lazydba.com/sql/1__4390.html) has a sample of how you can remove non-alphanumeric chars:
```
-- Put something like this into a user function:
DECLARE @cString VARCHAR(32)
DECLARE @nPos INTEGER
SELECT @cString = '90$%45623 *6%}~:@'
SELECT @nPos = PATINDEX('%[^0-9]%', @cString)
WHILE @nPo... | This will remove all non alphanumeric chracters
```
CREATE FUNCTION [dbo].[fnRemoveBadCharacter]
(
@BadString nvarchar(20)
)
RETURNS nvarchar(20)
AS
BEGIN
DECLARE @nPos INTEGER
SELECT @nPos = PATINDEX('%[^a-zA-Z0-9_]%', @BadString)
WHILE @nPos > 0
BEGIN
... | T-SQL trim   (and other non-alphanumeric characters) | [
"",
"sql",
"sql-server",
""
] |
I am writing a batch script in order to beautify JavaScript code. It needs to work on both **Windows** and **Linux**.
How can I beautify JavaScript code using the command line tools? | First, pick your favorite Javascript based Pretty Print/Beautifier. I prefer the one at [<http://jsbeautifier.org/>](http://jsbeautifier.org/), because it's what I found first. Downloads its file <https://github.com/beautify-web/js-beautify/blob/master/js/lib/beautify.js>
Second, download and install The Mozilla group... | **UPDATE April 2014**:
The beautifier has been rewritten since I answered this in 2010. There is now a python module in there, an npm Package for nodejs, and the jar file is gone. Please read the [project page on github.com](https://github.com/einars/js-beautify/).
Python style:
```
$ pip install jsbeautifier
```
... | How can I beautify JavaScript code using Command Line? | [
"",
"javascript",
"command-line-interface",
"pretty-print",
"multiplatform",
""
] |
I'm trying to write some PHP to upload a file to a folder on my webserver. Here's what I have:
```
<?php
if ( !empty($_FILES['file']['tmp_name']) ) {
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
header('Location: http://www.mywebsite.com/dump/');
exit;
... | As it's Windows, there is no real 777. If you're using [chmod](https://www.php.net/manual/en/function.chmod.php), check the Windows-related comments.
Check that the IIS Account can access (read, write, modify) these two folders:
```
E:\inetpub\vhosts\mywebsite.com\httpdocs\dump\
C:\WINDOWS\Temp\
``` | OMG
```
move_uploaded_file($_FILES['file']['tmp_name'], './' . $_FILES['file']['name']);
```
Don't do that. `$_FILES['file']['name']` could be `../../../../boot.ini` or any number of bad things. You should never trust this name. You should rename the file something else and associate the original name with your rando... | PHP Error - Uploading a file | [
"",
"php",
"iis",
"upload",
""
] |
I actually have an answer to my question but it is not parallelized so I am interested in ways to improve the algorithm. Anyway it might be useful as-is for some people.
```
int Until = 20000000;
BitArray PrimeBits = new BitArray(Until, true);
/*
* Sieve of Eratosthenes
* PrimeBits is a simple BitArray where all bi... | You might save some time by cross-referencing your bit array with a doubly-linked list, so you can more quickly advance to the next prime.
Also, in eliminating later composites once you hit a new prime p for the first time - the first composite multiple of p remaining will be p\*p, since everything before that has alr... | Parallelisation aside, you don't want to be calculating sqrt(Until) on every iteration. You also can assume multiples of 2, 3 and 5 and only calculate for N%6 in {1,5} or N%30 in {1,7,11,13,17,19,23,29}.
You should be able to parallelize the factoring algorithm quite easily, since the Nth stage only depends on the sqr... | Fastest way to calculate primes in C#? | [
"",
"c#",
".net",
"performance",
"algorithm",
"bitarray",
""
] |
Let's say that we have an ARGB color:
```
Color argb = Color.FromARGB(127, 69, 12, 255); //Light Urple.
```
When this is painted on top of an existing color, the colors will blend. So when it is blended with white, the resulting color is `Color.FromARGB(255, 162, 133, 255);`
The solution should work like this:
```
... | It's called [alpha blending](http://en.wikipedia.org/wiki/Alpha_compositing).
In psuedocode, assuming the background color (blend) always has 255 alpha. Also assumes alpha is 0-255.
```
alpha=argb.alpha()
r = (alpha/255)*argb.r() + (1 - alpha/255)*blend.r()
g = (alpha/255)*argb.g() + (1 - alpha/255)*blend.g()
b = (al... | I know this is an old thread, but I want to add this:
```
Public Shared Function AlphaBlend(ByVal ForeGround As Color, ByVal BackGround As Color) As Color
If ForeGround.A = 0 Then Return BackGround
If BackGround.A = 0 Then Return ForeGround
If ForeGround.A = 255 Then Return ForeGround
Dim Alpha As Inte... | Converting ARBG to RGB with alpha blending | [
"",
"c#",
"colors",
""
] |
Should you set all the objects to `null` (`Nothing` in VB.NET) once you have finished with them?
I understand that in .NET it is essential to dispose of any instances of objects that implement the `IDisposable` interface to release some resources although the object can still be something after it is disposed (hence t... | Karl is absolutely correct, there is no need to set objects to null after use. If an object implements `IDisposable`, just make sure you call `IDisposable.Dispose()` when you're done with that object (wrapped in a `try`..`finally`, or, a `using()` block). But even if you don't remember to call `Dispose()`, the finalise... | Another reason to avoid setting objects to null when you are done with them is that it can actually keep them alive for longer.
e.g.
```
void foo()
{
var someType = new SomeType();
someType.DoSomething();
// someType is now eligible for garbage collection
// ... rest of method not using 'som... | Setting Objects to Null/Nothing after use in .NET | [
"",
"c#",
".net",
"vb.net",
"memory-management",
"null",
""
] |
I'm looking for a book/site/tutorial on best practices for relational database design, tuning for performance etc. It turns out this kind of resource is a bit difficult to find; there's a lot of "here's normalization, here's ER diagrams, have at it," but not much in the way of real examples. Anyone have any ideas? | Book: [Database Design for Mere Mortals](https://rads.stackoverflow.com/amzn/click/com/0201752840) | Take a look at the [Library of Free Data Models](http://www.databaseanswers.org/data_models/index.htm). There are tons of example database designs, with diagrams that cover real-world scenarios (and some just fun/funny ones as well). I haven't ever used one as-is, but it's often been handy to get an idea of how to appr... | Good Resources for Relational Database Design | [
"",
"sql",
"database",
"performance",
""
] |
I have a table with a structure like the following:
---
| LocationID | AccountNumber |
| --- | --- |
| long-guid-here | 12345 |
| long-guid-here | 54321 |
To pass into another stored procedure, I need the XML to look like this:
```
<root>
<clientID>12345</clientID>
<clientID>54321</clientID>
</root>
```
T... | try
```
SELECT
1 AS Tag,
0 AS Parent,
AccountNumber AS [Root!1!AccountNumber!element]
FROM
Location.LocationMDAccount
WHERE
LocationID = 'long-guid-here'
FOR XML EXPLICIT
``` | Using SQL Server 2005 (or presumably 2008) I find for XML PATH to allow for much easier to maintain SQL than for XML Explicit (particularly once the SQL is longer).
In this case:
```
SELECT AccountNumber as "clientID"
FROM Location.LocationMDAccount
WHERE locationid = 'long-guid-here'
FOR XML PATH (''), Root ('root')... | SQL Server 2005 For XML Explicit - Need help formatting | [
"",
"sql",
"xml",
"sql-server-2005",
"formatting",
"for-xml",
""
] |
I need to do a dump of a table on a remote server, but I can't access the server directly. The only access I have is through PHP scripts.
Is there some way in which MySQL will return an
```
INSERT INTO `table_name` (`field1`, `field2`) VALUES ('a', 'b'), ('c', 'd')
```
statement, like what `mysqldump` will return?
... | 1) can you run mysqldump from exec or passthru
2) take a look at this: <http://www.php-mysql-tutorial.com/perform-mysql-backup-php.php> | If you can use php-scripts on the server i would recommend [phpmyadmin](http://www.phpmyadmin.net/home_page/index.php). Then you can do this from the web-interface. | MySQL statement that returns a SQL statement? | [
"",
"php",
"mysql",
"export",
""
] |
I have the next function:
```
function setImagesWidth(id,width) {
var images = document.getElementById(id).getElementsByTagName("img");
for(var i = 0; i < images.length;i++) {
// If the real width is bigger than width parameter
images[i].style.width=width;
//}
} ... | @Sergio del Amo: Indeed, if you check out my link you'll see that you want `clientWidth` instead.
@Sergio del Amo: You cannot, unfortunately, accept your own answer. But you do have an extraneous period in the "px" suffix, so let's go with this, including the `clientWidth` change:
```
// width in pixels
function setI... | Here is, hopefully, enough sample code to give you what you want:
```
var myImage = document.getElementById("myImagesId");
var imageWidth = myImage.offsetWidth;
var imageHeight = myImage.offsetHeight;
```
That should give you the numbers you need to derive the solution you want. I think you can write the rest of the ... | Real image width with JavaScript | [
"",
"javascript",
""
] |
How do I page results in SQL Server 2005?
I tried it in SQL Server 2000, but there was no reliable way to do this. I'm now wondering if SQL Server 2005 has any built in method?
What I mean by paging is, for example, if I list users by their username, I want to be able to only return the first 10 records, then the nex... | You can use `the Row_Number()` function.
Its used as follows:
```
SELECT Row_Number() OVER(ORDER BY UserName) As RowID, UserFirstName, UserLastName
FROM Users
```
From which it will yield a result set with a `RowID` field which you can use to page between.
```
SELECT *
FROM
( SELECT Row_Number() OVER(ORDER BY ... | If you're trying to get it in one statement (the total plus the paging). You might need to explore SQL Server support for the partition by clause (windowing functions in ANSI SQL terms). In Oracle the syntax is just like the example above using row\_number(), but I have also added a partition by clause to get the total... | Paging SQL Server 2005 Results | [
"",
"sql",
"sql-server-2005",
"paging",
""
] |
What's the most efficient way to resize large images in PHP?
I'm currently using the [GD](http://en.wikipedia.org/wiki/GD_Graphics_Library) function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).
This works great ... | People say that ImageMagick is much faster. At best just compare both libraries and measure that.
1. Prepare 1000 typical images.
2. Write two scripts -- one for GD, one
for ImageMagick.
3. Run both of them a few times.
4. Compare results (total execution
time, CPU and I/O usage, result
image quality).
Somet... | Here's a snippet from the php.net docs that I've used in a project and works fine:
```
<?
function fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {
// Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresample... | Efficient JPEG Image Resizing in PHP | [
"",
"php",
"image",
"gd",
"jpeg",
""
] |
I would like to be able to display some dynamic text at the mouse
cursor location in a win32 app, for instance to give an X,Y coordinate that
would move with the cursor as though attached. I can do this during a
mousemove event using a TextOut() call for the window at the mouse
coordinates and invalidate a rectange aro... | You may want to consider a small transparent window that you move to follow the mouse. In particular, since Windows 2000, [Layered](http://msdn.microsoft.com/en-us/library/ms632599(VS.85).aspx#layered) windows seem to be the weapon of choice (confession: no personal experience there). | You can do this via ToolTips - check out [CToolTipCtrl](http://msdn.microsoft.com/en-us/library/6b4cb3a5(VS.80).aspx).
If you want flicker free tracking ToolTips then you will need to derive your own classes from CToolTipCtrl that use the [trackActivate](http://msdn.microsoft.com/en-us/library/bb760421(VS.85).aspx) me... | How do I display dynamic text at the mouse cursor via C++/MFC in a Win32 application | [
"",
"c++",
"winapi",
"mfc",
""
] |
What would be the best way to fill a C# struct from a byte[] array where the data was from a C/C++ struct? The C struct would look something like this (my C is very rusty):
```
typedef OldStuff {
CHAR Name[8];
UInt32 User;
CHAR Location[8];
UInt32 TimeStamp;
UInt32 Sequence;
CHAR Tracking[16];
... | From what I can see in that context, you don't need to copy `SomeByteArray` into a buffer. You simply need to get the handle from `SomeByteArray`, pin it, copy the `IntPtr` data using `PtrToStructure` and then release. No need for a copy.
That would be:
```
NewStuff ByteArrayToNewStuff(byte[] bytes)
{
GCHandle ha... | Here is an exception safe version of the [accepted answer](https://stackoverflow.com/a/2887/184528):
```
public static T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try {
return (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(),... | Reading a C/C++ data structure in C# from a byte array | [
"",
"c#",
".net",
"data-structures",
"marshalling",
""
] |
**My Goal**
I would like to have a main processing thread (non GUI), and be able to spin off GUIs in their own background threads as needed, and having my main non GUI thread keep working. Put another way, I want my main non GUI-thread to be the owner of the GUI-thread and not vice versa. I'm not sure this is even pos... | **Application.Run** method displays one (or more) forms and initiates the standard message loop which runs until all the forms are closed. You cannot force a return from that method except by closing all your forms or forcing an application shutdown.
You can, however, pass an **ApplicationContext** (instad of a new Fo... | I'm sure this is possible if you hack at it hard enough, but I'd suggest it is not a good idea.
'Windows' (that you see on the screen) are highly coupled to processes. That is, each process which displays any GUI is expected to have a Message Loop, which processes all of the messages which are involved with creating a... | Possible to "spin off" several GUI threads? (Not halting the system at Application.Run) | [
"",
"c#",
".net",
"winforms",
""
] |
How do I perform an `IF...THEN` in an `SQL SELECT` statement?
For example:
```
SELECT IF(Obsolete = 'N' OR InStock = 'Y' ? 1 : 0) AS Saleable, * FROM Product
``` | The `CASE` statement is the closest to IF in SQL and is supported on all versions of SQL Server.
```
SELECT CAST(
CASE
WHEN Obsolete = 'N' or InStock = 'Y'
THEN 1
ELSE 0
END AS bit) as Saleable, *
FROM Product
```
You only need to use ... | The case statement is your friend in this situation, and takes one of two forms:
The simple case:
```
SELECT CASE <variable> WHEN <value> THEN <returnvalue>
WHEN <othervalue> THEN <returnthis>
ELSE <returndefaultcase>
END AS <newcolumnname>
F... | How do I perform an IF...THEN in an SQL SELECT? | [
"",
"sql",
"sql-server",
"t-sql",
"if-statement",
"case",
""
] |
Every time I create an object that has a collection property I go back and forth on the best way to do it?
1. public property with a getter that
returns a reference to private variable
2. explicit get\_ObjList and set\_ObjList
methods that return and create new or cloned
objects every time
3. explicit get\_Ob... | How you expose a collection depends entirely on how users are intended to interact with it.
**1)** If users will be adding and removing items from an object's collection, then a simple get-only collection property is best (option #1 from the original question):
```
private readonly Collection<T> myCollection_ = new .... | I usually go for this, a public getter that returns System.Collections.ObjectModel.ReadOnlyCollection:
```
public ReadOnlyCollection<SomeClass> Collection
{
get
{
return new ReadOnlyCollection<SomeClass>(myList);
}
}
```
And public methods on the object to modify the collection.
```
Clear();
Add... | How to expose a collection property? | [
"",
"c#",
".net",
"architecture",
""
] |
I have something like this:
```
barProgress.BeginAnimation(RangeBase.ValueProperty, new DoubleAnimation(
barProgress.Value, dNextProgressValue,
new Duration(TimeSpan.FromSeconds(dDuration)));
```
Now, how would you stop that animation (the `DoubleAnimation`)? The reason I want to do this, is because I would l... | To stop it, call `BeginAnimation` again with the second argument set to `null`. | When using storyboards to control an animation, make sure you set the second parameter to true in order to set the animation as controllable:
```
public void Begin(
FrameworkContentElement containingObject,
**bool isControllable**
)
``` | How to stop an animation in C# / WPF? | [
"",
"c#",
"wpf",
""
] |
I have a MySQL table with approximately 3000 rows per user. One of the columns is a datetime field, which is mutable, so the rows aren't in chronological order.
I'd like to visualize the time distribution in a chart, so I need a number of individual datapoints. 20 datapoints would be enough.
I could do this:
```
sel... | Michal Sznajder almost had it, but you can't use column aliases in a WHERE clause in SQL. So you have to wrap it as a derived table. I tried this and it returns 20 rows:
```
SELECT * FROM (
SELECT @rownum:=@rownum+1 AS rownum, e.*
FROM (SELECT @rownum := 0) r, entries e) AS e2
WHERE uid = ? AND rownum % 150 = ... | Something like this came to my mind
```
select @rownum:=@rownum+1 rownum, entries.*
from (select @rownum:=0) r, entries
where uid = ? and rownum % 150 = 0
```
I don't have MySQL at my hand but maybe this will help ... | Distribution of table in time | [
"",
"sql",
"mysql",
""
] |
I am getting the following error:
> Access denied for user 'apache'@'localhost' (using password: NO)
When using the following code:
```
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows(... | > And if it matters at all, apache@localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
If it is saying 'apache@localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is ... | Change the include() to require(). **If the "connect.php" file can't be require()d, the script will fail** with a fatal error, whereas **include() only generates a warning**. If the username you're passing to mysql\_connect() isn't "apache", an incorrect path to the connect script is the most common way to get this typ... | MySQL/Apache Error in PHP MySQL query | [
"",
"php",
"mysql",
"apache",
""
] |
What is reflection, and why is it useful?
I'm particularly interested in Java, but I assume the principles are the same in any language. | The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unles... | > **Reflection** is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.
For example, all objects in Java have the method `getClass()`, which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an `Object`) - this mi... | What is reflection and why is it useful? | [
"",
"java",
"reflection",
"terminology",
""
] |
Moving through the maze forward is pretty easy, but I can't seem to figure out how to back up through the maze to try a new route once you hit a dead end without going back too far? | Use [backtracking](http://www.cs.bu.edu/teaching/alg/maze/) by keeping a stack of previous direction decisions. | The simplest (to implement) algorithm would be to just keep a stack of locations you've been at, and the route you took from each, unless backtracking gives you that information.
To go back, just pop off old locations from the stack and check for more exits from that location until you find an old location with an unt... | How to traverse a maze programmatically when you've hit a dead end | [
"",
"c#",
"artificial-intelligence",
"maze",
""
] |
Actually, this question seems to have two parts:
* How to implement pattern matching?
* How to implement [send and receive](http://erlang.org/doc/reference_manual/expressions.html#6.9) (i.e. the Actor model)?
For the pattern matching part, I've been looking into various projects like [App](http://members.cox.net/nela... | One of the important things about erlang is how the features are used to make robust systems.
The send/recieve model is no-sharing, and explicitly copying.
The processes themselves are lightweight threads.
If you did desire the robust properties of the erlang model, you would be best to use real processes and IPC rat... | > As for the Actor model, there are
> existing implementations like ACT++
> and Theron, but I couldn't find
> anything but papers on the former, and
> the latter is single-threaded only.
As the author of Theron, I was curious why you believe it's single-threaded?
> Personally, I've implemented actors
> using threadin... | How would you implement Erlang-like send and receive in C++? | [
"",
"c++",
"erlang",
""
] |
I'm writing an application that is basically just a preferences dialog, much like the tree-view preferences dialog that Visual Studio itself uses. The function of the application is simply a pass-through for data from a serial device to a file. It performs many, many transformations on the data before writing it to the... | A tidier way is to create separate forms for each 'pane' and, in each form constructor, set
```
this.TopLevel = false;
this.FormBorderStyle = FormBorderStyle.None;
this.Dock = DockStyle.Fill;
```
That way, each of these forms can be laid out in its own designer, instantiated one or more times at runtime, and added to... | Greg Hurlman wrote:
> Why not just show/hide the proper container when a node is selected in the grid? Have the containers all sized appropriately in the same spot, and hide all but the default, which would be preselected in the grid on load.
Unfortunately, that's what I'm trying to avoid. I'm looking for an easy way... | How to create a tree-view preferences dialog type of interface in C#? | [
"",
"c#",
"user-interface",
""
] |
Occasionally, I've come across a webpage that tries to pop open a new window (for user input, or something important), but the popup blocker prevents this from happening.
What methods can the calling window use to make sure the new window launched properly? | If you use JavaScript to open the popup, you can use something like this:
```
var newWin = window.open(url);
if(!newWin || newWin.closed || typeof newWin.closed=='undefined')
{
//POPUP BLOCKED
}
``` | I tried a number of the examples above, but I could not get them to work with Chrome. This simple approach seems to work with Chrome 39, Firefox 34, Safari 5.1.7, and IE 11. Here is the snippet of code from our JS library.
```
openPopUp: function(urlToOpen) {
var popup_window=window.open(urlToOpen,"myWindow","tool... | How can I detect if a browser is blocking a popup? | [
"",
"javascript",
"html",
"popup",
""
] |
I discovered [template metaprogramming](http://en.wikipedia.org/wiki/Template_metaprogramming) more than 5 years ago and got a huge kick out of reading [Modern C++ Design](https://rads.stackoverflow.com/amzn/click/com/0201704315) but I never found an opertunity to use it in real life.
Have *you* ever used this techniq... | I once used template metaprogramming in C++ to implement a technique called "symbolic perturbation" for dealing with degenerate input in geometric algorithms. By representing arithmetic expressions as nested templates (i.e. basically by writing out the parse trees by hand) I was able to hand off all the expression anal... | I've found policies, described in Modern C++ Design, really useful in two situations:
1. When I'm developing a component that I expect will be reused, but in a slightly different way. Alexandrescu's suggestion of using a policy to reflect a design fits in really well here - it helps me get past questions like, "I coul... | Does anyone use template metaprogramming in real life? | [
"",
"c++",
"templates",
"template-meta-programming",
""
] |
Python works on multiple platforms and can be used for desktop and web applications, thus I conclude that there is some way to compile it into an executable for Mac, Windows and Linux.
The problem being I have no idea where to start or how to write a GUI with it, can anybody shed some light on this and point me in the... | First you will need some GUI library with Python bindings and then (if you want) some program that will convert your python scripts into standalone executables.
## Cross-platform GUI libraries with Python bindings (Windows, Linux, Mac)
Of course, there are many, but the most popular that I've seen in wild are:
* [Tk... | Another system (not mentioned in the accepted answer yet) is PyInstaller, which worked for a PyQt project of mine when py2exe would not. I found it easier to use.
<http://www.pyinstaller.org/>
Pyinstaller is based on Gordon McMillan's Python Installer. Which is no longer available. | Create a directly-executable cross-platform GUI app using Python | [
"",
"python",
"user-interface",
"deployment",
"tkinter",
"release-management",
""
] |
For parsing player commands, I've most often used the [split](http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29) method to split a string by delimiters and then to then just figure out the rest by a series of `if`s or `switch`es. What are some different ways of parsing strings i... | I assume you're trying to make the command interface as forgiving as possible. If this is the case, I suggest you use an algorithm similar to this:
1. Read in the string
* Split the string into tokens
* Use a dictionary to convert synonyms to a common form
* For example, convert "hit", "punch", "strike", and ... | I really like regular expressions. As long as the command strings are fairly simple, you can write a few regexes that could take a few pages of code to manually parse.
I would suggest you check out <http://www.regular-expressions.info> for a good intro to regexes, as well as specific examples for Java. | What are the different methods to parse strings in Java? | [
"",
"java",
"string",
"parsing",
""
] |
I'm absolutely stunned by the fact that MS just couldn't get it right to navigate to the definition of a method, when you're combining C# and VB projects in one solution. If you're trying to navigate from VB to C#, it brings up the "Object Explorer", and if from C# to VB, it generates a metadata file.
Honestly, what i... | This is general to both languages.
* F12 in VB.Net always takes you to the object browser
* F12 in C# always takes you to a meta-data definition
This is a deliberate mechanism to try and match expected behaviour for upgrading users. The C# way gives you the right information, but the VB way is what users of VBA or VB... | Make sure that your reference is to the VB *project* and not just a DLL file. | Intellisense in Visual Studio 2005 between C# and VB - can't navigate to definitions | [
"",
"c#",
"vb.net",
"visual-studio",
"intellisense",
""
] |
I have a class with a bunch of properties that look like this:
```
public string Name
{
get { return _name; }
set { IsDirty = true; _name = value; }
}
```
It would be a lot easier if I could rely on C# 3.0 to generate the backing store for these, but is there any way to factor out the IsDirty=true; so that I ... | **No. Not without writing considerably more (arcane?) code than the original version** (You'd have to use reflection to check for the attribute on the property and what not.. did I mention it being 'slower').. This is the kind of duplication I can live with.
MS has the same need for [raising events when a property is ... | You could try setting up a code snippet to make it easy to create those. | c# properties with repeated code | [
"",
"c#",
"properties",
"attributes",
""
] |
I am writing an application that needs to bring window of an external app to the foreground, and not necessarily steal focus (there is a setting the user can toggle to steal/not steal focus).
What is the best way to go about this using the win32 API? I have tried SetForeground() but it always steals focus and does not... | SetForegroundWindow is supposed to steal focus and there are certain cases where it will fail.
> The SetForegroundWindow function puts the thread that created the specified window into the foreground and activates the window. Keyboard input is directed to the window
Try capturing the focus with [SetCapture](http://ms... | > What is the difference between SetForeGroundWindow, SetActiveWindow, and BringWindowToTop? It appears as if they all do the same thing.
According to MSDN, SetForeGroundWindow will activate the window and direct keyboard focus to it. This attempts to work even when your process is in the background. SetActiveWindow d... | Bringing Window to the Front in C# using Win32 API | [
"",
"c#",
"winapi",
""
] |
I'd love to know if there is such a thing as a Gecko.NET ;) I mean, just like we can embed a WebView and that is an "instance" of IE7 inside any Windows Forms application (and tell it to `navigateto(fancy_url);`). I'd love to use Firefox or WebKit.
Anybody tried this?
**UPDATE**: Please bear in mind that although it ... | <http://code.google.com/p/geckofx/>
This is a nice .NET-wrapped version of Gecko | It certainly is possible. All you need to do is register the Mozilla ActiveX control (mozctlx.dll I believe), and you can drag it onto your form as any ActiveX control. The programming interface is similar (though not identical) to the IE one, and you can even use the Microsoft.MSHTML.dll managed library for control in... | Is it possible to Embed Gecko or Webkit in a Windows Form just like a WebView? | [
"",
"c#",
".net",
"winforms",
"webkit",
"gecko",
""
] |
C++ 0x has template aliases (sometimes referred to as template typedefs). See [here](http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates). Current spec of C++ does not.
What do you like to use as work around ? Container objects or Macros ?
Do you feel its worth it ? | > What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?
The canonical way is to use a metafunction like thus:
```
template <typename T>
struct my_string_map {
typedef std::map<std::string, T> type;
};
// Invoke:
my_string_map<int>::type my_str_int_map;
```
This is al... | > ```
> template <typename T>
> struct my_string_map : public std::map<std::string,T>
> {
> };
> ```
You shouldn't inherit from classes that do not have a virtual destructor. It's related to destructors in derived classes not being called when they should be and you could end up with unallocated memory.
That being s... | Template typedefs - What's your work around? | [
"",
"c++",
"templates",
"type-safety",
""
] |
1. Is it possible to capture Python interpreter's output from a Python script?
2. Is it possible to capture Windows CMD's output from a Python script?
If so, which librar(y|ies) should I look into? | If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standa... | I think I can point you to a good answer for the first part of your question.
> *1. Is it possible to capture Python interpreter's output from a Python
> script?*
The answer is "*yes*", and personally I like the following lifted from the examples in the *[PEP 343 -- The "with" Statement](http://www.python.org/dev/pe... | How to capture Python interpreter's and/or CMD.EXE's output from a Python script? | [
"",
"python",
"windows",
"cmd",
""
] |
By "generate", I mean auto-generation of the code necessary for a particular selected (set of) variable(s).
But any more explicit explication or comment on good practice is welcome. | Rather than using `Ctrl` + `K`, `X` you can also just type `prop` and then hit `Tab` twice. | Visual Studio also has a feature that will generate a Property from a private variable.
If you right-click on a variable, in the context menu that pops up, [click on the "Refactor" item, and then choose *Encapsulate Field...*](https://stackoverflow.com/questions/3017/how-can-we-generate-getters-and-setters-in-visual-s... | How can we generate getters and setters in Visual Studio? | [
"",
"c#",
"visual-studio",
"setter",
"getter",
""
] |
I'm using [PopBox](http://www.c6software.com/Products/PopBox/) for magnifying thumbnails on my page.
But I want my website to work even for users which turned javascript off.
I tried to use the following HTML code:
```
<a href="image.jpg">
<img src="thumbnail.jpg" pbsrc="image.jpg" onclick="Pop(...);"/>
</a>
```... | Just put the onclick on the a-tag:
```
<a href="image.jpg onclick="Pop()"; return false;"><img ...></a>
```
Make sure to return `false` either at the end of the function (here `Pop`) or inline like in the above example. This prevents the user from being redirected to the link by the `<a>`'s default behaviour. | Put the onclick event onto the link itself, and return false from the handler if you don't want the default behavior to be executed (the link to be followed) | Unobtrusive Javascript: Removing links if Javascript is enabled | [
"",
"javascript",
""
] |
We have an issue using the `PEAR` libraries on `Windows` from `PHP`.
Pear contains many classes, we are making use of a fair few, one of which is the Mail class found in `Mail.php`. We use PEAR on the path, rather than providing the full explicit path to individual PEAR files:
```
require_once('Mail.php');
```
Rathe... | having 2 files with the same name in the include path is not a good idea, rename your files so the files that you wrote have different names from third party libraries. anyway for your current situation I think by changing the order of paths in your include path, you can fix this.
PHP searches for the files in the incl... | As it's an OS level thing, I don't believe there's an easy way of doing this.
You could try changing your include from `include('Mail.php');` to `include('./Mail.php');`, but I'm not certain if that'll work on a Windows box (not having one with PHP to test on). | Including files case-sensitively on Windows from PHP | [
"",
"php",
"windows",
"apache",
"pear",
""
] |
I've seen a few attempted SQL injection attacks on one of my web sites. It comes in the form of a query string that includes the "cast" keyword and a bunch of hex characters which when "decoded" are an injection of banner adverts into the DB.
My solution is to scan the full URL (and params) and search for the presence... | I think it depends on what level you're looking to check/prevent SQL Injection at.
At the top level, you can use URLScan or some Apache Mods/Filters (somebody help me out here) to check the incoming URLs to the web server itself and immediately drop/ignore requests that match a certain pattern.
At the UI level, you c... | I don't.
Instead, I use parametrized SQL Queries and rely on the database to clean my input.
I know, this is a novel concept to PHP developers and MySQL users, but people using real databases have been doing it this way for years.
For Example (Using C#)
```
// Bad!
SqlCommand foo = new SqlCommand("SELECT FOO FROM B... | How do you check your URL for SQL Injection Attacks? | [
"",
"sql",
"sql-server",
""
] |
I've found out how to convert errors into exceptions, and I display them nicely if they aren't caught, but I don't know how to log them in a useful way. Simply writing them to a file won't be useful, will it? And would you risk accessing a database, when you don't know what caused the exception yet? | I really like [log4php](http://logging.apache.org/log4php/) for logging, even though it's not yet out of the incubator. I use log4net in just about everything, and have found the style quite natural for me.
With regard to system crashes, you can log the error to multiple destinations (e.g., have appenders whose thresh... | You could use [set\_error\_handler](http://www.php.net/manual/en/function.set-error-handler.php) to set a custom exception to log your errors. I'd personally consider storing them in the database as the default Exception handler's backtrace can provide information on what caused it - this of course won't be possible if... | How do I log uncaught exceptions in PHP? | [
"",
"php",
"exception",
"error-handling",
"error-logging",
""
] |
I'm trying to find a simple way to change the colour of the text and background in `listview` and `treeview` controls in WTL or plain Win32 code.
I really don't want to have to implement full owner drawing for these controls, simply change the colours used.
I want to make sure that the images are still drawn with pro... | Have a look at the following macros:
[ListView\_SetBkColor](http://msdn.microsoft.com/en-us/library/bb775063%28VS.85%29.aspx)
[ListView\_SetTextColor](http://msdn.microsoft.com/en-us/library/bb775116%28VS.85%29.aspx>)
[TreeView\_SetBkColor](http://msdn.microsoft.com/en-us/library/bb760036%28VS.85%29.aspx)
[TreeVi... | There are also appropriate methods of the `CListViewCtrl` and `CTreeViewCtrl` wrapper classes:
* GetBkColor
* SetBkColor | Simplest way to change listview and treeview colours | [
"",
"c++",
"winapi",
"wtl",
""
] |
How do I call a function, using a string with the function's name? For example:
```
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
``` | Given a module `foo` with method `bar`:
```
import foo
bar = getattr(foo, 'bar')
result = bar()
```
[`getattr`](https://docs.python.org/library/functions.html#getattr) can similarly be used on class instance bound methods, module-level methods, class methods... the list goes on. | * Using [`locals()`](http://docs.python.org/library/functions.html#locals), which returns a dictionary with the current local symbol table:
```
locals()["myfunction"]()
```
* Using [`globals()`](http://docs.python.org/library/functions.html#globals), which returns a dictionary with the global symbol table:
``... | Calling a function of a module by using its name (a string) | [
"",
"python",
"object",
"reflection",
""
] |
What are attributes in .NET, what are they good for, and how do I create my own attributes? | Metadata. Data about your objects/methods/properties.
For example I might declare an Attribute called: DisplayOrder so I can easily control in what order properties should appear in the UI. I could then append it to a class and write some GUI components that extract the attributes and order the UI elements appropriate... | Many people have answered but no one has mentioned this so far...
Attributes are used heavily with reflection. Reflection is already pretty slow.
It is *very worthwhile* marking your custom attributes as being `sealed` classes to improve their runtime performance.
It is also a good idea to consider where it would be... | What are attributes in .NET? | [
"",
"c#",
".net",
"glossary",
".net-attributes",
""
] |
I'm taking the leap: my PHP scripts will ALL fail gracefully!
At least, that's what I'm hoping for...`
I don't want to wrap (practically) every single line in `try...catch` statements, so I think my best bet is to make a custom error handler for the beginning of my files.
I'm testing it out on a practice page:
```
... | `set_error_handler` is designed to handle errors with codes of: `E_USER_ERROR | E_USER_WARNING | E_USER_NOTICE`. This is because `set_error_handler` is meant to be a method of reporting errors thrown by the *user* error function `trigger_error`.
However, I did find this comment in the manual that may help you:
> "The... | I guess you needs to use `register_shutdown_function` also
For example:
```
register_shutdown_function( array( $this, 'customError' ));.
function customError()
{
$arrStrErrorInfo = error_get_last();
print_r( $arrStrErrorInfo );
}
``` | How to catch undefined functions with set_error_handler in PHP | [
"",
"php",
""
] |
I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this? | If you mean you want them back as a string, in that format;
```
SELECT
CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120)
FROM customers
```
[Here are the other format options](http://msdn.microsoft.com/en-us/library/ms187928.aspx) | ```
select
datepart(month,getdate()) -- integer (1,2,3...)
,datepart(year,getdate()) -- integer
,datename(month,getdate()) -- string ('September',...)
``` | Get month and year from a datetime in SQL Server 2005 | [
"",
"sql",
"sql-server",
""
] |
I seem to remember reading something about how it is bad for structs to implement interfaces in CLR via C#, but I can't seem to find anything about it. Is it bad? Are there unintended consequences of doing so?
```
public interface Foo { Bar GetBar(); }
public struct Fubar : Foo { public Bar GetBar() { return new Bar()... | There are several things going on in this question...
It is possible for a struct to implement an interface, but there are concerns that come about with casting, mutability, and performance. See this post for more details: <https://learn.microsoft.com/en-us/archive/blogs/abhinaba/c-structs-and-interface>
In general, ... | Since no one else explicitly provided this answer I will add the following:
**Implementing** an interface on a struct has no negative consequences whatsoever.
Any *variable* of the interface type used to hold a struct will result in a boxed value of that struct being used. If the struct is immutable (a good thing) th... | Is it safe for structs to implement interfaces? | [
"",
"c#",
"interface",
"struct",
""
] |
We've occasionally been getting problems whereby our long-running server processes (running on Windows Server 2003) have thrown an exception due to a memory allocation failure. Our suspicion is these allocations are failing due to memory fragmentation.
Therefore, we've been looking at some alternative memory allocatio... | First, I agree with the other posters who suggested a resource leak. You really want to rule that out first.
Hopefully, the heap manager you are currently using has a way to dump out the actual total free space available in the heap (across all **free** blocks) and also the total number of blocks that it is divided ov... | I think you’ve mistakenly ruled out a memory leak too early.
Even a tiny memory leak can cause a severe memory fragmentation.
Assuming your application behaves like the following:
Allocate 10MB
Allocate 1 byte
Free 10MB
(oops, we didn’t free the 1 byte, but who cares about 1 tiny byte)
This seems like a very ... | How to solve Memory Fragmentation | [
"",
"c++",
"windows",
"memory",
""
] |
I would like to save the programs settings every time the user exits the program. So I need a way to call a function when the user quits the program. How do I do that?
I am using Java 1.5. | You can add a shutdown hook to your application by doing the following:
```
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
// what you want to do
}
}));
```
This is basically equivalent to having a try {} finally {} block around your entire program, and basically ... | Adding a shutdown hook [addShutdownHook(java.lang.Thread)](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html#addShutdownHook(java.lang.Thread)) is probably what you look for. There are problems with that approach, though:
* you will lose the changes if the program aborts in an uncontrolled way (i.e. if it... | Calling function when program exits in java | [
"",
"java",
"events",
""
] |
Is there any feasible way of using generics to create a Math library that does not depend on the base type chosen to store data?
In other words, let's assume I want to write a Fraction class. The fraction can be represented by two ints or two doubles or whatnot. The important thing is that the basic four arithmetic op... | Here is a way to abstract out the operators that is relatively painless.
```
abstract class MathProvider<T>
{
public abstract T Divide(T a, T b);
public abstract T Multiply(T a, T b);
public abstract T Add(T a, T b);
public abstract T Negate(T a);
public virtual T Subtra... | I believe this answers your question:
<http://www.codeproject.com/KB/cs/genericnumerics.aspx> | Creating a Math library using Generics in C# | [
"",
"c#",
"generics",
"interface",
"math",
""
] |
I have a cross-platform (Python) application which needs to generate a JPEG preview of the first page of a PDF.
On the Mac I am spawning [sips](http://web.archive.org/web/20090309234215/http://developer.apple.com:80/documentation/Darwin/Reference/ManPages/man1/sips.1.html). Is there something similarly simple I can do... | ImageMagick delegates the PDF->bitmap conversion to GhostScript anyway, so here's a command you can use (it's based on the actual command listed by the `ps:alpha` delegate in ImageMagick, just adjusted to use JPEG as output):
```
gs -q -dQUIET -dPARANOIDSAFER -dBATCH -dNOPAUSE -dNOPROMPT \
-dMaxBitmap=500000000 -dLast... | You can use ImageMagick's convert utility for this, see some examples in [http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html](https://web.archive.org/web/20120413111338/http://studio.imagemagick.org/pipermail/magick-users/2002-May/002636.html)
:
> ```
> Convert taxes.pdf taxes.jpg
> ```
>
> Will... | Get a preview JPEG of a PDF on Windows? | [
"",
"python",
"windows",
"image",
"pdf",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.