Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Syntactic sugar for properties for example in C#:
```
private int x;
public int X{
get { return x; }
set { x = value; }
}
```
or simply
```
public int X{ get; set; }
```
I am missing verbatim strings in java... @"C:\My Documents\" instead of "C:\\My Documents\\"
Do you agree Java needs more "sugar"? Any ... | While I don't necessarily agree with Java's philosophy, I think that adding lots of **syntactic sugar** to Java would go against its philosophy. Java is supposed to be a very simple, easy to reason about language with few constructs, kind of a lowest common denominator *lingua franca* in the programming community. It w... | "Syntactic sugar causes cancer of the semicolon."
-- Alan Perlis. Epigrams on Programming. | I want more syntactic sugar in my Java! | [
"",
"java",
"syntactic-sugar",
""
] |
I have a business user who tried his hand at writing his own SQL query for a report of project statistics (e.g. number of tasks, milestones, etc.). The query starts off declaring a temp table of 80+ columns. There are then almost 70 UPDATE statements to the temp table over almost 500 lines of code that each contain the... | First off, if this is not causing a business problem, then leave it until it becomes a problem. Wait until it becomes a problem, then fix everything.
When you do decide to fix it, check if there is one statement causing most of your speed issues ... issolate and fix it.
If the speed issue is over all the statements, ... | First thing I would do is check to make sure there is an active index maintenance job being run periodically. If not, get all existing indexes rebuilt or if not possible at least get statistics updated.
Second thing I would do is set up a trace (as described [here](https://stackoverflow.com/questions/257906/ms-sql-ser... | Refactoring "extreme" SQL queries | [
"",
"sql",
"sql-server-2005",
"refactoring",
""
] |
The question has been asked: [No PHP for large projects? Why not?](https://stackoverflow.com/questions/385203/no-php-for-large-projects-why-not) It's a recurring theme and PHP developers--with some cause--are forced to [defend PHP](https://stackoverflow.com/questions/309300/defend-php-convince-me-it-isnt-horrible).
Al... | For the most part, the problems with php are not so much with the language. The problems come from the coupling of a low barrier of entry and the lack of any infrastructure to avoid common programming problems or security problems. Its a language that, by itself, is pretty quick-and-dirty. Nevertheless, it still has ma... | Using PHP for large projects isn't different than with any other language. You need experience and knowledge in writing [maintainable](http://www.php.net/zend-engine-2.php) and [extendable](http://framework.zend.com/) source code. You need to be aware of [security pitfalls](http://phpsec.org/projects/guide/) and [perfo... | How to use PHP for large projects? | [
"",
"php",
""
] |
How would you access the cache from a jQuery ajax call?
I'm using jquery to do some data verification and quick data access. I have a static web-method that jquery is calling via json to return a value. I don't want to call to the database everytime so I'd like to cache the data I'm hitting, but I can't determine how ... | `System.Web.HttpContext.Current.Cache`
Cache is shared per app domain - not per Page. Page just has a [convenience property of Page.Cache](http://msdn.microsoft.com/en-us/library/system.web.ui.page.cache.aspx) to get the current Cache, which means you can just do Cache["key"] from a method in a page.
As you've notice... | I think calling a PageMethod may be the best you can really do, if you really want to do this:
<http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/> | Is there a way to access a cache or session from a static method? | [
"",
"c#",
"asp.net",
"jquery",
"ajax",
"dynamic",
""
] |
Edit: Warning - I now realize that the following technique is generally regarded as a bad idea because it creates hidden dependencies for the sake of looking neat.
---
I recently discovered that you can use the StackTrace to infer information about the caller of a method.
This enables you to create a seemingly "cool... | There's two reasons why not to do this:
* It's slow
* It's creates a brittle solution.
If you wanted to do this, you'd better off using a tool that supports Aspect Oriented Programming, such as Castle's Dynamic Proxy. | Another problem is that the compiler may "inline" your method in the optimisation process, e.g.
```
void MethodA() {
MethodB();
}
void MethodB() {
foo();
}
```
becomes:
```
void MethodA() {
foo();
}
```
This is obviously a problem because the immediately caller for foo is nolonger MethodB, but instead Me... | Using The StackTrace To Infer The Caller Of A Method | [
"",
"c#",
"stack-trace",
""
] |
Say a class
```
Person
+Name: string
+Contacts: List<Person>
```
I want to be able to check if a person has a contact with a certain name without having to create a dummy Person instance.
```
person.Contacts.Contains<string>("aPersonName");
```
This should check all persons in the Contacts list if their Name.Eq... | It's probably easiest to use [Enumerable.Any](http://msdn.microsoft.com/en-us/library/bb534972.aspx):
```
return person.Contacts.Any(person => person.Name=="aPersonName");
```
Alternatively, project and then contain:
```
return person.Select(person => person.Name).Contains("aPersonName");
``` | I'm assuming the Contacts is the Contacts for the person in question (person in your code snippit)
List has a contains method that takes an object of type T as a parameter and returns true or false if that object exists in the list. What your wanting is IList.Exists method, Which takes a predicate.
example (c# 3.0)
... | Contains<T>() and how to implement it | [
"",
"c#",
"linq",
""
] |
## Background
I have an application written in native C++ over the course of several years that is around 60 KLOC. There are many many functions and classes that are dead (probably 10-15% like the similar Unix based question below asked). We recently began doing unit testing on all new code and applying it to modified... | Ask the linker to remove unreferenced objects (/OPT:REF). If you use function-level linking, and verbose linker output, the linker output will list every function it can prove is unused. This list may be far from complete, but you already have the tools needed. | We use [Bullseye](http://www.bullseye.com/coverage.html), and I can recommend it. It doesn't need to be run from a unit test environment, although that's what we do. | Automated Dead code detection in native C++ application on Windows? | [
"",
"c++",
"windows",
"visual-studio-2005",
"code-coverage",
"dead-code",
""
] |
I have a model that looks like this:
```
class Category(models.Model):
name = models.CharField(max_length=60)
class Item(models.Model):
name = models.CharField(max_length=60)
category = models.ForeignKey(Category)
```
I want select count (just the count) of items for each category, so in SQL it would be ... | Here, as I just discovered, is how to do this with the Django 1.1 aggregation API:
```
from django.db.models import Count
theanswer = Item.objects.values('category').annotate(Count('category'))
``` | (**Update**: Full ORM aggregation support is now included in [Django 1.1](http://docs.djangoproject.com/en/dev/releases/1.1/#aggregate-support). True to the below warning about using private APIs, the method documented here no longer works in post-1.1 versions of Django. I haven't dug in to figure out why; if you're on... | Django equivalent for count and group by | [
"",
"python",
"django",
""
] |
I'm building a fairly simple PHP script that will need to send some emails with attachments. I've found these 2 libraries to do this.
Does either one have significant advantages over the other? Or should I just pick one at random and be done with it? | I was going to say that PHPMailer is no longer developed, and Swift Mailer is. But when I googled ...
<https://github.com/PHPMailer/PHPMailer>
That suggests its being worked on again.
I've used PHPMailer a lot, and its always been solid and reliable. I had recently started using Swift Mailer, for the above reason, a... | Whatever the features are, they have variety in their applicable licenses:
PHPMailer - LGPL 2.1 (<https://github.com/PHPMailer/PHPMailer>)
SwiftMailer - MIT license (<https://github.com/swiftmailer/swiftmailer>) | PhpMailer vs. SwiftMailer? | [
"",
"php",
"email",
"attachment",
"phpmailer",
"swiftmailer",
""
] |
Can someone explain to me why my code:
```
string messageBody = "abc\n" + stringFromDatabaseProcedure;
```
where valueFromDatabaseProcedure is not a value from the SQL database entered as
```
'line1\nline2'
```
results in the string:
```
"abc\nline1\\nline2"
```
This has resulted in me scratching my head somewhat... | I just did a quick test on a test NorthwindDb and put in some junk data with a \n in middle. I then queried the data back using straight up ADO.NET and what do you know, it does in fact escape the backslash for you automatically. It has nothing to do with the n it just sees the backslash and escapes it for you. In fact... | ASP.NET would use `<br />` to make linebreaks. `\n` would work with Console Applications or Windows Forms applications. Are you outputting it to a webpage?
**Method #1**
```
string value = "line1<br />line2";
string messageBody = "abc<br />" + value;
```
If that doesn't work, try:
```
string value = "line1<br>line2... | Newlines escaped unexpectedly in C#/ASP.NET 1.1 code | [
"",
"c#",
"asp.net",
""
] |
I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.
How can I do this? | See the [locale](https://docs.python.org/3/library/locale.html) module.
This does currency (and date) formatting.
```
>>> import locale
>>> locale.setlocale( locale.LC_ALL, '' )
'English_United States.1252'
>>> locale.currency( 188518982.18 )
'$188518982.18'
>>> locale.currency( 188518982.18, grouping=True )
'$188,51... | ## New in 2.7
```
>>> '{:20,.2f}'.format(18446744073709551616.0)
'18,446,744,073,709,551,616.00'
```
<http://docs.python.org/dev/whatsnew/2.7.html#pep-0378> | Currency formatting in Python | [
"",
"python",
"formatting",
"currency",
""
] |
What would you suggest as a replacement to the Maven Java build toolset? Just plain Ant scripts? SCons? | While I like the **idea** of Maven, I always find myself fighting it for anything but the simplest configurations. Its architecture is plugin-based, and the quality of the plugins varies widely. Documentation is sketchy at best; half the time I can't figure out if the doc I'm reading is for Maven 1 or 2. And how often ... | It depends on what you use anyway. Maven 1? Maven 2? I find Maven 2 decently documented, and quite powerful, when used in combination with Ant tasks and some home baked Java plugins.
There are Ant tasks to use Maven features from Ant: <http://maven.apache.org/ant-tasks/index.html> . So you don't really need to write y... | Maven replacement? | [
"",
"java",
"maven-2",
"build",
"continuous-integration",
""
] |
This is a sql newbie question.
Basically, I want an extra column to return with my select statement to number the rows.
I'm using mysql.
Eg:
```
select * from friends
David
Steve
Joe
```
What is the syntax to get:
```
1 David
2 Steve
3 Joe
``` | From: <http://markmal.blogspot.com/2006/04/oracle-like-rownum-in-mysql.html>
```
SELECT @rownum:=@rownum+1 rownum, t.*FROM (SELECT @rownum:=0) r, mytable t;
``` | In SQL Server 2005 and higher you can use the [Row\_Number](http://msdn.microsoft.com/en-us/library/ms186734.aspx) function. | SQL a numbering column - MySQL | [
"",
"sql",
"mysql",
""
] |
I want to create a unique id but `uniqid()` is giving something like `'492607b0ee414'`. What i would like is something similar to what tinyurl gives: `'64k8ra'`. The shorter, the better. The only requirements are that it should not have an obvious order and that it should look prettier than a seemingly random sequence ... | Make a small function that returns random letters for a given length:
```
<?php
function generate_random_letters($length) {
$random = '';
for ($i = 0; $i < $length; $i++) {
$random .= chr(rand(ord('a'), ord('z')));
}
return $random;
}
```
Then you'll want to call that until it's unique, in pse... | @[gen\_uuid()](https://stackoverflow.com/a/1516430/4061501) by gord.
preg\_replace got some nasty utf-8 problems, which causes the uid somtimes to contain "+" or "/".
To get around this, you have to explicitly make the pattern utf-8
```
function gen_uuid($len=8) {
$hex = md5("yourSaltHere" . uniqid("", true));
... | Short unique id in php | [
"",
"php",
"uniqueidentifier",
"unique-index",
""
] |
After tinkering around to solve [this][1] problem, I think the core of the problem is the following:
When you use the Html.RadioButton() html helper with an Enum as value field, you can only choose your option once. AFter reposting the page, the helpers will ignore the value set in the call and set all radio buttons t... | This is due to a bug in the ASP.NET MVC Beta code. I wrote a full explanation of the issue at asp.net MVC forum. Refer to this [link](http://forums.asp.net/t/1338576.aspx) | In case anybody cares here is a real quick and dirty work around in anticipation for the next update of the framework. It only regexreplaces the value with your value.
It's not unit tested, not guaranteed not whatever.
Put it in your HtmlHelper class library or wherever you put HtmlHelper extentions.
add the following... | Html.RadioButton sets all values to selected value | [
"",
"c#",
"html-helper",
"asp.net-mvc-beta1",
""
] |
Sometimes it seems natural to have a default parameter which is an empty list. However, [Python produces unexpected behavior in these situations](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument).
For example, consider this function:
```
def my_func(working_list=[]):
... | ```
def my_func(working_list=None):
if working_list is None:
working_list = []
# alternative:
# working_list = [] if working_list is None else working_list
working_list.append("a")
print(working_list)
```
[The docs](https://docs.python.org/reference/compound_stmts.html#function-definitio... | Other answers have already already provided the direct solutions as asked for, however, since this is a very common pitfall for new Python programmers, it's worth adding the explanation of why Python behaves this way, which is nicely summarized in [*The Hitchhikers Guide to Python*](https://docs.python-guide.org/writin... | How can I avoid issues caused by Python's early-bound default parameters (e.g. mutable default arguments "remembering" old data)? | [
"",
"python",
"default-parameters",
""
] |
I need to use lists for my program and needed to decide if I use std::vector or std::list.
The problem with vector is that there is no remove method and with list that there is no operator []. So I decided to write my own class extending std::list and overloading the [] operator.
My code looks like this:
```
#include... | All template code should be put in header file. This fill fix linking problems (that's the simplest way).
The reason it happens is because compilers compiles every source (.cc) file separately from other files. On the other hand it needs to know what code exactly it needs to create (i.e. what is the T in template is su... | Depending on your needs, you should use `std::vector` (if you need often appends/removes at the end, and random access), or `std::deque` (if you need often appends/removes at the end or at the beginning, and your dataset is huge, and still want random access). Here is a good picture showing you how to make the decision... | Extending std::list | [
"",
"c++",
"templates",
"list",
"linker",
""
] |
Is it possible to set the DataContext property of a usercontrol after the user control has been loaded, and force the usercontrol to rebind? | I'm pretty sure that if you just set the datacontext again, it will rebind | If you need to do extra work when the DataContext changes you can use a custom DependencyProperty and bind it to the DataContext property. Use the DependencyPropertyChangedEventHandler to know when the DP changed.
For a more complete explanation see my blog post at <http://msmvps.com/blogs/theproblemsolver/archive/200... | Silverlight: How to force binding after setting the DataContext property | [
"",
"c#",
".net",
"silverlight",
"data-binding",
""
] |
I have several functions that I wrote and I use regularly on my servers, is there a way I can add them to the core so I don't have to include them from external files?
I am running PHP5 | You could add your libraries as a [PEAR](http://pear.php.net/) extension. Then you could add it to your [local PEAR repository](http://kuziel.info/log/archives/2006/04/01/Installation-of-local-PEAR-repository). Pear is added to the default include path in php.ini. Then you can just use "pear install myextension" on you... | I've done this before.. it's a fairly involved process, but not too bad. This article at zend.com should tell you everything you need to know:
<http://devzone.zend.com/303/extension-writing-part-i-introduction-to-php-and-zend/>
edit: I should add that there are better ways to achieve the essence of what you're trying... | Adding functions to PHP core | [
"",
"php",
"deployment",
"pear",
"pecl",
""
] |
I would like to do something like the following:
```
def add(a, b):
#some code
def subtract(a, b):
#some code
operations = [add, subtract]
operations[0]( 5,3)
operations[1](5,3)
```
In python, is it possible to assign something like a function pointer? | Did you try it? What you wrote works exactly as written. Functions are first-class objects in Python. | Python has nothing called pointers, but your code works as written. Function are first-class objects, assigned to names, and used as any other value.
You can use this to implement a Strategy pattern, for example:
```
def the_simple_way(a, b):
# blah blah
def the_complicated_way(a, b):
# blah blah
def foo(wa... | function pointers in python | [
"",
"python",
"function-pointers",
""
] |
I have a table structure that looks like:
```
<table>
<tr id="row1">
<td>
<div>row 1 content1</div>
</td>
<td>
<div>row 1 content2</div>
</td>
<td>
<div>row 1 content3</div>
</td>
</tr>
<tr id="row2">
<td>
<div>row 2 content1</div>
</td>
<td>
<div>row 2 content2</... | jQuery always returns a set of elements. Sometimes, the set is empty. Sometimes, it contains only one element. The beauty of this is that you can write code to work the same way regardless of how many elements are matched:
```
$("selector").each(function()
{
this.style.backgroundColor = "red";
});
```
Fun! | If you prefer keeping a jQuery object, you may write instead:
```
$("selector").first().val()
``` | How do I select a single element in jQuery? | [
"",
"javascript",
"jquery",
""
] |
This is a purely theoretical question.
Given three simple classes:
```
class Base {
}
class Sub extends Base {
}
class SubSub extends Sub {
}
```
And a function meant to operate on these classes:
```
public static void doSomething(Base b) {
System.out.println("BASE CALLED");
}
public static void doSomething... | The formal specification can be found in [part 15.12.2.5 of the Java Language Specification (JLS)](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#301183). Thanks to generics this is pretty complicated, so you might want to look at [same section of the first edition of the JLS](http://java.sun.co... | As far as I know, Java and C++ make this decision at compilation time (since these are static functions that are not dynamically dispatchable) based on the most specific matching that they can make. If your static type is SubSub and you have an overload that takes SubSub, this is the one that will be invoked. I'm fairl... | How does Java pick which overloaded function to call? | [
"",
"java",
"inheritance",
"programming-languages",
"function",
""
] |
The GUI for managing plugins in Eclipse got a bit of an overhaul in version 3.4.0.
This GUI is accessed via the "Software Updates..." option in the Help menu.
The option to remove the selected Mylyn plugin is greyed out. In fact, this is true of virtually every installed plugin. I know that the Mylyn plugins are optio... | **The following text is quoted from the Eclipse help docs:**
The Uninstall wizard allows you to review and uninstall items in your configuration. This wizard is shown when you select items and press Uninstall... from the Installed Software page. To uninstall software from your system:
1. Click *Help > About and then ... | And just to update it for Helios - Eclipse 3.6
`Help->Install New Software` at the bottom of dialog there is link `What is already installed` once you click on that you will get list of installed plugins and `Uninstal...` button | How to uninstall plugins in Eclipse 3.4.X or higher | [
"",
"java",
"eclipse",
"ide",
"plugins",
"eclipse-plugin",
""
] |
Say I have three classes:
```
class X{};
class Y{};
class Both : public X, public Y {};
```
I mean to say I have two classes, and then a third class which extends both (multiple-inheritance).
Now say I have a function defined in another class:
```
void doIt(X *arg) { }
void doIt(Y *arg) { }
```
and I call this fun... | Simple: if it's ambiguous, then the compiler gives you an error, forcing you to choose. In your snippet, you'll get a different error, because the type of `new Both()` is a pointer to `Both`, whereas both overloads of `doIt()` accept their parameters by value (i.e. they do not accept pointers). If you changed `doIt()` ... | I get this error with gcc:
```
jeremy@jeremy-desktop:~/Desktop$ g++ -o test test.cpp
test.cpp: In function ‘int main(int, char**)’:
test.cpp:18: error: call of overloaded ‘doIt(Both&)’ is ambiguous
test.cpp:7: note: candidates are: void doIt(X)
test.cpp:11: note: void doIt(Y)
``` | How does C++ pick which overloaded function to call? | [
"",
"c++",
"inheritance",
"programming-languages",
"function",
"multiple-inheritance",
""
] |
How do I extract a double value from a string using regex.
```
import re
pattr = re.compile(???)
x = pattr.match("4.5")
``` | Here's the easy way. Don't use regex's for built-in types.
```
try:
x = float( someString )
except ValueError, e:
# someString was NOT floating-point, what now?
``` | A regexp from the [`perldoc perlretut`](http://perldoc.perl.org/perlretut.html#Building-a-regexp):
```
import re
re_float = re.compile("""(?x)
^
[+-]?\ * # first, match an optional sign *and space*
( # then match integers or f.p. mantissas:
\d+ # start out with a ...
... | Extract float/double value | [
"",
"python",
"regex",
""
] |
I have a goal to build an application with UI that would run on both Windows Mobile and "normal" desktop Windows. The priority is for it to "look good" under Windows Mobile, and for desktop Windows it is OK if it distorted. Before I invest days trying, I would like to hear if that is possible to begin with. There are s... | 1. The CF **contains** a subset of the full framework (FFx), but it is not a pure subset. There are actually several things available in the CF that aren't in the FFx, which makes it a bit more difficult. CF apps also, except in the most rudimentary cases, use P/Invoke. Those calls are never the same from the desktop t... | P.S. I found the poster online - it'll show you all the classes that are CF. I ordered it fro Microsoft because Kinkos wanted $65 to print it out in color for me! Microsoft sent me a couple of copies free - all I had to do was ask:
<http://www.microsoft.com/downloads/details.aspx?familyid=7B645F3A-6D22-4548-A0D8-C2A27... | Common C# source code for Windows and Windows Mobile | [
"",
"c#",
".net",
"winapi",
"windows-mobile",
"compact-framework",
""
] |
I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.
How can I do this? | You can convert a string to a 32-bit signed integer with the `int` function:
```
string = "1234"
i = int(string) # i is a 32-bit integer
```
If the string does not represent an integer, you'll get a `ValueError` exception. Note, however, that if the string does represent an integer, but that integer does not fit int... | Python only has a single `int` type. To convert a string to an `int`, use `int()` like this:
```
>>> str = '123'
>>> num = int(str)
>>> num
123
```
**Edit:** Also to convert to float, use `float()` in the exact same way. | Typecasting in Python | [
"",
"python",
"string",
"int",
"bit",
"casting",
""
] |
I have a base class in which I want to specify the methods a child class must have, but not implement them itself. However, the methods in a child class may have a different number of paramaters to the definition in the base class.
Having tried this with an abstract method, php doesn't allow this. Is it possible? | Short of specifying the abstract method with no parameters and requiring the subclassed method to access the args through func\_get\_args, I don't see how this would be possible. | The child class's function can add extra, optional arguments to the signature without it causing errors:
```
abstract class Foo {
abstract function bar($a);
}
class NewFoo extends Foo {
function bar($a, $b = null) {
//do something
}
}
``` | Can I specify a non strict method requirement for child classes? | [
"",
"php",
"oop",
"abstract-class",
""
] |
I have simple regex
```
"\".*\""
```
for me its says select everything between " and ", but it also catches
```
"text") != -1 || file.indexOf(".exe"
```
for me its two strings, for regex its one. how can i make regex to see that its two strings?
P.S. I'm using Java. | That's the non-greedy form:
```
".*?"
```
The `*?` means: "Match as little as possible", while the `*` alone means "Match as much as possible".
The latter basically goes on until the end of the string, giving characters back one by one so the final `"` can match. That's why you get everything between the first and t... | Regular expressions are "greedy". What you want to do is exclude quotes from the middle of the match, like
```
"\"[^\"]*\""
``` | Error in Regex for String | [
"",
"java",
"regex",
""
] |
I have a ListBox and I want to add a context menu to each item in the list. I've seen the "solution" to have the right click select an item and suppress the context menu if on white space, but this solution feels dirty.
Does anyone know a better way? | This way the menu will pop up next to the mouse
```
private string _selectedMenuItem;
private readonly ContextMenuStrip collectionRoundMenuStrip;
public Form1()
{
var toolStripMenuItem1 = new ToolStripMenuItem {Text = "Copy CR Name"};
toolStripMenuItem1.Click += toolStripMenuItem1_Click;
var toolStripMen... | Just to elaborate a little further to what Frans has said...Even though the ListBox owns the ContextMenuStrip, you can still customize the items in the menu strip at the time it's opening. Thus customizing it's contents based on the mouse position within the listbox.
The example below selects the item in the listbox b... | How can I add a context menu to a ListBoxItem? | [
"",
"c#",
"winforms",
"listbox",
"contextmenu",
""
] |
I recently took my Db initiating code out of the \_\_construct of my Page class and placed it just after I initiate the Page class. I removed it from within the Page class because I want to be able to access it from anywhere (other classes for example). It also takes server, username, password and database arguments to... | A global of some sort (Be that global variables, singleton or some other variant) is an improvement over your previous approach, and as such you're on the right track. Generally speaking though, you should try to minimise the scope of program state (For a number of reasons, which I won't get into here). Having a global... | Global variables do have a use, and this would be one of them. Unless it's likely that you're going to be needing multiple database connections, (or even still), then I don't see a problem with setting up a global $db object.
An alternative way is to have a static "Factory" class which you can use to get the object. I... | PHP - Where is the best place to initiate a database class? | [
"",
"php",
"oop",
""
] |
In python, is there a difference between calling `clear()` and assigning `{}` to a dictionary? If yes, what is it?
Example:
```
d = {"stuff":"things"}
d.clear() #this way
d = {} #vs this way
``` | If you have another variable also referring to the same dictionary, there is a big difference:
```
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}
```
This is because assigning `d = {}` creates a new, empty dictionary and assi... | `d = {}` will create a new instance for `d` but all other references will still point to the old contents.
`d.clear()` will reset the contents, but all references to the same instance will still be correct. | Difference between dict.clear() and assigning {} in Python | [
"",
"python",
"dictionary",
""
] |
I'm programming in PHP and would like to create web pages which have email addresses that are easily read by humans but not easily harvested by spammers. The email addresses are coming from user input, and I think I can identify an address by using a regular expression, but I'm not clear exactly how I should replace th... | You can obfuscate it using CSS as well...
```
<span class="email-encrypt">moc.liamelgoog@avynnib<span class="email-decrypt-message">(Reverse this text to get my Email address)</span></span>
/*Decrypt Email */
.email-encrypt {
unicode-bidi:bidi-override;
direction: rtl;
}
.email-encrypt .email-decrypt-message ... | ## Use [GD](https://www.php.net/gd) and create image of your Email ID
You can use the [PHP GD library](https://www.php.net/gd) to easily create an image of any given text.
A sample code will look like,
```
<?php
header("Content-type: image/png");
$im = @imagecreate(110, 20)or die("Cannot Initialize new GD image ... | How can I use PHP to obfuscate email addresses so they are not easily harvested by spammers? | [
"",
"php",
"regex",
"spam-prevention",
"email-spam",
""
] |
I have a class Agent with a property Id
Given a collection of Agents I need to check if any of them have duplicate Ids.
I am currently doing this with a hash table but am trying to get Linq-ified, what's a good way of doing this? | Similar to Y Low's approach,
**Edited:**
```
var duplicates = agents.GroupBy(a => a.ID).Where(a=>a.Count() > 1);
foreach (var agent in duplicates)
{
Console.WriteLine(agent.Key.ToString());
}
``` | For what it's worth, I just compared the two methods we've struck upon in this thread. First I defined a helper class:
```
public class Foo
{
public int ID;
}
```
... and then made a big list of instances with a random ID:
```
var list = new List<Foo>();
var r = new Random();
for (int i = 0; i < 10000; i++) li... | LINQy way to check if any objects in a collection have the same property value | [
"",
"c#",
"linq",
""
] |
I'm working a piece of code to turn phone numbers into links for mobile phone - I've got it but it feels really dirty.
```
import re
from string import digits
PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_. ]{0,1}\d{4})')
def numbers2links(s):
result = ""
last_match_index = 0
... | Nice first take :) I think this version is a bit more readable (and probably a teensy bit faster). The key thing to note here is the use of [re.sub](http://docs.python.org/library/re.html#module-contents). Keeps us away from the nasty match indexes...
```
import re
PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-... | Why not re-use the work of others - for example, from [RegExpLib.com](http://regexlib.com/REDetails.aspx?regexp_id=458)?
My second suggestion is to remember there are other countries besides the USA, and quite a few of them have telephones ;-) Please don't forget us during your software development.
Also, there is a ... | US-format phone numbers to links in Python | [
"",
"python",
"regex",
"mobile-website",
"phone-number",
""
] |
I am working through some of the exercises in The C++ Programming Language by Bjarne Stroustrup. I am confused by problem 11 at the end of Chapter 12:
> (\*5) Design and implement a library for writing event-driven simulations. Hint: <task.h>. ... An object of class task should be able to save its state and to have th... | > Hint: <task.h>.
is a reference to an old cooperative multi-tasking library that shipped with [early versions of CFront](http://www.softwarepreservation.org/projects/c_plus_plus#release_e) (you can also download at that page).
If you read the paper "[A Set of C++ Classes for Co-routine Style Programming](http://www.... | Here's my understanding of an "event-driven simulation":
* A controller handles an event queue, scheduling events to occur at certain times, then executing the top event on the queue.
* Events ocur instantaneously at the scheduled time. For example, a "move" event would update the position and state of an entity in th... | Event-driven simulation class | [
"",
"c++",
"simulation",
"event-driven",
""
] |
I would like to be able to refactor out the **OrderBy** clause in a linq expression.
Here is an example of a refactor of the **where** clause
before:
```
results = ctx.ActiveUsers
.Where(u => u.CompanyID != 1 &&
(u.LastName.ToLower().Contains(searchString)
|| u.Email.ToLower().Contains(sear... | Assuming you want to actually take a string such as "LastName", "FirstName" etc, I'd do something like:
```
var unordered = ctx.ActiveUsers
.Where(Employee.GetExpression(searchString))
.OrderBy(ordering)
.Select(u => new Employee {
ID = u.... | thanks jon,
that answer put me on the right path for now... However,
I need to preserve the **ThenBy** clause in my order. so while the solution below is not dynamic it still preserves the **ThenBy**
```
var unordered = ctx.ActiveUsers
.Where(Employee.GetExpression(searchString))
... | refactoring the OrderBy expression | [
"",
"c#",
"linq",
"lambda",
""
] |
A recent [question came up](https://stackoverflow.com/questions/349659/stringformat-or-not) about using String.Format(). Part of my answer included a suggestion to use StringBuilder.AppendLine(string.Format(...)). Jon Skeet suggested this was a bad example and proposed using a combination of AppendLine and AppendFormat... | I view `AppendFormat` followed by `AppendLine` as not only more readable, but also more performant than calling `AppendLine(string.Format(...))`.
The latter creates a whole new string and then appends it wholesale into the existing builder. I'm not going to go as far as saying "Why bother using StringBuilder then?" bu... | Just create an extension method.
```
public static StringBuilder AppendLine(this StringBuilder builder, string format, params object[] args)
{
builder.AppendFormat(format, args).AppendLine();
return builder;
}
```
Reasons I prefer this:
* Doesn't suffer as much overhead as `AppendLine(string.Format(...))`, a... | When do you use StringBuilder.AppendLine/string.Format vs. StringBuilder.AppendFormat? | [
"",
"c#",
".net",
"formatting",
"stringbuilder",
""
] |
I've been doing quite a bit of debugging of managed applications lately using both Visual Studio and WinDbg, and as such I'm often ask to assist colleagues in debugging situations. On several occasions I have found people aho just insert break points here and there and hope for the best. In my experience that is rarely... | One very best practice is not diving into debugger immediately but look at the code and *think hard* for some time. | If there was one tip I could give to everyone about debugging it would be to break it again.
That is, when you think you've found the fix and the system seems to work. Back the fix out and see if the system breaks again.
Sometimes you can get lost in the sequence of what you've tried as potential solutions and you fi... | Best practices for debugging | [
"",
"c#",
".net",
"debugging",
""
] |
I have two computers. Both running WinXP SP2 (I don't really know ho similar they are beyond that). I am running MS Visual C# 2008 express edition on both and that's what I'm currently using to program.
I made an application that loads in an XML file and displays the contents in a DataGridView.
The first line of my x... | I'm not sure of the cause of your problem, but one solution would be to to just strip out the carriage returns from your strings. For every string you add, just call `TrimEnd(null)` on it to remove trailing whitespace:
```
newrow["topic"] = att1.ToString().TrimEnd(null);
```
If your strings might end in other whitesp... | This doesn't have to do with UTF-8 or character encodings - this problem has to do with [line endings](http://en.wikipedia.org/wiki/Line_ending). In Windows, each line of a text file ends in the two characters carriage-return (CR) and newline (LF, for line feed), which are code points U+000D and U+000A respectively. In... | I think this is some kind of encoding problem | [
"",
"c#",
"xml",
"encoding",
"datagridview",
""
] |
# Background
In a C# command-line app I'm writing, several of the parameters have "yes" and "no" as the possible values.
I am storing their input using the Enum type shown below.
```
enum YesNo
{
Yes,
No
}
```
Which is fine - the code works. No problem there.
NOTE: Yes, I could store these as bool (that'... | I'd suggest you use a name that indicates the Value which is set to Yes or No.
E.G.
```
public enum Married
{
YES,
NO
}
``` | You say you don't want to use bool because it will be printed out for the user to see amongst other contents. That suggests the problem isn't in *storage* but in *display*. By all means present true/false as Yes/No, but there's no need to create a whole new type for it IMO.
EDIT: In addition to suggesting you don't us... | What's a good name for an Enum for Yes & No values | [
"",
"c#",
"coding-style",
"naming-conventions",
"naming",
""
] |
With jQuery, how do I find out which key was pressed when I bind to the keypress event?
```
$('#searchbox input').bind('keypress', function(e) {});
```
I want to trigger a submit when `ENTER` is pressed.
**[Update]**
Even though I found the (or better: one) answer myself, there seems to be some room for variation ;... | Actually this is better:
```
var code = e.keyCode || e.which;
if(code == 13) { //Enter keycode
//Do something
}
``` | Try this
```
$('#searchbox input').bind('keypress', function(e) {
if(e.keyCode==13){
// Enter pressed... do anything here...
}
});
``` | jQuery Event Keypress: Which key was pressed? | [
"",
"javascript",
"jquery",
"events",
"bind",
"keypress",
""
] |
I'm writing a java app using eclipse which references a few external jars and requires some config files to be user accessable.
1. What is the best way to package it up for deployment?
2. My understanding is that you cant put Jars inside another jar file, is this correct?
3. Can I keep my config files out of the jars ... | There is no one 'best way'. It depends on whether you are deploying a swing application, webstart, applet, library or web application. Each is different.
On point 2, you are correct. Jar files cannot contain other jar files. (Well, technically they can, its just that the inner jar file won't be on your classpath, effe... | (1) An alternative to ant that you may wish to consider is [maven](http://maven.apache.org/).
A brief intro to maven can be found [here](http://maven.apache.org/run-maven/index.html).
For building a JAR, maven has the [jar](http://maven.apache.org/maven-1.x/plugins/jar/properties.html) plugin, which can automate the ... | Whats best way to package a Java Application with lots of dependencies? | [
"",
"java",
"eclipse",
"deployment",
""
] |
```
Type.GetType("System.String")
```
Is there a lookup for the aliases available somewhere?
```
Type.GetType("string")
```
returns `null`. | This is not possible programmatically, since the 'aliases' are in fact keywords introduced in C#, and `Type.GetType` (like every other framework method) is part of the language-independent framework.
You could create a dictionary with the following values:
```
bool System.Boolean
byte System.Byte
... | The "aliases" are part of the language definition. You need to look them up in the [language spec](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx) in question. They are compiled away, and don't exist at runtime - string becomes System.String, int becomes System.Int32, etc. | Possible to get type of an aliased type in c#? | [
"",
"c#",
"c#-3.0",
""
] |
I read somewhere that one should never use error conditions as normal program flow. Makes excellent sense to me... But
C# application sitting on top of a MySQL db. I need to parse a string value into two parts, an ID, and a value. (The original data come from a Devonian database), then validate the value against a loo... | You shouldn't be calling ToString() at that point, first you should check if the value returned is null;
```
object productName = productAdapter.GetProductName(product_id);
if ( productName != null )
{
s_product = productName.ToString();
}
else
{
s_product = String.Empty;
}
``` | In addition to the recommendations of Rob and Marc, and based on your code above, I'd suggest another tweak; I'd be really surprised if `productAdapter.GetProductName()` doesn't *already* return a `String`, in which case calling ToString() on it is utterly redundant. If it does indeed already return a `String`, then yo... | How to Avoid Throwing An Error When SQL Select Returns Nothing | [
"",
"c#",
"mysql",
"null",
"catch-block",
""
] |
I frequently make use of `Request.QueryString[]` variables.
In my `Page_load` I often do things like:
```
int id = -1;
if (Request.QueryString["id"] != null) {
try
{
id = int.Parse(Request.QueryString["id"]);
}
catch
{
... | Below is an extension method that will allow you to write code like this:
```
int id = request.QueryString.GetValue<int>("id");
DateTime date = request.QueryString.GetValue<DateTime>("date");
```
It makes use of `TypeDescriptor` to perform the conversion. Based on your needs, you could add an overload which takes a d... | Use int.TryParse instead to get rid of the try-catch block:
```
if (!int.TryParse(Request.QueryString["id"], out id))
{
// error case
}
``` | How do you test your Request.QueryString[] variables? | [
"",
"c#",
"coding-style",
"tryparse",
"isnumeric",
"request.querystring",
""
] |
Is it possible to have a C static library API, which uses C++ internally and hide this from users of the library?
I have writen a portable C++ library I wish to statically link to an iPhone application.
I have created an Xcode project using the Max OS X 'static library' template, and copied the source across, as well... | It's too hard to do this in comments, so I'm just going to demonstrate for you quickly what the linking issues are that you're having. When Xcode encounters files, it uses build rules based on the suffix to decide which compiler to use. By default, gcc links the files to the standard C library, but does not link with t... | You should declare the functions you want to be visible `extern "C"`. Their signatures need to be C-compatible, but the contents do not (you may access C++ objects, for instance, but you cannot pass them directly; pointers are okay). The symbols will then be visible to any C-compatible environment.
EDIT: And compile i... | Using C/C++ static libraries from iPhone ObjectiveC Apps | [
"",
"c++",
"c",
""
] |
I remember reading in some Java book about any operator other than 'instanceof' for comparing the type hierarchy between two objects.
instanceof is the most used and common. I am not able to recall clearly whether there is indeed another way of doing that or not. | Yes, there is. Is not an operator but a method on the Class class.
Here it is:
[isIntance(Object o )](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isInstance(java.lang.Object))
Quote from the doc:
> *...This method is the dynamic equivalent of the Java language instanceof operator*
```
public class So... | You can also, for reflection mostly, use `Class.isInstance`.
```
Class<?> stringClass = Class.forName("java.lang.String");
assert stringClass.isInstance("Some string");
```
Obviously, if the type of the class is known at compile-time, then `instanceof` is still the best option. | Is there any way other than instanceof operator for object type comparison in java? | [
"",
"java",
""
] |
In Python, is there a portable and simple way to test if an executable program exists?
By simple I mean something like the `which` command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with `Popen` & al and see if it fails (that's what I'm doing now, but ... | Easiest way I can think of:
```
def which(program):
import os
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ.get("PATH"... | I know this is an ancient question, but you can use `distutils.spawn.find_executable`. This has been [documented since python 2.4](http://docs.python.org/release/2.4/dist/module-distutils.spawn.html) and has existed since python 1.6.
```
import distutils.spawn
distutils.spawn.find_executable("notepad.exe")
```
Also, ... | Test if executable exists in Python? | [
"",
"python",
"path",
""
] |
Does anyone know the query the last synchronization date from sql server (2008).
It is the same information displayed in replication monitor, but I want to be able to get that date from a query. | You can see a lot of info about merge sessions by using the system table msMerge\_sessions:
```
select * from msMerge_sessions
```
Depending on the info you need, use the other system tables available in your database. | I created a view like this to get last date by the subscriber
```
select subscriber_name, max(start_time) as last_sync
from msMerge_sessions inner join msMerge_agents
on msmerge_agents.id = msmerge_sessions.agent_id
group by subscriber_name
```
I called the view 'LastSync' - I then joined that view like this to... | sql server replication - get last synchronization date from query | [
"",
"sql",
"sql-server",
"synchronization",
"replication",
""
] |
I have a MS SQL table that I don't have any control over and I need to write to. This table has a int primary key that isn't automatically incremented. I can't use stored procs and I would like to use Linq to SQL since it makes other processing very easy.
My current solution is to read the last value, increment it, tr... | That looks like an expensive way to get the maximum ID. Have you already tried
```
var maxId = dc.Logs.Max(s => s.ID);
```
? Maybe it doesn't work for some reason, but I really *hope* it does...
(Admittedly it's more than possible that SQL Server optimises this appropriately.)
Other than that, it looks okay (smelly... | You didn't indicate whether your app is the only one inserting into the table. If it is, then I'd fetch the max value once right after the start of the app/webapp and use Interlocked.Increment on it every time you need next ID (or simple addition if possible race conditions can be ruled out). | Correctly incrementing values using Linq to SQL | [
"",
"c#",
"linq-to-sql",
"auto-increment",
""
] |
I have some data. I want to go through that data and change cells (for example - Background color), if that data meets a certain condition. Somehow, I've not been able to figure it out how to do this seemingly easy thing in Silverlight. | This is slightly old code (from before RTM), but does something like what you're looking for. It checks some data on an object in a row and then sets the colour of the row accordingly.
**XAML:**
```
<my:DataGrid x:Name="Grid" Grid.Row="1" Margin="5" GridlinesVisibility="None" PreparingRow="Grid_PreparingRow">
<my... | Actually this won't work in all examples. See these links for the 'proper' way of achieving this
<http://silverlight.net/forums/p/27465/93474.aspx#93474>
<http://silverlight.net/forums/t/27467.aspx> | Silverlight Datagrid: Changing cell styles, based on values | [
"",
"c#",
"silverlight",
"datagrid",
"cells",
""
] |
I am trying to help a small business that has an application that could benefit from occasional (or temporary) database expertise. The problem is, this company has all their IP in this database, so they are rightfully hesitant to give someone access it.
They would typically meet and gain trust in person, but the talen... | As the others have mentioned, NDA's are a good idea, that covers you from the standpoint of WHAT they see...
However, I can feel that you are also concerned about any potential "damage" the person could do to your database if they make mistakes. To get around, and protect from this is a bit harder, but there a few goo... | The simplest thing is requiring all employees and contractors who see the database, or its design, to sign non-disclosure agreements. There are plenty of boilerplate ones there, and a good attorney can provide guidance on what you'd need in one with less than an hour of billing time. Everyone in the industry is used to... | How do I find trustworthy database help out on the interweb? | [
"",
"sql",
"database",
""
] |
```
public static IQueryable<TResult> ApplySortFilter<T, TResult>(this IQueryable<T> query, string columnName)
where T : EntityObject
{
var param = Expression.Parameter(typeof(T), "o");
var body = Expression.PropertyOrField(param,columnName);
var sortExpression = Expression.Lambda(body, param);
return query.... | We did something similar (not 100% the same, but similar) in a LINQ to SQL project. Here's the code:
```
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) {
var type = typeof(T);
var property = type.GetProperty(ordering);
var parameter = Expression.P... | You can also use Dynamic Linq
Info here
<http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx>
C# download here
<http://msdn.microsoft.com/en-us/vcsharp/bb894665.aspx>
Then just add the using Linq.Dynamic; and you automatically get 2 additional extension met... | How do I apply OrderBy on an IQueryable using a string column name within a generic extension method? | [
"",
"c#",
".net",
"linq",
"entity-framework",
"expression-trees",
""
] |
Is it possible to use a DB sequence for some column that **is not the identifier/is not part of a composite identifier**?
I'm using hibernate as jpa provider, and I have a table that has some columns that are generated values (using a sequence), although they are not part of the identifier.
What I want is to use a se... | Looking for answers to this problem, I stumbled upon [this link](http://forum.hibernate.org/viewtopic.php?p=2405140)
It seems that Hibernate/JPA isn't able to automatically create a value for your non-id-properties. The `@GeneratedValue` annotation is only used in conjunction with `@Id` to create auto-numbers.
The `@... | I found that `@Column(columnDefinition="serial")` works perfect but only for PostgreSQL. For me this was perfect solution, because second entity is "ugly" option.
A call to `saveAndFlush` on the entity is also necessary, and `save` won't be enough to populate the value from the DB. | Hibernate JPA Sequence (non-Id) | [
"",
"java",
"hibernate",
"jpa",
"sequence",
""
] |
I have been working on a script with PHP4 that relies on NuSOAP. Now, I'm trying to move this to PHP5, and use the buildin support for SOAP there.
```
$wsdlPath = ""; // I have obviously set these variables to something meaningful, just hidden for the sake of security
$apiPath = "";
$username = "";
$password = "";
... | Make sure NuSoap and PHPv5-SOAP are running on the same server. If I'm not totally wrong, both libraries uses the same class-name. Maybe it will work better if you make sure none NuSopa-files are included? And also verify that the SOAP-library are loaded:
```
if(!extension_loaded('soap')){
dl('soap.so'); // Actually... | Without testing it, I have two suggestions:
First, put your error\_reporting to the highest possible (before creating the SoapClient):
```
error_reporting( E_ALL );
```
If there's something wrong with the authentication on the server's side, PHP will throw warnings. In most of the cases, it will tell you, what has g... | Moving from NuSOAP to PHP5 SOAP | [
"",
"php",
"soap",
"wsdl",
"port",
"nusoap",
""
] |
Assuming that writing nhibernate mapping files is not a big issue....or polluting your domain objects with attributes is not a big issue either....
what are the pros and cons?
is there any fundamental technical issues? What tends to influence peoples choice?
not quite sure what all the tradeoffs are. | The biggest pro of AR is that it gives you a ready-made repository and takes care of session management for you. Either of `ActiveRecordBase<T>` and `ActiveRecordMediator<T>` are a gift that you would have ended up assembling yourself under NHibernate. Avoiding the XML mapping is another plus. The AR mapping attributes... | I found ActiveRecord to be a good piece of kit, and very suitable for the small/medium projects I've used it for. Like Rails, it makes many important decisions for you, which has the effect of keeping you focused you on the meat of the problem.
In my opinion pro's and cons are:
**Pros**
* Lets you focus on problem i... | Whats the pros and cons of using Castle Active Record vs Straight NHibernate? | [
"",
"c#",
"nhibernate",
"castle-activerecord",
""
] |
I am getting this linker error.
> **mfcs80.lib(dllmodul.obj) : error LNK2005: \_DllMain@12 already defined in MSVCRT.lib(dllmain.obj)**
Please tell me the correct way of eliminating this bug. I read solution on microsoft support site about this bug but it didnt helped much.
I am using VS 2005 with Platform SDK | If you read the linker error thoroughly, and apply some knowledge, you may get there yourself:
The linker links a number of compiled objects and libraries together to get a binary.
Each object/library describes
* what symbols it expects to be present in other objects
* what symbols it defines
If two objects define ... | I had the same error message, but none of the answers here solved it for me.
So if you Encounter that Problem when creating a DLL Project that uses MFC, it can be resolved by entering the following line:
`extern "C" { int __afxForceUSRDLL; }`
to the cpp file where `DllMain` is defined. Then your own `DllMain` impleme... | error LNK2005: _DllMain@12 already defined in MSVCRT.lib | [
"",
"c++",
"visual-c++",
"linker",
""
] |
I often find linq being problematic when working with custom collection object.
They are often defened as
The base collection
```
abstract class BaseCollection<T> : List<T> { ... }
```
the collections is defined as
```
class PruductCollection : BaseCollection<Product> { ... }
```
Is there a better way to add resul... | The problem is that LINQ, through extension methods on `IEnumerable<T>`, knows how to build Arrays, Lists, and Dictionaries, it doesn't know how to build your custom collection. You could have your custom collection have a constructor that takes an `IEnumerable<T>` or you could write you. The former would allow you to ... | I can suggest you a way in that you don't have to enumerate the collection 2 times:
```
abstract class BaseCollection<T> : List<T>
{
public BaseCollection(IEnumerable<T> collection)
: base(collection)
{
}
}
class PruductCollection : BaseCollection<Product>
{
public PruductCollection(IEnumerabl... | Linq with custom base collection | [
"",
"c#",
"linq",
""
] |
What is the best resource for learning the features and benefits of windbg? I want to be able to discuss investigate memory issues (handles, objects), performance issues, etc . . . | These are some I like:
* [Maoni Stephens and Claudio Caldato's article on MSDN](http://msdn.microsoft.com/en-us/magazine/cc163528.)
* [Maoni's blog](http://blogs.msdn.com/maoni/) (it is not updated recently but it contains a lot of useful material)
* [Tess Fernandez](http://blogs.msdn.com/tess/) has a a LOT of info re... | Good resources here too!
<http://bartdesmet.net/blogs/bart> | What is the best resource for learning the features and benefits of windbg? | [
"",
"c#",
"debugging",
"windbg",
""
] |
I need to access a mysql database from c# code but I would prefer not to use ODBC for the reasons below.
I have to create a demo and I am using xampp on a USB drive. My code (database Read/Write code) is written in C#. So to keep the USB drive isolated from the computer that the demo runs on I am moving away from ODBC... | <http://dev.mysql.com/downloads/connector/net/5.2.html>
Last time I tried it it worked fine but if you need to connect to, for example, MySQL and SQL Server you'll need to duplicate the code once using SqlConnection and the other using MysqlConnection. | You'll probably want to use the [MySQL .Net connector](http://dev.mysql.com/downloads/connector/net/5.2.html) | what is the best way to use c# with mysql without using odbc | [
"",
"c#",
"mysql",
""
] |
I was searching here about converting a string like "16:20" to a DateTime type without losing the format, I said I dont want to add dd/MM/yyy or seconds or AM/PM, because db just accept this format.
I tried with Cultures yet
Thanks in Advance | All DateTime objects must have a date and a time.
If you want just the time, use TimeSpan:
```
TimeSpan span = TimeSpan.Parse("16:20");
```
If you want a DateTime, add that time to the min value:
```
TimeSpan span = TimeSpan.Parse("16.20");
DateTime dt = DateTime.MinValue.Add(span);
// will get you 1/1/1900 4:20 PM... | Just give a date format to your dateTime.
`string DateFormat = "yyyy MM d "` this willl give you the **year month and day**. after continuing;
`string DateFormat = "yyyy MM d HH:mm:ss "` in here the **Capital H** will give you the `24 hours time format` and lowerCase `"h" will give you the 12 hours time` format...
wh... | DateTime Format like HH:mm 24 Hours without AM/PM | [
"",
"c#",
"datetime",
"formatting",
""
] |
I have a list of input words separated by comma. I want to sort these words by alphabetical and length. How can I do this without using the built-in sorting functions? | Good question!! Sorting is probably the most important concept to learn as an up-and-coming computer scientist.
There are actually lots of different algorithms for sorting a list.
When you break all of those algorithms down, the most fundamental operation is the comparison of two items in the list, defining their "na... | Create a console application and paste this into the Program.cs as the body of the class.
```
public static void Main(string[] args)
{
string [] strList = "a,b,c,d,e,f,a,a,b".Split(new [] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string s in strList.Sort())
Console.WriteLine(s);
}
publ... | How can I sort an array of strings? | [
"",
"c#",
"arrays",
""
] |
I would need to create a temp table for paging purposes. I would be selecting all records into a temp table and then do further processing with it.
I am wondering which of the following is a better approach:
1) Select all the columns of my Primary Table into the Temp Table and then being able to select the rows I wou... | If you have a non-trivial amount of rows (more than 100) than a table variable's performance is generally going to be worse than a temp table equivalent. But test it to make sure.
Option 2 would use less resources, because there is less data duplication.
Tony's points about this being a dirty read are really somethin... | With approach 1, the data in the temp table may be out of step with the real data, i.e. if other sessions make changes to the real data. This may be OK if you are just viewing a snapshot of the data taken at a certain point, but would be dangerous if you were also updating the real table based on changes made to the te... | SQL - Temp Table: Storing all columns in temp table versus only Primary key | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I am currently reading "Beginning CakePHP:From Novice to Professional" by David Golding. At one point I have to use the CLI-command "cake bake", I get the welcome-screen but when I try to bake e.g. a Controller I get the following error messages:
```
Warning: mysql_connect(): Can't connect to local MySQL server throug... | From the error, it looks like it's trying to connect to an actual IP address and not a UNIX socket, look:
```
'/Applications/MAMP/tmp/mysql/mysql.sock:3306'
```
It's appending a port to the socket, which is wrong.
So, I'd first try to configure MySQL to listen to TCP/IP requests (edit the proper section in my.cnf) ... | I find the solution to this problem :
Add a socket config in the cakephp app/config/database.php file
```
class DATABASE_CONFIG {
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'localhost',
'port' => '/Applications/MAMP/tmp/mysql/mysql.sock', // here is the key !
'logi... | How do I get CakePHP bake to find mysql.sock and recognize MySQL while using MAMP on Mac OSX? | [
"",
"php",
"mysql",
"cakephp",
""
] |
In the past I've written sites in ASP.NET just to get nice reusable templating via master pages (layouts) and user controls (partials). I'm talking about sites that have no more complicated code in them than simple variable substitution in templates - I'm just using it to keep my HTML organized. It's great to be able t... | > I just want something that will let me
> properly modularize the HTML of my
> site.
Look at <http://code.google.com/p/hoduli/>
With that simple tool you'll be able to write like this:
```
<h:define name="header">
some header contents
</h:define>
...
<h:header />
<h:include file="middle_part.php" />
<h:footer... | [Zend\_View](http://framework.zend.com/manual/en/zend.view.html) supports layouts, partials and placeholders. Also checkout a new templating language called [Dwoo](http://dwoo.org) which is similar to Smarty but also takes some ideas from Django templating. And finally, [Calypso](http://www.beberlei.de/calypso/) which ... | Simple web page layout and templating in PHP | [
"",
"php",
"html",
"templates",
""
] |
I have a base class vehicle and some children classes like car, motorbike etc.. inheriting from vehicle.
In each children class there is a function Go();
now I want to log information on every vehicle when the function Go() fires, and on that log I want to know which kind of vehicle did it.
Example:
```
public class ... | Calling [`GetType()`](http://msdn.microsoft.com/en-us/library/system.object.gettype.aspx) from Vehicle.Go() would work - but only if Go() was actually called.
One way of enforcing this is to use the [template method pattern](http://en.wikipedia.org/wiki/Template_method_pattern):
```
public abstract class Vehicle
{
... | this.GetType() will give you the type of the current instance | In C#, can I know in the base class what children inherited from me? | [
"",
"c#",
".net",
"inheritance",
""
] |
Good morning,
Apologies for the newbie question. I'm just getting started with ASP.NET internationalization settings.
Background info:
I have a website which displays a `<table>` HTML object. In that `<table>` HTML object, I have a column which displays dates. My server being in the US, those dates show up as `MM/DD... | A couple of points:
* The <globalization> element also needs the attribute culture="auto". The uiCulture attribute affects the language used to retrieve resources. The culture attribute affects the culture used for formatting numbers an dates.
* As noted in [this MSDN article](http://msdn.microsoft.com/en-us/library/b... | You can allow the browser to set your UI culture automatically if you wish, by opening up the web.config, like this:
```
<configuration>
<system.web>
<globalization uiCulture="auto" />
...
```
And then the culture set by the browser will be automatically set in your app. This means that when you ... | ASP.NET Globalization -- Displaying dates | [
"",
"c#",
"asp.net",
"internationalization",
"globalization",
""
] |
I have read a lot of popular standards manuals for open source PHP projects.
A lot enforce underscores for variables spaces, and a lot enforce camelCase.
Should global functions and variables be named differently to class methods/properties?
I know the most important thing is consistency, but I'd like to hear some t... | I find camelCase a little more pleasant to type, because I find the underscore a bit awkward to type.
Don't use global variables.
I avoid procedural coding in PHP, I find OOP is easier to keep things organized. Besides, doesn't PHP have enough stuff in it's global namespace already?
Generally I try to stick to:
* C... | In PHP itself, almost every native function is underscore separated. Most of the PHP code examples in the documentation are underscore separated.
In most languages I think Camel or Pascal Casing is more appropriate, but I think there's clear history for using underscore separation in PHP. | PHP - Function/variable naming | [
"",
"php",
"naming-conventions",
""
] |
I'm thinking about how limiting it is for AJAX apps to have to poll for updates, when what would be ideal is for javascript to be able to set up a real two way connection to the server. I'm wondering if there is some method of integrating javascript with a browser plugin that can make a tcp connection so that I could p... | Here is an implementation with a similar approach:
* [socketjs](http://sly.w3m.hu/socketjs)
It uses a Java Applet and bridges its API to JavaScript, interesting...
And here another one:
* [jSocket](http://code.google.com/p/jsocket/)
This one is a wrapper of the Actionscript 3 Socket API, bridged to JavaScript... | [WebSockets](http://en.wikipedia.org/wiki/WebSockets) is designed to solve this problem. | How can I communicate over TCP sockets from JavaScript? | [
"",
"javascript",
"ajax",
"user-interface",
"sockets",
""
] |
I'm developing a PHP website that uses url routing. I'd like the site to be directory independent, so that it could be moved from <http://site.example.com/> to <http://example.com/site/> without having to change every path in the HTML. The problem comes up when I'm linking to files which are not subject to routing, lik... | You could put in the head
```
<base href="<?php echo url::base(); ?>" />
```
This will mean the browser will request any non-absolute URLs relative to that path. However I am not sure how this would affect URLs embedded in CSS files etc. This does not affect paths defined in CSS files. (thanks mooware) | The `<base>` thing will work but you need to remember it's going to affect your `<a>` tags too. Consider this example.:
```
<!-- this page is http://oursite.com/index.html -->
<html>
<head>
<base href="http://static.oursite.com/" />
</head>
<body>
<img src="logo.gif" alt="this is http://static.oursite.com/l... | How to keep a website with url routing directory independent | [
"",
"php",
"url-routing",
""
] |
When you run a JUnit 4 ParameterizedTest with the Eclipse TestRunner, the graphical representation is rather dumb: for each test you have a node called `[0]`, `[1]`, etc.
Is it possible give the tests `[0]`, `[1]`, etc. explicit names? Implementing a `toString` method for the tests does not seem to help.
(This is a fo... | JUnit4 now [allows specifying a name attribute](https://github.com/junit-team/junit/wiki/Parameterized-tests) to the Parameterized annotation, such that you can specify a naming pattern from the index and toString methods of the arguments. E.g.:
```
@Parameters(name = "{index}: fib({0})={1}")
public static Iterable<Ob... | I think there's nothing *built in* in jUnit 4 to do this.
I've implemented a solution. I've built my own `Parameterized` class based on the existing one:
```
public class MyParameterized extends TestClassRunner {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Para... | ParameterizedTest with a name in Eclipse Testrunner | [
"",
"java",
"eclipse",
"unit-testing",
"junit",
"parameterized-unit-test",
""
] |
Right now we just use something like this
```
stopWatch.Start();
try
{
method();
}
finally
{
stopWatch.Stop();
}
```
Which works fine for synchronous methods, but some are executing asynchronously, so the time is skewed when m... | Hmm, from Jon Skeet's answer to this question:
[Timing a line of code accurately in a threaded application, C#](https://stackoverflow.com/questions/252793/timing-a-line-of-code-accurately-in-a-threaded-application-c)
And also this article:
<http://lyon-smith.org/blogs/code-o-rama/archive/2007/07/17/timing-code-on-wi... | The stopwatch should measure time spent only in one thread. You would need to run a separate instance on every thread. This would give you probably the closes results to what you want.
Alternatively (preferred option if you want to monitor the whole application, and not just some methods), there are various performanc... | How do you measure code block (thread) execution time with multiple concurrent threads in .NET | [
"",
"c#",
".net",
"performance",
"multithreading",
"measurement",
""
] |
The docs for [Dictionary.TryGetValue](http://msdn.microsoft.com/en-us/library/bb347013.aspx) say:
> When this method returns, [the value argument] contains the value associated with the specified key, if the key is found; otherwise, the **default value for the type of the value parameter**. This parameter is passed un... | You are looking for this:
```
default(T);
```
so:
```
public T Foo<T>(T Bar)
{
return default(T);
}
``` | ```
default(T);
``` | default value for generic type in c# | [
"",
"c#",
"generics",
"default-value",
""
] |
Say I have the following code:
```
function One() {}
One.prototype.x = undefined;
function Two() {}
var o = new One();
var t = new Two();
```
`o.x` and `t.x` will both evaluate to `undefined`. `o.hasOwnProperty('x')` and `t.hasOwnProperty('x')` will both return false; the same goes for `propertyIsEnumerable`. Two q... | A slightly simpler way than your method is to use the [Javascript in operator](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/in_Operator)
```
alert('x' in o); // true
alert('x' in t); // false
``` | object.hasOwnProperty(name) only returns true for objects that are in the same object, and false for everything else, including properties in the prototype.
```
function x() {
this.another=undefined;
};
x.prototype.something=1;
x.prototype.nothing=undefined;
y = new x;
y.hasOwnProperty("something"); //false
y.hasO... | JavaScript - Identify whether a property is defined and set to 'undefined', or undefined | [
"",
"javascript",
"object",
"properties",
"undefined",
""
] |
Hi I'm very new to sql but have been passed a job in which I need to query the db(MS SQL 2005) I need to return all workers where a HeadID is given.(tables below)
So I need to get all the managers that match the HeadID and then all the workers that match those managers by ManagerID. How would I do this? Any help or any... | A simple way would be to do something like this:
```
select * from tb_Worker
join tb_Manager on tb_Worker.ManagerID = tb_Manager.ManagerID
join tb_Head on tb_Manager.HeadID = Head.HeadID
where tb_Head.HeadID = <given value>
```
Tune your table names and select columns as appropriate. | Use common table expression
```
USE AdventureWorks;
GO
WITH DirectReports(ManagerID, EmployeeID, EmployeeLevel) AS
(
SELECT ManagerID, EmployeeID, 0 AS EmployeeLevel
FROM HumanResources.Employee
WHERE ManagerID IS NULL
UNION ALL
SELECT e.ManagerID, e.EmployeeID, EmployeeLevel + 1
FROM HumanRes... | Nested Select statement? | [
"",
"sql",
"sql-server",
""
] |
The example below throws an InvalidOperationException, "Collection was modified; enumeration operation may not execute." when executing the code.
```
var urls = new List<string>();
urls.Add("http://www.google.com");
foreach (string url in urls)
{
// Get all links from the url
List<string> newUrls = GetLinks(u... | You can't, basically. What you really want here is a queue:
```
var urls = new Queue<string>();
urls.Enqueue("http://www.google.com");
while(urls.Count != 0)
{
String url = url.Dequeue();
// Get all links from the url
List<string> newUrls = GetLinks(url);
foreach (string newUrl in newUrls)
{
... | There are three strategies you can use.
1. Copy the List<> to a second collection (list or array - perhaps use ToArray()). Loop through that second collection, adding urls to the first.
2. Create a second List<>, and loop through your urls List<> adding new values to the second list. Copy those to the original list wh... | How to add items to a collection while consuming it? | [
"",
"c#",
".net",
""
] |
I'm trying to make some types in Django that map to standard Django types. The [custom model field documentation](http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields) goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.
... | I'd do this with a subclass of Django's PositiveIntegerField:
```
from django.db import models
class Card(object):
"""The ``Card`` class you described."""
...
class CardField(models.PositiveIntegerField):
__metaclass__ = models.SubfieldBase
def get_db_prep_value(self, value):
"""Return the `... | Why can't you do something like the following?
```
class Card(models.Model):
""" A playing card. """
self.suit = models.PositiveIntegerField()
self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES )
def as_number(self):
""" returns a number from 1 (Ace of Clubs) and 52 (King of Spades)... | How do I create trivial customized field types in Django models? | [
"",
"python",
"django",
"django-models",
""
] |
I want to display documents on my website. The server is hosted on a Debian machine. I was thinking I can allow the upload of support documents then use a Linux app or PHP app to convert the doc into PDF and display that in an HTML page. Are there any APIs or binaries that allow me to do this? | If it is an office document, one option would be to use openoffice in headless mode. See here for a python script that shows how: <http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html>
If it is any other kind of document (e.g. your own XML document), then you would need to do a bit more work. I... | You can create a PDF print-to-file printer and send any number of documents to the printer via lpr.
```
function lpr($STR,$PRN,$TITLE) {
$prn=(isset($PRN) && strlen($PRN))?"$PRN":C_DEFAULTPRN ;
$title=(isset($TITLE))?"$TITLE":"stdin" . rand() ;
$CMDLINE="lpr -P $prn -T $title";
$pipe=popen("$CMDLINE... | How to convert documents to PDF on a Linux/PHP stack? | [
"",
"php",
"linux",
"pdf",
""
] |
I have the table (Product\_Id, category priority, atribute1, atribute2...) in MS Access, and I am trying to make a query that orders the data grouped by Category and ordered by the highest priority. Priority can be Null, so it should be placed at the end.
Example:
Table
```
1, 100, 2, atr1, atr2
2, 300, , atr1, atr2
... | In Jet SQL, this may suit:
```
SELECT t2.MinOfPriority, tn.Field2, Nz([tn.Field3],999) AS Priority,
tn.Field4, tn.Field5
FROM tn
INNER JOIN (SELECT Min(Nz(tn.Field3,999)) AS MinOfPriority, tn.Field2
FROM tn GROUP BY tn.Field2) AS t2 ON tn.Field2 = t2.Field2
ORDER BY t2.MinOfPriority, tn.Field2, N... | The easiest solution (not necessarily the best in some cases) is to use column numbers in your ordering expressions:
```
SELECT t2.MinOfPriority,
tn.Field2,
Nz([tn.Field3],999) AS Priority,
tn.Field4,
tn.Field5
ORDER BY 1,2,3
``` | How to Order a SQL Query with grouped rows | [
"",
"sql",
"ms-access",
"sql-order-by",
""
] |
Below is my table, a User could have multiple profiles in certain languages, non-English profiles have a higher priority.
```
+----------+--------+----------------+----------------+
|ProfileID |UserID |ProfileLanguage |ProfilePriority |
+----------+--------+----------------+----------------+
|1 |1 |en-U... | This may work, if profilepriority and userid could be a composite unique key;
```
select p.* from Profile p join
(SELECT UserID, MIN(ProfilePriority) AS ProfilePriority
FROM Profile
WHERE ProfileLanguage = 'en-US' OR ProfilePriority = 2
GROUP BY UserID) tt
on p.userID = tt.UserID and p.ProfilePriority = tt.ProfilePri... | ```
SELECT *
FROM Profile as tb1 inner join
(SELECT UserID, MIN(ProfilePriority) AS ProfilePriority
FROM Profile
WHERE ProfileLanguage = 'es-MX' OR ProfilePriority = 2
GROUP BY UserID) as tb2 on
tb1.userid = tb2.userid and tb1.ProfilePriority = tb2.ProfilePriority
```
Enter all the columns you require in separated wi... | SQL expression problem | [
"",
"sql",
"group-by",
"expression",
""
] |
I have the following method in my code:
```
private bool GenerateZipFile(List<FileInfo> filesToArchive, DateTime archiveDate)
{
try
{
using (ZipOutputStream zipStream = new ZipOutputStream(File.Create(GetZipFileName(archiveDate))))
{
zipStream.SetLevel(9); // maximum compression.
... | I used to use SharpZipLib until I switched to [DotNetZip](http://www.codeplex.com/DotNetZip) You may want to check it out as an alternative.
Example:
```
try
{
using (ZipFile zip = new ZipFile("MyZipFile.zip")
{
zip.AddFile("c:\\photos\\personal\\7440-N49th.png");
zip.AddFile("c:\\Desktop\\... | See the post by [Tyler Holmes](http://blog.tylerholmes.com/2008/12/windows-xp-unzip-errors-with.html)
The issue with Winzip 8.0 and others is with Zip64. Set the original file size when adding the ZipEntry and the error goes away.
e.g.
```
string fileName = ZipEntry.CleanName(fi.Name);
ZipEntry entry = new ZipEntry(... | Basics of SharpZipLib. What am I missing? | [
"",
"c#",
".net",
".net-2.0",
"compression",
"sharpziplib",
""
] |
JavaScript does funky automatic conversions with objects:
```
var o = {toString: function() {return "40"; }};
print(o + o);
print((o+1)+o);
print((o*2) + (+o));
```
will print:
```
4040
40140
120
```
This is because +, if any of the arguments are objects/strings, will try to convert all the arguments to strings the... | From [ECMAScript Language Specification](http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)
> ## 11.3 Postfix Expressions
>
> **Syntax**
>
> PostfixExpression :
>
> * LeftHandSideExpression
> * LeftHandSideExpression [no LineTerminator here] ++
> * LeftHandSideExpression [no LineTerminator here... | The following code illustrates this well:
```
var a = {toString: function() {return "40"; }};
nl(typeof a);
nl(typeof +a);
nl(typeof a);
nl(typeof (a++));
nl(a);
nl(typeof a);
```
The output is:
```
object
number
object
number
41
number
```
Unary plus converts the object to a number and doesn't modify it. a++ first... | How does JavaScript treat the ++ operator? | [
"",
"javascript",
"operators",
"type-conversion",
"coercion",
""
] |
I am writing a website with PHP. Since it will need to be accessed by anyone on the network to access the internet I have to create a mobile version. How do I best check if it's a mobile device? I don't want to have a switch statement with 50 devices at the end since I don't only want to support the iPhone.
Is there a... | You need to check several headers that the client sends, such as USER\_AGENT and HTTP\_ACCEPT. Check out [this article](http://mobiforge.com/developing/story/lightweight-device-detection-php) for a comprehensive detection script for mobile user-agents in PHP. | You should look at [Tera-WURFL](http://www.tera-wurfl.com), it is a PHP & MySQL-based software package that detects mobile devices and their capabilities. Here is the Tera-WURFL code that you would use to detect if the visiting device is mobile:
```
<?php
require_once("TeraWurfl.php");
$wurflObj = new TeraWurfl();
$wu... | How do I determine whether it's a mobile device with PHP? | [
"",
"php",
"mobile",
""
] |
I have a XML with a structure similar to this:
```
<category>
<subCategoryList>
<category>
</category>
<category>
<!--and so on -->
</category>
</subCategoryList>
</category>
```
I have a Category class that has a `subcategory` list (`List<Category>`). I'm trying to parse this ... | [This link](http://www.roseindia.net/tutorials/xPath/java-xpath.shtml) has everything you need. In shorts:
```
public static void main(String[] args)
throws ParserConfigurationException, SAXException,
IOException, XPathExpressionException {
DocumentBuilderFactory domFactory =
DocumentBuilderF... | I believe the XPath expression for this would be "`//category/subCategoryList/category`". If you just want the children of the root `category` node (assuming it is the document root node), try "`/category/subCategoryList/category`". | Parsing XML with XPath in Java | [
"",
"java",
"xml",
"xpath",
""
] |
What is the smartest way to get an entity with a field of type List persisted?
## Command.java
```
package persistlistofstring;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
impo... | Use some JPA 2 implementation: it adds a @ElementCollection annotation, similar to the Hibernate one, that does exactly what you need. There's one example [here](http://jazzy.id.au/2008/03/24/jpa_2_0_new_features_part_1.html).
**Edit**
As mentioned in the comments below, the correct JPA 2 implementation is
```
javax... | Should anyone be looking for an alternative solution where you store your string lists as one field in your database, here's how I solved that. Create a Converter like this:
```
import java.util.Arrays;
import java.util.List;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import sta... | How to persist a property of type List<String> in JPA? | [
"",
"java",
"orm",
"jpa",
""
] |
I am running a windows machine have installed Python 2.5. I also used the windows installer to install NumPy.
This all works great when I run the Python (command line) tool that comes with Python.
However, if I run cygwin and then run Python from within, it cannot find the numpy package.
What environment variable do... | Cygwin comes with its own version of Python, so it's likely that you have two Python installs on your system; one that installed under Windows and one which came with Cygwin.
To test this, try opening a bash prompt in Cygwin and typing `which python` to see where the Python executable is located. If it says `/cygdrive... | You're running a separate copy of python provided by cygwin.
You can run /cygdrive/c/python25/python (or wherever you installed it)
to get your win32 one, or just install another copy of numpy. | Running numpy from cygwin | [
"",
"python",
"numpy",
""
] |
Not many are aware of this feature, but Python's functions (and methods) can have [attributes](http://www.python.org/dev/peps/pep-0232/). Behold:
```
>>> def foo(x):
... pass
...
>>> foo.score = 10
>>> dir(foo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__h... | I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)
```
class Foo(WebService):
@webmethod
def bar(self, arg1, arg2):
...
```
then I can define
```
def webmethod(func... | I've used them as static variables for a function. For example, given the following C code:
```
int fn(int i)
{
static f = 1;
f += i;
return f;
}
```
I can implement the function similarly in Python:
```
def fn(i):
fn.f += i
return fn.f
fn.f = 1
```
This would definitely fall into the "abuses" e... | Python function attributes - uses and abuses | [
"",
"python",
"function",
"attributes",
""
] |
Is it possible to read the data in the php $\_SESSION array in the .htaccess file in Apache? So say I have the following:
```
$_SESSION['foo'] = 'bar';
```
could I then in .htaccess do something like:
```
RewriteRule bla.png folder/{the php session var foo}/file.png
```
Is that possible?
I already have a working w... | I'm not aware that its possible.
But I can think of a few workarounds involving rewriting to a PHP script. | # Answer to the main question:
**No,** at least not as you imagine. The file is called `.ht`***`access`*** because they are *"distributed configuration files"* and of course configuration && ***access*** handling must happen first - therefor you can't get "PHP session variable" because it simply comes after the proces... | Get PHP session vars in .htaccess | [
"",
"php",
"apache",
"session",
".htaccess",
""
] |
I am using the following code to attempt to read a large file (280Mb) into a byte array from a UNC path
```
public void ReadWholeArray(string fileName, byte[] data)
{
int offset = 0;
int remaining = data.Length;
log.Debug("ReadWholeArray");
FileStream stream = new FileStream(fileName, FileMode.Open, ... | I suspect that something lower down is trying to read into another buffer, and reading all 280MB in one go is failing. There may be more buffers required in the network case than in the local case.
I would read about 64K at a time instead of trying to read the whole lot in one go. That's enough to avoid too much overh... | Also, the code as written needs to put the `FileStream` into a `using` block. Failing to dispose of resources is a very possible reason for receiving "Insufficient system resources":
```
public void ReadWholeArray(string fileName, byte[] data)
{
int offset = 0;
int remaining = data.Length;
log.Debug("Read... | IOException reading a large file from a UNC path into a byte array using .NET | [
"",
"c#",
".net",
"arrays",
"large-files",
"unc",
""
] |
the following js works fine in FF2 but in IE6 the dropdown always selects one option to early, IE -> testix2 vs. FF2 -> testix3
If we add an alertBox somewhere in the script, it also works fine in IE6.
But how to solve this without an alertBox?
tia
```
<script language="JavaScript" type="text/javascript">
<!--
functi... | I'm not entirely sure why your example does not work, but it works if you do it like this (i.e. setting the selectedIndex on the <select> rather than setting the <option>'s selected propery). Tested FF3, IE6, Chrome.
```
var i = 0;
for (i in productCategoryLevel2) {
var optL2 = document.createElement('option');
... | I can't test this right now, but you may want to iterate over your array using a standard for(;;) loop rather than the for..in construct, which should only ever be used on objects in javascript. | javascript options selected IE6 vs. FF2 | [
"",
"javascript",
"html",
"internet-explorer-6",
"html-select",
""
] |
Should I start a Python program with:
```
if__name__ == '__main__':
some code...
```
And if so, why? I saw it many times but don't have a clue about it. | If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, `__name__` evaluates to `'foo'`, but if you run "py... | A better pattern is this:
```
def main():
...
if __name__ == '__main__':
main()
```
This allows your code to be invoked by someone who imported it, while also making programs such as [pychecker](http://pychecker.sourceforge.net/) and [pylint](http://www.logilab.org/projects/pylint) work. | Python program start | [
"",
"python",
""
] |
What are all the other things the `new` operator does other than allocating memory and calling a constructor? | The C++ standard has this to say about the single object form (the form usually used) of the new operator from the `<new>` header:
> Required behavior:
>
> Return a nonnull pointer to suitably aligned storage (3.7.3), or else throw a
> bad\_alloc exception. This requirement is binding on a replacement version of this ... | I've written a explanation of what it does in [this](https://stackoverflow.com/questions/365887/how-do-malloc-and-new-work-how-are-they-different-implementation-wise#365891) answer. It explains how
* `new` gets the memory
* `new` handles memory failure
* `new` handles constructor exceptions
* `new` handles special pla... | What does the C++ new operator do other than allocation and a ctor call? | [
"",
"c++",
"new-operator",
""
] |
I have some code which I did not originally create that uses \_beginthreadex and \_endthreadex. For some reason, when it calls \_endthreadex(0), the call just hangs and never returns. Any ideas as to what would normally cause this call to hang? | \_endthreadex ends the thread, so it can't return. That's the whole point of calling it.
EDIT: It's a bit unusual to call \_endthreadex, normally you just let the thread start procedure return and the runtime calls \_endthreadex for you. You may need to explain a bit more, what you are trying to do before we can help. | My answer is too far late, but still someone will use it.
In my case \_endthreadex hanged when I unload dll and deleted some global objects. One of global objects had another thread inside and that thread also performed thread exit. This caused deadlock since DLLMain already locked crt memory map. Read DLLMain help an... | _endthreadex(0) hangs | [
"",
"c++",
"multithreading",
""
] |
I'm using ASP.NET MVC and I have a partial control that needs a particular CSS & JS file included. Is there a way to make the parent page render the `script` and `link` tags in the 'head' section of the page, rather than just rendering them inline in the partial contol?
To clarify the control that I want to include th... | <http://www.codeproject.com/Articles/38542/Include-Stylesheets-and-Scripts-From-A-WebControl-.aspx>
This article contains information about overriding HttpContext.Response.Filter which worked great for me. | If I have requirements for CSS/Javascript in a partial view, I simply make sure that any page that may include the partial view, either directly or as content retrieved from AJAX, has the CSS/Javascript included in it's headers. If the page has a master page, I add a content placeholder in the master page header and po... | How can I include css files from an MVC partial control? | [
"",
"javascript",
"asp.net-mvc",
"css",
""
] |
I'm doing some research in code generation from xsd schema files.
My requirements:
* Must generate C# 2.0 code (or above), using generic collections where needed.
* Must generate comments from the xsd comments
* Must generate fully serializable code.
* Should be able to generate resuable basetypes when generating from... | I believe [XSD2Code](http://xsd2code.codeplex.com/) is the best tool currently available (in 2011).
I recently went through the same process at work of analysing the available tools out there so i thought i would provide an updated answer that relates to **VS2010**.
Our main driver was that **xsd.exe** does not gener... | I have not yet checked this out, but [Linq2XSD](http://blogs.msdn.com/marcelolr/archive/2009/06/03/linq-to-xsd-on-codeplex.aspx) might be a useful alternative.
I'm going to give this one a shot. LINQ with XSD generation would be better than any of these tools you mentioned - provided it works nicely. | Comparison of XSD Code Generators | [
"",
"c#",
"xsd",
"code-generation",
""
] |
My users are presented a basically a stripped down version of a spreadsheet. There are textboxes in each row in the grid. When they change a value in a textbox, I'm performing validation on their input, updating the collection that's driving the grid, and redrawing the subtotals on the page. This is all handled by the ... | Use the semaphore (let's call it StillNeedsValidating). if the SaveForm function sees the StillNeedsValidating semaphore is up, have it activate a second semaphore of its own (which I'll call FormNeedsSaving here) and return. When the validation function finishes, if the FormNeedsSaving semaphore is up, it calls the Sa... | Disable the save button during validation.
Set it to disabled as the first thing validation does, and re-enable it as it finishes.
e.g.
```
function UserInputChanged(control) {
// --> disable button here --<
currentControl = control;
// use setTimeout to simulate slow validation code (production code doe... | Avoiding a Javascript race condition | [
"",
"javascript",
"dom-events",
"race-condition",
""
] |
I always tell in c# a variable of type double is not suitable for money. All weird things could happen. But I can't seem to create an example to demonstrate some of these issues. Can anyone provide such an example?
(edit; this post was originally tagged C#; some replies refer to specific details of `decimal`, which th... | Very, very unsuitable. Use decimal.
```
double x = 3.65, y = 0.05, z = 3.7;
Console.WriteLine((x + y) == z); // false
```
(example from Jon's page [here](http://csharpindepth.com/Articles/General/FloatingPoint.aspx) - recommended reading ;-p) | You will get odd errors effectively caused by rounding. In addition, comparisons with exact values are extremely tricky - you usually need to apply some sort of epsilon to check for the actual value being "near" a particular one.
Here's a concrete example:
```
using System;
class Test
{
static void Main()
{
... | Is a double really unsuitable for money? | [
"",
"c#",
"language-agnostic",
"decimal",
"currency",
""
] |
The db I am querying from is returning some null values.
How do I safeguard against this and make sure the caller gets some data back.
The code I have is:
Using DataReader
```
while (dr.Read())
{
vo = new PlacementVO();
vo.PlacementID = dr.GetString(0);
```
If I use dataset, ... | There is `IsDBNull(int ordinal)` if you are using ordinals (which you are).
So:
```
string email = reader.IsDBNull(0) ? null : reader.GetString(0);
```
If you are working with string column names, then to use this you'll have to call `GetOrdinal` first, for example:
```
string GetSafeString(this IDataReader reader,... | Another way is to add **isnull**(*column which can be null* , *replacement when it is null*) to the actual SQL query. Less code and works without doing anything in the client code. | Dealing with null values from DB | [
"",
"c#",
".net",
""
] |
What is best language to learn next to Java?
Criteria for this secondary language are:
1. High potential of being the "next big thing". e.g. If the market for Java open positions *hypothetically* dies/dwindles, what is the next programming language that will have a bigger market for open positions? Another way to fra... | Python almost meets all of them, but I don't know about being "the next big thing", but hey, Google uses it, and I think its popularity is raising.
It's a scripting language, btw.
I use it for web applications (using [django](http://djangoproject.com)), and you can definitely create desktop applications with it (alth... | For employability: Any of the .Net languages, probably C#. Then you're well set for most potential customers.
For stretching yourself: something functional (F# to cover .Net too?), or something Lisp, or Smalltalk - was once the next big thing but it probably never will be again, but still a language that changed signf... | Java Developer looking for a 2nd'ary language to play with | [
"",
"java",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.