Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
The only thing I don't have an automated tool for when working with SQL Server is a program that can create `INSERT INTO` scripts. I don't desperately need it so I'm not going to spend money on it. I'm just wondering if there is anything out there that can be used to generate INSERT INTO scripts given an existing database without spending lots of money.
I've searched through SQL Server Management Studio Express with no luck in finding such a feature. If it exists in SSMSE then I've never found it. | This web site has many useful scripts including [generating inserts](http://vyaskn.tripod.com/code.htm#inserts).
You can utilise `sp_msforeachtable` with it to generate for an entire DB.
**Update**: There is built-in functionality to script data as INSERTs in SQL Server Management Studio 2008(onwards).
**SQL Server 2008**:
Right-click on your database in SSMS, select `Tasks –> Generate Scripts`, ensure your database is highlighted and click next. Scroll down the options list to the “Table/View Options” section, and change “Script Data” to True.

**SQL Server 2012**:
Right-click on your database in SSMS, select `Tasks –> Generate Scripts`. Choose the tables you want to generate scripted INSERTs for, then click `Next`. Choose where you want to send the output to (such as a new Query Window), and then click the `Advanced` button (which for some reason is in the Save to File Section!). Scroll down the options list to the “Types of data to script” option and change it to either "Data only" or "Schema and data". Click `Next` twice.

 | you can also use this add-in for SSMS that provides this functionality:
<http://www.ssmstoolspack.com/>
it also provide other useful features as well. | Are there any free tools to generate 'INSERT INTO' scripts in MS SQL Server? | [
"",
"sql",
"sql-server",
""
] |
The java.library.path property appears to be read-only. For example when you run ant on the following buildfile
```
<project name="MyProject" default="showprops" basedir=".">
<property name="java.library.path" value="test"/>
<property name="some.other.property" value="test1"/>
<target name="showprops">
<echo>java.library.path=${java.library.path}</echo>
<echo>some.other.property=${some.other.property}</echo>
</target>
</project>
```
you get
```
> ant -version
Apache Ant version 1.6.5 compiled on June 2 2005
> ant -Djava.library.path=commandlinedefinedpath
Buildfile: build.xml
showprops:
[echo] java.library.path=commandlinedefinedpath
[echo] some.other.property=test1
BUILD SUCCESSFUL
Total time: 0 seconds
```
The output indicates that the **java.library.path** hasn't been changed, but **some.other.property** was set correctly.
I would like to know how to modify the java.library.path within a buildfile. Specifying the java.library.path on the ant command line is not really an easy option, because the library path location is not know at that time.
Note: I would like this to work so that I can specify the location of native libraries used in a unit test. | Ant properties do not work the way you expect: they are immutable, i.e. you cannot change a property's value after you have set it once. If you run
> ant -Dsome.other.property=commandlinedefinedpath
the output will no longer show
> [echo] some.other.property=test1 | I think you can modify it if you use fork=true in your "java" task. You can supply java.library.path as a nested sysproperty tag. | ANT: How to modify java.library.path in a buildfile | [
"",
"java",
"ant",
""
] |
I am using impersonation is used to access file on UNC share as below.
```
var ctx = ((WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();
string level = WindowsIdentity.GetCurrent().ImpersonationLevel);
```
On two Windows 2003 servers using IIS6, I am getting different impersonation levels: *Delegation* on one server and *Impersonation* on the other server.
This causes issues where I am unable to access the UNC share on the server with 'Impersonation' level.
What could be causing this difference? I searched through machine.config and IIS settings for the app pool, site and virtual directories - but aren't able to find the cause of this problem. | It sounds like one of the computer is trusted for delegation by your Active Directory, but the other is not. If the app pool identity is Network Service, make sure the Computer Account is marked "Trusted for Delegation" in AD.
You may need to ask your AD admin to force a replication and then log out/in to your workstation to refresh your Kerberos ticket cache. | If your testing with localhost as webserver and its working but when deployed you receive errors you could be running into the double-hop issue....outlined in this [blog post](http://blogs.msdn.com/knowledgecast/archive/2007/01/31/the-double-hop-problem.aspx) | Impersonation and Delegation | [
"",
"c#",
"asp.net",
"iis-6",
"impersonation",
"delegation",
""
] |
I'm using a DataGridView in my WinForms application. My main objective is to make the Enter key not move to the next row in the grid. I still want the enter key to validate and end edit mode.
I found [this FAQ entry](http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/a44622c0-74e1-463b-97b9-27b87513747e/#faq9) and subclassed DataGridView to override ProcessDialogKey(). If the key pressed is Enter, I call EndEdit(), otherwise I call base.ProcessDialogKey().
It works great, except the CellValidating event isn't fired.
Currently, I'm just manually calling my validation logic before I call EndEdit, but it seems like I'm missing something.
I guess I could call OnCellValidating, but then I'd be worried I'm missing some other event. What I really want is some flavour of EndEdit() that behaves just like pressing enter on the last row of a grid with adding disabled. | CellValidating doesn't get called until you change the CurrentCell. So the way I kludged around this was to change the CurrentCell, then switch back to the current one.
```
protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Enter)
{
DataGridViewCell currentCell = CurrentCell;
EndEdit();
CurrentCell = null;
CurrentCell = currentCell;
return true;
}
return base.ProcessDialogKey(keyData);
}
``` | JJO's code will crash if cell is in edit mode. Below avoids validation exception:
```
DataGridViewCell currentCell = AttachedGrid.CurrentCell;
try
{
AttachedGrid.EndEdit();
AttachedGrid.CurrentCell = null;
AttachedGrid.CurrentCell = currentCell;
}
catch
{
AttachedGrid.CurrentCell = currentCell;
AttachedGrid.CurrentCell.Selected = true;
}
```
Source: [Kennet Harris's answer here](http://social.msdn.microsoft.com/Forums/en/winforms/thread/1f5d313a-203d-4e7a-ac46-eee65347a9f4) | Can I make DataGridView.EndEdit trigger the CellValidating event? | [
"",
"c#",
"winforms",
"datagridview",
""
] |
I'm working on a project where there is a lot of external service messaging. A good way to describe it in only a slightly "hyperbolas" way would be an application where the system has to send messages to the Flicker API, the Facebook API, and the Netflix API.
To support disconnected scenarios, logging concerns, developer usability, configuration, etc... I've experimented using an approach which heavily uses generics and expression trees. The end result looks like this:
```
Messenger<NetflixApi>.SendCustom( netflix => netflix.RecommendMovie("my message"));
```
Overall I'm happy with the end result but feel like I've made a mistake, or overlooked a design principal someplace with regards to testing and disconnected scenarios.
During testing, whether automated, unit, or human based, I've implemented an object factory that initially uses DI to perform the correct action in "Live mode" and used Mocks to provide a sort of sterile messenger that doesn't do anything at all when in a testing mode.
I've only seen or read about Mocks being used in pure TDD mode and not being used to be sort of a dumb object. The approaches I've seen would revolve around stubbing or mocking out the HTTP communication functionality which all the APIs I'm using depend on.
My main concern is that will all the different services I expect to connect to I'd end up having to do a lot of granular work substituting specific HTTP implementation and if I used a stub approach I'd have 3 classes for each of these services( IService, ConcreteService, StubService ) and maintaining those when implementing a new method or changing anything would be a real PITA.
In the current implementation I'm using Mocks to get "sterile mode" for free almost without having to implement anything extra just to conform to a certain testing principal.
The question is am I missing something? Did I violate a design principal using Mocks in a more... convenient way?
Can anybody offer any advice on how to get a sterile mode out of many different outside services without jumping through a lot of hoops?
Does this question make sense?
Thanks for all the answers.
Edit #1:
I wasn't clear in my original question. Any null or mock objects are to be used purely in a development/debug/testing environment. In production the code that sends these messages will be the actual implementation of them.
I voted everybody up because there seem to be a lot of different solutions to this problem and I'll be exploring each one.
Please don't think this question has been answered yet, I'd appreciate as much advice as I can get. | There is a design pattern called Null Object. A null object is an object that implements a Interface, so it could be used in an scenario like yours.
The important thing about the Null Object is that DON'T return null in places where that could break the system.
The purpose of the Null Object is to have a void and simple implementation of something, just like a Mock, but to be used in the production environment.
The most simple example is something like this:
```
class Logger{
private static ILogger _Logger;
static Logger(){
//DI injection here
_Logger = new NullLogger(); //or
_Logger = new TraceLogger();
}
}
interface ILogger{
void Log(string Message);
}
internal class TraceLogger:ILooger{
public void Log(string Message){
//Code here
}
}
internal class NullLogger{
public void Log(string Message){
//Don't don anything, in purporse
}
}
```
I hope this could help you | I think you may need to clarify your question.
I'm unclear as to whether you are talking about using test doubles in testing without stubbing or testing expectations (so using them as fakes to meet required interfaces) or whether you are talking about using mocks in a production scenario to fill in for services that are not available (your disconnected scenario).
If you are talking about in test situations:
Mocks are test doubles. There's nothing wrong with testing using fakes as opposed to mocks or stubs. If you don't need to use the service in a specific test and it is just there to provide a given interface that the object under test has a dependency on then that it fine. That is not breaking any testing principal.
Good mocking libraries are blurring the lines between mocks, stubs and fakes.
Have a look at some of the information from Martin Fowler on the different types of test doubles. [Mocks Aren't Stubs](http://martinfowler.com/articles/mocksArentStubs.html), [TestDoubles](http://www.martinfowler.com/bliki/TestDouble.html).
I really like the way that moq allows a continuum between dummy, fake, stub and mock objects without you needing to jump through hoops to get specific behaviors. [Check it out](http://www.clariusconsulting.net/blogs/kzu/archive/2007/12/21/47152.aspx).
If you are talking about using mocks in your disconnected scenario for production use... I'd be worried. A fake is going to return null objects or default values for any calls that you make. This will leak complexity into all of the code consuming these services (they'll need to handle checking for null return values and empty arrays...). I think it would make more sense for your disconnected / sterile scenario to be coded to handle that the dependencies themselves are unavailable rather than accepting mock implementations of them and continuing as if everything is working. | Using mock objects outside of testing, bad practice? | [
"",
"c#",
"tdd",
"dependency-injection",
"mocking",
"dependencies",
""
] |
I'm working on an embedded processor (400 MHz Intel PXA255 XScale), and I thought I saw one case where there wasn't enough memory to satisfy a 'new' operation. The program didn't crash, so I assumed other threads had freed their memory and it was just a transient thing. This is some pretty critical code, so exiting is not an option, and some sort of error needs to be returned to the remote user.
Would the following small fix be enough to solve the problem, or is there a better way? Before replacing every 'new' with the following code, I thought I'd ask.
```
char someArr[];
do{
someArr = new char[10];
Sleep(100); // no justification for choosing 100 ms
} while ( someArr == NULL );
```
Does the Sleep help? Should I set some max number of retries? Is it possible to use static initialization everywhere?
**FINAL UPDATE:** Thank you very much for the helpful responses, but it turns out there was an error in the code checking for failed memory allocation. I will keep all of these answers in mind, and replace as many malloc's and new's as I can, though (especially in error-handling code). | There are a few different ways to attack this - note that the tool instructions will vary a bit, based on what version of Windows CE / Windows Mobile you are using.
Some questions to answer:
**1. Is your application leaking memory, leading to this low memory condition?**
**2. Does your application simply use too much memory at certain stages, leading to this low memory condition?**
1 and 2 can be investigated using the Windows CE AppVerifier tool, which can provide detailed memory logging tools for your product. Other heap wrapping tools can also provide similar information (and may be higher-performance), depending on your product design.
<http://msdn.microsoft.com/en-us/library/aa446904.aspx>
**3. Are you allocating and freeing memory very frequently in this process?**
Windows CE, prior to OS version 6.0 (don't confuse with Windows Mobile 6.x) had a 32MB / process virtual memory limit, which tends to cause lots of fun fragmentation issues. In this case, even if you have sufficient physical memory free, you might be running out of virtual memory. Use of custom block allocators is usually a mitigation for this problem.
**4. Are you allocating very large blocks of memory? (> 2MB)**
Related to 3, you could just be exhausting the process virtual memory space. There are tricks, somewhat dependent on OS version, to allocate memory in a shared VM space, outside the process space. If you are running out of VM, but not physical RAM, this could help.
**5. Are you using large numbers of DLLs?**
Also related to 3, Depending on OS version, DLLs may also reduce total available VM very quickly.
**Further jumping off points:**
Overview of CE memory tools
<http://blogs.msdn.com/ce_base/archive/2006/01/11/511883.aspx>
Target control window 'mi' tool
<http://msdn.microsoft.com/en-us/library/aa450013.aspx> | You are trying to solve a global problem through local reasoning. The global problem is that the entire device has a limited amount of RAM (and possibly backing store) for the operating system and all of the applications. To make sure this amount of RAM is not exceeded, you have a few options:
* Each process operates in a fixed amount of RAM to be determined per process at startup time; the programmer does the reasoning to make sure everything fits. So, **yes, it is possible to allocate everything statically**. It's just a lot of work, and **every time you change your system's configuration, you have to reconsider the allocations**.
* Processes are aware of their own memory usage and needs and continually advise each other about how much memory they need. They **cooperate so they don't run out of memory**. This assumes that at least some processes in the system can adjust their own memory requirements (e.g., by changing the size of an internal cache). Alonso and Appel wrote a [paper about this approach](http://portal.acm.org/citation.cfm?id=98753).
* Each process is aware that memory can become exhausted and can **fail over to a state in which it consumes a minimum amount of memory**. Often this strategy is implemented by having an out-of-memory exception. The exception is handled in or near main() and the out-of-memory event essentially restarts the program from scratch. This failover mode can work if memory grows in response to user requests; if the program's memory requirements grow independent of what the user does, **it can lead to thrashing.**
**Your proposal above matches none of the scenarios.** Instead, you are hoping **some other process will solve the problem** and the memory you need will eventually appear. You might get lucky. You might not.
If you want your system to work reliably, you would do well to **reconsider the design of every process running on the system** in light of the need to share limited memory. It might be a bigger job than you expected, but if you understand the problem, you can do this. Good luck! | Dynamic Memory Allocation Failure Recovery | [
"",
"c++",
"embedded",
"windows-ce",
"new-operator",
"viper",
""
] |
I need to access the crypto functions of OpenSSL to encode Blowfish data in a CBC streams. I've googled and found some Blowfish libraries (hand written) and some OpenSSL wrappers (none of the seem complete.)
In the end, I need to access the certain OpenSSL functions, such as the full blowfish.h library of [commands](http://www.openssl.org/docs/crypto/blowfish.html). What's the pythonic/right way of accessing them? Using something like SWIG to allow Python/C bindings, or is there a better way?
Thanks! | There's lots of ways to interface with C (and C++) in Python. ctypes is pretty nice for quick little extensions, but it has a habit of turning would be compile time errors into runtime segfaults. If you're looking to write your own extension, SIP is very nice. SWIG is very general, but has a larger following. Of course, the first thing you should be doing is seeing if you really need to interface. Have you looked at PyCrypto? | [ctypes](http://docs.python.org/library/ctypes.html) is the place to start. It lets you call into DLLs, using C-declared types, etc. I don't know if there are limitations that will keep you from doing everything you need, but it's very capable, and it's included in the standard library. | What's the most pythonic way of access C libraries - for example, OpenSSL? | [
"",
"c",
"encryption",
"openssl",
"python",
""
] |
I posted this question: <https://stackoverflow.com/questions/418597/java-and-net-for-php-programmer> and the answers I was given didn't really help me out.
I read a few of the tutorials at sun.
The basic syntax I understand. The thing I don't understand and really need to (because I think my company is going to tell me start working with this) is to learn how to work with java for the web. I am a php programmer and I did some asp.net c# a few months ago. I am really not understanding how to work with java on the web.
I installed netbeans.
When I start a web project I also get asked what frameworks I want.
I don't know any java frameworks (I do know about spring but never really worked with it).
Is there no simple tutorial on how to do some java for the web??? I never had these much problems when I was first introduced to php :(
Someone help me out, or at least point me in a good direction. | You may find [this](https://stackoverflow.com/questions/125160/java-developer-moving-to-web-design-easiest-transition) question helpful.
All you really need to know is HTML, Java, and [JSP](http://java.sun.com/products/jsp/)s.
Creating dynamic content is very easy using [JSP](http://java.sun.com/products/jsp/)s and Java. You also need a webserver like [Tomcat](http://tomcat.apache.org/) or [Glass Fish](http://glassfish.java.net/).
As far as the back end Java code goes, there is no difference between that and a desktop application. The only thing that you are changing is the user interface. One of the biggest challenges with switching to a web interface is the fact that it is stateless by design. | The frameworks make web programming easier, they're not required. You can write web applications using plain old servlets and JSPs (with a web application container like Tomcat or JBoss) or even do all the HTTP I/O yourself (obviously that's pointless with Tomcat, etc, around).
A framework like Spring with Hibernate, etc, is similar to frameworks in PHP like CakePHP, they make development easier, they enforce sensible patterns (MVC) upon the programmer, the abstract code that is always going to be done the same way for this type of application. Yes, they limit your choices and abilities, and restrict the actions you can take, to varying degrees. Some are far more heavyweight than others. But there's a lot of choice in the Java world which is a strength, but you just have to spend time evaluating them, and picking one based upon your capabilities.
Take struts and tiles. You can simply use Struts as an MVC system and avoid all of the utility JSP tags it provides. It would take you a short time to rewrite the functionality you end up using yourself, but that's time you don't have, and then there's debugging, and specific domain knowledge and experience that you can't account for. | Java for the web | [
"",
"java",
""
] |
Is there a way in Java to have a map where the type parameter of a value is tied to the type parameter of a key? What I want to write is something like the following:
```
public class Foo {
// This declaration won't compile - what should it be?
private static Map<Class<T>, T> defaultValues;
// These two methods are just fine
public static <T> void setDefaultValue(Class<T> clazz, T value) {
defaultValues.put(clazz, value);
}
public static <T> T getDefaultValue(Class<T> clazz) {
return defaultValues.get(clazz);
}
}
```
That is, I can store any default value against a Class object, provided the value's type matches that of the Class object. I don't see why this shouldn't be allowed since I can ensure when setting/getting values that the types are correct.
EDIT: Thanks to cletus for his answer. I don't actually need the type parameters on the map itself since I can ensure consistency in the methods which get/set values, even if it means using some slightly ugly casts. | You're not trying to implement Joshua Bloch's typesafe hetereogeneous container pattern are you? Basically:
> ```
> public class Favorites {
> private Map<Class<?>, Object> favorites =
> new HashMap<Class<?>, Object>();
>
> public <T> void setFavorite(Class<T> klass, T thing) {
> favorites.put(klass, thing);
> }
>
> public <T> T getFavorite(Class<T> klass) {
> return klass.cast(favorites.get(klass));
> }
>
> public static void main(String[] args) {
> Favorites f = new Favorites();
> f.setFavorite(String.class, "Java");
> f.setFavorite(Integer.class, 0xcafebabe);
> String s = f.getFavorite(String.class);
> int i = f.getFavorite(Integer.class);
> }
> }
> ```
From [Effective Java (2nd edition)](https://rads.stackoverflow.com/amzn/click/com/0321356683) and [this presentation](http://developers.sun.com/learning/javaoneonline/2006/coreplatform/TS-1512.pdf). | The question and the answers made me come up with this solution: [Type-safe object map](http://blog.pdark.de/2010/05/28/type-safe-object-map/). Here is the code. Test case:
```
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class TypedMapTest {
private final static TypedMapKey<String> KEY1 = new TypedMapKey<String>( "key1" );
private final static TypedMapKey<List<String>> KEY2 = new TypedMapKey<List<String>>( "key2" );
@Test
public void testGet() throws Exception {
TypedMap map = new TypedMap();
map.set( KEY1, null );
assertNull( map.get( KEY1 ) );
String expected = "Hallo";
map.set( KEY1, expected );
String value = map.get( KEY1 );
assertEquals( expected, value );
map.set( KEY2, null );
assertNull( map.get( KEY2 ) );
List<String> list = new ArrayList<String> ();
map.set( KEY2, list );
List<String> valueList = map.get( KEY2 );
assertEquals( list, valueList );
}
}
```
This is the Key class. Note that the type `T` is never used in this class! It's purely for the purpose of type casting when reading the value out of the map. The field `key` only gives the key a name.
```
public class TypedMapKey<T> {
private String key;
public TypedMapKey( String key ) {
this.key = key;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( key == null ) ? 0 : key.hashCode() );
return result;
}
@Override
public boolean equals( Object obj ) {
if( this == obj ) {
return true;
}
if( obj == null ) {
return false;
}
if( getClass() != obj.getClass() ) {
return false;
}
TypedMapKey<?> other = (TypedMapKey<?>) obj;
if( key == null ) {
if( other.key != null ) {
return false;
}
} else if( !key.equals( other.key ) ) {
return false;
}
return true;
}
@Override
public String toString() {
return key;
}
}
```
TypedMap.java:
```
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TypedMap implements Map<Object, Object> {
private Map<Object, Object> delegate;
public TypedMap( Map<Object, Object> delegate ) {
this.delegate = delegate;
}
public TypedMap() {
this.delegate = new HashMap<Object, Object>();
}
@SuppressWarnings( "unchecked" )
public <T> T get( TypedMapKey<T> key ) {
return (T) delegate.get( key );
}
@SuppressWarnings( "unchecked" )
public <T> T remove( TypedMapKey<T> key ) {
return (T) delegate.remove( key );
}
public <T> void set( TypedMapKey<T> key, T value ) {
delegate.put( key, value );
}
// --- Only calls to delegates below
public void clear() {
delegate.clear();
}
public boolean containsKey( Object key ) {
return delegate.containsKey( key );
}
public boolean containsValue( Object value ) {
return delegate.containsValue( value );
}
public Set<java.util.Map.Entry<Object, Object>> entrySet() {
return delegate.entrySet();
}
public boolean equals( Object o ) {
return delegate.equals( o );
}
public Object get( Object key ) {
return delegate.get( key );
}
public int hashCode() {
return delegate.hashCode();
}
public boolean isEmpty() {
return delegate.isEmpty();
}
public Set<Object> keySet() {
return delegate.keySet();
}
public Object put( Object key, Object value ) {
return delegate.put( key, value );
}
public void putAll( Map<? extends Object, ? extends Object> m ) {
delegate.putAll( m );
}
public Object remove( Object key ) {
return delegate.remove( key );
}
public int size() {
return delegate.size();
}
public Collection<Object> values() {
return delegate.values();
}
}
``` | Java map with values limited by key's type parameter | [
"",
"java",
"generics",
""
] |
To illustrate the question check the following code:
```
class MyDescriptor(object):
def __get__(self, obj, type=None):
print "get", self, obj, type
return self._v
def __set__(self, obj, value):
self._v = value
print "set", self, obj, value
return None
class SomeClass1(object):
m = MyDescriptor()
class SomeClass2(object):
def __init__(self):
self.m = MyDescriptor()
x1 = SomeClass1()
x2 = SomeClass2()
x1.m = 1000
# -> set <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> 10000
x2.m = 1000 # I guess that this overwrites the function. But why?
# ->
print x1.m
# -> get <__main__.MyDescriptor object at 0xb787c7ec> <__main__.SomeClass1 object at 0xb787cc8c> <class '__main__.SomeClass1'> 10000
print x2.m
# -> 10000
```
1. Why doesn't **x2.m = 1000** not call the **\_\_set\_\_**-function? It seems that this overwrites the function. But why?
2. Where is **\_v** in x1? It is not in **x1.\_v** | To answer your second question, where is `_v`?
Your version of the descriptor keeps `_v` in the descriptor itself. Each instance of the descriptor (the class-level instance `SomeClass1`, and all of the object-level instances in objects of class `SomeClass2` will have distinct values of `_v`.
Look at this version. This version updates the object associated with the descriptor. This means the object (`SomeClass1` or `x2`) will contain the attribute `_v`.
```
class MyDescriptor(object):
def __get__(self, obj, type=None):
print "get", self, obj, type
return obj._v
def __set__(self, obj, value):
obj._v = value
print "set", self, obj, value
``` | You should read [this](http://docs.python.org/reference/datamodel.html#implementing-descriptors) and [this](http://users.rcn.com/python/download/Descriptor.htm).
It overwrites the function because you didn't overload the `__set__` and `__get__` functions of SomeClass but of MyDescriptor class. Maybe you wanted for SomeClass to inherit MyDescriptor? SomeClass1 prints the "get" and "set" output because it's a static method AFAIK. For details read the upper links. | Why do managed attributes just work for class attributes and not for instance attributes in python? | [
"",
"python",
"attributes",
"descriptor",
""
] |
Let's say I have some XML like this
```
<channel>
<item>
<title>This is title 1</title>
</item>
</channel>
```
The code below does what I want in that it outputs the title as a string
```
$xml = simplexml_load_string($xmlstring);
echo $xml->channel->item->title;
```
Here's my problem. The code below doesn't treat the title as a string in that context so I end up with a SimpleXML object in the array instead of a string.
```
$foo = array( $xml->channel->item->title );
```
I've been working around it like this
```
$foo = array( sprintf("%s",$xml->channel->item->title) );
```
but that seems ugly.
**What's the best way to force a SimpleXML object to a string, regardless of context?** | **Typecast the SimpleXMLObject to a string:**
```
$foo = array( (string) $xml->channel->item->title );
```
The above code internally calls `__toString()` on the SimpleXMLObject. This method is not publicly available, as it interferes with the mapping scheme of the SimpleXMLObject, but it can still be invoked in the above manner. | You can use the PHP function
```
strval();
```
This function returns the string values of the parameter passed to it. | Forcing a SimpleXML Object to a string, regardless of context | [
"",
"php",
"xml",
"simplexml",
""
] |
Is mono the only route , any specific visual studio like editors that you recommend? | Without meaning to state the obvious and miss the point, if you mean a Mac computer rather than a Mac OS, you could install [bootcamp](http://www.apple.com/macosx/features/bootcamp.html) or use [parallels](http://www.parallels.com/) to run windows on the Mac and then use Visual Studio (there are also free versions of [Visual Studio](http://www.microsoft.com/Express/)) | Yeah, mono is really your only option, unless some undergrad somewhere has developed some very experimental thing I don't know about. As for an IDE, well I believe the only thing half way stable that will work right now on Mac OS X is Monodevelop:
<http://tirania.org/blog/archive/2008/Feb-07-2.html>
I mean, you could run Parallels and develop your code on a Windows VM with Visual Studio and as long as you follow certain guidelines about portability, you could use VS to develop your mono apps. Although, you probably might as well get familiar with Monodevelop. It would be interesting to see if SharpDevelop ever gets ported. | Learn C# on mac? | [
"",
"c#",
"macos",
""
] |
When I retrieve any Scalar value from the database, I usually write code like this for nullable fields.
```
cmd.ExecuteScalar() == DBNull.Value ? 0 : (int)cmd.ExecuteScalar()
```
But I don't like it because it executes the Executescalar statement twice. It's an extra trip to the server for my website and in favor of performance I don't want to do this.
Is there any way I can get rid of this extra ExecuteScalar()? | Write yourself an extension method for the sql command.
```
public static T ExecuteNullableScalar<T>(this SqlCommand cmd)
where T : struct
{
var result = cmd.ExecuteScalar();
if (result == DBNull.Value) return default(T);
return (T)result;
}
```
Usage becomes:
```
int value = cmd.ExecuteNullableScalar<int>();
``` | Just use a variable to cache the result:
```
var o = cmd.ExecuteScalar();
return o == DBNull.Value ? 0 : (int)o;
``` | How can I check for DBNull while executing my command only once? | [
"",
".net",
"sql",
"database",
"ado.net",
""
] |
I am developing a Web Album using Grails and for image processing, I am using grails-image-tools plugin. I need a functionality to resize the images if the uploaded images size is too big (for eg: more than 600 \* 840 ) . In this case I need to resize this image to 600 \* 840). What is the most efficient way to do this? Thanks a lot. | ```
import java.awt.Image as AWTImage
import java.awt.image.BufferedImage
import javax.swing.ImageIcon
import javax.imageio.ImageIO as IIO
import java.awt.Graphics2D
static resize = { bytes, out, maxW, maxH ->
AWTImage ai = new ImageIcon(bytes).image
int width = ai.getWidth( null )
int height = ai.getHeight( null )
def limits = 300..2000
assert limits.contains( width ) && limits.contains( height ) : 'Picture is either too small or too big!'
float aspectRatio = width / height float requiredAspectRatio = maxW / maxH
int dstW = 0
int dstH = 0
if (requiredAspectRatio < aspectRatio) {
dstW = maxW dstH = Math.round( maxW / aspectRatio)
} else {
dstH = maxH dstW = Math.round(maxH * aspectRatio)
}
BufferedImage bi = new BufferedImage(dstW, dstH, BufferedImage.TYPE_INT_RGB)
Graphics2D g2d = bi.createGraphics() g2d.drawImage(ai, 0, 0, dstW, dstH, null, null)
IIO.write( bi, 'JPEG', out )
}
``` | In `BuildConfig.groovy` add a dependency to [imgscalr](http://www.thebuzzmedia.com/software/imgscalr-java-image-scaling-library/)
```
dependencies {
compile 'org.imgscalr:imgscalr-lib:4.1'
}
```
Then resizing images becomes a one-liner:
```
BufferedImage thumbnail = Scalr.resize(image, 150);
``` | Image resize in Grails | [
"",
"java",
"grails",
"image-processing",
"frameworks",
""
] |
I'm customizing the product view page and I need to show the user's name.
How do I access the account information of the current user (if he's logged in) to get Name etc. ? | Found under "app/code/core/Mage/Page/Block/Html/Header.php":
```
public function getWelcome()
{
if (empty($this->_data['welcome'])) {
if (Mage::app()->isInstalled() && Mage::getSingleton('customer/session')->isLoggedIn()) {
$this->_data['welcome'] = $this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
} else {
$this->_data['welcome'] = Mage::getStoreConfig('design/header/welcome');
}
}
return $this->_data['welcome'];
}
```
So it looks like `Mage::getSingleton('customer/session')->getCustomer()` will get your current logged in customer ;)
To get the currently logged in admin:
```
Mage::getSingleton('admin/session')->getUser();
``` | Have a look at the helper class: **Mage\_Customer\_Helper\_Data**
To simply get the customer name, you can write the following code:-
```
$customerName = Mage::helper('customer')->getCustomerName();
```
For more information about the customer's entity id, website id, email, etc. you can use **getCustomer** function. The following code shows what you can get from it:-
```
echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";
```
From the helper class, you can also get information about customer login url, register url, logout url, etc.
From the **isLoggedIn** function in the helper class, you can also check whether a customer is logged in or not. | Current user in Magento? | [
"",
"php",
"magento",
""
] |
How do I call the parent function from a derived class using C++? For example, I have a class called `parent`, and a class called `child` which is derived from parent. Within
each class there is a `print` function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this? | I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's `private`).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons `base_class::foo(...)`. You should note that unlike Java and C#, C++ does **not** have a keyword for "the base class" (`super` or `base`) since C++ supports [multiple inheritance](http://en.wikipedia.org/wiki/Multiple_inheritance) which may lead to ambiguity.
```
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
```
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
```
class bottom : public left, public left { // Illegal
};
``` | Given a parent class named `Parent` and a child class named `Child`, you can do something like this:
```
class Parent {
public:
virtual void print(int x);
};
class Child : public Parent {
void print(int x) override;
};
void Parent::print(int x) {
// some default behavior
}
void Child::print(int x) {
// use Parent's print method; implicitly passes 'this' to Parent::print
Parent::print(x);
}
```
Note that `Parent` is the class's actual name and not a keyword. | How to call a parent class function from derived class function? | [
"",
"c++",
"oop",
"inheritance",
""
] |
Trying to build a GUI application in Java/Swing. I'm mainly used to "painting" GUIs on the Windows side with tools like VB (or to be more precise, Gupta SQLWindows... wonder how many people know what that is ;-)).
I can't find an equivalent of a Group Box in Swing...
With a group box, you have a square box (usually with a title) around a couple of related widgets. One example is a group box around a few radio buttons (with the title explaining what the radio buttons are about, e.g. Group Box entitled "Sex" with "Male" and "Female" radio buttons).
I've searched around a bit... the only way I found was to add a sub-pane, set the border on the sub-pane and then add all the widgets in the "group" to the sub-pane. Is there a more elegant way to do that? | Create a JPanel, and add your radiobuttons to it. Don't forget to set the layout of the JPanel to something appropriate.
Then call `panel.setBorder(BorderFactory.createTitledBorder(name));` | Others have already commetned about JPanel and using a TitledBorder, that's fine.
However, when playing with Swing LayoutManagers, you may find it annoying that components in different JPanels cannot align correctly (each panel has its own LayoutManager).
For this reason, it is a good practice (check "JGoodies" on the web for more details) in Swing GUIs to NOT use TitledBorders but rather separate groups of components in a JPanel by a JLabel followed by a horizontal JSeparator.
Ref. "[First Aid for Swing](http://www.jgoodies.com/download/presentations/first%20aid%20for%20swing-75min.pdf)" | Is there a "Group Box" equivalent in Java Swing? | [
"",
"java",
"swing",
"grouping",
""
] |
I'm still learning about REST and, in my test, came up with this scenario I don't know how to deal with.
I have an existing sample WCF service which uses Linq-to-Sql. Its a tremendously simple database with a single table called "Tasks" which has four fields: Id, Description, IsCompleted, and EnteredDate. (I mentioned this because I have no data contracts defined in the service itself, it all comes from the Context created by Linq.)
Getting data was trivial to convert to REST... as was deleting data. However, inserting new records doesn't seem as easy.
My RPC-style contract operation looks like this:
```
[OperationContract]
void AddTask(string description);
```
The Id, IsCompleted, and EnteredDate are not needed as the service implementation looks like this:
```
public void AddTask(string description)
{
TaskListLinqDataContext db = new TaskListLinqDataContext();
Task task = new Task()
{ Description = description, IsCompleted = false,
EntryDate = DateTime.Now };
db.Tasks.InsertOnSubmit(task);
db.SubmitChanges();
}
```
The Id is an Identity and therefore handled by the database.
My first thought was to decorate the Operation contract like this:
```
[WebInvoke(Method="PUT", UriTemplate="tasks/{description}")]
[OperationContract]
void AddTask(string description);
```
But I don't really know how to get this to work. When I try using Fiddler to add this it returns a result of 411 (Length Required).
What would be the proper way to do this? Will I have to re-write the implementation to accept a whole XML document representing the new record? | Results:
I finally found a [nice blog post](http://blog.donnfelker.com/post/How-To-REST-Services-in-WCF-35-Part-2-The-POST.aspx) that helped me resolve this. It turns out I was pretty much doing things correctly but I was putting the test into Fiddler improperly. I also added a few more details to my attribute.
```
[WebInvoke(RequestFormat = WebMessageFormat.Xml,
ResponseFormat = WebMessageFormat.Xml,
Method = "POST", UriTemplate = "tasks/{description}",
BodyStyle = WebMessageBodyStyle.Bare)]
[OperationContract]
void AddTask(string description);
```
When I put my Uri into Fiddler it needed to look like this:
<http://ipv4.fiddler:8054/tasks/this+is+a+sample+desc+that+works>
Now my service correctly accepts the data and can add the task to the database. | Take a look at the [WCF REST Starter Kit](http://msdn.microsoft.com/en-us/netframework/cc950529.aspx), which can be downloaded from CodePlex [here](http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18830). | How would I add new data via a REST service opposed to RPC style service? | [
"",
"c#",
"wcf",
"rest",
""
] |
Say I only needed to use findall() from the re module, is it more efficient to do:
```
from re import findall
```
or
```
import re
```
Is there actually any difference in speed/memory usage etc? | There is no difference on the import, however there is a small difference on access.
When you access the function as
```
re.findall()
```
python will need to first find the module in the global scope and then find findall in modules dict. May make a difference if you are calling it inside a loop thousands of times. | When in doubt, time it:
```
from timeit import Timer
print Timer("""re.findall(r"\d+", "fg12f 1414 21af 144")""", "import re").timeit()
print Timer("""findall(r"\d+", "fg12f 1414 21af 144")""", "from re import findall").timeit()
```
I get the following results, using the minimum of 5 repetitions of 10,000,000 calls:
```
re.findall(): 123.444600105
findall(): 122.056155205
```
There appears to be a very slight usage advantage to using `findall()` directly, rather than `re.findall()`.
However, the actual import statements differ in their speed by a significant amount. On my computer, I get the following results:
```
>>> Timer("import re").timeit()
2.39156508446
>>> Timer("from re import findall").timeit()
4.41387701035
```
So `import re` appears to be approximately twice as fast to execute. Presumably, though, execution of the imported code is your bottleneck, rather than the actual import. | Is it more efficient to use "import <module>" or "from <module> import <func>"? | [
"",
"python",
"import",
""
] |
First, how do I format the XML processing instruction, is it:
```
<?processingInstructionName attribute="value" attribute2="value2"?>
```
Using StAX, I then want to read it by handling the `XMLStreamConstants.PROCESSING_INSTRUCTION` ([javadoc](http://java.sun.com/javase/6/docs/api/javax/xml/stream/XMLStreamConstants.html#PROCESSING_INSTRUCTION)) event, but it only provides two methods to then retrieve information about the processing instruction from the `XMLStreamReader`:
```
getPITarget()
getPIData()
```
The [javadoc](http://java.sun.com/javase/6/docs/api/javax/xml/stream/XMLStreamReader.html#getPIData()) for these two methods isn't very helpful.
1. Is the XML formatting correct?
2. Is this the proper way to go about
parsing processing instructions
using the StAX `XMLStreamReader`
APIs?
3. How do I use `getPITarget()` and `getPIData()` to return multiple arguments? | > 1.Is the XML formatting correct?
**Yes**, however **do note that a [processing instruction](http://www.w3.org/TR/2006/REC-xml-20060816/#sec-pi) does not have [attributes](http://www.w3.org/TR/2006/REC-xml-20060816/#attdecls)** -- only data. What looks like attributes are part of the data and some people call them "`pseudo-attributes`".
> 2.Is this the proper way to go about parsing processing instructions using the StAX XMLStreamReader APIs?
Yes.
> 3.How do I use getPITarget() and getPIData() to return multiple arguments?
If by "multiple arguments" you mean the possibly more than one pseudo-attributes contained in the data, the answer is that your code must parse the data (using some standard string methods as the C# [**`split()`**](http://msdn.microsoft.com/en-us/library/ms228388.aspx), and retrieve the set of name-value pairs for all pseudo-attributes. | I think that this notion of processing instructions having attributes comes from some old xml manuals. At one point there was discussion of recommending PIs to honor or require such structuring. However, the official xml specification has never mandated or even recommended such usage.
So basically you do have to parse contents yourself -- they may be in any format, but if you do know that it uses attribute notation you can parse it.
As far as I know, none of Java xml parsers or processing packages support such usage, unfortunately. | How do I format and read XML processing instructions using Java StAX? | [
"",
"java",
"xml",
"stax",
""
] |
I know it sounds weird but I am required to put a wrapping try catch block to every method to catch all exceptions. We have thousands of methods and I need to do it in an automated way. What do you suggest?
I am planning to parse all cs files and detect methods and insert a try catch block with an application. Can you suggest me any parser that I can easily use? or anything that will help me...
every method has its unique number like 5006
```
public static LogEntry Authenticate(....)
{
LogEntry logEntry = null;
try
{
....
return logEntry;
}
catch (CompanyException)
{
throw;
}
catch (Exception ex)
{
logEntry = new LogEntry(
"5006",
RC.GetString("5006"), EventLogEntryType.Error,
LogEntryCategory.Foo);
throw new CompanyException(logEntry, ex);
}
}
```
I created this for this;
<http://thinkoutofthenet.com/index.php/2009/01/12/batch-code-method-manipulation/> | I had to do something kinda sorta similar (add something to a lot of lines of code); I used regex.
I would create a regex script that found the beginning of each function and insert the try catch block right after the beginning. I would then create another regex script to find the end of the function (by finding the beginning of the function right after it) and insert the try catch block at the end. This won't get you 100% of the way there, but it will hit maybe 80% which would hopefully be close enough that you could do the edge cases without too much more work. | DONT DO IT. There is no good reason for pokemon ("gotta catch em all")error handling.
EDIT: After a few years, a slight revision is in order. I would say instead "at least dont do this manually". Use an AOP tool or weaver like PostSharp or Fody to apply this to the end result code, but make sure to consider other useful tracing or diagnostic data points like capturing time of execution, input parameters, output parameters, etc. | Parsing C#, finding methods and putting try/catch to all methods | [
"",
"c#",
"parsing",
""
] |
This has bugged me for a long time.
99% of the time, the GROUP BY clause is an exact copy of the SELECT clause, minus the aggregate functions (MAX, SUM, etc.).
This breaks the Don't Repeat Yourself principle.
When can the GROUP BY clause not contain an exact copy of the SELECT clause minus the aggregate functions?
## edit
I realise that some implementations allow you to have different fields in the GROUP BY than in the SELECT (hence 99%, not 100%), but surely that's a very minor exception?
Can someone explain what is supposed to be returned if you use different fields?
Thanks. | I tend to agree with you - this is one of many cases where SQL should have slightly smarter defaults to save us all some typing. For example, imagine if this were legal:
```
Select ClientName, InvoiceAmount, Sum(PaymentAmount) Group By *
```
where "\*" meant "all the non-aggregate fields". If everybody knew that's how it worked, then there would be no confusion. You could sub in a specific list of fields if you wanted to do something tricky, but the splat means "all of 'em" (which in this context means, all the **possible** ones).
Granted, "\*" means something different here than in the SELECT clause, so maybe a different character would work better:
```
Select ClientName, InvoiceAmount, Sum(PaymentAmount) Group By !
```
There are a few other areas like that where SQL just isn't as eloquent as it could be. But at this point, it's probably too entrenched to make many big changes like that. | Because they are two different things, you can group by items that aren't in the select clause
EDIT:
Also, is it safe to make that assumption?
I have a SQL statement
```
Select ClientName, InvAmt, Sum(PayAmt) as PayTot
```
Is it "correct" for the server to assume I want to group by ClientName AND InvoiceAmount?
I personally prefer (and think it's safer) to have this code
```
Select ClientName, InvAmt, Sum(PayAmt) as PayTot
Group By ClientName
```
throw an error, prompting me to change the code to
```
Select ClientName, Sum(InvAmt) as InvTot, Sum(PayAmt) as PayTot
Group By ClientName
``` | Why does SQL force me to repeat all non-aggregated fields from my SELECT clause in my GROUP BY clause? | [
"",
"sql",
"group-by",
""
] |
I am trying to start a new MVC project with tests and I thought the best way to go would have 2 databases. 1 for testing against and 1 for when I run the app and use it (also test really as it's not production yet).
For the test database I was thinking of putting create table scripts and fill data scripts within the test setup method and then deleting all this in the tear down method.
I am going to be using Linq to SQL though and I don't think that will allow me to do this?
Will I have to just go the ADO route if I want to do it this way? Or should I just use a mock object and store data as an array or something?.
Any tips on best practices?
How did Jeff go about doing this for StackOveflow? | I checked out the link from tvanfosson and RikMigrations and after playing about with them I prefer the mocking datacontext method best. I realised I don't need to create tables and drop them all the time.
After a little more research I found Stephen Walther's article <http://stephenwalther.com/blog/archive/2008/08/17/asp-net-mvc-tip-33-unit-test-linq-to-sql.aspx> which to me seems easier and more reliable.
So I am going with this implementation.
Thanks for the help. | What I do is define an interface for a DataContext wrapper and use an implementation of the wrapper for the DataContext. This allows me to use an alternate, fake DataContext implementation in my tests (or mock it, if easier). This abstracts the database out of my unit tests completely. I found some starter code at <http://andrewtokeley.net/archive/2008/07/06/mocking-linq-to-sql-datacontext.aspx>, although I've extended it so that it handles the validation implementations on my entity classes.
I should also mention that I have a separate staging server for QA, so there is live testing of the entire system. I just don't use an actual database in my unit testing. | ASP.NET MVC TDD with LINQ and SQL database | [
"",
"sql",
"asp.net-mvc",
"linq",
"tdd",
""
] |
```
var y = new w();
var x = y.z;
y.z= function() {
doOneThing();
x();
}
```
*where `w` does not contain a `z` object but contains other objects (e.g, `a`, `b`, `c`)*
What is `x();` possibly referring too? (Again, this is JavaScript)
Is the function calling itself? | ```
var y = new w();
var x = y.z; # x = undefined ( you say there is no w().z )
y.z= function() {
doOneThing();
x(); # undefined, unless doOneThing defines x
};
```
however, if you manage to define x sometime before y.z(); then x() will be whatever it was defined at that time.
the following code does something analogous, as per your statements.
```
var y = {};
var x;
y.z = function(){
x();
};
y.z(); # type error, x is not a function.
x = function(){ } ;
y.z(); # works.
x = undefined;
y.z(); # type error, x is not a function.
``` | ```
var y = new w();
// Create a global variable x referring to the y.z method
var x = y.z;
y.z= function() {
doOneThing();
// Refers to the global x
x();
}
```
It would probably be clearer to rename `x` to `oldZ` | What does x(); refer to? | [
"",
"javascript",
""
] |
I'm looking for a way to (preferably) strongly type a master page from a user control which is found in a content page that uses the master page.
Sadly, you can't use this in a user control:
```
<%@ MasterType VirtualPath="~/Masters/Whatever.master" %>
```
I'm trying to access a property of the master page from the user control and would rather not have to pass the property from the master page to the content page to the user control because multiple content pages use the same user control. One change, one place whatnot. | Try `Page.Master`.
```
Whatever whatev = (Whatever)Page.Master;
```
You'll have to make sure you add the proper `using` statements to the top of your file, or qualify the Master page type inline.
One potential gotcha is if this control is used by a different page whose master page is NOT the same type. This would only get caught at runtime. | Have you tryed Page.FindControl("name") on the usercontrol? | How to reference a Master Page from a user control? | [
"",
"c#",
"asp.net",
"master-pages",
"user-controls",
""
] |
`cd` is the shell command to change the working directory.
How do I change the current working directory in Python? | You can change the working directory with:
```
import os
os.chdir(path)
```
You should be careful that changing the directory may result in destructive changes your code applies in the new location. Potentially worse still, do not catch exceptions such as `WindowsError` and `OSError` after changing directory as that may mean destructive changes are applied in the *old* location!
If you're on Python 3.11 or newer, then consider using this context manager to ensure you return to the original working directory when you're done:
```
from contextlib import chdir
with chdir(path):
# do stuff here
```
If you're on an older version of Python, Brian M. Hunt's answer shows how to roll your own context manager: [his answer](https://stackoverflow.com/questions/431684/how-do-i-cd-in-python/13197763#13197763).
Changing the current working directory in a subprocess does not change the current working directory in the parent process. This is true of the Python interpreter as well. You cannot use `os.chdir()` to change the CWD of the calling process. | Here's an example of a context manager to change the working directory. It is simpler than an [ActiveState version](http://code.activestate.com/recipes/576620-changedirectory-context-manager) referred to elsewhere, but this gets the job done.
### Context Manager: `cd`
```
import os
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
```
Or try the [more concise equivalent(below)](https://stackoverflow.com/a/24176022/263998), using [ContextManager](https://docs.python.org/2/library/contextlib.html#contextlib.contextmanager).
### Example
```
import subprocess # just to call an arbitrary command e.g. 'ls'
# enter the directory like this:
with cd("~/Library"):
# we are in ~/Library
subprocess.call("ls")
# outside the context manager we are back wherever we started.
``` | Equivalent of shell 'cd' command to change the working directory? | [
"",
"python",
"cd",
""
] |
I can send any windows application key strokes with `PostMessage` api. But I can't send key strokes to Game window by using `PostMessage`.
Anyone know anything about using Direct Input functions for sending keys to games from C#. | An alternate way would be to hook the DirectInput API directly - Microsoft Research has provided a library to do this already: <http://research.microsoft.com/en-us/projects/detours/>
Once you hook into the API, you can do whatever you want with it. However, it's worth noting that in recent versions of Windows, DirectInput for mouse & keyboard input is just a wrapper around the Win32 windows messages. DirectInput spawns a thread in the background and simply intercepts window messages before passing them along back to the application. It's one of the reasons why Microsoft no longer recommends the use of DirectInput - and it means that messaging APIs like PostMessage *should* work just fine. | One alternative, instead of hooking into DirectX, is to use a keyboard driver (this is not SendInput()) to simulate key presses - and event mouse presses.
You can use [Oblita's Interception keyboard driver](http://oblita.com/interception.html) (for Windows 2000 - Windows 7) and the [C# library Interception](https://github.com/jasonpang/Interceptor) (wraps the keyboard driver to be used in C#).
With it, you can do cool stuff like:
```
input.MoveMouseTo(5, 5);
input.MoveMouseBy(25, 25);
input.SendLeftClick();
input.KeyDelay = 1; // See below for explanation; not necessary in non-game apps
input.SendKeys(Keys.Enter); // Presses the ENTER key down and then up (this constitutes a key press)
// Or you can do the same thing above using these two lines of code
input.SendKeys(Keys.Enter, KeyState.Down);
Thread.Sleep(1); // For use in games, be sure to sleep the thread so the game can capture all events. A lagging game cannot process input quickly, and you so you may have to adjust this to as much as 40 millisecond delay. Outside of a game, a delay of even 0 milliseconds can work (instant key presses).
input.SendKeys(Keys.Enter, KeyState.Up);
input.SendText("hello, I am typing!");
/* All these following characters / numbers / symbols work */
input.SendText("abcdefghijklmnopqrstuvwxyz");
input.SendText("1234567890");
input.SendText("!@#$%^&*()");
input.SendText("[]\\;',./");
input.SendText("{}|:\"<>?");
```
Because the mechanism behind these key presses is a keyboard driver, it's pretty much unrestricted. | Send Key Strokes to Games using Direct Input | [
"",
"c#",
""
] |
I see this in a stack trace:
> myorg.vignettemodules.customregistration.NewsCategoryVAPDAO.getEmailContentByID(I)Lmyorg/pushemail/model/EmailContent;
What does the "`(I)L`" mean? | It means the method takes an `int`, and returns `myorg.pushemail.model.EmailContent`
The string from "L" to ";" is one type descriptor, for the return type. The stuff inside parentheses are the method parameters (in this case, there's just one).
These type descriptors are defined as part of the Java Virtual Machine Specification, in [section 4.3.2](http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2). [Table 4.3-A](http://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2-200) shows all of the codes used. When a class is compiled, descriptors of this form are used to specify the signature of methods and the types of fields and variables.
In Java serialization, method descriptors are part of the information that is hashed to [form the default `serialVersionUID`](http://docs.oracle.com/javase/8/docs/platform/serialization/spec/class.html#a4100) for a `Serializable` class.
In RMI, method descriptors are hashed, and the result is used to [identify which method is being invoked](http://docs.oracle.com/javase/8/docs/platform/rmi/spec/rmi-stubs24.html) in the remote interface. | It's a form of [name mangling](http://en.wikipedia.org/wiki/Name_mangling) used for disambiguating method overloads. The method name is appended by a series of characters describing the parameters and return type: the parameters appear sequentially inside parentheses, and the return type follows the closing parenthesis. The codes are as follows:
* `Z`: `boolean`
* `B`: `byte`
* `C`: `char`
* `S`: `short`
* `I`: `int`
* `J`: `long`
* `F`: `float`
* `D`: `double`
* `L`*fully-qualified-class-name* `;` : fully qualified class
* `[` *type* : array of *type*
* `V`: `void`
So, in your case, the `(I)Lmyorg/pushemail/model/EmailContent;` means the method takes one argument of type `int` and returns an object of type `myorg.pushemail.model.EmailContent`. | What does this mean in a stack trace? | [
"",
"java",
"exception",
"stack-trace",
""
] |
I have two classes: Media and Container.
I have two lists `List<Media>` and `List<Container>`
I'm passing these lists to another function (one at a time);
it can be one or another;
what's the proper way to check for the "template" type of the list so i can call an asssociated method depending on the list type?
or should i just try casting to the List<> and put Try/Catch blocks around it ?
```
Object tagObj = mediaFlow1.BackButton.Tag;
if (tagObj == Media)
//do this
else if (tagObj == Container)
//do this
else
throw new Exception("Not a recognized type");
``` | You can use the GetGenericArguments method of type Type, something like this:
object[] templates = myObject.GetType().GetGenericArguments(); | The proper thing to do is to have two overloads for this function, accepting each type:
```
public void MyMethod(List<Media> source)
{
//do stuff with a Media List
}
public void MyMethod(List<Container> source)
{
//do stuff with a Container List
}
``` | List Generics and Casting | [
"",
"c#",
"generics",
"casting",
""
] |
I just joined a new C++ software project and I'm trying to understand the design. The project makes frequent use of unnamed namespaces. For example, something like this may occur in a class definition file:
```
// newusertype.cc
namespace {
const int SIZE_OF_ARRAY_X;
const int SIZE_OF_ARRAY_Y;
bool getState(userType*,otherUserType*);
}
newusertype::newusertype(...) {...
```
What are the design considerations that might cause one to use an unnamed namespace? What are the advantages and disadvantages? | Unnamed namespaces are a utility to make an identifier [translation unit](https://stackoverflow.com/a/1106167/) local. They behave as if you would choose a unique name per translation unit for a namespace:
```
namespace unique { /* empty */ }
using namespace unique;
namespace unique { /* namespace body. stuff in here */ }
```
The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like `::name` that are defined in that namespace, since the using directive already took place.
This means you can have free functions called (for example) `help` that can exist in multiple translation units, and they won't clash at link time. The effect is almost identical to using the `static` keyword used in C which you can put in in the declaration of identifiers. Unnamed namespaces are a superior alternative, being able to even make a type translation unit local.
```
namespace { int a1; }
static int a2;
```
Both `a`'s are translation unit local and won't clash at link time. But the difference is that the `a1` in the anonymous namespace gets a unique name.
Read the excellent article at comeau-computing [Why is an unnamed namespace used instead of static?](http://www.comeaucomputing.com/techtalk/#nostatic) ([Archive.org mirror](https://web.archive.org/web/20181115023158/http://www.comeaucomputing.com/techtalk/#nostatic)). | Having something in an anonymous namespace means it's local to this [translation unit](https://en.wikipedia.org/wiki/Translation_unit_(programming)) (.cpp file and all its includes) this means that if another symbol with the same name is defined elsewhere there will not be a violation of the [One Definition Rule](http://en.wikipedia.org/wiki/One_Definition_Rule) (ODR).
This is the same as the C way of having a static global variable or static function but it can be used for class definitions as well (and should be used rather than `static` in C++).
All anonymous namespaces in the same file are treated as the same namespace and all anonymous namespaces in different files are distinct. An anonymous namespace is the equivalent of:
```
namespace __unique_compiler_generated_identifer0x42 {
...
}
using namespace __unique_compiler_generated_identifer0x42;
``` | Why are unnamed namespaces used and what are their benefits? | [
"",
"c++",
"oop",
"namespaces",
""
] |
Is there a way to bypass the following IE popup box:
> The webapge you are viewing is trying
> to close the window. Do you want to
> close this window? Yes|No
This is occurring when I add window.close() to the onclick event of an asp.net button control. | Your JavaScript code can only close a window without confirmation that was previously opened by window.open(). This is an intentional security precaution because a script running on a webpage does not own the window, and by closing it discards the browsing history in that window.
The workaround is to either have a "welcome page" or otherwise some sort of page that pops up the window you want to close with window.open in the first place, or to tell your users to modify their browser security settings to allow your application to close their windows. | # In the opened popup write following
```
var objWin = window.self;
objWin.open('','_self','');
objWin.close();
``` | Bypass IE "The webpage you are viewing..." pop up | [
"",
"javascript",
"asp.net",
"internet-explorer",
"popup",
""
] |
I have an Array of Objects that need the duplicates removed/filtered.
I was going to just override equals & hachCode on the Object elements, and then stick them in a Set... but I figured I should at least poll stackoverflow to see if there was another way, perhaps some clever method of some other API? | I would agree with your approach to override `hashCode()` and `equals()` and use something that implements `Set`.
Doing so also makes it absolutely clear to any other developers that the non-duplicate characteristic is required.
Another reason - you get to choose an implementation that meets your needs best now:
* [HashSet](http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashSet.html)
* [TreeSet](http://java.sun.com/j2se/1.5.0/docs/api/java/util/TreeSet.html)
* [LinkedHashSet](http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedHashSet.html)
and you don't have to change your code to change the implementation in the future. | I found this in the web
Here are two methods that allow you to remove duplicates in an ArrayList. removeDuplicate does not maintain the order where as removeDuplicateWithOrder maintains the order with some performance overhead.
1. The removeDuplicate Method:
```
/** List order not maintained **/
public static void removeDuplicate(ArrayList arlList)
{
HashSet h = new HashSet(arlList);
arlList.clear();
arlList.addAll(h);
}
```
2. The removeDuplicateWithOrder Method:
```
/** List order maintained **/
public static void removeDuplicateWithOrder(ArrayList arlList)
{
Set set = new HashSet();
List newList = new ArrayList();
for (Iterator iter = arlList.iterator(); iter.hasNext();) {
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
arlList.clear();
arlList.addAll(newList);
}
``` | What is the best way to remove duplicates in an Array in Java? | [
"",
"java",
"filtering",
"duplicates",
""
] |
I imagine I can compile a C# DLL and then expose it as a COM object so that it can be CreateObject'd from VBscript. I'm just not sure the steps involved in doing this... | It can be very simple to do this. But there are a lot of places where it's not so simple. It depends a lot on what your class needs to be able to do, and how you intend to deploy it.
Some issues to consider:
* Your class has to have a parameterless constructor.
* It can't expose static methods.
* Is deploying your COM DLL in the global assembly cache OK? If not, you're going to have to give it a strong name and register it using `regasm /codebase`.
* Do you care what GUIDs identify the class and its interfaces? If not, you can let `regasm` assign them, but they'll be different every time (and every place) the class is registered. If you need the GUIDs to remain invariant across installations, you'll need to mark members with the `Guid` attribute.
* Are you going to use the default marshaling of data types between .NET and COM? If not, you're going to need to mark properties and methods with the `MarshalAs` attribute.
* Does it matter to you what kind of COM interface your class exposes? If so, you're going to need to deal with the `InterfaceType` attribute.
* Does your class need to raise or respond to events? If so, there are implications for how you design your class interface.
There's a very good (if dated) article about COM interop and .Net [here](http://www.codeproject.com/KB/COM/cominterop.aspx). (A lot of things that article talks about, like generating type libraries, is handled for you automatically now.) And [Microsoft's documentation](http://msdn.microsoft.com/en-us/library/zsfww439.aspx) is up to date, but not quite so detailed. | You should use the `regasm` utility to register an assembly (just like you do `regsvr32` with COM servers). Then you can use it from COM. Make sure it's installed in the GAC. The stuff should have `[ComVisible(true)]` to be usable from COM. | How do I call .NET code (C#/vb.net) from vbScript? | [
"",
"c#",
".net",
"com",
"asp-classic",
""
] |
Is there a way where I can add a connection string to the ConnectionStringCollection returned by the ConfigurationManager at runtime in an Asp.Net application?
I have tried the following but am told that the configuration file is readonly.
```
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings(params));
```
Is there another way to do this at runtime? I know at design time I can add a connection string to the web.config; however, I'm looking to add something to that collection at run time.
Thanks
EDIT:
One of the reasons why I'm attempting to do this is due to a security requirement that prevents me from placing ConnectionStrings in the web.config (even encrypted). I would like to use elements like Membership and Profiles on my project; however, I am looking into an alternative to doing such w/o writing a custom provider. Custom Provider's aren't all that bad, but if I can find an easier solution, I'm all for it. | ```
var cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(@"/");
cfg.ConnectionStrings.ConnectionStrings.Add(new ConnectionStringSettings(params));
cfg.Save();
```
Be Advised this will cause your website to recycle since it modifies the config file. Check out [http://msdn.microsoft.com/en-us/library/4c2kcht0(VS.80).aspx](http://msdn.microsoft.com/en-us/library/4c2kcht0%28VS.80%29.aspx) | You can use reflection to disable the private bReadOnly field (bad idea, etc.):
```
typeof(ConfigurationElementCollection)
.GetField("bReadOnly", BindingFlags.Instance | BindingFlags.NonPublic)
.SetValue(ConfigurationManager.ConnectionStrings, false);
ConfigurationManager.ConnectionStrings.Add(new ConnectionStringSettings());
```
This is similar to the technique required to [modify an existing connection string](http://david.gardiner.net.au/2008/09/programmatically-setting.html), and added as a comment there by Brian Rodgers. | Can I Add ConnectionStrings to the ConnectionStringCollection at Runtime? | [
"",
"c#",
"asp.net",
"web-config",
"connection-string",
""
] |
I am trying to create a simple page that enters data in to a database and my code is below.
```
<%@ LANGUAGE="VBSCRIPT" %>
<% Option Explicit %>
<!--#include FILE=dbcano.inc-->
<%
dim username,password,f_name,l_name,objConn,objs,query
username = Request.Form("user")
password = Request.Form("pass")
f_name = Request.Form("fname")
l_name = Request.Form("lname")
if((f_name <> null) or (f_name <> "")) then
response.redirect("patti_account.asp")
else
Set objConn = ConnectDB()
query = "INSERT INTO user (username,password,f_name,l_name) VALUES ('"& username &"','"& password &"','"& f_name &"','"& l_name &"')"
Set objs = objConn.Execute(query)
Response.Redirect ("thankyou.asp")
end if
%>
```
I am getting this error when I run my page:
> Microsoft OLE DB Provider for SQL
> Server error '80040e14'
>
> Incorrect syntax near the keyword
> 'user'.
>
> create\_account.asp, line 18
I have checked everything, my field names exist and my table name is correct as well.
Any suggestions? | **User** is a reserved word in SQL server. Put it into square brackets, e.g. **[user]**. | This is vulnerable to SQL Injection. Imagine what would happen if someone put this in for the last name:
```
');DROP Table [user];--
```
Fix it or I will personally track you down and beat you with a wet noodle until you do. | Using ASP and INSERT INTO - | [
"",
"sql",
"asp-classic",
"vbscript",
"ado",
""
] |
Someone asserted on SO today that you should never use unnamed namespaces in header files. Normally this is correct, but I seem to remember once someone told me that one of the standard libraries uses unnamed namespaces in header files to perform some sort of initialization.
Am I remembering correctly? Can someone fill in the details? | The only situation in which a nameless namespace in header can be useful is when you want to distribute code as header files only. For example, a large standalone subset of Boost is purely headers.
The token `ignore` for tuples, mentioned in another answer is one example, the `_1`, `_2` etc. bind placeholders are others. | I don't see any point in putting an anonymous namespace into a header file. I've grepped the standard and the libstdc++ headers, found no anonymous namespaces apart of one in the `tuple` header (C++1x stuff):
```
// A class (and instance) which can be used in 'tie' when an element
// of a tuple is not required
struct _Swallow_assign
{
template<class _Tp>
_Swallow_assign&
operator=(const _Tp&)
{ return *this; }
};
// TODO: Put this in some kind of shared file.
namespace
{
_Swallow_assign ignore;
}; // anonymous namespace
```
This is so you can do
```
std::tie(a, std::ignore, b) = some_tuple;
```
elements of the some\_tuple are assigned the variables at the left side (see [here](https://stackoverflow.com/questions/275128/parallel-assignment-in-c#275149)), a similar technique is used for [this](https://stackoverflow.com/questions/335930/discarding-the-output-of-a-function-that-needs-an-output-iterator#335972) iterator. The second element is ignored.
But as they say, it should be put into a .cpp file and the one instance should be shared by all users. They would put a declaration of it into the header like this then:
```
extern _Swallow_assign ignore;
``` | Are there any uses for unnamed namespaces in header files? | [
"",
"c++",
"namespaces",
"initialization",
"header-files",
"unnamed-namespace",
""
] |
This might seem like a ridiculous question since I'm quite inexperienced in .NET.
Is it possible to build components in C#, using .NET, which can be reused in ASP.NET. For example if one would like to port an application onto the web.
If possible, how portable are they? I.e. can GUI be reused in some extent? Is there an intermediate format to use as base or is it required to use C# components as binaries?
Thanks.
**Edit:**
Thanks for your input! I'm quite familiar with the design aspects of this problem, i.e. how to model components for reuse. However you made me realize that the question really is about - To what extent is .NET reusable between ASP and Windows? Can one say that certain packages of .NET components are independent of environment and some are platform specific? | Absolutely - a .NET class can be used in any kind of .NET application. However, it kind of depends on what part of the application you're talking about.
Generally, Windows Forms user interfaces are NOT reusable as ASP.NET user interfaces, because the design constraints are so different (i.e. web browsers only support a small number of controls, often use flow (not grid) layout, etc. Similarly, the events are different (a web form button isn't the same as a windows form button, etc.).
What you can reuse easily, though, if you do things correctly, is the business logic. Design your classes so that they don't internally know anything about whether it's a windows form or a web form (or a console application, or web service, etc.). That is, the classes should be pure implementations of your business logic. Then you can use those classes in any context you want to. | The short answer to your question is yes - simply separate out the code you want to share between the two views into a interface-independent class, preferably in a separate assembly, and include that assembly.
The long answer is more complicated - the ability to do this will vary between application and application. You'll be able to separate out less code for UI intensive applications that don't do much behind the scenes (such as, say, some sort of graphics game), than you will for a very simple UI application that does a lot behind the scenes (say, a UI that consists of a single button that then kicks off a complex data manipulation process).
In the end - .NET provides the ability for you to do this. Your actual ability to do this will be very dependent on your own design abilities and your particular requirements. There's a lot of writing available on this subject - I suggest starting by taking a look at Design Patterns (though the original book writes examples in C++, I believe that someone has done a book with examples in C#. I cannot, however, speak to the quality of it.) | Component reuse between ASP.NET and C#.NET | [
"",
"c#",
".net",
"asp.net",
"portability",
"reusability",
""
] |
I know this is a pretty basic question, and I *think* I know the answer...but I'd like to confirm.
Are these queries truly equivalent?
```
SELECT * FROM FOO WHERE BAR LIKE 'X'
SELECT * FROM FOO WHERE BAR ='X'
```
Perhaps there is a performance overhead in using like with no wild cards?
I have an app that optionally uses LIKE & wild cards. The SP currently does the like and appends the wild cards -- I am thinking of just updating the query to use like but have the app append the wild cards as needed. | As @ocdecio says, if the optimizer is smart enough there should be no difference, but if you want to make sure about what is happening behind the scenes you should compare the two query's execution plans. | Original Answer by Matt Whitfield from [here](https://ask.sqlservercentral.com/questions/20216/why-use-like-without-a-wildcard.html)
**There is a difference** between `=` and `LIKE`. When you perform string comparisons by using `LIKE`, all characters in the pattern string are significant. This includes leading or trailing spaces.
So if you have a column that is `char` or `nchar` and not `nvarchar` or `varchar`, there will be different results due to trailing spaces.
Small example to reproduce this behaviour:
```
CREATE TABLE #temp (nam [varchar](MAX))
INSERT INTO [#temp] ([nam])
VALUES ('hello')
INSERT INTO [#temp] ([nam])
VALUES ('hello ')
SELECT * FROM #temp WHERE [nam] = 'hello '
SELECT * FROM #temp WHERE [nam] LIKE 'hello '
``` | SQL LIKE with no wildcards the same as '='? | [
"",
"sql",
"wildcard",
"sql-like",
""
] |
In the constructor of my class, I map the current object (*this*), along with its key (a string entered as a parameter in the constructor) into a static LinkedHashMap so I can reference the object by the string anywhere I might need it later.
Here's the code (if it helps):
```
public class DataEntry {
/** Internal global list of DataEntry objects. */
private static LinkedHashMap _INTERNAL_LIST;
/** The data entry's name. */
private String NAME;
/** The value this data entry represents. */
private Object VALUE;
/** Defines a DataEntry object with a name and a value. */
public DataEntry( String name, Object value )
{
if( _INTERNAL_LIST == null )
{
_INTERNAL_LIST = new LinkedHashMap();
}
_INTERNAL_LIST.put( name, this );
NAME = name;
VALUE = value;
}
}
```
The problem? Instances of this class won't get garbage collected when I'm done using them.
I'm just curious if there's a way to have instances of this class clean themselves up when I'm done using them without having to manually call a Remove() method or something each time (to remove its reference in the internal LinkedHashMap when I'm no longer using them, I mean). | Making an object visible to others before its constructor is complete is not thread safe.
It's not clear how the map is being used in this case, but suppose there's a static method like this in the class:
```
public static DataEntry getEntry(String name) {
return _INTERNAL_LIST.get(name);
}
```
Another thread, running concurrently, can access a `DataEntry` while it is being created, and start to use an entry with an uninitialized `VALUE`. Even you reorder the code in the constructor so that adding the new instance to the map is the last thing you do, the JVM is allowed to reorder the instructions so that the object is added to the list first. Or, if the class is extended, the subclass initialization could take place after the object has been published.
If more than one thread accesses the interacts with the `DataEntry` class, you could have a concurrency bug that is platform dependent, intermittent, and very tough to diagnose.
The article, ["Safe Construction,"](http://www.ibm.com/developerworks/java/library/j-jtp0618.html#2) by Brian Goetz has more information on this topic.
Back to the original question: using `WeakReference`, as mentioned by others, is a good approach, but rather than iterating over every entry in the map, I'd recommend creating a wrapper for your values that extends `WeakReference` (it could be your `DataEntry` itself, or a helper), and queuing each reference in a [`ReferenceQueue`](http://java.sun.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html). That way, you can quickly poll the queue for any collected entries, and remove them from the map. This could be done by a background thread (blocking on [`remove`](http://java.sun.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html#remove())) started in a class initializer, or any stale entries could be cleaned (by [polling](http://java.sun.com/javase/6/docs/api/java/lang/ref/ReferenceQueue.html#poll())) each time a new entry is added.
If your program is multi-threaded, you should abandon `LinkedHashMap` for a map from [`java.util.concurrent`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentMap.html), or wrap the `LinkedHashMap` with [`Collections.synchronizedMap()`](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedMap(java.util.Map)). | Make the values [WeakReferences](http://java.sun.com/javase/6/docs/api/java/lang/ref/WeakReference.html) (or [SoftReferences](http://java.sun.com/javase/6/docs/api/java/lang/ref/SoftReference.html)) instead. That way the values can still be garbage collected. You'll still have entries in the map, of course - but you can periodically clear out the map of any entries where the Weak/SoftReference is now empty. | Garbage Collecting objects which keep track of their own instances in an internal Map | [
"",
"java",
"garbage-collection",
"dictionary",
"object",
""
] |
What is the difference between the three functions and when to use them?? | WinMain is used for an application (ending .exe) to indicate the process is starting. It will provide command line arguments for the process and serves as the user code entry point for a process. WinMain (or a different version of main) is also a required function. The OS needs a function to call in order to *start* a process running.
DllMain is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when
1. The DLL is loaded into the process: DLL\_PROCESS\_ATTACH
2. The DLL is unloaded from the process: DLL\_PROCESS\_DETACH
3. A thread is started in the process: DLL\_THREAD\_ATTACH
4. A thread is ended in the process: DLL\_THREAD\_DETACH
DllMain is an optional construct and has a lot of implicit contracts associated with it. For instance, you should not be calling code that will force another DLL to load. In general it's fairly difficult function to get right and should be avoided unless you have a very specific need for it. | **main()** means your program is a [console application](http://en.wikipedia.org/wiki/Console_application).
**WinMain()** means the program is a [GUI application](http://en.wikipedia.org/wiki/Graphical_user_interface) -- that is, it displays windows and dialog boxes instead of showing console.
**DllMain()** means the program is a [DLL](http://en.wikipedia.org/wiki/Dynamic-link_library). A DLL cannot be run directly but is used by the above two kinds of applications.
Therefore:
* Use WinMain when you are writing a program that is going to display windows etc.
* Use DLLMain when you write a DLL.
* Use main in all other cases. | Difference between WinMain,main and DllMain in C++ | [
"",
"c++",
"windows",
"entry-point",
"winmain",
""
] |
I have two tables, tblEntities and tblScheduling.
tblEntities:
```
EntityID ShortName Active
1 Dirtville 1
2 Goldtown 1
3 Blackston 0
4 Cornfelt 1
5 Vick 1
```
tblScheduling:
```
ScheduleID EntityID SchedulingYearID
1 1 20
2 1 21
3 2 20
4 3 19
5 5 20
```
I need a query that will show **ALL ACTIVE** Entities and their schedule information for a particular ScheduleYearID.
Output should look like (the desired SchedulingYearID in this case is 20):
```
EntityID ScheduleID
1 1
2 3
4 NULL
5 5
```
The query that I have written so far is:
```
SELECT tblEntities.EntityID, tblEntities.ShortName, tblScheduling.ScheduleID
FROM tblScheduling RIGHT OUTER JOIN
tblEntities ON tblScheduling.EntityID = tblEntities.EntityID
WHERE (tblScheduling.SchedulingYearID = @SchedulingYearID)
AND (tblEntities.Active = 1)
ORDER BY tblEntities.EntityID
```
My problem is that using this query it will not include active entities without schedule information (such as EntityID 4 in the example above). I can write the query to display all active entities and their schedule status fine, but once I start limiting it via the SchedulingYearID I lose those particular entities.
Are there any solutions that I am obviously missing without having to resort to subqueries, cursors, etc.? If not it's not a big deal, I just feel like I am missing something simple here. | Try this... Join conditions are evaluated to produce the intermediate Join result set, and then, (for an outer join), all the rows from the "Outer" side are added back in before moving on... Where conditions are evaluated after all joins are done...
```
SELECT E.EntityID, E.ShortName, S.ScheduleID
FROM tblEntities E
Left Join tblScheduling S
ON S.EntityID = E.EntityID
And S.SchedulingYearID = @SchedulingYearID
WHERE E.Active = 1
ORDER BY E.EntityID
```
I change your join order cause I prefer left joins... but it doesn't matter | It's your conditions in the where clause:
(tblScheduling.SchedulingYearID = @SchedulingYearID)
when there is no tblScheduling info this wil always fail. Add
(((tblScheduling.SchedulingYearID = @SchedulingYearID) OR (tblScheduling.SchedulingYearID is null) )
or wathever null condition checking your DB uses. | Problem with SQL Join | [
"",
"sql",
"database",
"sql-server-2005",
""
] |
I have this enum:
```
enum ButtonState {
BUTTON_NORMAL = 0,
BUTTON_PRESSED = 1,
BUTTON_CLICKED = 2
};
const u8 NUM_BUTTON_STATES = 3;
```
In my Button class I have member variables `ButtonState state;` and `ButtonColors colors[NUM_BUTTON_STATES];`. When drawing the button, I use `colors[state]` to get the colours for whatever state the button is in.
My questions:
1. Is this good programming style? Is there a better way to do it? (I usually only use enums with switch statements... using an enum as an array index doesn't feel right.)
2. Do I *have* to specify the values of the enum? It seems to start from 0 by default and increment by 1 but is it guaranteed to work that way in all compilers? | ***Is this good programming style?***
I think so. I do the same thing quite frequently.
***Is there a better way to do it?***
```
class Button
{
public:
// Used for array indexes! Don't change the numbers!
enum State {
NORMAL = 0,
PRESSED,
CLICKED,
NUMBER_OF_BUTTON_STATES
};
};
```
Drawback is that *NUMBER\_OF\_BUTTON\_STATES* is now a valid *Button::State* value. Not a big issue if you are passing these values around as *ints*. But trouble if you are actually expecting a *Button::State*.
***Using an enum as an array index doesn't feel right.***
It's fine. Just **DOCUMENT** it, so the next guy knows what's going on! (That's what comments are for.)
***Do I have to specify the values of the enum?***
With no '=' assignment, enum's *are supposed to* start at zero and increment upwards.
If a enum entry has an '=' assigned value, subsequent non '=' enum entries continue counting from there.
Source: *The Annotated C++ Reference Manual*, pg 113
That said, I like to specify the initial value just to make the code that much clearer. | Yeah it will work well. That said, in any case, you *really* should put another entry in your enumeration defining the value of the amount of items:
```
enum ButtonState {
BUTTON_NORMAL,
BUTTON_PRESSED,
BUTTON_CLICKED,
STATE_COUNT
};
```
Then you can define the array like
```
Color colors[STATE_COUNT];
```
otherwise, it's a mess to keep the amount of states synchronous with the size of the array. Enumerations will always start with zero if not otherwise initialized, and then each additional entry will be assigned a value one above the previous one, if not otherwise initialized. Of course it also wouldn't hurt if you put a zero explicitly if you want. If you don't mind additional code, i would wrap the access to the raw array using a function like
```
Color & operator[](ButtonState state) {
return array[state];
}
```
Or an equivalent `getColor` function forwarding the request. That would forbid directly indexing the array with some integer, which would almost certainly at some point fail because one gets the indexes wrong. | Using an enum as an array index | [
"",
"c++",
"enums",
""
] |
I'm using Zend\_Form to output a set group of checkboxes:
```
<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>
```
With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:
```
$("input[@name='user_group[]']").val()
```
but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas? | You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):
```
$("input[name='user_group[]']:checked")
```
With those checked items, you can either create a collection of those values or do something to the collection:
```
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});
``` | I'm not sure about the "@" used in the selector. At least with the latest jQuery, I had to remove the @ to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
```
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
```
Now both, items and about work. | Select values of checkbox group with jQuery | [
"",
"javascript",
"jquery",
""
] |
I'm building a distributed C++ application that needs to do lots of serialization and deserialization of simple data structures that's being passed between different processes and computers.
I'm not interested in serializing complex class hierarchies, but more of sending structures with a few simple members such as number, strings and data vectors. The data vectors can often be many megabytes large.
I'm worried that text/xml-based ways of doing it is too slow and I really don't want to write this myself since problems like string encoding and number endianess can make it way more complicated than it looks on the surface.
I've been looking a bit at protocol buffers and boost.serialize. According to the documents protocol buffers seems to care much about performance.
Boost seems somewhat more lightweight in the sense that you don't have an external language for specifying the data format which I find quite convenient for this particular project.
So my question comes down to this: does anyone know if the boost serialization is fast for the typical use case I described above?
Also if there are other libraries that might be right for this, I'd be happy to hear about them. | I would strongly suggest protocol buffers. They're incredibly simple to use, offer great performance, and take care of issues like endianness and backwards compatibility. To make it even more attractive, serialized data is language-independent thanks to numerous language implementations. | ACE and ACE TAO come to mind, but you might not like the size and scope of it.
<http://www.cs.wustl.edu/~schmidt/ACE.html>
Regarding your query about "fast" and boost. That is a subjective term and without knowing your requirements (throughput, etc) it is difficult to answer that for you. Not that I have any benchmarks for the boost stuff myself...
There are messaging layers you can use, but those are probably slower than boost. I'd say that you identified a good solution in boost, but I've only used ACE and other proprietary communications/messaging products. | C++ Serialization Performance | [
"",
"c++",
"performance",
"serialization",
"boost",
"protocol-buffers",
""
] |
For Web-dev, can the PHP Processor be installed on a regular Windows XP machine, such that viewing PHP files through a browser executes the PHP script? *(NOT Windows Server 2003)*
I even [downloaded PHP](http://www.php.net/downloads.php) but it appears they want it installed on a server.
Any other ways to **quickly preview and run PHP on a local machine** WITHOUT uploading the file to server? *([Dreamweaver](http://www.adobe.com/products/dreamweaver/) can process the static HTML within PHP files..)* | I suggest:
<http://www.wampserver.com/en/>
or
<http://www.apachefriends.org/en/xampp.html>
These are easy-install packages of apache+php+mysql for windows. | I use the [XAMPP LAMP stack](http://www.apachefriends.org/en/xampp.html). One click install on Windows XP Pro and Home versions. | Can PHP be installed on a local machine? | [
"",
"php",
"wysiwyg",
"localhost",
"offline",
""
] |
I'm trying to work this out.
In my project, i have a file called 'Hello.java' which is the file with the main() argument and which is called when the program is compiled. And I have another file called MyObj.java which has got just a random class I made up to test java's OO features. I'm trying to do this:
```
class Hello
{
public MyObj an_obj;
public static void main(String[] args)
{
setObj();
}
public void setObj()
{
this.an_obj.set_size(7);
say("size is " + this.an_obj.get_size());
}
}
```
In the MyObj.java class i have this code:
```
public class MyObj
{
private int size;
public MyObj()
{
//do nothing
}
public void set_size(int new_size)
{
this.size=new_size;
}
public int get_size()
{
return this.size;
}
}
```
This however gives the error:
> "Cannot make a static reference to
> non-static method setObj() from the
> type Hello".
If I add 'static' to the declaration of setObj, i.e
```
public static void setObj()
```
Then I get:
> Cannot make a static reference to
> non-static field an\_obj.
My question is, how can I accomplish what I'm doing, i.e setting and retreiving an object's field if the only way to start a program is with the Main method, and the main Method can only call static methods?? In what, how can I do anything at all with this limitation of being able to call static methods only????? | You can either add "static" to the member variable as well, or instantiate the class from within your main method. Here is some example code for both approaches:
```
/* Static */
class Hello {
public static MyObj an_obj;
public static void main(String[] args) {
setObj();
}
public static void setObj() {
this.an_obj.set_size(7);
say("size is " + this.an_obj.get_size());
}
}
/* Non-Static */
class Hello {
public MyObj an_obj;
public static void main(String[] args) {
Hello hello = new Hello();
hello.setObj();
}
public void setObj() {
this.an_obj.set_size(7);
say("size is " + this.an_obj.get_size());
}
}
```
The primary difference between these two approaches is that in the first, "an\_obj" is static--that is to say, there is only one variable for the entire program. If you were to instantiate multiple Hello objects, they would all have the same "an obj" reference. In the second, each Hello object has its own "an obj" reference, each of which can point to a different MyObj instance.
Obviously in this simple situation it doesn't make any difference one way or the other, but generally speaking, static members and methods should be avoided when possible. | Make both the `setObj()` method and the `an_obj` variable `static`, or do something like:
```
public static void main(String[] args) {
new Hello().setObj();
}
``` | How to overcome limitations of Java's Static Main() Method | [
"",
"java",
""
] |
I have code where I schedule a task using `java.util.Timer`. I was looking around and saw `ExecutorService` can do the same. So this question here, have you used `Timer` and `ExecutorService` to schedule tasks, what is the benefit of one using over another?
Also wanted to check if anyone had used the `Timer` class and ran into any issues which the `ExecutorService` solved for them. | According to [Java Concurrency in Practice](http://jcip.net/):
* `Timer` can be sensitive to changes in the system clock, `ScheduledThreadPoolExecutor` isn't.
* `Timer` has only one execution thread, so long-running task can delay other tasks. `ScheduledThreadPoolExecutor` can be configured with any number of threads. Furthermore, you have full control over created threads, if you want (by providing `ThreadFactory`).
* Runtime exceptions thrown in `TimerTask` kill that one thread, thus making `Timer` dead :-( ... i.e. scheduled tasks will not run anymore. `ScheduledThreadExecutor` not only catches runtime exceptions, but it lets you handle them if you want (by overriding `afterExecute` method from `ThreadPoolExecutor`). Task which threw exception will be canceled, but other tasks will continue to run.
If you can use `ScheduledThreadExecutor` instead of `Timer`, do so.
One more thing... while `ScheduledThreadExecutor` isn't available in Java 1.4 library, there is a [Backport of JSR 166 (`java.util.concurrent`) to Java 1.2, 1.3, 1.4](http://backport-jsr166.sourceforge.net/), which has the `ScheduledThreadExecutor` class. | If it's available to you, then it's difficult to think of a reason *not* to use the Java 5 executor framework. Calling:
```
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
```
will give you a `ScheduledExecutorService` with similar functionality to `Timer` (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the `Timer` class). Using a `ScheduledExecutorService` also gives you advantages such as:
* You can customize it if need be (see the `newScheduledThreadPoolExecutor()` or the `ScheduledThreadPoolExecutor` class)
* The 'one off' executions can return results
About the only reasons for sticking to `Timer` I can think of are:
* It is available pre Java 5
* A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case) | Java Timer vs ExecutorService? | [
"",
"java",
"timer",
"scheduled-tasks",
"scheduling",
"executorservice",
""
] |
I'm a Java EE person who would like to climb the .NET learning curve.
I've always had the impression that one important difference between Java and .NET was that the Microsoft suite required that you (or your employer) had put up some coin to get access to the tools. A Java person has the advantage of being able to download a JVM, Eclipse or NetBeans, Tomcat or Glassfish, MySQL or PostgreSQL, and they're in business. Is that still fair? What's the best way for a guy who works in a Java EE shop to learn C# without breaking the bank? Is it possible learn C# well without a paid subscription to MSDN? | No subscription is required. You can even download the free [Visual Studio Express Edition](http://www.microsoft.com/express/), and also access to the [MSDN library](http://msdn.microsoft.com/en-us/library/default.aspx) is free. And there is also [Sql Server Express edition](http://www.microsoft.com/express/) which is also free.
Add to this all the great free online resources, like stackoverflow, [asp.net](http://asp.net), [codeproject](http://www.codeproject.com), blogs etc. and you are ready to go. | In addition to the Express tools that have already been mentioned, you'll also want IIS for web development. That comes included in the various pro/business versions of Windows.
The MSDN documentation is available online for free as well.
The [main difference](http://msdn.microsoft.com/en-us/vs2005/aa700921.aspx "main difference") between the free Express and the paid versions of Visual Studio is that you don't get support for plug-ins, some debugging tools, some projects (such as Windows services), Crystal Reports, installers, and other tool which are useful in business, but aren't important for learning.
After you've learned C#, if you need features that aren't in the free versions, you can buy the tools you need separately from the MSDN and save some cash. Visual Studio standard is about $250 and SQL Developer is about $50. The primary advantage of the MSDN is that it gives you *all* of the tools you need for development using the Microsoft stack. Depending on the [type of MSDN (pdf)](http://download.microsoft.com/download/1/d/2/1d28cf80-667f-4d68-bb70-48875e0e10f5/80024_msdnSubscription.pdf "type of MSDN (pdf)") you get desktop and server OSes, Office, Visual Studio, and various server applications. Those can be very useful, but certainly aren't needed for learning.
Microsoft also provides 30+ day evaluations of many of their professional tools. [Windows Server](http://msdn.microsoft.com/en-us/evalcenter/cc137233.aspx "Windows Server"), [Visual Studio](http://msdn.microsoft.com/en-us/visualc/aa700831.aspx "Visual Studio"), [SQL](http://www.microsoft.com/sqlserver/2008/en/us/trial-software.aspx "SQL"), [Sharepoint](http://www.microsoft.com/downloads/details.aspx?FamilyId=2E6E5A9C-EBF6-4F7F-8467-F4DE6BD6B831&displaylang=en "Sharepoint"), [Expression](http://www.microsoft.com/expression/try-it/Default.aspx "Expression")
In my opinion, there is absolutely no reason you need an MSDN subscription to learn C# well. But it is useful for a professional developer who focuses on Microsoft tools. | Does Learning C#/.NET Require An MSDN Subscription? | [
"",
"c#",
".net",
"jakarta-ee",
""
] |
I am trying to execute this SQL command:
```
SELECT page.page_namespace, pagelinks.pl_namespace, COUNT(*)
FROM page, pagelinks
WHERE
(page.page_namespace <=3 OR page.page_namespace = 12
OR page.page_namespace = 13
)
AND
(pagelinks.pl_namespace <=3 OR pagelinks.pl_namespace = 12
OR pagelinks.pl_namespace = 13
)
AND
(page.page_is_redirect = 0)
AND
pagelinks.pl_from = page.page_id
GROUP BY (page.page_namespace, pagelinks.pl_namespace)
;
```
When I do so, I get the following error:
```
ERROR: could not identify an ordering operator for type record
HINT: Use an explicit ordering operator or modify the query.
********** Error **********
ERROR: could not identify an ordering operator for type record
SQL state: 42883
Hint: Use an explicit ordering operator or modify the query.
```
I have tried adding : *ORDER BY (page.page\_namespace, pagelinks.pl\_namespace) ASC* to the end of the query without success.
UPDATE:
I also tried this:
```
SELECT page.page_namespace, pagelinks.pl_namespace, COUNT(*)
FROM page, pagelinks
WHERE pagelinks.pl_from = page.page_id
GROUP BY (page.page_namespace, pagelinks.pl_namespace)
;
```
But I still get the same error.
Thx | I haven't checked any documentation but the fact that you have your `GROUP BY` expression in parentheses looks unusual to me. What happens if you don't use parentheses here? | I'm not really an expert, but my understanding of that message is that PostgreSQL compains about not being able to handle either `page.page_namespace <=3` or `pagelinks.pl_namespace <=3`. To make a comparison like that you need to have an order defined and maybe one of these fields is not a standard numerical field. Or maybe there is some issue with integer vs. floating point -- e.g. the question if "3.0 = 3" isn't really that easy to answer since the floating point representation of 3.0 is most likely not exactly 3.
All just guesswork, but I'm pretty sure those two `<=`s are your problem. | PostgreSQL query inconsistency | [
"",
"sql",
"postgresql",
"rdbms",
"wikipedia",
""
] |
PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the `empty()` function. This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc? | This didn't work for me.
```
if (empty($variable) && '0' != $variable) {
// Do something
}
```
I used instead:
```
if (empty($variable) && strlen($variable) == 0) {
// Do something
}
``` | I seldom use `empty()` for the reason you describe. It confuses legitimate values with emptiness. Maybe it's because I do a lot of work in SQL, but I prefer to use `NULL` to denote the absence of a value.
PHP has a function `is_null()` which tests for a variable or expression being `NULL`.
```
$foo = 0;
if (is_null($foo)) print "integer 0 is null!\n";
else print "integer 0 foo is not null!\n";
$foo = "0";
if (is_null($foo)) print "string '0' is null!\n";
else print "string '0' is not null!\n";
$foo = "";
if (is_null($foo)) print "string '' is null!\n";
else print "string '' is not null!\n";
$foo = false;
if (is_null($foo)) print "boolean false is null!\n";
else print "boolean false is not null!\n";
```
You can also use the exactly equals operator `===` to do a similar test:
```
if ($foo === null) print "foo is null!\n";
```
This is true if `$foo` is `NULL`, but not if it's `false`, zero, `""`, etc. | Fixing the PHP empty function | [
"",
"php",
"function",
"object",
""
] |
I'm relatively new to the Component Object Model specification - I have a simple question:
* How can I access a **COM interface** from a C or C++ application
For instance, accessing Microsoft Excel COM interface to perform basic operations, without user intervention.
Kind regards | Actually, you will need to instantiate the object using the COM interface.
This is fairly complicated, more than we can just answer here.
here is a good primer: <http://www.codeproject.com/KB/COM/comintro.aspx>
Another one: <http://www.codeguru.com/cpp/com-tech/activex/tutorials/article.php/c5567> | I would suggest looking into ATL if you are using C++, and using C++ if using C. It is very easy to use the #import construct to access COM objects in DLLs or EXEs. | Accessing COM interface from C or C++ in Windows environment | [
"",
"c++",
"c",
"windows",
"com",
""
] |
Can a **PHP script** (which can be working with a MySQL DB) **send and/or receive SMSs** using some sort of server-side solution?
Any special server-side **application**, or special **hardware** required?
And compatibility? Windows, **Linux?** | There are plenty of companies like [Esendex](http://www.esendex.co.uk/) that offer APIs for sending/receiving SMS messages. I'm not sure if you're looking to send them directly from your hardware though? | If you are in the UK, txtlocal is a good option. They already have example code on their site to get you up and running. Very simple, using curl functions.
<http://www.txtlocal.co.uk/> | Send and receive SMSs to a PHP script? | [
"",
"php",
"sms",
"bulksms",
"cellular-network",
""
] |
The [yield](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield) keyword is one of those [keywords](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/) in C# that continues to mystify me, and I've never been confident that I'm using it correctly.
Of the following two pieces of code, which is the preferred and why?
**Version 1:** Using yield return
```
public static IEnumerable<Product> GetAllProducts()
{
using (AdventureWorksEntities db = new AdventureWorksEntities())
{
var products = from product in db.Product
select product;
foreach (Product product in products)
{
yield return product;
}
}
}
```
**Version 2:** Return the list
```
public static IEnumerable<Product> GetAllProducts()
{
using (AdventureWorksEntities db = new AdventureWorksEntities())
{
var products = from product in db.Product
select product;
return products.ToList<Product>();
}
}
``` | I tend to use `yield return` when I calculate the next item in the list (or even the next group of items).
Using your Version 2, you must have the complete list before returning.
By using `yield return`, you really only need to have the next item before returning.
Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.
Another case where `yield return` is preferable is if the `IEnumerable` represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full `IEnumerable` at once, so you use `yield return` to return the list incrementally.
In your particular example, you have the full list of products, so I'd use Version 2. | Populating a temporary list is like downloading the whole video, whereas using `yield` is like streaming that video. | Proper use of 'yield return' | [
"",
"c#",
"yield-return",
""
] |
I've been a java developer for a couple years and have heard that you can do some pretty useful and powerful things with JNI. I don't know if I just haven't needed to use it or if it isn't terribly relevant to me; but I have not had to touch it at all.
I am wondering what the usefulness of this aspect of Java is. Examples would be great. | It is very useful. I can see 2 primary reasons to use JNI (there are likely more).
1. Performance. If you have a piece of code in which the Java Runtime for whatever reason can't cut it performance wise. You can implement that function in native code and call it from Java. This allows you to hand tune the implementation if you *really* need to. This is likely the least common reason though, Java usually performs just fine.
2. Access to OS Specific APIs. This one is a biggie. I've had a case where I needed to do something in Java but also needed access to something that Java simply could not provide. In my case it was UNIX domain sockets. Since (as you can tell by the name) they are UNIX specific, there is no standard Java way to use them. So I made a class that acted like a wrapper around them in C and accessed it with JNI. viola, problem solved. | I have written an extensive JNI layer for the iSeries to access DB2, user queues, data queues and a few other OS/400 specifics. Much of our system on the iSeries would have been impossible without JNI. So, yes, JNI has it's place, and when you need it, you *really* need it.
It's relatively difficult (next to pure Java), but powerful and not horrible.
Also, whenever I am looking at some JNI code, I also consider using [JNA](https://github.com/twall/jna/). | Usefulness of JNI | [
"",
"java",
"interop",
"java-native-interface",
""
] |
I'm an Objective-C developer porting an application to the .Net world. In my Obj-C application, I use NSNotification objects to communicate asynchronously between a handful of objects. Is there some way to do something similar in the .Net world (more specifically, using the C# language)? The fundamental approach is that one object posts a notification that one or more objects listen for.
There's probably an obvious way of doing this, but I haven't found it yet... | Using Delegates in C# or VB.NET is the equivalent language integrated feature. You can create events by defining or using a predefined Delegate to define the "notification" that can be published and subscribed to. Then define an event on a class that you can subscribe to and raise. The MSDN documentation has a good overview once you find it [here](http://msdn.microsoft.com/en-us/library/edzehd2t.aspx). A good example is [here](http://msdn.microsoft.com/en-us/library/9aackb16.aspx). | You probably use NSNotification with NSNotificationCenter which is implementation of [Event Aggregator pattern](http://martinfowler.com/eaaDev/EventAggregator.html), it is [implemented in Prism library](http://msdn.microsoft.com/en-us/library/ff921122%28v=pandp.20%29.aspx) | C#/.Net equivalent of NSNotification | [
"",
"c#",
"objective-c",
"notifications",
"message-passing",
""
] |
One of the advantages of Flash/Flex is that you can use vector graphics (SVG), which is nice. I did a bit of searching around and came across this [Javascript vector graphics library](http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm). It's pretty simple stuff but it got me thinking: is there any possibility of using vector graphics files such as SVG with Javascript/HTML or it just can't be done or done reasonably? | I've used [Raphaël Javascript Library](http://raphaeljs.com/) and it worked quite well. Currently the library supports Firefox 3.0+, Safari 3.0+, Opera 9.5+ and Internet Explorer 6.0+. | I know this is a pretty old question, but in case anyone comes across this question, the most impressive vector graphics I've seen in JavaScript is [Paper.js](http://paperjs.org/).
Hope that helps. | Vector graphics in Javascript? | [
"",
"javascript",
"html",
"vector-graphics",
""
] |
I'm using VS2008 C# Express and the Northwind database on a Windows Form application.
I used drag and drop to set up the master details binding (I used the Orders and Order Details) for the two datagridviews. At this point, everything works as expected. So as not to return every row in the table, I want to filter the Orders table based on a filter for the Orders Table AND also on a field in the Orders Details table. In the TableAdapter Configuration Wizard, I used the query builder to add a new FillByMyFilter which created the following query:
SELECT Orders.[Order ID], Orders.[Customer ID], Orders.[Employee ID], Orders.[Ship Name], Orders.[Ship Address], Orders.[Ship City], Orders.[Ship Region],
Orders.[Ship Postal Code], Orders.[Ship Country], Orders.[Ship Via], Orders.[Order Date], Orders.[Required Date], Orders.[Shipped Date],
Orders.Freight
FROM Orders INNER JOIN
[Order Details] ON Orders.[Order ID] = [Order Details].[Order ID]
WHERE (Orders.[Ship Name] LIKE N'A%') AND ([Order Details].Quantity < 20)
I got this by adding both tables but did not check any of the field boxes in the Order Details table so that it would only return the columns that were used in the original Fill query. I'm only trying to filter the DataSet in the master table at this point and not return a different number of columns. Child rows of the Order Details should still work like the default unfiltered result set.
Now the problem: When I click the Execute Query button it works fine. I get 53 rows from the above query rather than the 1078 using the default Fill created by the designer. It return the same columns as the original fill query. However, when I try and run the application I get the following constraint error:
"Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."
What am I doing wrong?
UPDATE: I think I'm getting the constraint error because of the INNER JOIN created by the Wizard. If I edit the query to use LEFT JOIN then the Wizard changes it back to INNER JOIN.
My question still stands as how to filter records in the Parent table (Orders) based on criteria from both the Parent and Child table. My next test is to try and use a stored proc but would like to know using just the TableAdapter custom FillBy method.
Regards,
DeBug | Thanks to all that posted an answer. Here is how I did it using the TableAdapter Wizard and the Northwind typed dataset.
1) Right click the Parent table in the xsd designer to add or configure the query.
2) Click the "Next" button in the Wizard until you see the "Query Builder" button. Click the Query Builder button to get yourself in the query builder mode.
3) Right click and add the child table in the design pane. You should have both tables and the default constraint that connects them.
4) Click the column on the child table that you want to filter (this check mark will be removed later) in order to add it to the criteria pane so you can filter it.
5) Add the filter for the Parent and Child columns. In this example, I filtered the Ship Name LIKE 'A%' and the Order Quantity < 20.
Note that at this point you can test your query by clicking the Execute Query button. Using the Northwind DB for SQL 2008 compact edition I get 53 rows returned. If you were to save it at this point it would fail at runtime because of the duplicate Primary Keys in the result set. So the next few steps will get rid of 'em.
6) In the criteria pane, uncheck the child table column that you added previously. The filter will remain and the same column will now be uncheck in the design pane as well. If you run the query you will still have 53 rows but without the child table column.
7) Right click the design pane and add the "Group By". At this point, when you execute this query, you should have no duplicates in the Order ID. I got exactly 29 rows returned.
8) Click OK and then the "Next" button until you save your new FillBy query.
9) Change your source code to use your new FillBy.
When I ran the application, I got the filtered Parent table with the same 29 rows that the Execute Query button returned. The child table worked as expected and contained at least one child row that contained a quantity of < 20.
For a real world application, I think it would be better to use a stored proc or LINQ. But this problem had me scratching my head and so I "made it fit" just because it was a challenge (at least for me). | This article contains some troubleshooting suggestions to pinpoint the exact row causing the problem:
[DataSet hell - "Failed to enable constraints. One or more rows contain values...."](http://osherove.com/blog/2004/10/3/dataset-hell-failed-to-enable-constraints-one-or-more-rows-c.html) | How do you filter a TableAdapter's FillBy based on two tables? | [
"",
"c#",
"filter",
"strongly-typed-dataset",
"tableadapter",
""
] |
I'm learning Python now because of the Django framework. I have been a Perl programmer for a number of years and I'm so used to Perl's tools. One of the things that I really miss is Perl's CPAN and its tools. Is there anything equivalent in Python? I would like to be able to search, install and maintain Python modules as easy as CPAN. Also, a system that can handle dependencies automatically. I tried to install a module in Python by downloading a zip file from a website, unzipped it, then do:
`sudo python setup.py install`
but it's looking for another module. Now, lazy as I am, I don't like chasing dependencies and such, is there an easy way? | sammy, have a look at [pip](http://pip.openplans.org/), which will let you do "pip install foo", and will download and install its dependencies (as long as they're on [PyPI](http://pypi.python.org/)). There's also [EasyInstall](http://peak.telecommunity.com/DevCenter/EasyInstall), but pip is intended to replace that. | It might be useful to note that pip and easy\_install both use the [Python Package Index (PyPI)](http://pypi.python.org/pypi), sometimes called the "Cheeseshop", to search for packages. Easy\_install is currently the most universally supported, as it works with both setuptools and distutils style packaging, completely. See [James Bennett's commentary](http://www.b-list.org/weblog/2008/dec/14/packaging/) on python packaging for good reasons to use pip, and [Ian Bicking's reply](http://blog.ianbicking.org/2008/12/14/a-few-corrections-to-on-packaging/) for some clarifications on the differences. | For Python programmers, is there anything equivalent to Perl's CPAN? | [
"",
"python",
"perl",
""
] |
```
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,
hrl.unq, hrl.LcnsId, hc.Business,hc.Name,hc.Phone,
hrl.Frn,hrl.CallSign, hrl.gsamarkettypeid,
gmt.[Market Type Code] + ' - ' + gmt.gsamarkettype,
hrl.gsalatitude,hrl.gsalongitude,
rsc.RadioServiceCode + ' - ' + rsc.RadioService,
GrantDt, ExpirationDt, EffectiveDt,
CancellationDt
FROM dbo.sbi_f_HldrRgstrtnLcns hrl
INNER JOIN dbo.sbi_f_HldrCntcts hc on
hc.CallSign = hrl.CallSign
INNER JOIN dbo.sbi_l_radioservicecodes rsc on
rsc.radioservicecodeid = hrl.radioservicecodeid
LEFT OUTER JOIN dbo.sbi_l_GSAMarketTypes gmt on
gmt.GSAMarketTypeId = hrl.GSAMarketTypeId
WHERE hc.Entity_Type = 'L' AND hrl.LicenseStatusId IN (1)
and Row >=1 and Row <= 20) -- The error occurs here,
-- it says incorrect syntax near )
``` | Move your Row criteria into the outer select
```
SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY hrl.Frn) as Row,
...
WHERE hc.Entity_Type = 'L' AND hrl.LicenseStatusId IN (1)
) T
WHERE T.Row >=1 and T.Row <= 20)
``` | You could do this using a CTE:
```
WITH NumberedRows AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY hrn.Frl) AS RowNum,
...
WHERE
hc.Entity_Type = 'L'
AND hrl.LicenseStatusId IN (1)
)
SELECT
*
FROM
NumberedRows
WHERE
RowNum <= 20
``` | What is wrong with this query? Can't get ROW_NUMBER() to work | [
"",
"sql",
"sql-server",
"t-sql",
"row-number",
""
] |
I can't find much information on `const_cast`. The only info I could find (on Stack Overflow) is:
> The `const_cast<>()` is used to add/remove const(ness) (or volatile-ness) of a variable.
This makes me nervous. Could using a `const_cast` cause unexpected behavior? If so, what?
Alternatively, when is it okay to use `const_cast`? | `const_cast` is safe only if you're casting a variable that was originally non-`const`. For example, if you have a function that takes a parameter of a `const char *`, and you pass in a modifiable `char *`, it's safe to `const_cast` that parameter back to a `char *` and modify it. However, if the original variable was in fact `const`, then using `const_cast` will result in undefined behavior.
```
void func(const char *param, size_t sz, bool modify)
{
if(modify)
strncpy(const_cast<char *>(param), sz, "new string");
printf("param: %s\n", param);
}
...
char buffer[16];
const char *unmodifiable = "string constant";
func(buffer, sizeof(buffer), true); // OK
func(unmodifiable, strlen(unmodifiable), false); // OK
func(unmodifiable, strlen(unmodifiable), true); // UNDEFINED BEHAVIOR
``` | I can think of two situations where const\_cast is safe and useful (there may be other valid cases).
One is when you have a const instance, reference, or pointer, and you want to pass a pointer or reference to an API that is not const-correct, but that you're CERTAIN won't modify the object. You can const\_cast the pointer and pass it to the API, trusting that it won't really change anything. For example:
```
void log(char* text); // Won't change text -- just const-incorrect
void my_func(const std::string& message)
{
log(const_cast<char*>(&message.c_str()));
}
```
The other is if you're using an older compiler that doesn't implement 'mutable', and you want to create a class that is logically const but not bitwise const. You can const\_cast 'this' within a const method and modify members of your class.
```
class MyClass
{
char cached_data[10000]; // should be mutable
bool cache_dirty; // should also be mutable
public:
char getData(int index) const
{
if (cache_dirty)
{
MyClass* thisptr = const_cast<MyClass*>(this);
update_cache(thisptr->cached_data);
}
return cached_data[index];
}
};
``` | Is const_cast safe? | [
"",
"c++",
"casting",
"const-cast",
""
] |
Something I'm not to clear about, I understand there are differences between C# and VB.NET (mainly in the use of pointers) but why if both have a Common CLR, does XNA (for example) only work with C# and not VB.NET, or is it that the add ins to visual studio have been aimed at C# rather than VB.Net, and infact the language extensions work in both
Sorry if it's a obvious question, thought I'd ask | The CLR has been ported to various platforms, not all of which are equal. The XBox 360 CLR, for instance, [does not have Reflection.Emit or even all of the IL ops that the full CLR does](http://forums.xna.com/forums/p/2706/13402.aspx#13402). Hence, a different compiler may emit IL codes that are legal on the full CLR, but illegal on the Compact CLR.
The other issue is the availability of class libraries. The full BCL includes the [Microsoft.VisualBasic](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.aspx) namespace, which is automatically referenced by the VB.NET compiler. This contains [VB6 compatibility](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compatibility.vb6.aspx) functions, the [My namespace](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.myservices.aspx) features, as well as some [compiler helper functions](http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.compilerservices.aspx), and is commonly referred to as the VB.NET runtime.
Whenever the CLR is ported, certain assemblies are ported - and others are not. For the XBox, Microsoft.VisualBasic was not ported. This means that you cannot reference anything from that namespace. While it's fairly easy to not reference the compatibility or My namespaces, the compiler services can be inserted into the compiled IL without you explicitly calling them.
In VB.NET 8, you could pass an [undocumented and unsupported -novbruntimeref](http://www.codeproject.com/KB/vb/novbruntimeref.aspx) switch to vbc.exe to keep it from referencing Microsoft.VisualBasic.dll. Unfortunately, this would sometimes cause odd compiler errors. In VB.NET 9, it's become [documented and supported and renamed to /vbruntime](http://msdn.microsoft.com/en-us/library/bb531259.aspx).
The 3rd case is addins and Visual Studio support. This is up to the individual packages, as to whether they support templates, code gen, etc. for each language. I believe some 3rd parties have released VB.NET templates for XNA, though [it's not officially supported](http://forums.xna.com/forums/p/1464/7267.aspx#7267).
Bottom line, I guess, is that it's a mix of technical concerns (CLR ports, BCL availability, compiler IL output) and support (testing, funding, and addins for other languages). | It's the tool set that defines the language support. XNA, for example, simply did all their work with C# and only shipped support for it. You could still write an app in VB.NET and manually compile it from the command line. As long as your app didn't compile down to any illegal IL (opcodes that XNA doesn't support) it will still run. The primary issue is resources - they don't have the manpower to do full development and testing of all of the languages, so they picked one. | Common Runtime? | [
"",
"c#",
".net",
"vb.net",
"clr",
"runtime",
""
] |
I am making a game in JAVA where I want to come up with a list of files in a certain directory in my jar so I can make sure to have a list of those classes to be used in the game.
For example say in my jar I have a directory
```
mtd/entity/creep/
```
I want to get a list of all the .class files in that directory **using java code from another class in the jar**.
What is the best code to do so? | Old java1.4 code, but that would give you the idea:
```
private static List getClassesFromJARFile(String jar, String packageName) throws Error
{
final List classes = new ArrayList();
JarInputStream jarFile = null;
try
{
jarFile = new JarInputStream(new FileInputStream(jar));
JarEntry jarEntry;
do
{
try
{
jarEntry = jarFile.getNextJarEntry();
}
catch(IOException ioe)
{
throw new CCException.Error("Unable to get next jar entry from jar file '"+jar+"'", ioe);
}
if (jarEntry != null)
{
extractClassFromJar(jar, packageName, classes, jarEntry);
}
} while (jarEntry != null);
closeJarFile(jarFile);
}
catch(IOException ioe)
{
throw new CCException.Error("Unable to get Jar input stream from '"+jar+"'", ioe);
}
finally
{
closeJarFile(jarFile);
}
return classes;
}
private static void extractClassFromJar(final String jar, final String packageName, final List classes, JarEntry jarEntry) throws Error
{
String className = jarEntry.getName();
if (className.endsWith(".class"))
{
className = className.substring(0, className.length() - ".class".length());
if (className.startsWith(packageName))
{
try
{
classes.add(Class.forName(className.replace('/', '.')));
} catch (ClassNotFoundException cnfe)
{
throw new CCException.Error("unable to find class named " + className.replace('/', '.') + "' within jar '" + jar + "'", cnfe);
}
}
}
}
private static void closeJarFile(final JarInputStream jarFile)
{
if(jarFile != null)
{
try
{
jarFile.close();
}
catch(IOException ioe)
{
mockAction();
}
}
}
``` | Probably the best approach is to list the classes at compile time.
There is a fragile runtime approach. Take you `Class` (`MyClass.class` of `this.getClass()`). Call `getProtectionDomain`. Call `getCodeSource`. Call `getLocation`. Call `openConnection`. (Alternatively open a resource.) Cast to `JarURLConnection`. Call `getJarFile`. Call `entries`. Iterate through checking `getName`. I really do not recommend this approach. | Listing the files in a directory of the current JAR file | [
"",
"java",
"class",
"jar",
"loading",
""
] |
The following code for a co-worker throws the following error when he tries to compile it using VS 2008:
Error:
> A new expression requires () or []
> after type
Code:
MyClass Structure:
```
public class MyClass
{
public MyClass() {}
public string Property1 { get; set; }
public string Property2 { get; set; }
}
```
Sample Source Code:
```
List<MyClass> x = new List<MyClass>();
x.Add(new MyClass
{
Property1 = "MyValue",
Property2 = "Another Value"
});
```
It "works on my machine", but not his. Any idea why?
**UPDATE**
He is targeting the 3.5 .NET framework
He is using the System.Collections.Generics namespace
The MyClass object does have a constructor
**UPDATE 1:**
@Funky81 - Your example and my example were able to compile on my PC.
**Update 2:**
Included schema of MyClass in sample
**UPDATE 3:**
@DK - I had my co-worker add the following configuration section to his application:
```
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="OptionInfer" value="true"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
```
And he received the following compilation error: Unrecognized element 'providerOption'. | Here's what seems to be the only similar, but not exactly the same, error available in VS.2008:
> Compiler Error CS1526 : A new
> expression requires (), []**, or {}**
> after type
Note those `{}` in error message, which are part of c# 3.0 syntax. This is not related to framework version, but to the version of the language.
My bet is that somehow a different version of compiler was used.
Added: this looks like a likely issue with ASP.Net. Place to check is in .config file(s), element
```
configuration\system.codedom\compilers\compiler @language="c#..."
```
there should be
```
<providerOption name="CompilerVersion" value="v3.5"/>
``` | It gives me bad compile message in my PC
Try this
```
x.Add(new MyClass()
{
Property1 = "MyValue",
Property2 = "Another Value"
});
```
Notice, there is another bracket after MyClass class creation. | A new expression requires () or [] after type compilation error - C# | [
"",
"c#",
"visual-studio-2008",
".net-3.5",
""
] |
I was wondering how can I set a timeout on a `socket_read` call? The first time it calls `socket_read`, it waits till data is sent, and if no data is sent within 5 secs I want to shutdown the connection. Any Help? I already tried `SO_RCVTIMEO` with no luck.
I'm creating a socket with `socket_create()` and listening on it for connections, then when connected I listen for the data and then do something with it. When the timeout hits, I want to run `socket_shutdown()` and then `socket_close()`. | I did a socket\_listen and then I made a manual timeout with time()+2 and a while loop with nonblock set and socket\_read() inside. Seems to be working ok. Any alternatives?
UPDATE: I found that setting the socket as nonblocking and then using socket\_listen provided the timeout I needed. | this set 5 sec timeout of the socket.
```
socket_set_option($socket,SOL_SOCKET, SO_RCVTIMEO, array("sec"=>5, "usec"=>0));
``` | Set a timeout on socket_read | [
"",
"php",
"sockets",
"timeout",
""
] |
I am trying to figure out the following problem.
I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.
Now I am working on the background and the ticking of X, Y axes (if any axes are shown).
I worked out the following.
I have a fixed width of 250 p
The tick gap should be between 12.5 and 50p.
The ticks should indicate either unit or half unit range, by that i mean the following.
x range (-5, 5): one tick = 1
x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate.
x range (0.1, 0.3): 0.05
Given a Xrange
How would you get the number of ticks between either full or half unit range ?
Or maybe there are other way to approach this type of problems. | One way to do this would be to "normalise" the difference between the minimum and maximum and do a case distinction on that value. In python:
```
delta = maximum - minimum
factor = 10**math.ceil(math.log(delta,10)) # smallest power of 10 greater than delta
normalised_delta = delta / factor # 0.1 <= normalised_delta < 1
if normalised_delta/5 >= 0.1:
step_size = 0.1
elif normalised_delta/5 >= 0.05:
step_size = 0.05
elif normalised_delta/20 <= 0.01:
step_size = 0.01
step_size = step_size * factor
```
The above code assumes you want the biggest possible gap. For the smallest you would use the following if:
```
if normalised_delta/20 == 0.005:
step_size = 0.005
elif normalised_delta/20 <= 0.01:
step_size = 0.01
elif normalised_delta/5 >= 0.05:
step_size = 0.05
```
Besides the possibility that there are more than one suitable values, there is also the somewhat worrisome possibility that there are none. Take for example the range [0,24] where a gap of 12.5p would give a step size of 1.2 and a gap of 50p would give step size 4.8. There is no "unit" or "half unit" in between. The problem is that the difference between a gap of 12.5p and one of 50p is a factor 4 while the difference between 0.01 and 0.05 is a factor 5. So you will have to widen the range of allowable gaps a bit and adjust the code accordingly.
Clarification of some of the magic numbers: divisions by 20 and 5 correspond to the number of segments with the minimal and maximal gap size, respectively (ie. 250/12.5 and 250/50). As the normalised delta is in the range [0.1,1), you get that dividing it by 20 and 5 gives you [0.005,0.05) and [0.02,0.2), respectively. These ranges result in the possible (normalised) step sizes of 0.005 and 0.01 for the first range and 0.05 and 0.1 for the second. | You might want to take a look at [Jgraph](http://www.cs.utk.edu/~plank/plank/jgraph/jgraph.html), which solves a complementary problem: it is a data grapher rather than a function grapher. But there are a lot of things in common such as dealing with major and minor tick marks, axis labels, and so on and so forth. I find the input language a little verbose for my taste, but Jgraph produces really nice technical graphs. There are a lot of examples on the web site and probably some good ideas you could steal.
And you know what they say: talent imitates, but genius steals :-) | Ticking function grapher | [
"",
"python",
"algorithm",
"math",
""
] |
Scenario: a web application written in PHP utilizes an [Amazon Web Service](http://aws.amazon.com/) and must keep the Access Key ID and a Secret Access Key handy in order to function. Are there current recommendations and/or API's out there for storing this data securely?
My thought is to symmetrically encrypt it into a file based on a key created from local server variables. That way it's [hopefully] gibberish if someone gets a copy of the file through FTP, lost laptop with files copied, etc. The concern I have is that a skilled attacker could just upload their own script to decrypt it.
This seems like a [common situation](http://www.codinghorror.com/blog/archives/000953.html) and one I've never achieved a comfortable solution for. Obviously I can't use a one-way hash, because I need the original data to create a HMAC to send to AWS. Links to related S.O. questions are very welcome. | Ah. The question of security.
I think the question you should be asking here is what do you do with say, for example mySQL passwords in your php config files?
To be quite frank, I would say that if someone managed to get a copy of your files, then your security needs rethinking anyway. For my own use, I generally only keep the passwords in one place, (on the server where they should be used) and make sure that I use a randomly generated password each time (paste it into the config file, and voila!)
To be honest, if it's not your own host, ANY sensitive data can be compromised.
If it is your own host, I'd suggest using proper permissions within Linux, and [PHPSuExec](http://alain.knaff.lu/howto/PhpSuexec/) to make sure that only the scripts that YOU write can access the files.
Anyway, to answer your original question, your AWS Access / Secret Keys are just the same as a MySQL password, Ok, it has the potential to let someone access your service, but it doesn't give them access to your personal details. Even with symetric encryption, if your script has a security hole, the information can be accessed.
Put simply, you take a risk when you put these keys anywhere that is accessible to anyone but you. How much do you trust Amazon's servers not to be compromised?
My suggestion would be to try and add as much security as you can, but keep an eye on your account, I'll generally have a cron job running to send me an email with changes to my S3 account (new files uploaded, new buckets etc etc) and from that I can tell what's going on.
There is no easy solution, it's a mix of securing each seperate layer of the System. I mean, if you use symetric encryption, the password for that has to be stored somewhere, right? or are you going to type it in every time ?
Hope this helps | > *My thought is to symmetrically encrypt it into a file based on a key created from local server variables. That way it's [hopefully] gibberish if someone gets a copy of the file through FTP, lost laptop with files copied, etc. The concern I have is that a skilled attacker could just upload their own script to decrypt it*.
This wouldn't hurt, but ultimately it is just security through obscurity as somebody who can read the file can probably also read and reverse engineer your code. Short of typing in a password or otherwise providing a secret every time the server starts, encryption isn't going to help. It just shifts the problem to how will you protect the encryption key (which also needs to be accessible to the server)?
You have to harden and design your application and server (don't forget the OS, and remote access to the OS) so that nobody unauthorised can read the files on the system in the first place.
If you're worried about someone getting physical access to the box, concentrate on physical security to stop that happening. | What are your suggestions for storing AWS authentication data? | [
"",
"php",
"encryption",
"amazon-web-services",
"passwords",
""
] |
I was curious what the differences are between the debug and release modes of the .NET compiler and came across these questions about [debug vs release in .NET](https://stackoverflow.com/questions/90871/debug-vs-release-in-net) and [reasons that release will behave differently than debug](https://stackoverflow.com/questions/312312/what-are-some-reasons-a-release-build-would-run-differently-than-a-debug-build). Up to this point I really haven't paid much attention to these compiler modes. Now I will.
My question is, assuming that I am using a testing framework (NUnit) and TDD, would I run into any issues if I simply always compiled in release mode? | You're using TDD. You write your test. The test fails. You write the code to pass the test. The code fails. You look at the code you wrote and can't see any obvious reason why it fails. Do you reason some more or start up the test in the debugger (using TestDriven.Net) and step through the test? Maybe I'm just not smart enough to always figure out why my code doesn't work, but I usually do the latter when I'm stumped. | Debug mode turns off a lot of the optimizations. This means when you get a stack trace it will look more like the original code. | Why would I want to use the debug mode of the .NET compiler? | [
"",
"c#",
"compiler-construction",
"nunit",
"debugging",
"release",
""
] |
I've got a c# WINDOWS Application that is multi-threaded. It is my understanding that in a web environment, connections are pooled automatically. It is also my understanding that in a Windows app, this is not the case. Therefore, for a Windows app, the same connection should be used and not closed after each call, but instead closed when the app shuts down.
I'm curious though - is my correct? If it is, can two threads use the same connection to get a dataset from the DB at the same time or is that functionality queued up?
Thanks | The Connection Pooling is one feature of ADO.NET. Therefore the connections are already pooled. Not only in the web environment.
<http://www.ondotnet.com/pub/a/dotnet/2004/02/09/connpool.html> | > It is my understanding that in a web
> environment, connections are pooled
> automatically. It is also my
> understanding that in a Windows app,
> this is not the case.
No, this is wrong, as m3rLinEz pointed out. Connections are always pooled.
> Therefore, for a Windows app, the same
> connection should be used and not
> closed after each call, but instead
> closed when the app shuts down.
You *could* keep a connection open for the duration of the application in a monolithic WinForms app. But it's better to use the standard pattern of opening/closing connections whenever you need them. Connection pooling means you won't notice a performance difference. And your data access code will be compatible with server applications such as ASP.NET.
> If it is, can two threads use the same
> connection to get a dataset from the
> DB at the same time or is that
> functionality queued up?
No. The ADO.NET classes (connection, command etc) are not thread-safe and should not be shared between threads without synchronisation. But as noted above, you should prefer the standard pattern for data access. | C# Windows Application - Many threads using the same connection? | [
"",
"c#",
"database",
"multithreading",
"ado.net",
""
] |
I'm having some trouble updating a row in a MySQL database. Here is the code I'm trying to run:
```
import MySQLdb
conn=MySQLdb.connect(host="localhost", user="root", passwd="pass", db="dbname")
cursor=conn.cursor()
cursor.execute("UPDATE compinfo SET Co_num=4 WHERE ID=100")
cursor.execute("SELECT Co_num FROM compinfo WHERE ID=100")
results = cursor.fetchall()
for row in results:
print row[0]
print "Number of rows updated: %d" % cursor.rowcount
cursor.close()
conn.close()
```
The output I get when I run this program is:
> 4
> Number of rows updated: 1
It seems like it's working but if I query the database from the MySQL command line interface (CLI) I find that it was not updated at all. However, if from the CLI I enter `UPDATE compinfo SET Co_num=4 WHERE ID=100;` the database is updated as expected.
What is my problem? I'm running Python 2.5.2 with MySQL 5.1.30 on a Windows box. | I am not certain, but I am going to guess you are using a INNODB table, and you haven't done a commit. I believe MySQLdb enable transactions automatically.
Call `conn.commit()` before calling `close`.
From the FAQ: [Starting with 1.2.0, MySQLdb disables autocommit by default](http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away) | MySQLdb has autocommit off by default, which may be confusing at first. Your connection exists in its own transaction and you will not be able to see the changes you make from other connections until you commit that transaction.
You can either do `conn.commit()` after the update statement as others have pointed out, or disable this functionality altogether by setting `conn.autocommit(True)` right after you create the connection object. | Database does not update automatically with MySQL and Python | [
"",
"python",
"mysql",
"mysql-python",
""
] |
So in C#, I can treat a `string[]` as an `IEnumerable<string>`.
Is there a Java equivalent? | `Iterable<String>` is the equivalent of `IEnumerable<string>`.
It would be an odditity in the type system if arrays implemented `Iterable`. `String[]` is an instance of `Object[]`, but `Iterable<String>` is not an `Iterable<Object>`. Classes and interfaces cannot multiply implement the same generic interface with different generic arguments.
`String[]` will work just like an `Iterable` in the enhanced for loop.
`String[]` can easily be turned into an `Iterable`:
```
Iterable<String> strs = java.util.Arrays.asList(strArray);
```
Prefer collections over arrays (for non-primitives anyway). Arrays of reference types are a bit odd, and are rarely needed since Java 1.5. | Are you looking for `Iterable<String>`?
```
Iterable<T> <=> IEnumerable<T>
Iterator<T> <=> IEnumerator<T>
``` | Java Arrays & Generics : Java Equivalent to C# IEnumerable<T> | [
"",
"java",
"arrays",
"generics",
""
] |
I need to read smallish (few MB at the most, UTF-8 encoded) XML files, rummage around looking at various elements and attributes, perhaps modify a few and write the XML back out again to disk (preferably with nice, indented formatting).
What would be the best XML parser for my needs? There are lots to choose from. Some I'm aware of are:
* [JDOM](http://www.jdom.org/)
* [Woodstox](http://wiki.fasterxml.com/WoodstoxHome)
* [XOM](http://xom.nu/)
* [dom4j](http://dom4j.sourceforge.net/)
* [VTD-XML](http://vtd-xml.sourceforge.net/)
* [Xerces-J](http://xerces.apache.org/xerces-j/)
* [Crimson](http://xml.apache.org/crimson/)
And of course the one in the JDK (I'm using Java 6). I'm familiar with Xerces but find it clunky.
Recommendations? | If speed and memory is no problem, *dom4j* is a really good option. If you need speed, using a StAX parser like *Woodstox* is the right way, but you have to write more code to get things done and you have to get used to process XML in streams. | I think you should not consider any specific parser implementation. [Java API for XML Processing](http://en.wikipedia.org/wiki/JAXP) lets you use any conforming parser implementation in a standard way. The code should be much more portable, and when you realise that a specific parser has grown too old, you can replace it with another without changing a line of your code (if you do it correctly).
Basically there are three ways of handling XML in a standard way:
* [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML) This is the simplest API. You read the XML by defining a Handler class that receives the data inside elements/attributes when the XML gets processed in a serial way. It is faster and simpler if you only plan to read some attributes/elements and/or write some values back (your case).
* [DOM](http://en.wikipedia.org/wiki/Document_Object_Model) This method creates an object tree which lets you modify/access it randomly so it is better for complex XML manipulation and handling.
* [StAX](http://en.wikipedia.org/wiki/StAX) This is in the middle of the path between SAX and DOM. You just write code to pull the data from the parser you are interested in when it is processed.
Forget about proprietary APIs such as JDOM or Apache ones (i.e. [Apache Xerces XMLSerializer](http://xerces.apache.org/xerces-j/apiDocs/org/apache/xml/serialize/XMLSerializer.html)) because will tie you to a specific implementation that can evolve in time or lose backwards compatibility, which will make you change your code in the future when you want to upgrade to a new version of JDOM or whatever parser you use. If you stick to Java standard API (using factories and interfaces) your code will be much more modular and maintainable.
There is no need to say that all (I haven't checked all, but I'm almost sure) of the parsers proposed comply with a JAXP implementation so technically you can use all, no matter which. | Best XML parser for Java | [
"",
"java",
"xml",
"parsing",
""
] |
Microsoft Linq to SQL, Entity Framework (EF), and nHibernate, etc are all proposing ORMS as the next generation of Data Mapping technologies, and are claiming to be lightweight, fast and easy. Like for example this article that just got published in VS magazine:
<http://visualstudiomagazine.com/features/article.aspx?editorialsid=2583>
Who all are excited about implementing these technologies in their projects? Where is the innovation in these technologies that makes them so great over their predecessors? | I have written data access layers, persistence components, and even my own ORMs in hundreds of applications over the years (one of my "hobbies"); I have even implemented my own business transaction manager (discussed elsewhere on SO).
ORM tools have been around for a long time on other platforms, such as Java, Python, etc. It appears that there is a new fad now that Microsoft-centric teams have discovered them. Overall, I think that is a good thing--a necessary step in the journey to explore and comprehend the concepts of architecture and design that seems to have been introduced along with the arrival of .NET.
Bottom line: I would always prefer to do my own data access rather than fight some tool that is trying to "help" me. It is never acceptable to give up my control over my destiny, and data access is a critical part of my application's destiny. Some simple principles make data access very manageable.
Use the basic concepts of modularity, abstraction, and encapsulation--so wrap your platform's basic data access API (e.g., ADO.NET) with your own layer that raises the abstraction level closer to your problem space. DO NOT code all your data access DIRECTLY against that API (also discussed elsewhere on SO).
Severely apply the DRY (Don't Repeat Yourself) principle = refactor the daylights out of your data access code. Use code generation when appropriate as a means of refactoring, but seek to eliminate the need for code generation whenever you can. Generally, code generation reveals that something is missing from your environment--language deficiency, designed-in tool limitation, etc.
Meanwhile, learn to use the available API well, particularly regarding performance and robustness, then incorporate those lessons into your own abstracted data access layer. For example, learn to make proper use of parameters in your SQL rather than embedding literal values into SQL strings.
Finally, keep in mind that any application/system that becomes successful will grow to encounter performance problems. Fixing performance problems relies more on designing them out rather than just "tweaking" something in the implementation. That design work will affect the database and the application, which must change in sync. Therefore, seek to be able to make such changes easily (agile) rather than attempt to avoid ever changing the application itself. In part, that eventually means being able to deploy changes without downtime. It is not hard to do, if you don't "design" away from it. | I'm a huge ORM advocate. Code generation with ORM saves my shop about 20-30% on most of our projects.
And we do contract development, so this is a big win.
Chris Lively made an interesting point about having to do a redeploy any time a query gets touched. This may be a problem for some people, but it does not touch us at all. We have rules against making production database changes directly.
Also, you can still rely on traditional sprocs and even views when appropriate... We are not dogmatically 100% ORM, that's for sure. | Is everyone here jumping on the ORM band wagon? | [
"",
"c#",
".net",
"nhibernate",
"linq-to-sql",
"orm",
""
] |
I'm using the jQuery validation plugin to validate a form, and I'd like to remove the validation and submit the form if a certain link is clicked.
I am submitting form with javascript like `jQuery('form#listing').submit()`, so I must remove the validation rules/function with javascript.
The problem is that I can't figure out how to do this. I've tried things like `jQuery('form#listing').validate({});` and `jQuery('form#listing').validate = null`, but with no luck. | Trigger the DOM submit method to skip the validation:
```
$("#listing")[0].submit();
``` | You can remove events of nodes with [unbind](http://docs.jquery.com/Events/unbind#typefn):
```
jQuery('form#listing').unbind('submit'); // remove all submit handlers of the form
```
What you are probably looking for is that the validation plugin can also unassign itself from the submit event:
```
jQuery('form#listing').validate({
onsubmit : false
});
```
For both of these you should be able to follow up with a call to `.submit()` to submit the form:
```
jQuery('form#listing').unbind('submit').submit();
``` | How do I remove jQuery validation from a form? | [
"",
"javascript",
"jquery",
"validation",
""
] |
I'm having a little problem with the following:
When I execute this line:
```
echo exec(createDir($somevariable));
```
I get this error:
```
Warning: exec() [function.exec]: Cannot execute a blank command in /home/mydir/myfile.inc.php on line 32
```
Any ideas.
Thanks. | [`exec()`](http://php.net/exec) expects a string argument, which it would pass on to your operating system to be executed. In other words, this is a portal to the server's command line.
I'm not sure what function `createDir()` is, but unless it's returning a valid command line string, it's probably failing because of that.
In Linux, you might want to do something like
```
exec('/usr/bin/mkdir '.$path);
```
...on the other hand, you should abstain from using `exec()` at all costs. What you can do here, instead, is take a look at [`mkdir()`](http://php.net/mkdir) | With [exec](http://de3.php.net/manual/de/function.exec.php) you can execute system calls like if you were using the command line. It hasn't to do anything with executing PHP functions.
To create a directory you could do the following:
```
exec( 'mkdir [NAME OF DIRECTORY]' );
``` | php exec() error | [
"",
"php",
"exec",
""
] |
what are the benefits of using [HTTP authentication with PHP](http://www.php.net/features.http-auth) (HTTP 401 headers)
instead of using a normal form submit authentication?? | From security perspective, both the **form based** and **[HTTP Basic Access Authentication](http://en.wikipedia.org/wiki/Basic_access_authentication)** use plain text for sending the authentication data. (Sure, HTTP Basic Auth additionally uses Base64, but that’s no hitch.)
While HTTP Basic Auth sends the authentication data on every request, the form based authentication only sends the authentication data when the form is sent (remember: both in plain text). Commonly sessions are used to maintain the state when using form based authentication.
So if you want to use one of these, be sure to encrypt your connection using HTTPS to prevent sniffing and [man-in-the-middle attacks](http://en.wikipedia.org/wiki/Session_hijacking). And when you choose the form and session based variant, be sure to secure your session handling too to prevent or at least detect session frauds like [Session Hijacking](http://en.wikipedia.org/wiki/Session_fixation) and [Session Fixation](http://en.wikipedia.org/wiki/Digest_access_authentication).
The last variant is **[HTTP Digest Access Authentication](http://en.wikipedia.org/wiki/Challenge-response_authentication)**. The main difference between this and Basic is, that Digest is a [challenge-response authentication](http://en.wikipedia.org/wiki/Challenge-response_authentication) whereas the client has to fulfill a challenge on every request and the response is just a MD5 hash. So no authentication data in plain text is being send. | Your question is a bit vague, but the general answer is that using this method gives you a more "RESTful" implementation that follows what HTTP is already good at. In this case, throwing a 401 is something that other web servers, web proxies and web browsers know how to handle. If you're just spitting out an HTML form it is only actionable by an end user whereas using the HTTP status codes allow machine interaction.
I'd recommend checking out [`http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol`](http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) to understand what HTTP really is. I think that should make all of this make more sense. | benefits of "HTTP authentication with PHP" | [
"",
"php",
"security",
"authentication",
""
] |
I ask because I am sending a byte stream from a C process to Java. On the C side the 32 bit integer has the LSB is the first byte and MSB is the 4th byte.
So my question is: On the Java side when we read the byte as it was sent from the C process, what is [endian](https://en.wikipedia.org/wiki/Endianness) on the Java side?
A follow-up question: If the endian on the Java side is not the same as the one sent, how can I convert between them? | Use the network byte order (big endian), which is the same as Java uses anyway. See man htons for the different translators in C. | I stumbled here via Google and got my answer that Java is **big endian**.
Reading through the responses I'd like to point out that bytes do indeed have an endian order, although mercifully, if you've only dealt with “mainstream” microprocessors you are unlikely to have ever encountered it as Intel, Motorola, and Zilog all agreed on the shift direction of their UART chips and that MSB of a byte would be `2**7` and LSB would be `2**0` in their CPUs (I used the FORTRAN power notation to emphasize how old this stuff is :) ).
I ran into this issue with some Space Shuttle bit serial downlink data 20+ years ago when we replaced a $10K interface hardware with a Mac computer. There is a NASA Tech brief published about it long ago. I simply used a 256 element look up table with the bits reversed (`table[0x01]=0x80` etc.) after each byte was shifted in from the bit stream. | Does Java read integers in little endian or big endian? | [
"",
"java",
"endianness",
""
] |
```
dev%40bionic%2Dcomms%2Eco%2Euk
```
I want to turn the above back in to readable text. Can anyone tell me how? Thanks
EDIT
Forgive my oversight, PHP is the language of choice! | You haven't said which language, but in many the function you want is urldecode
(Looking at your other questions, you probably want PHP. It is [urldecode](https://www.php.net/urldecode) there :)) | In JavaScript: `decodeURIComponent("dev%40bionic%2Dcomms%2Eco%2Euk")` | Returning %40 to an @ symbol | [
"",
"php",
"html",
""
] |
When programming in C++ in Visual Studio 2008, why is there no functionality like that seen in the refactor menu when using C#?
I use **Rename** constantly and you really miss it when it's not there. I'm sure you can get plugins that offer this, but why isn't it integrated in to the IDE when using C++? Is this due to some gotcha in the way that C++ must be parsed? | The syntax and semantics of C++ make it **incredibly difficult** to correctly implement refactoring functionality. It's possible to implement something relatively simple to cover 90% of the cases, but in the remaining 10% of cases that simple solution will horribly break your code by changing things you never wanted to change.
Read <http://yosefk.com/c++fqa/defective.html#defect-8> for a brief discussion of the difficulties that any refactoring code in C++ has to deal with.
Microsoft has evidently decided to punt on this particular feature for C++, leaving it up to third-party developers to do what they can. | I'm not sure why it is like this, but third-party tools exist that help. For example, right now I'm evaluating [Visual Assist X](http://www.wholetomato.com/) (by Whole Tomato). We're also using Visual Studio 2005. | Why is Visual C++ lacking refactor functionality? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"visual-c++",
""
] |
I'm trying to follow code-to-interface on a project. Should I be creating an interface first then implementing that interface for entity classes? I'm thinking this might be taking the interface first approach too far and entities should be ignored. This is what I mean...
```
public interface Address {
public String getStreet();
public void setStreet(String street);
}
@Entity
public class AddressImpl implements Address {
private String street;
public String getStreet(){
return this.street;
}
public void setStreet(String street){
this.street = street;
}
}
@Entity
public class OfficeImpl /* implements Office */ {
private Address location;
public Address getLocation(){
return this.location;
}
public void setLocation(Address location){
this.location = location;
}
}
public class Driver {
public static void main(String[] args) {
Office work = new OfficeImpl();
Address workAddress = new AddressImpl();
workAddress.setStreet("Main St.");
work.setLocation(workAddress);
}
}
``` | I think creating Interfaces for Entities is probably not necessary.
The purpose of creating Interfaces (or at least, one of the purposes) is to make it easier to swap out one concrete implementation in favour of another. This is obviously a good thing for your DAOs, Business Logic etc.
But unless you have plans for the implementation of your entities to change as well, I would avoid it! | In your example, you are probably taking it too far, but once you add methods, write test cases and possibly use dependency injection, it will make more sense.
For simple projects like this, it is overkill, but once you get into a 'real' application, then it is often a good idea. Just be careful not to overdo it, everything doesn't need to implement an interface, just where it makes sense. | Does the code-to-interface principle apply to entity classes? | [
"",
"java",
""
] |
I'm trying to display a picture in an openGL environment. The picture's origninal dimensions are 3648x2432, and I want to display it with a 256x384 image. The problem is, 384 is not a power of 2, and when I try to display it, it looks stretched. How can I fix that? | There's three ways of doing this that I know of -
* The one Albert suggested (resize it until it fits).
* Subdivide the texture into 2\*\*n-sized rectangles, and piece them together in some way.
* See if you can use `GL_ARB_texture_non_power_of_two`. It's probably best to avoid it though, since it looks like it's an Xorg-specific extension. | You can resize your texture so it *is* a power of two (skew your texture so that when it is mapped onto the object it looks correct). | openGL textures that are not 2^x in dimention | [
"",
"c++",
"opengl",
"ldf",
""
] |
Well I have a videos website and a few of its tables are:
**tags**
```
id ~ int(11), auto-increment [PRIMARY KEY]
tag_name ~ varchar(255)
```
**videotags**
```
tag_id ~ int(11) [PRIMARY KEY]
video_id ~ int(11) [PRIMARY KEY]
```
**videos**
```
id ~ int(11), auto-increment [PRIMARY KEY]
video_name ~ varchar(255)
```
Now at this point the tags table has >1000 rows and the videotags table has >32000 rows. So when I run a query to display all tags from most common to least common it takes >15 seconds to execute.
I am using PHP and my code (watered down for simplicity) is as follows:
```
foreach ($database->query("SELECT tag_name,COUNT(tag_id) AS 'tag_count' FROM tags LEFT OUTER JOIN videotags ON tags.id=videotags.tag_id GROUP BY tags.id ORDER BY tag_count DESC") as $tags)
{
echo $tags["tag_name"] . ', ';
}
```
Now keeping in mind that this being 100% accurate isn't as important to me as it being fast. So even if the query was executed once a day and its results were used for the remainder of the day, I wouldn't care.
I know absolutely nothing about MySQL/PHP caching so please help! | [MarkR](https://stackoverflow.com/questions/346842/mysql-query-takes-15-seconds-to-run-what-can-i-do-to-cacheimprove-it-php#346851) mentioned the index. Make sure you:
```
create index videotags_tag_id on videotags(tag_id);
``` | 32,000 rows is still a small table - there's no way your performance should be that bad.
Can you run `EXPLAIN` on your query - I'd guess you're indexes are wrong somewhere.
You say in the question:
```
tag_id ~ int(11) [PRIMARY KEY]
video_id ~ int(11) [PRIMARY KEY]
```
Are they definitely in that order? If not, then it won't use the index. | MySQL query takes >15 seconds to run; what can I do to cache/improve it? | [
"",
"php",
"mysql",
"caching",
""
] |
I ran into this today when unit testing a generic dictionary.
```
System.Collections.Generic.Dictionary<int, string> actual, expected;
actual = new System.Collections.Generic.Dictionary<int, string> { { 1, "foo" }, { 2, "bar" } };
expected = new System.Collections.Generic.Dictionary<int, string> { { 1, "foo" }, { 2, "bar" } };
Assert.AreEqual(expected, actual); //returns false
```
fails except when `actual == expected` (object references are the same). Obviously, `actual.Equals(expected)` returns false as well.
Fine, but if the implementation of `System.Collections.Generic.Dictionary<int, string>.Equals` only does reference equality, what's the point of `IEquatable`? In other words, why is there no baked-in way to do value equality for generic collections?
**Edit** Thanks for the responses so far. Obviously my example is using value types, but I think my complaint holds for all objects. Why can't a generic collection equality just be a union of equalities of its types? Unexpected behavior doesn't really cut it since there are separate provisions for finding reference equality. I suppose this would introduce the constraint of collections only holding object that implement `IEquatable`, as Konrad Rudolph points out. However, in an object like Dictionary, this doesn't seem too much to ask. | > In other words, why is there no baked-in way to do value equality for generic collections?
Probably because it's hard to formulate in generic terms, since this would only be possible if the value type (and key type) of the dictionary also implemented `IEquatable`. However, requiring this would be too strong, making `Dictionary` unusable with a lot of types that don't implement this interface.
This is an inherent problem with constrained generics. Haskell provides a solution for this problem but this requires a much more powerful and complicated generics mechanism.
Notice that something similar is true for `IComparable` in comparison with containers, yet there is support for this, using `Comparer<T>.Default` if necessary. | `Dictionary<T,T>.Equals` is inherited from Object.Equals and thus does a simple comparison of the object references.
Why do the generic collections not do value equality semantic? Because that may not be what you want. Sometimes you want to check if they're the same instance. What would the alternative do? Call Equals on each of the keys and values? What if these inherit Equals from Object? It wouldn't be a full deep comparison.
So it's up to you to provide some other semantic if and when necessary. | What does System.Collections.Generic.Dictionary<T,T>.Equals actually do? | [
"",
"c#",
"generics",
"collections",
"comparison",
"equality",
""
] |
I'm trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I'd like to extract just the number part of the string. I can't just tokenize on the space (using sstream and <<) because the text in front of the colon may or may not have spaces in it.
Some example strings might be:
> Total disk space: 9852465
>
> Free disk space: 6243863
>
> Sectors: 4095
I'd like to use the standard library, but if you have another solution you can post that too, since others with the same question might like to see different solutions. | ```
std::string strInput = "Total disk space: 9852465";
std::string strNumber = "0";
size_t iIndex = strInput.rfind(": ");
if(iIndex != std::string::npos && strInput.length() >= 2)
{
strNumber = strInput.substr(iIndex + 2, strInput.length() - iIndex - 2)
}
``` | For completeness, here's a simple solution in C:
```
int value;
if(sscanf(mystring.c_str(), "%*[^:]:%d", &value) == 1)
// parsing succeeded
else
// parsing failed
```
Explanation: the `%*[^:]` says to read in as many possible characters that aren't colons, and the `*` suppresses assignment. Then, the integer is read in, after the colon and any intervening white space. | How do you search a std::string for a substring in C++? | [
"",
"c++",
"string",
""
] |
I'm creating my own dictionary and I am having trouble implementing the [TryGetValue](http://msdn.microsoft.com/en-us/library/ms132143(VS.85).aspx) function. When the key isn't found, I don't have anything to assign to the out parameter, so I leave it as is. This results in the following error: "The out parameter 'value' must be assigned to before control leaves the current method"
So, basically, I need a way to get the default value (0, false or nullptr depending on type). My code is similar to the following:
```
class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
bool IDictionary<K, V>.TryGetValue (K key, out V value)
{
return false;
}
....
}
``` | You are looking for the [`default`](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/default-value-expressions) keyword.
For example, in the example you gave, you want something like:
```
class MyEmptyDictionary<K, V> : IDictionary<K, V>
{
bool IDictionary<K, V>.TryGetValue (K key, out V value)
{
value = default(V);
return false;
}
....
}
``` | ```
default(T)
``` | Returning a default value. (C#) | [
"",
"c#",
"generics",
"default-value",
""
] |
I want to create an associative array:
```
var aa = {} // Equivalent to Object(), new Object(), etc...
```
And I want to be sure that any key I access is going to be a number:
```
aa['hey'] = 4.3;
aa['btar'] = 43.1;
```
I know JavaScript doesn't have typing, so I can't automatically check this, but I can ensure in my own code that I only assign strings to this `aa`.
Now I'm taking keys from the user. I want to display the value for that key. However, if the user gives me something like "toString", the user gets back a function, not an int! Is there a way to make sure any string the user gives me is only something I define?
Is the only solution something like the following?
```
delete aa['toString'];
delete aa['hasOwnProperty'];
```
etc... | This may work for you:
```
function getValue(id){
return (!isNaN(aa[id])) ? aa[id] : undefined;
}
```
Alternatively, I recommend this generic solution:
```
function getValue(hash,key) {
return Object.prototype.hasOwnProperty.call(hash,key) ? hash[key] : undefined;
}
```
Note the following: The key will internally be converted to a string because the key is actually a name of an attribute.
```
var test = {
2: "Defined as numeric",
"2": "Defined as string"
}
alert(test[2]); // Alerts "Defined as string"
```
If trying to use an object:
```
var test = {}, test2 = {};
test[test2] = "message"; // Using an object as a key.
alert(test[test2]); // Alerts "message". It looks like it works...
alert(test[test2.toString()]);
// If it really was an object this would not have worked,
// but it also alerts "message".
```
Now that you know that it is always a string, let’s use it:
```
var test = {};
var test2 = {
toString:function(){return "some_unique_value";}
// Note that the attribute name (toString) don't need quotes.
}
test[test2] = "message";
alert(test["some_unique_value"]); // Alerts "message".
``` | One possibility would be to use hasOwnProperty to check that the key is something you explicitly added to the array. So instead of:
```
function findNumber(userEnteredKey) {
return aa[userEnteredKey];
}
```
you'd say:
```
function findNumber(userEnteredKey) {
if (Object.prototype.hasOwnProperty.call(aa, userEnteredKey))
return aa[userEnteredKey];
}
```
Alternately, you could use typeof to check that anything is a number before returning it. But I like the hasOwnProperty approach, because it'll keep you from returning anything that you didn't intentionally put in the array. | Associative array without toString, etc | [
"",
"javascript",
"object",
"maps",
"associative-array",
""
] |
I would like to ensure that I only subscribe once in a particular class for an event on an instance.
For example I would like to be able to do the following:
```
if (*not already subscribed*)
{
member.Event += new MemeberClass.Delegate(handler);
}
```
How would I go about implementing such a guard? | If you are talking about an event on a class that you have access to the source for then you could place the guard in the event definition.
```
private bool _eventHasSubscribers = false;
private EventHandler<MyDelegateType> _myEvent;
public event EventHandler<MyDelegateType> MyEvent
{
add
{
if (_myEvent == null)
{
_myEvent += value;
}
}
remove
{
_myEvent -= value;
}
}
```
That would ensure that only one subscriber can subscribe to the event on this instance of the class that provides the event.
**EDIT** please see comments about why the above code is a bad idea and not thread safe.
If your problem is that a single instance of the client is subscribing more than once (and you need multiple subscribers) then the client code is going to need to handle that. So replace
> *not already subscribed*
with a bool member of the client class that gets set when you subscribe for the event the first time.
**Edit (after accepted):** Based on the comment from @Glen T (the submitter of the question) the code for the accepted solution he went with is in the client class:
```
if (alreadySubscribedFlag)
{
member.Event += new MemeberClass.Delegate(handler);
}
```
Where alreadySubscribedFlag is a member variable in the client class that tracks first subscription to the specific event.
People looking at the first code snippet here, please take note of @Rune's comment - it is not a good idea to change the behavior of subscribing to an event in a non-obvious way.
**EDIT 31/7/2009:** Please see comments from @Sam Saffron. As I already stated and Sam agrees the first method presented here is not a sensible way to modify the behavior of the event subscription. The consumers of the class need to know about its internal implementation to understand its behavior. Not very nice.
@Sam Saffron also comments about thread safety. I'm assuming that he is referring to the possible race condition where two subscribers (close to) simultaneously attempt to subscribe and they may both end up subscribing. A lock could be used to improve this. If you are planning to change the way event subscription works then I advise that you [read about how to make the subscription add/remove properties thread safe](https://stackoverflow.com/questions/1037811/c-thread-safe-events). | I'm adding this in all the duplicate questions, just for the record. This pattern worked for me:
```
myClass.MyEvent -= MyHandler;
myClass.MyEvent += MyHandler;
```
Note that doing this every time you register your handler will ensure that your handler is registered only once. | How to ensure an event is only subscribed to once | [
"",
"c#",
"events",
"event-handling",
"subscription",
""
] |
It has been said that C# can be regarded as a functional programming language, even though it is widely recognized as a OO programming language.
So, what feature set makes C# a functional programming language?
I can only think of:
1. delegates (even without anonymous methods and lambda expressions)
2. closures
Anything else? | C# has borrowed a lot of features from ML and Haskell for example:
* C# 2.0 brought us parametric polymorphism (or "generics"). I've heard that Dom Syme, one of the creators of F#, was largely responsible for implementing generics in the .NET BCL.
* C# 2.0 also allows programmers to pass and returns functions as values for higher-order functions, and has limited support for anonymous delegates.
* C# 3.0 and 3.5 improved support anonymous functions for true closures.
* LINQ can be considered C#'s own flavor of list comprehensions.
* Anonymous types look like an approximation of ML records
* Type-inference is a given.
* I don't know about you, but C# [extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx) look an awful lot like Haskell [type classes](http://en.wikipedia.org/wiki/Type_class).
* There's been a lot of talk about the "dynamic" keyword in C# 4.0. I'm not 100% sure of its implementation details, but I'm fairly sure its going to use [structural typing](http://en.wikipedia.org/wiki/Structural_type_system) rather than late binding to retain C#'s compile time safety. Structural typing is roughly equivalent to "duck typing for static languages", its a feature that Haskell and ML hackers have been enjoying for years.
This isn't to say that C# is a functional programming language. Its still missing important features such as pattern matching, tail-call optimization, and list and tuple literals. Additionally, idiomatic C# is fundamentally imperative with a heavy dependence on mutable state.
I wouldn't necessarily consider some of those features mentioned above as exclusive to functional programming languages, but its pretty clear that the C# developers have taken a lot of inspiration from functional programming languages in the past few years. | There being no rigourous definition of "OO Language", "Functional Language", "Procedural Language", one can make arguments that any language fits mostly any classification; one can write procedural Java, object oriented C and functional C++. I typically use a classification based around what the main semantic features support, along with common development practice. A good way of looking at this is to examine builtin and popular frameworks, and see what style they use.
Functional languages are mostly defined as those with first class function primitives, with development styles that use these to reduce complexity with idioms like "map". One other common feature is pattern matching, but I don't see this as exclusively functional. "Pure" functional languages also have no side effects, but that's not mandatory (see how fuzzy these concepts are? :).
So, what's C#? Well, it has first class function style primitives, with delegates (and has gained better syntactic support for the style with anonymous delegates and lambdas). Does this make it functional? Perhaps, if one writes in a functional style. Does the Framework use this style? No, not really.
As such, I wouldn't class C# as functional in general discussion - it is, at best, multi-paradigm, with some functional flavour. | Why is C# a functional programmming language? | [
"",
"c#",
"functional-programming",
""
] |
I have a table like so:
```
keyA keyB data
```
keyA and keyB together are unique, are the primary key of my table and make up a clustered index.
There are 5 possible values of keyB but an unlimited number of possible values of keyA,. keyB generally increments.
For example, the following data can be ordered in 2 ways depending on which key column is ordered first:
```
keyA keyB data
A 1 X
B 1 X
A 3 X
B 3 X
A 5 X
B 5 X
A 7 X
B 7 X
```
or
```
keyA keyB data
A 1 X
A 3 X
A 5 X
A 7 X
B 1 X
B 3 X
B 5 X
B 7 X
```
Do I need to tell the clustered index which of the key columns has fewer possible values to allow it to order the data by that value first? Or does it not matter in terms of performance which is ordered first? | You should order your composite clustered index with the most selective column first. This means the column with the most distinct values compared to total row count.
"B\*TREE Indexes improve the performance of queries that select a small percentage of rows from a table." <http://www.akadia.com/services/ora_index_selectivity.html>?
This article is for Oracle, but still relevant.
Also, if you have a query that runs constantly and returns few fields, you may consider creating a composite index that contains all the fields - it will not have to access the base table, but will instead pull data from the index.
ligget78's comment on making sure to mention the first column in a composite index is important to remember. | If you create an index (regardless clustered or not) with (keyA, keyB) then this is how values will be ordered, e.g. first keyA, then keyB (this is the second case in your question). If you want it the other way around, you need to specify (keyB, keyA).
It could matter performance-wise, depends on your query of course. For example, if you have (keyA, keyB) index and the query looks like WHERE keyB = ... (without mentioning keyA) then the index can't be utilized. | SQL Server Clustered Index - Order of Index Question | [
"",
"sql",
"sql-server",
"database",
"performance",
"indexing",
""
] |
I am unit testing a .NET application (.exe) that uses an app.config file to load configuration properties. The unit test application itself does not have an app.config file.
When I try to unit test a method that utilizes any of the configuration properties, they return *null*. I'm assuming this is because the unit test application is not going to load in the target application's app.config.
Is there a way to override this or do I have to write a script to copy the contents of the target app.config to a local app.config?
[This](https://stackoverflow.com/questions/168931/unit-testing-the-appconfig-file-with-nunit) post kind-of asks this question but the author is really looking at it from a different angle than I am.
**EDIT:** I should mention that I'm using VS08 Team System for my unit tests. | The simplest way to do this is to add the `.config` file in the deployment section on your unit test.
To do so, open the `.testrunconfig` file from your Solution Items. In the Deployment section, add the output `.config` files from your project's build directory (presumably `bin\Debug`).
Anything listed in the deployment section will be copied into the test project's working folder before the tests are run, so your config-dependent code will run fine.
Edit: I forgot to add, this will not work in all situations, so you may need to include a startup script that renames the output `.config` to match the unit test's name. | In Visual Studio 2008 I added the `app.config` file to the test project as an existing item and selected copy as link in order to make sure it's not duplicated. That way I only have one copy in my solution. With several test projects it comes in really handy!
[](https://i.stack.imgur.com/Bl8Ss.png)
[](https://i.stack.imgur.com/j0DWV.png) | Can a unit test project load the target application's app.config file? | [
"",
"c#",
".net",
"unit-testing",
"app-config",
""
] |
Given:
```
FieldInfo field = <some valid string field on type T>;
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");
```
How do I compile a lambda expression to set the field on the "target" parameter to "value"? | **.Net 4.0** : now that there's `Expression.Assign`, this is easy to do:
```
FieldInfo field = typeof(T).GetField("fieldName");
ParameterExpression targetExp = Expression.Parameter(typeof(T), "target");
ParameterExpression valueExp = Expression.Parameter(typeof(string), "value");
// Expression.Property can be used here as well
MemberExpression fieldExp = Expression.Field(targetExp, field);
BinaryExpression assignExp = Expression.Assign(fieldExp, valueExp);
var setter = Expression.Lambda<Action<T, string>>
(assignExp, targetExp, valueExp).Compile();
setter(subject, "new value");
```
**.Net 3.5** : you can't, you'll have to use System.Reflection.Emit instead:
```
class Program
{
class MyObject
{
public int MyField;
}
static Action<T,TValue> MakeSetter<T,TValue>(FieldInfo field)
{
DynamicMethod m = new DynamicMethod(
"setter", typeof(void), new Type[] { typeof(T), typeof(TValue) }, typeof(Program));
ILGenerator cg = m.GetILGenerator();
// arg0.<field> = arg1
cg.Emit(OpCodes.Ldarg_0);
cg.Emit(OpCodes.Ldarg_1);
cg.Emit(OpCodes.Stfld, field);
cg.Emit(OpCodes.Ret);
return (Action<T,TValue>) m.CreateDelegate(typeof(Action<T,TValue>));
}
static void Main()
{
FieldInfo f = typeof(MyObject).GetField("MyField");
Action<MyObject,int> setter = MakeSetter<MyObject,int>(f);
var obj = new MyObject();
obj.MyField = 10;
setter(obj, 42);
Console.WriteLine(obj.MyField);
Console.ReadLine();
}
}
``` | Setting a field is, as already discussed, problematic. You can can (in 3.5) a single method, such as a property-setter - but only indirectly. This gets much easier in 4.0, as discussed [here](http://marcgravell.blogspot.com/2008/11/future-expressions.html). However, if you actually have properties (not fields), you can do a lot simply with `Delegate.CreateDelegate`:
```
using System;
using System.Reflection;
public class Foo
{
public int Bar { get; set; }
}
static class Program
{
static void Main()
{
MethodInfo method = typeof(Foo).GetProperty("Bar").GetSetMethod();
Action<Foo, int> setter = (Action<Foo, int>)
Delegate.CreateDelegate(typeof(Action<Foo, int>), method);
Foo foo = new Foo();
setter(foo, 12);
Console.WriteLine(foo.Bar);
}
}
``` | How do I set a field value in an C# Expression tree? | [
"",
"c#",
"lambda",
"expression-trees",
""
] |
I have a problem with uninitialized proxies in nhibernate
**The Domain Model**
Let's say I have two parallel class hierarchies: Animal, Dog, Cat and AnimalOwner, DogOwner, CatOwner where Dog and Cat both inherit from Animal and DogOwner and CatOwner both inherit from AnimalOwner. AnimalOwner has a reference of type Animal called OwnedAnimal.
Here are the classes in the example:
```
public abstract class Animal
{
// some properties
}
public class Dog : Animal
{
// some more properties
}
public class Cat : Animal
{
// some more properties
}
public class AnimalOwner
{
public virtual Animal OwnedAnimal {get;set;}
// more properties...
}
public class DogOwner : AnimalOwner
{
// even more properties
}
public class CatOwner : AnimalOwner
{
// even more properties
}
```
The classes have proper nhibernate mapping, all properties are persistent and everything that can be lazy loaded is lazy loaded.
The application business logic only let you to set a Dog in a DogOwner and a Cat in a CatOwner.
**The Problem**
I have code like this:
```
public void ProcessDogOwner(DogOwner owner)
{
Dog dog = (Dog)owner.OwnedAnimal;
....
}
```
This method can be called by many diffrent methods, in most cases the dog is already in memory and everything is ok, but rarely the dog isn't already in memory - in this case I get an nhibernate "uninitialized proxy" but the cast throws an exception because nhibernate genrates a proxy for Animal and not for Dog.
I understand that this is how nhibernate works, but I need to know the type without loading the object - or, more correctly I need the uninitialized proxy to be a proxy of Cat or Dog and not a proxy of Animal.
**Constraints**
* I can't change the domain model, the model is handed to me by another department, I tried to get them to change the model and failed.
* The actual model is much more complicated then the example and the classes have many references between them, using eager loading or adding joins to the queries is out of the question for performance reasons.
* I have full control of the source code, the hbm mapping and the database schema and I can change them any way I want (as long as I don't change the relationships between the model classes).
* I have many methods like the one in the example and I don't want to modify all of them.
Thanks,
Nir | It's easiest to turn off lazy loading for the animal class. You say it's mostly in memory anyway.
```
<class name="Animal" lazy="false">
<!-- ... -->
</class>
```
As a variant of that, you could also use `no-proxy`, see [this post](http://ayende.com/blog/4378/nhibernate-new-feature-no-proxy-associations):
```
<property name="OwnedAnimal" lazy="no-proxy"/>
```
As far as I can see, it only works when the `AnimalOwner` actually is a proxy.
**OR**
You can use generics on the animal owner to make the reference a concrete class.
```
class AnimalOwner<TAnimal>
{
virtual TAnimal OwnedAnimal {get;set;}
}
class CatOwner : AnimalOwner<Cat>
{
}
class DogOwner : AnimalOwner<Dog>
{
}
```
**OR**
You can map the `DogOwners` and `CatOwners` in separate tables, and define the concrete animal type in the mapping.
```
<class name="CatOwner">
<!-- ... -->
<property name="OwnedAninal" class="Cat"/>
</class>
<class name="DogOwner">
<!-- ... -->
<property name="OwnedAninal" class="Dog"/>
</class>
```
**OR**
You mess a little around with NHibernate, as proposed in [this blog](http://guildsocial.web703.discountasp.net/dasblogce/2009/07/24/NHibernateProxyCastingWithSubclasses.aspx). NH is actually able to return the real object behind the proxy. Here a bit simpler implementation as proposed there:
```
public static T CastEntity<T>(this object entity) where T: class
{
var proxy = entity as INHibernateProxy;
if (proxy != null)
{
return proxy.HibernateLazyInitializer.GetImplementation() as T;
}
else
{
return entity as T;
}
}
```
which can be used like this:
```
Dog dog = dogOwner.OwnedAnimal.CastEntity<Dog>();
``` | I think we recently had a similar problem, AFAIR solution was to give 'Animal' a self -"method/property":
```
public Animal Self { get { return this; } }
```
This could then be casted to correct "animal". What happens is that your original object has a reference to nhibernate proxy object (when it's lazily loaded), which acts as Animal for all methods exposed via Animal class (it passes all calls to the loaded object). However it cannot be casted as any of your other animals because it is none of these, it only emulates the Animal class. However the class that is encapsulated by AnimalProxy can be casted as subclassed animal because it is a real instance of correct class, you only need to get to it's `this` reference. | Getting proxies of the correct type in NHibernate | [
"",
"c#",
".net",
"nhibernate",
"proxy",
""
] |
I'm looking library, to create Bluetooth connection between my device and other devices.
I want use:
1. .NET2.0 for Windows Mobile
2. WindowsCE 5.0 | If you're using a particular device, most companies have a useful SDK available with Bluetooth functions/routines.
However, if you're looking for generic abilities across multiple devices you could check out [32Feet.net](http://32feet.net/) or [OpenNetCF](http://community.opennetcf.com/).
Be warned though, that if you're using CE 5.0 the bthutil.dll is not included by default anymore, so many of the functions in 32Feet.net (In the Hand) won't actually work. | Have not done much with it myself (yet), but I've read that *[Mobile in the Hand](http://32feet.net/)* has nice managed libraries that included Bluetooth support. | Bluetooth for WindowsCE 5.0 and .NET2.0 with C# | [
"",
"c#",
"windows-mobile",
".net-2.0",
""
] |
I have a situation that has been partially covered by other answers at SO, but I cannot find a complete answer. In short, we are trying to use URL's for our specific data types that when double clicked will open up our application and load those data sets into that app. We have this part working.
(for example, an URL might look like this: resource://shaders/basic\_shader.hlsl)
What we would like to do is to prevent new instances of the application from opening when a new URL is double clicked. For example, let's say we have a URL that opens up a shader in our shader editor. When clicking this resource URL, it will open our shader editor. When a new shader URL is clicked, we'd like to be able to open up the shader in the currently running application and have it open up the new shader in a new tab in our editor.
We can easily detect if another instance of our application is running. The problem that we don't know how to easily solve is how to tell the currently running application to open up this new file for editing. This behavior is very much like the Apple Finder.
In unix, you could emulate this behavior by having your application open some named pipe and then new apps could check if this pipe is active and then send the document data down the pipe. Is there a more standard windows way of achieving this behavior?
We need a C/C++ solution. Thanks. | Create a named mutex when application launches as David Grant said, then before displaying the UI for the second URL, check for this mutex, if it is already created then just quit by passing the new URL to the first launched application (Have interface in the application to set the URL and tell to redirect programatically) | Named pipe is the best way.
First instance of your application opens the pipe and listens to it (use PIPE\_ACCESS\_INBOUND as dwOpenMode and the same code will also allow you to detect running instances).
All subsequent instances check that they are not alone, send command line argument to the pipe and shut down. | How do I open a new document in running application without opening a new instance of the application? | [
"",
"c++",
"windows",
""
] |
I would like to keep a list of a certain class of objects in my application. But I still want the object to be garbage collected. Can you create **weak references** in .NET?
For reference:
* [Garbage Collecting objects which keep track of their own instances in an internal Map](https://stackoverflow.com/questions/346762)
* [Create a weak reference to an object](https://stackoverflow.com/questions/258505)
Answer From MSDN:
> To establish a weak reference with an
> object, you create a WeakReference
> using the instance of the object to be
> tracked. You then set the Target
> property to that object and set the
> object to null. For a code example,
> see WeakReference in the class
> library. | Yes, there's a generic weak reference class.
[MSDN > Weak Reference](http://msdn.microsoft.com/en-us/library/xt0a1s34.aspx) | > Can you create weak references in .NET?
Yes:
```
WeakReference r = new WeakReference(obj);
```
Uses [`System.WeakReference`](http://msdn.microsoft.com/en-us/library/system.weakreference(VS.80).aspx). | Are there Weak References in .NET? | [
"",
"c#",
".net",
"garbage-collection",
"weak-references",
""
] |
We're a team of a programmer and a designer and we want to make a medium-sized java game which will be played as an applet in the web browser. Me (the programmer) has 3 years of general development experience, but I haven't done any game programming before.
We're assuming that:
* We'll decide on a plot, storyline of the game, etc.
* We'll create a list of assets (images) that we need, i.e player images, monster images, towns, buildings, trees, objects, etc. (We're not adding any music/sound efffects for now)
* The designer will get started on creating those images while I finish reading some of the game programming books i've bought. The designer will create the first town/level of the game, then pass on those images to me, I will begin coding that first level and he would start on the next level, and after 4-5 levels we'll release v.1 of the game.
**Question 1:** Is this the correct methodology to use for this project?
**Question 2:** What format should the designer create those images in. Should they be .bmp, .jpeg, or .gif files? And, would he put all those images in one file, or put each monster/object/building in its own file? Note; We are sticking to 2D for now and not doing 3D.
**Question 3:** I've seen some game artware where there would be a file for a monster, and in that file there'd be about 3-4 images of a monster from different directions, all put in one file, i think because they're part of an animation. Here's an illustraton:
[Monster looking to right] ... [Monster looking in the front] ... [Monster looking to right[
And all of them are in one file. Is this how he'll have to supply me with those animations?
What i'm trying to find out is, what is the format he'll have to supply me the designed images in, for me to be able to access/manipulate them easily in the Java code.
All answers appreciated :) | I have some comments for each question.
**Question 1:** You say that you will begin coding level 1, 2, .. one by one. I recommend you to create a *reusable framework* instead or see it in the big picture instead. For the information you provide I think you are going to make some kind of RPG game. There are lots of things that can be shared between levels such as the Shop, the dialog system, for example. So focus for extensibility.
Why wait for designers to pass on the image? You can begin your coding by starting with pseudo graphics file you created yourself. You can then work with designer in parallel this way. And you can replace your pseudo graphics file with ones provided by designer later.
**Question 2:** JPG is not suitable for pixel-art style image, that appears a lot in most 2D game. And the GIF support only 256 color. The best choice to me seems to be PNG.
The designer should always keep the original artworks in editable format as well. It's likely that you want to change the graphics in the future.
**Question 3:** It depends. The format mentioned, where character's animations are kept in single file, is called [Sprite](http://en.wikipedia.org/wiki/Sprite_(computer_graphics)). If you kept your resource in this sprite format than you will have some works reading each of the sub-image by specifying coordinates. However, sprite helps you keep things organized. All the 2D graphics related to "Zombie" character is kept in one place. It is therefore easy to maintain. | About the image format: don't let the designer deliver anything as jpg, because you'll lose quality.
Let him send it as png instead, and convert it to your preferred format as needed.
Also, remember to have him send the source files (photoshop/illustrator/3dsmax/whatever) in case you'll ever need tiny changes that you can make yourself without hiring the graphics dude. Who knows if he'll still be available in the future anyway. | Java 2D game programming - Newbie questions | [
"",
"java",
"3d",
"2d",
"sprite",
""
] |
Would there be difference in speed between
```
if (myInt == CONST_STATE1)
```
and
```
if (myEnum == myENUM.State1)
```
in c#? | In C# Enums are in-lined to be constants by the compilier anyway, so the benefit is code legibility | The thing to be careful about when using Enums is not to use any of the operations that require reflection (or use them with care). For example:
1. myEnumValue.ToString().
2. Enum.Parse()
3. Enum.IsDefined()
4. Enum.GetName()
5. Enum.GetNames()
In case of constants the option of doing any operations that require reflection doesn't exist. However, in case of enums it does. So you will have to be careful with this.
I have seen profile reports where operations relating to enum validations / reflections took up to 5% of the CPU time (a scenario where enum validations were done on every call to an API method). This can be greatly reduced by writing a class that caches the results of the reflection of the enum types being used.
Having said that, **I would recommend making the decision of using enum vs. constant based on what makes sense from a design point of view**. This is while making sure that the team is aware of the performance implications of the operations involving reflection. | Performance comparisons betweeen enum evaluations and ints | [
"",
"c#",
"enums",
"performance",
"integer",
""
] |
In my application I need to temporarily gray out the minimize button of the main form. Any ideas how this can be achieved? I don't mind doing p/invokes to Win32 dlls.
Edit: Graying out the minimize button would be the preferred solution, but is there any other way of preventing the form from becoming minimized? | I read your comment in regards to my response and was able to drum up a more complete solution for you. I ran this quickly and it seemed to have the behavior that you wanted. Instead of deriving your winforms from Form, derive from this class:
```
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace NoMinimizeTest
{
public class MinimizeControlForm : Form
{
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MINIMIZE = 0xf020;
protected MinimizeControlForm()
{
AllowMinimize = true;
}
protected override void WndProc(ref Message m)
{
if (!AllowMinimize)
{
if (m.Msg == WM_SYSCOMMAND)
{
if (m.WParam.ToInt32() == SC_MINIMIZE)
{
m.Result = IntPtr.Zero;
return;
}
}
}
base.WndProc(ref m);
}
[Browsable(true)]
[Category("Behavior")]
[Description("Specifies whether to allow the window to minimize when the minimize button and command are enabled.")]
[DefaultValue(true)]
public bool AllowMinimize
{
get;
set;
}
}
}
```
You could do a bit more if you wanted to be able to decide whether to allow minimizing at the time the click is sent, for instance:
```
using System;
using System.Windows.Forms;
using System.ComponentModel;
namespace NoMinimizeTest
{
public class MinimizeControlForm : Form
{
private const int WM_SYSCOMMAND = 0x0112;
private const int SC_MINIMIZE = 0xf020;
protected MinimizeControlForm()
{
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_SYSCOMMAND)
{
if (m.WParam.ToInt32() == SC_MINIMIZE && !CheckMinimizingAllowed())
{
m.Result = IntPtr.Zero;
return;
}
}
base.WndProc(ref m);
}
private bool CheckMinimizingAllowed()
{
CancelEventArgs args = new CancelEventArgs(false);
OnMinimizing(args);
return !args.Cancel;
}
[Browsable(true)]
[Category("Behavior")]
[Description("Allows a listener to prevent a window from being minimized.")]
public event CancelEventHandler Minimizing;
protected virtual void OnMinimizing(CancelEventArgs e)
{
if (Minimizing != null)
Minimizing(this, e);
}
}
}
```
For more information about this window notification, see the [MSDN article about it](http://msdn.microsoft.com/en-us/library/ms646360(VS.85).aspx "WM_SYSCOMMAND Notification"). | ```
form.MinimizeBox = false;
```
or if in the form scope
```
MinimizeBox = false;
``` | How to disable the minimize button in C#? | [
"",
"c#",
"winforms",
"minimize",
""
] |
I'd like a way to show natural times for dated items in Python. Similar to how Twitter will show a message from "a moment ago", "a few minutes ago", "two hours ago", "three days ago", etc.
Django 1.0 has a "humanize" method in django.contrib. I'm not using the Django framework, and even if I were, it's more limited than what I'd like.
Please let me (and generations of future searchers) know if there is a good working solution already. Since this is a common enough task, I imagine there must be something. | While not useful to you at this very moment, it may be so for future searchers:
The babel module, which deals with all sorts of locale stuff, has a function for doing more or less what you want. Currently it's only in their trunk though, not in the latest public release (version 0.9.4). Once the functionality lands in a release, you could do something like:
```
from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'
```
This is taken straight from [the babel documentation on time delta formatting](http://babel.edgewall.org/wiki/Documentation/dates.html#time-delta-formatting). This will at least get you parts of the way. It wont do fuzziness down to the level of "moments ago" and such, but it will do "n minutes" etc. correctly pluralized.
For what it's worth, the babel module also contains functions for formatting dates and times according to locale, Which might be useful when the time delta is large. | Twitter dates in specific are interesting because they are relative only for the first day. After 24 hours they just show the month and day. After a year they start showing the last two digits of the year. Here's a sample function that does something more akin to Twitter relative dates, though it always shows the year too after 24 hours. It's US locale only, but you can always alter it as needed.
```
# tested in Python 2.7
import datetime
def prettydate(d):
diff = datetime.datetime.utcnow() - d
s = diff.seconds
if diff.days > 7 or diff.days < 0:
return d.strftime('%d %b %y')
elif diff.days == 1:
return '1 day ago'
elif diff.days > 1:
return '{} days ago'.format(diff.days)
elif s <= 1:
return 'just now'
elif s < 60:
return '{} seconds ago'.format(s)
elif s < 120:
return '1 minute ago'
elif s < 3600:
return '{} minutes ago'.format(s/60)
elif s < 7200:
return '1 hour ago'
else:
return '{} hours ago'.format(s/3600)
``` | Natural/Relative days in Python | [
"",
"python",
"datetime",
"human-readable",
"datetime-parsing",
"humanize",
""
] |
I know that a lot of examples exist where a SqlConnection is defined and then a SqlCommand is defined, both in Using blocks:
```
using (var conn = new SqlConnection(connString)) {
using (var cmd = new SqlCommand()) {
cmd.Connection = conn;
//open the connection
}
}
```
My question: If I define the connection directly on the SqlCommand, does the connection close when the command is disposed?
```
using (var cmd = new SqlCommand()) {
cmd.Connection = new SqlConnection(connString);
//open the connection
}
``` | No, SqlCommand never attempts to close/dispose of the connection. | No, the connection object will not be disposed until you dispose it explicitly. But my recommendation is to use **using blocks** whenever you can. | Does connection close when command is disposed and the connection is defined directly on the command? | [
"",
"c#",
"using",
"using-statement",
""
] |
What is the simplest way of testing if an object implements a given interface in C#? (Answer to this question
[in Java](https://stackoverflow.com/questions/766106/test-if-object-implements-interface)) | ```
if (object is IBlah)
```
or
```
IBlah myTest = originalObject as IBlah
if (myTest != null)
``` | Using the `is` or `as` operators is the correct way if you know the interface type at compile time and have an instance of the type you are testing. Something that no one else seems to have mentioned is `Type.IsAssignableFrom`:
```
if( typeof(IMyInterface).IsAssignableFrom(someOtherType) )
{
}
```
I think this is much neater than looking through the array returned by `GetInterfaces` and has the advantage of working for classes as well. | Test if object implements interface | [
"",
"c#",
"reflection",
"interface",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.