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 datab...
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 ...
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"> ...
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: *Delega...
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 worksta...
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-27b8...
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 current...
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; ...
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, develo...
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 sim...
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 ar...
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 ...
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 muc...
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 ...
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](h...
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...
[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 m...
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 J...
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, ...
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 m...
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...
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 { ...
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 = MyDescrip...
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. Thi...
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 Som...
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...
**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 a...
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 [...
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...
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 ...
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.ExecuteNullableScala...
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...
``` 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...
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(...
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....
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...
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 colo...
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) { ...
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 w...
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 th...
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...
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. ``` [...
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:...
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....
> 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 "`...
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...
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...
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 b...
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 usef...
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? ...
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 ho...
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 ...
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 t...
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...
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 <htt...
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 do...
``` 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 ...
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 on...
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...
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 f...
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, DirectI...
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://gi...
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 S...
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...
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 ...
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(user...
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 ...
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:...
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 "we...
# 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: * [...
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 stat...
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 CO...
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(pa...
``` 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...
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 ConnectionSt...
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 = R...
**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 fil...
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 othe...
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 s...
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...
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 ...
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. Y...
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...
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 trai...
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 { /** Interna...
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, run...
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 ca...
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 ...
**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...
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 SchedulingYearI...
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 ...
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 th...
***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...
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...
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 usi...
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 ...
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());...
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 nu...
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 benchmark...
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 p...
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 ...
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 s...
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...
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....
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)...
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 do...
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 ...
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 "mai...
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.p...
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...
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($...
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...
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 computation...
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. Exam...
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 implementati...
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...
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 tha...
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 ove...
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 usi...
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 ...
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 t...
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 ...
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....
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 + ' - '...
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` 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 ...
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 po...
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 langu...
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, ...
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 ...
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 **u...
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 ja...
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...
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;...
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 la...
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...
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 t...
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 <= normalis...
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 fin...
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...
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 onl...
> *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...
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/ques...
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 smar...
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 ...
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...
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 compin...
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.h...
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, o...
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 diff...
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. Som...
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 ...
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?e...
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,...
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 u...
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 fi...
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#listin...
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 ...
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 authenticati...
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 ...
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 ...
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...
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 ...
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...
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 ...
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 t...
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, ever...
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 X...
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) ``...
[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, the...
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, "...
> 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<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...
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 spac...
``` 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 ...
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 'valu...
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>.T...
``` 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 ...
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 intern...
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, user...
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 ...
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 Anyt...
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 value...
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 ...
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 way...
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_sele...
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...
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 tes...
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 deploy...
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! [![Add Existing Item](https://i.stack.imgur.com/Bl8Ss.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 he...
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...
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 A...
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): ``` <prope...
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), w...
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 yo...
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 ...
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 programatica...
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/346...
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 ...
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 thi...
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 yo...
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 refl...
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; ...
``` 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 th...
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 ...
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 ...
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 de...
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 muc...
Test if object implements interface
[ "", "c#", "reflection", "interface", "" ]