Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am trying to write a C# P/Invoke wrapper for a C API (a native Win dll), and generally this is working fine. The only exception is a specific method which takes a struct as a parameter in the C code. The function is invoked without any exceptions, but it returns false indicating that something failed in the execution.
In the API header file the involved method and structs are defined as follows:
```
#define MAX_ICE_MS_TRACK_LENGTH 256
typedef struct tagTRACKDATA
{
UINT nLength;
BYTE TrackData[MAX_ICE_MS_TRACK_LENGTH];
} TRACKDATA, FAR* LPTRACKDATA;
typedef const LPTRACKDATA LPCTRACKDATA;
BOOL ICEAPI EncodeMagstripe(HDC /*hDC*/,
LPCTRACKDATA /*pTrack1*/,
LPCTRACKDATA /*pTrack2*/,
LPCTRACKDATA /*pTrack3*/,
LPCTRACKDATA /*reserved*/);
```
I have made an attempt to create a C# P/Invoke wrapper using the following code:
```
public const int MAX_ICE_MS_TRACK_LENGTH = 256;
[StructLayout(LayoutKind.Sequential)]
public class MSTrackData {
public UInt32 nLength;
public readonly Byte[] TrackData = new byte[MAX_ICE_MS_TRACK_LENGTH];
}
[DllImport("ICE_API.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool EncodeMagstripe(IntPtr hDC,
[In]ref MSTrackData pTrack1,
[In]ref MSTrackData pTrack2,
[In]ref MSTrackData pTrack3,
[In]ref MSTrackData reserved);
```
Then I try to invoke the EncodeMagstripe method using the following C# code:
```
CardApi.MSTrackData trackNull = null;
CardApi.MSTrackData track2 = new CardApi.TrackData();
byte[] trackBytes = Encoding.ASCII.GetBytes(";0123456789?");
track2.nLength = (uint)trackBytes.Length;
Buffer.BlockCopy(trackBytes, 0, track2.TrackData, 0, trackBytes.Length);
if (!CardApi.EncodeMagstripe(hDC, ref trackNull, ref track2, ref trackNull, ref trackNull)) {
throw new ApplicationException("EncodeMagstripe failed", Marshal.GetLastWin32Error());
}
```
This causes an ApplicationException to be thrown, and the error code is 801 which according to the documentation means "Data includes too many characters for the selected Track 2 format.". However the selected track format should allow up to 39 characters (I have also tried shorter strings).
I suspect the problem occurrs due to something I did wrong in the MSTrackData definition, but I cannot see what this may be. Does anyone have any suggestions? | All the answers given so far have a bit of the answer but are incomplete. You need the MarshalAs - ByValArray as well as the new, your MSTrackDatas are already references so you do not need to pass them by ref and you must check what calling convention ICEAPI represents, if it is StdCall you don't need to change anything but if it is cdecl you will need to add the CallingConvention to your DllImport attribute. Also, you may need to add a MarshalAs attribute to your bool return value to make sure it is marshaled as 4 byte WinApi style bool. Here are the declares you'll (probably) need:
```
public const int MAX_ICE_MS_TRACK_LENGTH = 256;
[StructLayout(LayoutKind.Sequential)]
public class MSTrackData {
public UInt32 nLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
public Byte[] TrackData = new byte[MAX_ICE_MS_TRACK_LENGTH];
}
[DllImport("ICE_API.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EncodeMagstripe(IntPtr hDC,
[In] MSTrackData pTrack1,
[In] MSTrackData pTrack2,
[In] MSTrackData pTrack3,
[In] MSTrackData reserved);
``` | I would define the BYTE array not with new, but use the following code instead to initialise the right size:
> [MarshalAs(UnmanagedType.byValTSt, SizeConst =256)]
> public readonly Byte[] TrackData;
I have used this successfully on char arrays in the past. | C# P/Invoke structure problem | [
"",
"c#",
"struct",
"pinvoke",
""
] |
When debugging, sometimes you need to attach an already running process instead of just starting the application in a debugger.
It's common for myself to put in a Sleep() or MessageBox call, so that it's easier to attach a debugger. I worry that some of these may be committed eventually to source control.
What is the best thing to do to avoid this situation while still delaying enough time so that you can attach your debugger to a running process?
Guarding the Sleep or message box with an `#ifdef _DEBUG` is one way, but I'm wondering if there is a better way.
With a Sleep you also have the problem that you may not attach in time. With a MessageBox you have the problem that you may be remotely debugging, or debugging a process that has no visible GUI (example running as a service on Vista) | you can use DebugBreak, check these links:
<http://www.epsilon-delta.net/articles/vc6_debug.html#breaking-with-debugbreak>
<http://blogs.msdn.com/calvin_hsia/archive/2006/08/25/724572.aspx> | another variant, which I sometimes use is
```
while( !::IsDebuggerPresent() )
::Sleep( 100 ); // to avoid 100% CPU load
```
it should just silently wait until you attach your debugger to the process. | What is the best way to attach a debugger to a process in VC++ at just the right point in time? | [
"",
"c++",
"debugging",
"visual-c++",
"debugbreak",
""
] |
I've never used it in the professional software even though in our shop, and others I have worked for, we design large scale systems. The only time I messed with virtual inheritance was during my interview in a company. Nonetheless, I played with it during afterhours.
Do you guys use it? Do you understand how it works in depth (how most popular compiler vendors implement it)? I would really like to know how it is used in professional software, if at all. Tricks and tips would be appreciated, too.
To me, virtual inheritance was just a solution to an infamous diamond problem. Hence, it never found its way in our software, as we don't have in our architecture MI resulting in the diamond.
Thanks. | The main point with virtual inheritance is to prevent derived classes from inheriting multiple copies of different superior classes. This can occur in any case where there may be multiple inheritance -- as you correctly note, the "diamond problem", which is to say where the inheritance graph is a DAG instead of a strict tree.
The [C++ FAQ goes into it in some detail](http://www.parashift.com/c++-faq-lite/multiple-inheritance.html). I'd also recommend the C++ FAQ Book; I used to work for the authors and they're quite good. | > I've never used it in the professional software even though in our shop,
Do you use `iostream`? We do. Look up the design of iostreams and you'll know you've been using virtual inheritance. | Virtual inheritance in C++ usages/tricks | [
"",
"c++",
"oop",
""
] |
I am very puzzled about this code:
```
var closures = [];
function create() {
for (var i = 0; i < 5; i++) {
closures[i] = function() {
alert("i = " + i);
};
}
}
function run() {
for (var i = 0; i < 5; i++) {
closures[i]();
}
}
create();
run();
```
From my understanding it should print `0,1,2,3,4` (isn't this the concept of closures?).
Instead it prints `5,5,5,5,5`.
I tried Rhino and Firefox.
Could someone explain this behavior to me? | Fixed Jon's answer by adding an additional anonymous function:
```
function create() {
for (var i = 0; i < 5; i++) {
closures[i] = (function(tmp) {
return function() {
alert("i = " + tmp);
};
})(i);
}
}
```
The explanation is that JavaScript's scopes are function-level, not block-level, and creating a closure just means that the enclosing scope gets added to the lexical environment of the enclosed function.
After the loop terminates, the function-level variable `i` has the value `5`, and that's what the inner function 'sees'.
---
As a side note: you should beware of unnecessary function object creation, espacially in loops; it's inefficient, and if DOM objects are involved, it's easy to create circular references and therefore introduce memory leaks in Internet Explorer. | I think this might be what you want:
```
var closures = [];
function createClosure(i) {
closures[i] = function() {
alert("i = " + i);
};
}
function create() {
for (var i = 0; i < 5; i++) {
createClosure(i);
}
}
``` | Doesn't JavaScript support closures with local variables? | [
"",
"javascript",
"loops",
"closures",
""
] |
In php I have:
```
$result = mysql_query($query);
// if successful query, return the records
if ($result)
{
// if not empty result, return array of records
if (mysql_num_rows($result))
{
$records = array();
while ($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
return $records;
}
}
```
In Objective-C - After the POST I have the following code...
```
NSURLResponse *newStr = [[NSURLResponse alloc] init];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&newStr error:nil];
```
returnData is equal to the literal "Array", not the contents of $records[] | You should serialise the data into a XML type `plist` format if you can, then it can be natively interpreted by Cocoa classes like NSArray and NSDictionary. NSPropertyListSerializer is capable of producing mutable or immutable arrays and dictionaries from a file or from an NSData object containing serialized data in plist format.
NSDictionary can also read files in this format:
```
"key" = "value";
"key2" = "value2";
```
Likewise, NSArray can read files in this format:
```
(
"value1",
"value2",
"value3",
"30",
"value5"
);
```
In fact, I think if the strings don't contain spaces, the quotes are optional (but I guess they would force string types).
Check out [this URL](http://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/OldStylePlists/OldStylePLists.html) for more information about oldschool ASCII property lists. They are read-only, but then again they are easy enough to generate manually or systematically. | You need to format your array in some format that you can read in Objective-C. I recommend using [JSON](http://json.org).
If you have PHP 5.2, you can use [the built in functions](https://www.php.net/json) to encode your data. For example:
```
echo json_encode($records);
```
On the Objective-C side, you can use [TouchJSON](http://code.google.com/p/touchcode/wiki/TouchJSON) to decode/encode JSON. | How do I read in a php array, in Objective-C? | [
"",
"php",
"objective-c",
"associative-array",
""
] |
I'm having trouble within a block of code that I believe is related to a mouse click event but I cannot seem to capture the exact event within my code. I've used the C# debugger to step through my code and after the end of one of my events the code simply locks up.
The purpose of my post is to ask if there is any software that will watch my process and let me know the events that are firing off after I hit the F11 key and the code freezes up. I've tried SysInternals' `procmon.exe` but that isn't telling me which events are firing off. | Have you tried Spy++ ? It's a tool that comes with Visual Studio (at least 2003 & 2005). On my default 2003 and 2005 installs, Spy++ is at:
Start | Program Files | Microsoft Visual Studio 200X | Visual Studio Tools | Spy++
After you run Spy++, select Find Window... from the Search menu. Drag the "Finder Tool" to the window or control you want to watch events on and click OK. Right-click on the item selected in the tree and select "Messages". This will bring up a window that shows the messages as they hit your window of interest.
If Spy++ doesn't get what you need, what about [Managed Spy](http://msdn.microsoft.com/en-us/magazine/cc163617.aspx)? It appears to be like Spy++ but specifically for managed code. I haven't tried it.
> [It] displays a treeview of controls in your .NET-based client application. You can select any control and get or set any property on it. You can also log a filtered set of events that the control raises. | Are you using multi-threading? If so, try to avoid passing controls and other Windows Forms objects out side of the forms thread, as the debugger will try to access the object's value, which will cause the debugger to freeze for some time. | Software to monitor events fired from code | [
"",
"c#",
"events",
"monitoring",
"deadlock",
""
] |
I'm in the situation where I've installed the JDK, but I can't run applets in browsers (I may not have installed the JRE).
However, when I install the JRE, it clobbers my JDK as the default runtime. This breaks pretty much everything (Eclipse, Ant) - as they require a server JVM.
There's no `JAVA_HOME` environment variable these days - it just seems to use some registry magic (setting the system path is of no use either). Previously, I've just uninstalled the JRE after I've used it to restore the JDK. This time I want to fix it properly.
This also manifests itself with the jre autoupdater - once upon a time, I had a working setup with the JDK and JRE, but it updated and bust everything. | This is a bit of a pain on Windows. Here's what I do.
Install latest Sun JDK, e.g. **6u11**, in path like `c:\install\jdk\sun\6u11`, then let the installer install public JRE in the default place (`c:\program files\blah`). This will setup your default JRE for the majority of things.
Install older JDKs as necessary, like **5u18** in `c:\install\jdk\sun\5u18`, but don't install the public JREs.
When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set `JAVA_HOME=c:\jdk\sun\JDK_DESIRED` and then set `PATH=%JAVA_HOME%\bin;%PATH%`. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the `JAVA_HOME` variable.
The path is important because most public JRE installs put a linked executable at `c:\WINDOWS\System32\java.exe`, which usually *overrides* most other settings. | I have patched the behaviour of my eclipse startup shortcut in the properties dialogue
from
```
"E:\Program Files\eclipse\eclipse.exe"
```
to
```
"E:\Program Files\eclipse\eclipse.exe" -vm "E:\Program Files\Java\jdk1.6.0_30\bin"
```
as described [in the Eclipse documentation](http://www.google.com.au/url?sa=t&rct=j&q=eclipse%20launcher&source=web&cd=3&ved=0CD4QFjAC&url=http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/reference/misc/launcher_ini.html&ei=tYgTT821O6uTiQe9o4lE&usg=AFQjCNGbNdEYhkI2HTj2PVLG3LIoNkl3Tw&sig2=nk5-P118j3rCEsuU52wf4Q)
It is a patch only, as it depends on the shortcut to fix things...
The alternative is to set the parameter permanently in the eclipse initialisation file. | How do I set the default Java installation/runtime (Windows)? | [
"",
"java",
"windows",
"installation",
"runtime",
""
] |
The following Function is executing in its own thread:
```
private void doSendData()
{
try {
//writeToFile(); // just a temporary location of a call
InetAddress serverAddr = InetAddress.getByName(serverAddress);
serverAddr.wait(60000);
//Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, portNumber);
socket.setSoTimeout(3000);
try {
//Log.d("TCP", "C: Sending: '" + message + "'");
PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
String message = packData();
out.println(message);
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
connectionAvailable = true;
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
connectionAvailable = false;
} finally {
socket.close();
announceNetworkAvailability(connectionAvailable);
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
announceNetworkAvailability(connectionAvailable);
}
}
```
When the execution reaches the line `serverAddr.wait(60000)` it throws an Exception:
```
java.lang.IllegalMonitorStateException: object not locked by thread before wait()
```
Does anyone know how to lock an object or a function in order to prevent the concurrency?
I've tried to add a Lock object:
```
private final Lock lock = new ReentrantLock();
```
and the line
```
boolean locked = lock.tryLock();
```
at the beginning of function but it didn't work. | In order to call wait() on an object, you have to hold the synchronized lock on that object (though the lock is actually released while the thread is waiting):
```
synchronized (serverAddr) {
serverAddr.wait();
}
```
I have to admit that *why* you're wanting to do this baffles me in this case... | Maybe the method you are looking for is [Thread.sleep(long)](https://docs.oracle.com/javase/8/docs/api/java/lang/Thread.html#sleep-long-)? This method will *wait* (as in stop the execution of the thread) for the specified time in milliseconds before resuming.
[object.wait(long)](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait-long-) (which is what you are using) does something entirely different. It waits for another object from another thread to notify it (ie: send it a sort of wakeup message), and will wait at most the specified number of milliseconds. Given the code you posted, I highly doubt this is what you really want.
If Thread.sleep() is not what you want, then you should use the synchronized block as mentioned by the other posters. | Threading in Java: How to lock an object? | [
"",
"java",
"multithreading",
"concurrency",
"locking",
""
] |
I am looking at design by contract for a Java library, this what I came up with so far in terms of the interface.
The user could call executeContract and executeContract invokes invokeContract after calling 'require'. ensure is called after executeContract to ensure the correctness of what is returned by invokeContract.
This code also works as a callback method (anonymous inner class call).
What are your thoughts? Is this design by contract?, so far this helps me write testable Java code.
```
public interface IContractHandler {
/**
* Execute contract will invoke the #invokeContract method. In the execute method,
* check for the validity of the preconditions and the post conditions.
*
* The precondition can be null.
*
* @param precondInput - Precondition Input Data, can be null.
* @return Post condition output
*/
public Object executeContract(final Object precondInput) throws ContractError;
/**
* Require that the preconditions are met.
*/
public Object require(final Object precondInput) throws ContractError;
/**
* Ensure that the postconditions are met.
*/
public Object ensure(final Object precondInput) throws ContractError;
/**
* The precondition can be null if the contract allows for that.
*
* @param precondInput - Precondition Input Data, can be null.
* @return Post condition output
*/
public Object invokeContract(final Object precondInput) throws ContractError;
}
``` | If you are looking for a generic solution to this I would recommend the [*Java Modelling Language*](http://www.eecs.ucf.edu/~leavens/JML/ "JML"). All of the *pre/post-conditions* (`@requires/@ensures`) can be specified in the annotations above the method you wish to check. It's my understanding that the *JML compiler* (`jmlc`) inserts runtime assertions into the bytecode.
I believe *ESC/Java2* has a similar type of functionallity but I've never used it before. | Actually, what you are looking for in this situation is a a pattern called a [Template Method](http://en.wikipedia.org/wiki/Template_method_pattern). Interfaces don't determine the implementation, which is what you are trying to do in your executeContract() method. | Design by Contract library (interface) thoughts? | [
"",
"java",
"design-by-contract",
"contract",
""
] |
Is there any way python is natively, or through some code available online (preferably under the GPL), capable of doing process management. The goal is similar to the functionality of ps, but preferably in arrays, lists, and/or dicts. | <http://pypi.python.org/pypi/PSI> | This one is cross-platform:
<http://code.google.com/p/psutil/> | Python process management | [
"",
"python",
"process",
"ps",
""
] |
In a Java program, I have multiple subclasses inheriting from a parent (which is abstract). I wanted to express that every child should have a member that is set once only (which I was planning to do from the constructor). My plan was to code s.th. like this:
```
public abstract class Parent {
protected final String birthmark;
}
public class Child extends Parent {
public Child(String s) {
this.birthmark = s;
}
}
```
However, this seems to not please the Java gods. In the parent class, I get the message that `birthmark` "might not have been initialized", in the child class I get "The final field `birthmark` cannot be accessed".
So what's the Java way for this? What am I missing? | You can't do it because while comparing the parent class, the compiler can't be sure that the subclass will initialize it. You'll have to initialize it in the parent's constructor, and have the child call the parent's constructor:
```
public abstract class Parent {
protected final String birthmark;
protected Parent(String s) {
birthmark = s;
}
}
public class Child extends Parent {
public Child(String s) {
super(s);
...
}
}
``` | Pass it to the parent constructor:
```
public abstract class Parent {
private final String birthmark;
public Parent(String s) {
birthmark = s;
}
}
public class Child extends Parent {
public Child(String s) {
super(s);
}
}
``` | In Java, why can't I declare a final member (w/o initializing it) in the parent class and set its value in the subclass? How can I work around? | [
"",
"java",
"final",
""
] |
is there a built-in support in Groovy to handle Zip files (the groovy way)?
Or do i have to use Java's java.util.zip.ZipFile to process Zip files in Groovy ? | AFAIK, there isn't a native way. But check out the article [Powerful Groovy](https://web.archive.org/web/20151120062929/http://blog.xebia.com/2008/05/25/powerful-groovy/) on how you'd add a `.zip(...)` method to File, which would be very close to what you're looking for. You'd just need to make an `.unzip(...)` method. | Maybe Groovy doesn't have 'native' support for zip files, but it is still pretty trivial to work with them.
I'm working with zip files and the following is some of the logic I'm using:
```
def zipFile = new java.util.zip.ZipFile(new File('some.zip'))
zipFile.entries().each {
println zipFile.getInputStream(it).text
}
```
You can add additional logic using a `findAll` method:
```
def zipFile = new java.util.zip.ZipFile(new File('some.zip'))
zipFile.entries().findAll { !it.directory }.each {
println zipFile.getInputStream(it).text
}
``` | Unzip Archive with Groovy | [
"",
"java",
"groovy",
"zip",
"unzip",
""
] |
I've got a set of Java2D calls that draw vectors on a graphics context. I'd like for the image to be doubled in size and then rotated 90 degrees.
I'm using the following code to do this:
```
Graphics2D g2 = // ... get graphics 2d somehow ...
AffineTransform oldTransform = g2.getTransform();
AffineTransform newTransform = (AffineTransform)oldTransform.clone();
newTransform.concatenate(AffineTransform.getTranslateInstance(x1, x2));
newTransform.concatenate(AffineTransform.getScaleInstance((double)newW/(double)iconW, (double)newH/(double)iconH));
newTransform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(rotationAngle), (double)iconW/2.0d, (double)iconH/2.0d));
// ... do my drawing ...
```
This rotates and scales, however, the scale isn't applied the way I would like. It is as if it is rotated before scaling, thus making the image wider on the wrong axis.
Is there a better way to do this? | I believe those transforms are implemented like a stack - so the last transform is performed first. Try reversing the order of the rotate and scale transformations and you should get what you are looking for.
```
newTransform.concatenate(AffineTransform.getTranslateInstance(x1, x2));
newTransform.concatenate(AffineTransform.getRotateInstance(Math.toRadians(rotationAngle), (double)iconW/2.0d, (double)iconH/2.0d));
newTransform.concatenate(AffineTransform.getScaleInstance((double)newW/(double)iconW, (double)newH/(double)iconH));
``` | Rotations are always performed about the origin. In order to [rotate about a certain point](http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm) you must translate the points.
[This page](http://www.euclideanspace.com/maths/geometry/transform/index.htm) explains the maths behind what you're trying to do and show why transformations need to be applied in a certain order. | Rotation and Scaling -- How to do both and get the right result? | [
"",
"java",
"graphics",
"linear-algebra",
"java-2d",
"affinetransform",
""
] |
I am trying to figure out what is the best way to connect an (existing) ASP.Net application to an Oracle database to read its dictionary information.
There are simply too many possibilities:
* MS Data Provider for Oracle (requires 8.1.7, namespace System.Data.OracleClient)
* Oracle Data Provider for .NET (requires 9.2, namespace Oracle.DataAccess)
* Oracle Provider for OLE DB
* MSDASQL and ODBC
As my current app uses MSSQL server, further options would be:
* Linked Server, access via server..user.object
* Linked Server via OPENROWSET
There are a couple of questions on similar topics on SO, but only some have accepted answers.
What's your experience with each of the drivers? What are their pros and cons?
Of course Oracle is recommending ODP.Net. Is the requirement of version 9.2 (or higher) a problem today? | I too recommend ODP.NET. Choose the latest provider (<http://www.oracle.com/technology/tech/windows/odpnet/index.html>). It can connect with an Oracle 9.2 database or a newer release of the database.
The MS Data Provider for Oracle is very limited. You can't work with arrays for example and user defined types. And why would Microsoft provide good support for connecting to Oracle?
You can also check out the provider of devart: <http://www.devart.com/dotconnect/oracle/> . It supports the entity framework. | Dump OLE DB and ODBC options, if you have direct data access provider there is no need in using OLE DB or ODBC.
I recommend Oracle Data Provider for .NET. | How to choose an Oracle provider for .Net application? | [
"",
"c#",
"oracle",
"asp.net-2.0",
"provider",
""
] |
I am currently writing a Windows application in C# that will add documents to a document library list. I am trying to reference Microsoft.Sharepoint, however I do not see the COM or .NET library inside visual studio 2005 add references lists. What dll do I need to reference and where can I find this?
Thanks,
Alex | To access a document library I would recommend going through the list web service which SharePoint exposes. From personal experience that is the easiest, most portable and upgradable way.
The documentation for ALL the web services and .NET libraries to do it as well can be download in [Visual studio extensions for windows sharepoint services](http://www.microsoft.com/downloads/details.aspx?displaylang=en&FamilyID=b2c0b628-5cab-48c1-8cae-c34c1ccbdc0a) | to access the SharePoint library you have to include following assembly into your project: Microsoft.SharePoint.dll
You can find it on your SharePoint Server under the 12 hives folder: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\ISAPI
There you can find some more assemblies you might need for more SharePoint functionality. | Using C# to access Sharepoint - where can I find the reference library? | [
"",
"c#",
"sharepoint",
"reference",
""
] |
I have the following arrays:
```
var original= new int[] { 2, 1, 3 };
var target = new int[] { 1, 3, 4 };
enum Operation {Added,Removed}
```
I would like to execute a LINQ query that would return the following:
```
{{2,Removed},{4,Added}}
```
Limitation: I would like LINQ to perform this very efficiently and avoid and O(n^2) style algorithms. | Perhaps a LINQ solution is not the best option in this case.
This will produce a dictionary with the result that you want.
```
Dictionary<int, Operation> difference = new Dictionary<int,Operation>();
foreach (int value in original) {
difference.Add(value, Operation.Removed);
}
foreach (int value in target) {
if (difference.ContainsKey(value)) {
difference.Remove(value);
} else {
difference.Add(value, Operation.Added);
}
}
```
To keep the size of the dictionary down, perhaps it's possible to loop the enumerations in parallell. I'll have a look at that...
Edit:
Here it is:
```
Dictionary<int, Operation> difference = new Dictionary<int,Operation>();
IEnumerator<int> o = ((IEnumerable<int>)original).GetEnumerator();
IEnumerator<int> t = ((IEnumerable<int>)target).GetEnumerator();
bool oActive=true, tActive=true;
while (oActive || tActive) {
if (oActive && (oActive = o.MoveNext())) {
if (difference.ContainsKey(o.Current)) {
difference.Remove(o.Current);
} else {
difference.Add(o.Current, Operation.Removed);
}
}
if (tActive && (tActive = t.MoveNext())) {
if (difference.ContainsKey(t.Current)) {
difference.Remove(t.Current);
} else {
difference.Add(t.Current, Operation.Added);
}
}
}
```
Edit2:
I did some performance testing. The first version runs 10%-20% faster, both with sorted lists and randomly ordered lists.
I made lists with numbers from 1 to 100000, randomly skipping 10% of the numbers. On my machine the first version of the code matches the lists in about 16 ms. | ```
enum Operation { Added, Removed, }
static void Main(string[] args)
{
var original = new int[] { 2, 1, 3 };
var target = new int[] { 1, 3, 4 };
var result = original.Except(target)
.Select(i => new { Value = i, Operation = Operation.Removed, })
.Concat(
target.Except(original)
.Select(i => new { Value = i, Operation = Operation.Added, })
);
foreach (var item in result)
Console.WriteLine("{0}, {1}", item.Value, item.Operation);
}
```
I don't think you can do this with LINQ using only a single pass given the stock LINQ extension methods but but might be able to code a custom extension method that will. Your trade off will likely be the loss of deferred execution. It would be interesting to compare the relative performance of both. | LINQ for diffing sets | [
"",
"c#",
"linq",
""
] |
I have an 'optional' parameter on a method that is a KeyValuePair. I wanted an overload that passes null to the core method for this parameter, but in the core method, when I want to check if the KeyValuePair is null, I get the following error:
```
Operator '!=' cannot be applied to operands of type System.Collections.Generic.KeyValuePair<string,object>' and '<null>.
```
How can I not be allowed to check if an object is null? | `KeyValuePair<K,V>` is a struct, not a class. It's like doing:
```
int i = 10;
if (i != null) ...
```
(Although that is actually legal, with a warning, due to odd nullable conversion rules. The important bit is that the `if` condition will never be true.)
To make it "optional", you can use the nullable form:
```
static void Foo(KeyValuePair<object,string>? pair)
{
if (pair != null)
{
}
// Other code
}
```
Note the ? in `KeyValuePair<object,string>?` | I'm answering this despite its age because it is the 1st Google result for "test keyvaluepair to null"
The answer specified is correct, but it doesn't completely answer the problem, at least the one I was having, where I need to test the existence of the `KeyValuePair` and move on to another check of the `Dictionary` if it doesn't exist the way I'm expecting.
Using the method above didn't work for me because the compiler chokes on getting `KeyValuePair.Value` of `KeyValuePair<>?`, so it is better to utilize `default(KeyValuePair<>)` as seen in this question + answers. [The default for KeyValuePair](https://stackoverflow.com/q/1641392/528748) | How can an object not be compared to null? | [
"",
"c#",
".net",
"generics",
""
] |
Once a class is loaded is there a way to invoke static initializers again?
```
public class Foo {
static {
System.out.println("bar");
}
}
```
Edit:
I need to invoke the static initializer because I didn't write the original class and the logic I need to invoke is implemented in the static initializer. | One circumstance in which the logic would be run more than once is if the class is loaded multiple times by different ClassLoaders. Note that in this instance, they are essentially different classes.
Generally, though, these are one-shot deals. If you want to be able to invoke the logic multiple times, do as others have suggested and put it in a static method. | Put the initalisation code in a separate public static method, so you can call it from the static initializer and from elsewhere? | Invoke static initializer again | [
"",
"java",
"static",
"static-initializer",
""
] |
I am trying to use os.system() to call another program that takes an input and an output file. The command I use is ~250 characters due to the long folder names.
When I try to call the command, I'm getting an error: `The input line is too long`.
I'm guessing there's a `255 character limit` (its built using a C system call, but I couldn't find the limitations on that either).
I tried changing the directory with `os.chdir()` to reduce the folder trail lengths, but when I try using `os.system()` with `"..\folder\filename"` it apparently can't handle relative path names. Is there any way to get around this limit or get it to recognize relative paths? | You should use the subprocess module instead. See [this](http://docs.python.org/library/subprocess.html#subprocess-replacements) little doc for how to rewrite os.system calls to use subprocess. | Even it's a good idea to use `subprocess.Popen()`, this does not solve the issue.
**Your problem is not the 255 characters limit**, this was true on DOS times, later increased to 2048 for Windows NT/2000, and increased again to 8192 for Windows XP+.
The **real solution** is to workaround a very old bug in Windows APIs: [\_popen() and \_wpopen()](http://msdn.microsoft.com/en-us/library/96ayss4b.aspx).
If you ever use quotes during the command line you have to add the entire command in quoates or you will get the `The input line is too long` error message.
All Microsoft operating systems starting with Windows XP had a 8192 characters limit which is now enough for any decent command line usage but they forgot to solve this bug.
To overcome their bug **just include your entire command in double quotes**, and if you want to know more real the [MSDN comment on \_popen()](http://msdn.microsoft.com/en-us/library/96ayss4b.aspx).
Be careful because these works:
```
prog
"prog"
""prog" param"
""prog" "param""
```
But these will not work:
```
""prog param""
```
If you need a function that does add the quotes when they are needed you can take the one from <http://github.com/ssbarnea/tendo/blob/master/tendo/tee.py> | What to do with "The input line is too long" error message? | [
"",
"python",
"command-line",
"windows-console",
""
] |
a theoretical question. After reading Armstrongs 'programming erlang' book I was wondering the following:
It will take some time to learn Erlang. Let alone master it. It really is fundamentally different in a lot of respects.
So my question: Is it possible to write 'like erlang' or with some 'erlang like framework', which given that you take care not to create functions with sideffects, you can create scaleable reliable apps as well as in Erlang? Maybe with the same msgs sending, loads of 'mini processes' paradigm.
The advantage would be to not throw all your accumulated C/C++ knowledge over the fence.
Any thoughts about this would be welcome | *Yes*, it is possible, **but**...
Probably the best answer for this question is given by Robert Virding’s First Rule:
> “Any sufficiently complicated
> concurrent program in another language
> contains an ad hoc,
> informally-specified, bug-ridden, slow
> implementation of half of Erlang.”
Very good rule is **use the right tool for the task**. Erlang excels in concurrency and reliability. C/C++ was not designed with these properties in mind.
If you *don't want to throw away your C/C++ knowledge* and experience and **your project allows** this kind of division, good approach is to create a **mixed solution**. Write concurrent, communication and error handling code in Erlang, then add C/C++ parts, which will do CPU and IO bound stuff. | You clearly can - the Erlang/OTP system is largely written in C (and Erlang). The question is 'why would you want to?'
In 'ye olde days' people used to write their own operating system - but why would you want to?
If you elect to use an operating system your ***unwritten*** software has certain properties - it can persist to hard disk, it can speak to a network, it can draw on screens, it can run from the command line, it can be invoked in batch mode, etc, etc...
The Erlang/OTP system is 1.5M lines of code which has been demonstrated to give 99.9999999% uptime in large systems (the UK phone system) - that's 31ms downtime a year.
With Erlang/OTP your ***unwritten*** software has high reliability, it can hot-swap itself, your ***unwritten*** application can failover when a physical computer dies.
Why would you want to rewrite that functionality? | can one make concurrent scalable reliable programs in C as in erlang? | [
"",
"c++",
"concurrency",
"erlang",
"multicore",
""
] |
I'm trying to figure out how to make a virtual listbox (or tree or outline) in Swing -- this would be one where the listbox can show a "view" within a large result set from a database without getting the entire result set's contents; all it needs to give me is a heads up that Items N1 - N2 are going to need to be displayed soon, so I can fetch them, and ask for the contents of item N.
I know how to do it in Win32 ([ListView + LVS\_OWNERDATA](http://msdn.microsoft.com/en-us/library/bb774735(VS.85).aspx)) and in XUL ([custom treeview](https://developer.mozilla.org/en/XUL_Tutorial/Tree_View_Details)), and I found something for [SWT](http://www.java2s.com/Tutorial/Java/0280__SWT/Createatablewith1000000itemslazy.htm), but not Swing.
Any suggestions?
---
update: aha, I didn't understand what to look for in search engines, & the tutorials don't seem to call it a "virtual listbox" or use the idea. I found a [good tutorial](http://www.java2s.com/Tutorial/Java/0240__Swing/extendsAbstractListModel.htm) that I can start from, and one of the [Sun tutorials](https://docs.oracle.com/javase/tutorial/uiswing/components/list.html) seems ok also.
Here's my example program, which works the way I expect... *except* it seems like the listbox queries my AbstractListModel for **all** rows, not just the rows that are visible. For a million-row virtual table this isn't practical. How can I fix this? (edit: it seems like setPrototypeCellValue fixes this. But I don't understand why...)
```
package com.example.test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
// based on:
// http://www.java2s.com/Tutorial/Java/0240__Swing/extendsAbstractListModel.htm
// http://www.java2s.com/Tutorial/Java/0240__Swing/SpinnerNumberModel.htm
// http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/SpinnerNumberModel.html
// http://www.java2s.com/Tutorial/Java/0240__Swing/ListeningforJSpinnerEventswithaChangeListener.htm
public class HanoiMoves extends JFrame {
public static void main(String[] args) {
HanoiMoves hm = new HanoiMoves();
}
static final int initialLevel = 6;
final private JList list1 = new JList();
final private HanoiData hdata = new HanoiData(initialLevel);
public HanoiMoves() {
this.setTitle("Solution to Towers of Hanoi");
this.getContentPane().setLayout(new BorderLayout());
this.setSize(new Dimension(400, 300));
list1.setModel(hdata);
SpinnerModel model1 = new SpinnerNumberModel(initialLevel,1,31,1);
final JSpinner spinner1 = new JSpinner(model1);
this.getContentPane().add(new JScrollPane(list1), BorderLayout.CENTER);
JLabel label1 = new JLabel("Number of disks:");
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(label1, BorderLayout.WEST);
panel1.add(spinner1, BorderLayout.CENTER);
this.getContentPane().add(panel1, BorderLayout.SOUTH);
ChangeListener listener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
Integer newLevel = (Integer)spinner1.getValue();
hdata.setLevel(newLevel);
}
};
spinner1.addChangeListener(listener);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
class HanoiData extends AbstractListModel {
public HanoiData(int level) { this.level = level; }
private int level;
public int getLevel() { return level; }
public void setLevel(int level) {
int oldSize = getSize();
this.level = level;
int newSize = getSize();
if (newSize > oldSize)
fireIntervalAdded(this, oldSize+1, newSize);
else if (newSize < oldSize)
fireIntervalRemoved(this, newSize+1, oldSize);
}
public int getSize() { return (1 << level); }
// the ruler function (http://mathworld.wolfram.com/RulerFunction.html)
// = position of rightmost 1
// see bit-twiddling hacks page:
// http://www-graphics.stanford.edu/~seander/bithacks.html#ZerosOnRightMultLookup
public int rulerFunction(int i)
{
long r1 = (i & (-i)) & 0xffffffff;
r1 *= 0x077CB531;
return MultiplyDeBruijnBitPosition[(int)((r1 >> 27) & 0x1f)];
}
final private static int[] MultiplyDeBruijnBitPosition =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
public Object getElementAt(int index) {
int move = index+1;
if (move >= getSize())
return "Done!";
int disk = rulerFunction(move)+1;
int x = move >> (disk-1); // guaranteed to be an odd #
x = (x - 1) / 2;
int K = 1 << (disk&1); // alternate directions for even/odd # disks
x = x * K;
int post_before = (x % 3) + 1;
int post_after = ((x+K) % 3) + 1;
return String.format("%d. move disk %d from post %d to post %d",
move, disk, post_before, post_after);
}
}
```
---
update:
per jfpoilpret's suggestion, I put a breakpoint in the `getElementData()` function.
```
if ((index & 0x3ff) == 0)
{
System.out.println("getElementAt("+index+")");
}
```
I looked at the stacktrace for the thread in question. It's not really that helpful (posted below). From some other tweaking, however, it looks like the culprits are the fireIntervalAdded()/fireIntervalRemoved() and the change in the result of getSize(). The fireIntervalxxxx seems to clue Swing into checking the getSize() function, and if the size changes, it goes and refetches ALL of the row contents immediately (or at least it puts requests into the event queue to do so).
There **must** be some way to tell it Don't Do That!!!! but I don't know what.
```
com.example.test.HanoiMoves at localhost:3333
Thread [main] (Suspended (breakpoint at line 137 in HanoiData))
HanoiData.getElementAt(int) line: 137
BasicListUI.updateLayoutState() line: not available
BasicListUI.maybeUpdateLayoutState() line: not available
BasicListUI.getPreferredSize(JComponent) line: not available
JList(JComponent).getPreferredSize() line: not available
ScrollPaneLayout$UIResource(ScrollPaneLayout).layoutContainer(Container) line: not available
JScrollPane(Container).layout() line: not available
JScrollPane(Container).doLayout() line: not available
JScrollPane(Container).validateTree() line: not available
JPanel(Container).validateTree() line: not available
JLayeredPane(Container).validateTree() line: not available
JRootPane(Container).validateTree() line: not available
HanoiMoves(Container).validateTree() line: not available
HanoiMoves(Container).validate() line: not available
HanoiMoves(Window).show() line: not available
HanoiMoves(Component).show(boolean) line: not available
HanoiMoves(Component).setVisible(boolean) line: not available
HanoiMoves(Window).setVisible(boolean) line: not available
HanoiMoves.<init>() line: 69
HanoiMoves.main(String[]) line: 37
Thread [AWT-Shutdown] (Running)
Daemon Thread [AWT-Windows] (Running)
Thread [AWT-EventQueue-0] (Running)
```
---
Update: I tried using some of the FastRenderer.java code from the [Advanced JList Programming article](http://java.sun.com/products/jfc/tsc/tech%5Ftopics/jlist%5F1/jlist.html) and that fixed it. But it turns out it's not the renderer at all! One line of code fixed my problem, and I don't understand why:
```
list1.setPrototypeCellValue(list1.getModel().getElementAt(0));
``` | I suspect the reason for accessing the whole model might be related to list size computation.
What you could try is to add some breakpoint in your model getElementAt() method. I suggest you do it this way:
```
if (index == 100)
{
System.out.println("Something");//Put the breakpoint on this line
}
```
The 100 constant is a value < getSize() but bigger than the initial visible number of rows (that way you won't have a break for all visible rows).
When you enter this breakpoint take a look at where your model was called from, this may give you some hints. You could post the stack trace here for us to try and help you further. | The problem is that even using intelligent pre-fetch you cannot guarantee that all visible rows were prefetched when they are needed.
I'll sketch a solution which I used once in a project and which worked extremely well.
My solution was to make a ListModel will return a stub for missing rows that tell the user, that the item is loading. (You can enhance the visual experience with a custom `ListCellRenderer` which renders the stub specially). Additionally make the `ListModel` enqueue a request to fetch the missing row. The `ListModel` will have to spawn a thread which reads the queue and fetches the missing rows. After a row was fetched invoke `fireContentsChanges` to the fetched row. You can also use a Executor in you listmodel:
```
private Map<Integer,Object> cache = new HashMap<Integer,Object>();
private Executor executor = new ThreadPoolExecutor(...);
...
public Object getElementAt(final int index) {
if(cache.containsKey(index)) return cache.get(index);
executor.execute(new Runnable() {
Object row = fetchRowByIndex(index);
cache.put(index, row);
fireContentsChanged(this, index, index);
}
}
```
You can improve this sketched solution in the following ways:
* No only fetch the requested item but also some items "around" it. The user likely will scroll up and down.
* In case of really big lists make the `ListModel` forget those rows which are far away from the ones fetched last.
* Use a LRU-cache
* If desired prefetch all items in the background thread.
* Make the ListModel a Decorator for a eager implementation of ListModel (this is what I did)
* If you have multiple "big" ListModels for Lists visible at the same time use a central request queue to fetch the missing items. | virtual listbox in Swing | [
"",
"java",
"swing",
"list",
"virtual",
""
] |
I have the following TSQL codes:
```
-- 1. define a cursor
DECLARE c_Temp CURSOR FOR
SELECT name FROM employees;
DECLARE @name varchar(100);
-- 2. open it
OPEN c_Temp;
-- 3. first fetch
FETCH NEXT FROM c_Temp INTO @name;
WHILE @@FETCH_STATUS = 0
BEGIN
print @name;
FETCH NEXT FROM c_Temp INTO @name; -- fetch again in a loop
END
-- 4. close it
....
```
I use the name value only in a loop block. Here I have to
1. define a cursor variable,
2. open it,
3. fetch twice and
4. close it.
In PL/SQL, the loop can be like this:
```
FOR rRec IN (SELECT name FROM employees) LOOP
DBMS_OUTPUT.put_line(rRec.name);
END LOOP;
```
It is much simpler than my TSQL codes. No need to define a cursor. It is created dynamically which is accessible within a loop block (much like C# for loop). Not sure if there something similar like this in TSQL? | Cursors are evil in Sql Server as they can really degrade performance - my favoured approach is to use a Table Variable (>= Sql Server 2005) with an auto inc ID column:
```
Declare @LoopTable as table (
ID int identity(1,1),
column1 varchar(10),
column2 datetime
)
insert into @LoopTable (column1, column2)
select name, startdate from employees
declare @count int
declare @max int
select @max = max(ID) from @LoopTable
select @count = 1
while @count <= @max
begin
--do something here using row number '@count' from @looptable
set @count = @count + 1
end
```
It looks pretty long winded however works in any situation and should be far more lightweight than a cursor | Something along these lines might work for you, although it depends on having an ID column or some other unique identifier
```
Declare @au_id Varchar(20)
Select @au_id = Min(au_id) from authors
While @au_id IS NOT NULL
Begin
Select au_id, au_lname, au_fname from authors Where au_id = @au_id
Select @au_id = min(au_id) from authors where au_id > @au_id
End
``` | Dynamic cursor used in a block in TSQL? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I'm trying to use the **Oracle ODP.NET 11g (11.1.0.6.20) Instant Client** on my ASP.net project as a **Data Provider** but when I run the aspx page I get a "*The provider is not compatible with the version of Oracle client*" error message. Any help would be appreciated.
I've referenced the Data Provider in Visual Studio 2005 and the code behind looks like this:
```
using Oracle.DataAccess.Client;
..
OracleConnection oOracleConn = new OracleConnection();
oOracleConn.ConnectionString =
"Data Source=MyOracleServerName;" +
"Integrated Security=SSPI";
oOracleConn.Open();
//Do Something
oOracleConn.Close();
```
The error for the page looks like this:
```
Exception Details: Oracle.DataAccess.Client.OracleException: The provider is not compatible with the version of Oracle client
Source Error:
Line 21:
Line 22:
Line 23: OracleConnection oOracleConn = new OracleConnection();
Line 24: oOracleConn.ConnectionString =
Line 25: "Data Source=MyOracleServerName;" +
[OracleException (0x80004005): The provider is not compatible with the version of Oracle client]
Oracle.DataAccess.Client.OracleInit.Initialize() +494
Oracle.DataAccess.Client.OracleConnection..cctor() +483
Stack Trace:
[TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception.]
Oracle.DataAccess.Client.OracleConnection..ctor() +0
Boeing.IVX.Web.RoyTesting.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\CE218C\Desktop\IVX.Net\Web\IVX\RoyTesting.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
``` | I only installed the **Oracle Data Provider for .NET 2.0 (11.1.0.6.20)** and I did not install the **Oracle Instant Client (11.1.0.6.0)**.
I just installed it and the error disappeared! | I've been looking into this problem further, and you simply need to grab all the appropriate DLL's from the same downloaded version of ODP.Net and put them in the same folder as your Exe file, because ODP.Net is fussy about not mixing version numbers.
I've explained how to do this here: <http://splinter.com.au/using-the-new-odpnet-to-access-oracle-from-c>
Here's the gist of it though:
* Download ODP.Net
* Unzip the file
* Unzip all the JAR's in it
* Grab these dll's that were just unzipped:
+ oci.dll (renamed from 'oci.dll.dbl')
+ Oracle.DataAccess.dll
+ oraociicus11.dll
+ OraOps11w.dll
+ orannzsbb11.dll
+ oraocci11.dll
+ ociw32.dll (renamed from 'ociw32.dll.dbl')
* Put all the DLLs in the same folder as your C# Executable | The provider is not compatible with the version of Oracle client | [
"",
"c#",
"asp.net",
"oracle",
"odp.net",
"oracleclient",
""
] |
I have a warehouse. Sometimes I want to lookup a box location by a name, sometimes by a description, sometimes by a UPC, maybe something else, etc. Each of these lookup methods call the same various private methods to find information to help locate the data.
For example, upc calls a private method to find a rowid, so does name, so does X. So I need to have that method for all of them. I might use that rowid for some way to find a shelf location (it's just an example.)
But my question is should I have an abstract class (or something else) because I am looking up my box in different ways.
In other words, say my code for lookups is very similar for UPC and for location. Each method may call something with (select \* from xxxx where location =, or select \* from xxxx where upc =). I could just create two different methods in the same class
```
LocateByUPC(string upc)...
LocateByLocation(string location)...
LocateByDescription(string description)
```
... again, this would be in one big class
Would there be any reason that I would want a super class that would hold
```
abstract class MySuper
{
properties...
LocateBox(string mycriteria)...
}
```
and then inherit that and create a second class that overrides the LocateBox method for whichever version I need?
I don't know why I'd want to do this other than it looks OOD, which really means I'd like to do this if I have a good reason. But, I know of no advantage. I just find that my class gets bigger and bigger and I just slightly change the name of the methods and a little bit of code and it makes me think that inheritance might be better.
Using C# if that matters.
Edit - Would I do this if I only gave someone a .dll with no source but the class definition? The class def. would tell my properties, etc. and what methods to override. | # Neither
neither using an abstract class nor an interface will simplify the protocol, i.e. you will still end up with a bunch of LocateXXX methods
I would recommend having a generic Locate(string criteria) method as the basis, and only defining specialized method signatures for the ones you know you will use frequently; the generic can be a catch-all for future expansion in case you need it (and relying on the generic simplifies coding and testing) | It sounds like you might want to implement the design pattern called Template Method. Basically you would define the outline of the lookup algorithm in a base class as final methods, placing common code in those methods. For the methods that require different behavior depending on the type, simply have the base class' final methods call protected methods in the children, and have each child type implement that behavior.
You can take a look online at some resources, just do a google search for Template Method design pattern. Hopefully it will shed some light on your question. | Do I need an abstract class or interface here (or neither)? | [
"",
"c#",
"oop",
"interface",
"abstract-class",
""
] |
How do I remove an element from a list **by index**?
I found `list.remove()`, but this slowly scans the list for an item **by value**. | Use `del` and specify the index of the element you want to delete:
```
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del a[-1]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8]
```
Also supports slices:
```
>>> del a[2:4]
>>> a
[0, 1, 4, 5, 6, 7, 8, 9]
```
[Here](http://docs.python.org/tutorial/datastructures.html#the-del-statement) is the section from the tutorial. | You probably want `pop`:
```
a = ['a', 'b', 'c', 'd']
a.pop(1)
# now a is ['a', 'c', 'd']
```
By default, `pop` without any arguments removes the last item:
```
a = ['a', 'b', 'c', 'd']
a.pop()
# now a is ['a', 'b', 'c']
``` | How to remove an element from a list by index | [
"",
"python",
"list",
"indexing",
""
] |
I have the following structure:
```
abstract class Base {
public abstract List<...> Get(); //What should be the generic type?
}
class SubOne : Base {
public override List<SubOne> Get() {
}
}
class SubTwo : Base {
public override List<SubTwo> Get() {
}
}
```
I want to create an abstract method that returns whatever class the concrete sub class is. So, as you can see from the example, the method in `SubOne` should return `List<SubOne>` whereas the method in `SubTwo` should return `List<SubTwo>`.
What type do I specify in the signature declared in the Base class ?
---
**[UPDATE]**
Thank you for the posted answers.
The solution is to make the abstract class generic, like such:
```
abstract class Base<T> {
public abstract List<T> Get();
}
class SubOne : Base<SubOne> {
public override List<SubOne> Get() {
}
}
class SubTwo : Base<SubTwo> {
public override List<SubTwo> Get() {
}
}
``` | Your abstract class should be generic.
```
abstract class Base<T> {
public abstract List<T> Get();
}
class SubOne : Base<SubOne> {
public override List<SubOne> Get() {
}
}
class SubTwo : Base<SubTwo> {
public override List<SubTwo> Get() {
}
}
```
If you need to refer to the abstract class without the generic type argument, use an interface:
```
interface IBase {
//common functions
}
abstract class Base<T> : IBase {
public abstract List<T> Get();
}
``` | ```
public abstract class Base<T>
{
public abstract List<T> Get();
}
class SubOne : Base<SubOne>
{
public override List<SubOne> Get() { return new List<SubOne>(); }
}
class SubTwo : Base<SubTwo>
{
public override List<SubTwo> Get() { return new List<SubTwo>(); }
}
``` | Specifying the return type of an abstract method from a Base Class according to a Sub Class | [
"",
"c#",
"generics",
"polymorphism",
"abstract-class",
"overriding",
""
] |
I am working in a C# winforms project and I have a user control which gets loaded upon its selection from a tool-strip menu. I have a dictionary lookup set to occur upon form load of the user control for other functionality. Also, when I close the user control I am just using the ".Hide();" method. I noticed that when I load the user control the first time everything is fine, but when I close it and choose to open it again the 2nd time it creates a new instance of the object thus throwing off my dictionary lookup. Therefore, I wrote some code in an attempt to fix the issue.
What I need to do is to somehow say that if an instance of the user control already exists, do not create a new instance of that object. Instead, just make the user control visible again. Therefore I have written code in an attempt to accomplish this purpose. When I select the item the first time, everything is fine. When I hide the user control and try to re-open it again nothing happens.
The following is the code I have written for this purpose which occurs upon the selection of the item from the tool-strip menu:
```
if (Controls.ContainsKey("CheckAvailUserControl"))
{
Controls["CheckAvailUserControl"].Dock = DockStyle.Fill;
Controls["CheckAvailUserControl"].Visible = true;
Controls["CheckAvailUserControl"].Show();
Controls["CheckAvailUserControl"].Refresh();
}
else
{
UserControl checkAvailUserControlLoad = new CheckAvailUserControl();
Controls.Add(checkAvailUserControlLoad);
checkAvailUserControlLoad.Dock = DockStyle.Fill;
checkAvailUserControlLoad.Visible = true;
checkAvailUserControlLoad.Show();
}
```
When I trace through my code in the debugger it is in fact hitting the right parts of the above if/else statement. Its just not displaying the user control on the screen the 2nd time I attempt to load it.
The question is: How do I get the user control to load correctly after I close it, then select it from the tool-strip menu again? | I think that Controls.ContainsKey(...) is always returning false, because you never assigned a name to your control when you created it.
If, when you create the control, you say
```
//...
checkAvailUserControlLoad.Name = "Something"
//...
Controls.Add(checkAvailUserControlLoad);
```
then
```
Controls.ContainsKey("Something")
```
will return true, and you'll be able to re-use the control by using `Controls["Something"]` | Here you go:
```
private void button_Click(object sender, EventArgs e)
{
// pass in the containing panel
LoadControl<MyControls.MyControl>(panelContainer);
}
void LoadControl<T>(Panel panel) where T : Control, new()
{
T _Control = GetControl<T>(panel);
if (_Control == null)
{
_Control = new T();
_Control.Dock = DockStyle.Fill;
panel.Controls.Add(_Control);
}
_Control.BringToFront();
}
T GetControl<T>(Panel panel) where T : Control
{
Type _Type = typeof(T);
String _Name = _Type.ToString();
if (!panel.Controls.ContainsKey(_Name))
return null;
T _Control = panel.Controls[_Name] as T;
return _Control;
}
``` | Dynamically Created User Controls In C# | [
"",
"c#",
".net",
"winforms",
"dynamic-controls",
""
] |
I am using multiple queries to pull data from the same server in my application. The issue is that I have to open a new connection every time I have a new query.
Is it even possible to:
* Open the connection
* Run query
* Pull results
* Run another query
* Pull another result
* Run final query
* Pull another result
* Close connection. | Although you may not yet know it, you are doing it correctly.
Open the connection, do your query, close it. Preferably using a `using` block or `try`/`finally`.
This may sound like a lot of overhead, but the connection pool in the .NET Framework Data Provider for SQL Server will actually optimize this for you.
In fact closing the connection is recommended.
Here is a quote from the documentation:
> It is recommended that you always
> close the Connection when you are
> finished using it in order for the
> connection to be returned to the pool.
> This can be done using either the
> Close or Dispose methods of the
> Connection object. Connections that
> are not explicitly closed might not be
> added or returned to the pool. For
> example, a connection that has gone
> out of scope but that has not been
> explicitly closed will only be
> returned to the connection pool if the
> maximum pool size has been reached and
> the connection is still valid.
Here is an example of some code that does this:
```
try {
conn.Open();
// Perform query here
} finally {
conn.Close();
}
```
For reference:
<http://msdn.microsoft.com/en-us/library/8xx3tyca(VS.71).aspx> | If you are using ASP.NET with the same connection string you will be using a pooled connection that may never get physically closed, so you will pretty much always use an available open connection. | How can I keep a Connection open when performing multiple queries? | [
"",
"c#",
".net",
"asp.net",
""
] |
I have a program that is using a configuration file.
I would like to tie the configuration file to the PC, so copying the file on another PC with the same configuration won't work.
I know that Windows Activation Mecanism is monitoring hardware to detect changes and that it can tolerates some minor changes to the hardware.
Is there any library that can help me doing that?
My other option is to use WMI to get Hardware configuration and to program my own tolerance mecanism.
Thanks a lot,
Nicolas | [Microsoft Software Licensing and Protection Services](http://www.microsoft.com/slps/Default.aspx) has functionality to bind a license to hardware. It might be worth looking into. Here's a [blog posting](http://blogs.msdn.com/slps/archive/2008/02/07/activation-continued-machine-binding.aspx) that might be of interest to you as well. | If you wish to restrict the use of data to a particular PC you'll have to implement this yourself, or find a third-party solution that can do this. There are no general Windows API's that offer this functionality. | Restrict functionality to a certain computer | [
"",
"c++",
"windows",
"drm",
"copy-protection",
""
] |
I'm trying to use this tool
<https://swingexplorer.dev.java.net/>
to find some information out about an applet's swing structure. Unfortunately, I didn't develop the applet. I've pulled the jars for the applet from the cache, but there are several hundred .class files in the jars, and I don't know which one has the main method.
Is there a way to pinpoint the applet's entry point? The browser must be able to figure it out to run the applet, so that information has to be somewhere in the jar (or maybe the .idx files that were in the same directory with the jars).
Ideas appreciated. | The lifecycle of an [Applet](http://docs.oracle.com/javase/6/docs/api/java/applet/Applet.html) (or [JApplet](http://docs.oracle.com/javase/6/docs/api/javax/swing/JApplet.html)) is more complicated than *start and run until the program is finished* so there is no single `main` method. It will be managed by the browser ([lifecycle tutorial](http://docs.oracle.com/javase/tutorial/deployment/applet/appletMethods.html).)
The applet class is specified by the deployment mechanism (e.g. applet/object/embed tags.) See the [deployment tutorial](http://docs.oracle.com/javase/tutorial/deployment/deploymentInDepth/runAppletFunction.html) for determining how this type is specified. | The entry class will either be in the applet tag, or JNLP for new plugin JRE 6u10+ applets. You should be able to see which one it is from the jar alone by grepping for referecnes to the Applet or JApplet classes or, say, the init()V method. | Finding the class with the main method in an applet | [
"",
"java",
"class",
"applet",
"main-method",
""
] |
I have a couple of classes that want to pass each other some information and be called back later, using that information (Callback pattern).
Within my application, this mechanism serves two purposes:
* scheduled / delayed execution
* asynchronous execution involving messaging
My objects basically say to each other *"when you're finished doing X, call me back and tell me to do Y with Z (because I'll have forgotten about it by then)"*. Where X might just be waiting for the right time, but also communicating with a remote service or calling a local function.
Now, were there function pointers (or equivalent) in Java, I would implement some "Job" class containing one plus the arguments it needs. For example, in PHP this structure would have to store a class name, a function name and an array of arguments. In C, it would be a pointer to the function and I'd have to make the arguments the same number and type for all calls.
In Java, the usual approach is to have an interface that's implemented by all classes that want to be called back, like this:
```
public interface ICallable {
public void call_me(Object data);
}
```
Now this wouldn't work for me, because
* the objects to be called back might have a different set of methods to take the call
* the caller is not the one to decide what call should be made
Maybe my problem is that I'm trying to have a common data structure and calling procedure for the various callbacks, but in principle, it seems to make sense to me.
What's a good design pattern to approach this situation in Java? | I think you'll find that an Interface is the best solution. I don't understand your objection to them. If the receiver needs to have a different method called, then have the Interface method call the different method.
If your receiver class needs to have multiple handlers, you can use anonymous inner classes that implement the Interface, one for each type of handler you need. For instance, if the sender uses an interface called "ListenerInterface", your receiver might define an anonymous inner class that implements the ListenerInterface and calls the receiver method "handlerFunction".
```
sender.addListener(new ListenerInterface()
{
public void callback(Object arg)
{
handlerFunction(arg);
}
});
``` | You could be using a concept similar to [anonymous inner classes](http://www.exciton.cs.rice.edu/javaresources/Java/innerclasses.htm)
Another reference [here](http://www.developer.com/java/other/article.php/3300881) | W/o function pointers, what's a recommended way to implement Callback in Java - other than interfaces? | [
"",
"java",
"design-patterns",
"callback",
""
] |
This question is a more special case of the problem described (and solved) in [this question](https://stackoverflow.com/questions/223918/java-efficient-equivalent-to-removing-while-iterating-a-collection).
I have two methods, stopAndRemove(ServerObject server) and a close() method. The later should close all servers and remove them from the server list. The list is defined as
```
List<ServerObject> server.
```
I do not want to have almost the same code from stopAndRemove in closeCurrentlyOpen, so I want to do something like:
```
public void closeCurrentlyOpen() {
for(ServerObject server : this.servers) {
stopAndRemove(server)
}
}
```
This won't work, as this will cause a ConcurrentModificationException. I tried to make a copy of the list
```
List<ServerObject> copyList = new ArrayList<ServerObject>(this.servers);
```
and use that as the list for the foreach-loop. But then it might be possible that an other thread appends a Server to the servers list while I am iterating over copyList but closeCurrentlyOpen is supposed to result in an emtpy list.
As the addServerToList method is synchronized to the servers-list, doing this
```
public void closeCurrentlyOpen() {
synchronized(this.servers) {
for(ServerObject server : this.servers) {
stopAndRemove(server)
}
}
}
```
will solve the problem with modifications. But then I can not synchronize the code in the stopAndRemove method which is necessary if it is directly called.
I seems to me that the design of this three methods probably needs a workover.
Ideas anybody? | Split off a method stop() from stopAndRemove(). Then write the loop with an explicit iterator, do the stop and then iterator.remove().
"and" in a method name is a code smell. | Perhaps this is the wrong way to do it, but I always create a removal collection, which contains indexes or references to the objects that need to be removed. I then iterate over that collection and remove those indexes/objects from the original collection. Probably not the most efficient but it got the job done.
Instead of
```
for(Collection things : thing)
things.remove(thing)
```
I use
```
Collection toRemove = new LinkedList();
for(things : thing)
toRemove.add(thing);
for(toRemove : thing)
things.remove(thing)
``` | Java: How to remove elements from a list while iterating over/adding to it | [
"",
"java",
"algorithm",
"collections",
"list",
""
] |
I have a MySQL table called `items` that contains thousands of records. Each record has a `user_id` field and a `created` (datetime) field.
Trying to put together a query to `SELECT` 25 rows, passing a string of user ids as a condition and sorted by `created DESC`.
In some cases, there might be just a few user ids, while in other instances, there may be hundreds.
If the result set is greater than 25, I want to pare it down by eliminating duplicate `user_id` records. For instance, if there were two records for `user_id = 3`, only the most recent (according to `created` datetime) would be included.
In my attempts at a solution, I am having trouble because while, for example, it's easy to get a result set of 100 (allowing duplicate `user_id` records), or a result set of 16 (using `GROUP BY` for unique `user_id` records), it's hard to get 25.
One logical approach, which may not be the correct MySQL approach, is to get the most recent record for each for each `user_id`, and then, if the result set is less than 25, begin adding a second record for each `user_id` until the 25 record limit is met (maybe a third, fourth, etc. record for each `user_id` would be needed).
Can this be accomplished with a MySQL query, or will I need to take a large result set and trim it down to 25 with code? | I don't think what you're trying to accomplish is possible as a SQL query. Your desire is to return 25 rows, no matter what the normal data groupings are whereas SQL is usually picky about returning based on data groupings.
If you want a purely MySQL-based solution, you may be able to accomplish this with a stored procedure. (Supported in MySQL 5.0.x and later.) However, it might just make more sense to run the query to return all 100+ rows and then trim it programmatically within the application. | This will get you the most recent for each user --
> SELECT user\_id, create
> FROM items AS i1
> LEFT JOIN items AS i2
> ON i1.user\_id = i2.user\_id AND i1.create > i2.create
> WHERE i2.id IS NULL
his will get you the most recent two records for each user --
> SELECT user\_id, create
> FROM items AS i1
> LEFT JOIN items AS i2
> ON i1.user\_id = i2.user\_id AND i1.create > i2.create
> LEFT JOIN items IS i3
> ON i2.user\_id = i3.user\_id AND i2.create > i3.create
> WHERE i3.id IS NULL
Try working from there.
You could nicely put this into a stored procedure. | Semi-Distinct MySQL Query | [
"",
"sql",
"mysql",
""
] |
I have the following class hierarchy
```
public abstract BaseClass : System.Web.UI.UserControl
{
public virtual void Process(string sType)
{
//Do something
//Here I want to create a CSV list Ex: "type1, type2"
//Do I need to create a static variable? There might be several controls calling //Process. I need to scope it to the UserControl
}
}
```
In a user control that inherits from BaseClass
```
public void ProcessParams()
{
base.Process("type1");
base.Process("type2");
}
``` | I would avoid doing this in a static, unless you want to store params from across all instances. You could add a collection to your base class, or have an IEnumerable as the parameter for Process(). | Further, you could use the Singleton Pattern. | C# Design question - Static var? | [
"",
"c#",
""
] |
edit: in case anyone is wondering, the actionhandler invokes code that creates and disposes the same kind of datacontext, in case that might have anything to do with this behaviour. the code doesn't touch the MatchUpdateQueue table, but i figure i should mention it just in case.
double edit: everyone who answered was correct! i gave the answer to the respondent who suffered most of my questioning. fixing the problem allowed another problem (hidden within the handler) to pop up, which happened to throw exactly the same exception. whoops!
I'm having some issues with deleting items in LINQ. The DeleteOnSubmit call in the code below causes a LINQ Exception with the message "Cannot add an entity with a key that is already in use." I'm not sure what I'm doing wrong here, it is starting to drive me up the wall. The primary key is just an integer autoincrement column and I have no other problems until I try to remove an item from the database queue. Hopefully I'm doing something painfully retarded here that is easy to spot for anyone who isn't me!
```
static void Pacman()
{
Queue<MatchUpdateQueue> waiting = new Queue<MatchUpdateQueue>();
events.WriteEntry("matchqueue worker thread started");
while (!stop)
{
if (waiting.Count == 0)
{
/* grab any new items available */
aDataContext db = new aDataContext();
List<MatchUpdateQueue> freshitems = db.MatchUpdateQueues.OrderBy(item => item.id).ToList();
foreach (MatchUpdateQueue item in freshitems)
waiting.Enqueue(item);
db.Dispose();
}
else
{
/* grab & dispatch waiting item */
MatchUpdateQueue item = waiting.Peek();
try
{
int result = ActionHandler.Handle(item);
if (result == -1)
events.WriteEntry("unknown command consumed : " + item.actiontype.ToString(), EventLogEntryType.Error);
/* remove item from queue */
waiting.Dequeue();
/* remove item from database */
aDataContext db = new aDataContext();
db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(i => i == item));
db.SubmitChanges();
db.Dispose();
}
catch (Exception ex)
{
events.WriteEntry("exception while handling item : " + ex.Message, EventLogEntryType.Error);
stop = true;
}
}
/* to avoid hammering database when there's nothing to do */
if (waiting.Count == 0)
Thread.Sleep(TimeSpan.FromSeconds(10));
}
events.WriteEntry("matchqueue worker thread halted");
}
``` | You could do something to the effect of
```
db.MatchUpdateQueues.DeleteOnSubmit(db.MatchUpdateQueues.Single(theItem => theItem == item));
```
Just a note as other answers hinted towards Attach.. you will not be able to use attach on a context other then the original context the item was received on unless the entity has been serialized. | Use:
```
aDataContext db = new aDataContext();
item = new MatchUpdateQueue { id=item.id }; // <- updated
db.MatchUpdateQueues.Attach(item);
db.MatchUpdateQueues.DeleteOnSubmit(item);
db.SubmitChanges();
```
Since you are using a new datacontext it doesn't know that the object is already in the db. | DeleteOnSubmit LINQ exception "Cannot add an entity with a key that is already in use" | [
"",
"c#",
"linq",
""
] |
Here is something that I find myself using from time to time and I just wanted to get some feedback on the merits of the practice.
Lets say that I have a base class:
```
abstract class RealBase {
protected RealBase(object arg) {
Arg = arg;
}
public object Arg { get; private set; }
public abstract void DoThatThingYouDo();
}
```
I often create a second base class that is generic that handles the cast from the "object" type in the base class to the "T" type, like this:
```
abstract class GenericBase<T> : RealBase {
protected GenericBase(T arg)
: base( arg ) {
}
new public T Arg { get { return (T) base.Arg; } }
}
```
This allows me to access "Arg" as its explicit type without a cast operation:
```
class Concrete : GenericBase<string> {
public Concrete( string arg )
: base( arg ) {
}
public override void DoThatThingYouDo() {
// NOTE: Arg is type string. No cast necessary.
char[] chars = Arg.ToLowerInvariant().ToCharArray();
// Blah( blah, blah );
// [...]
}
}
```
All the while being able to also work with it via the "RealBase":
```
class Usage {
public void UseIt() {
RealBase rb = new Concrete( "The String Arg" );
DoTheThing(rb);
}
private void DoTheThing(RealBase thingDoer) {
rb.DoThatThingYouDo();
}
}
```
It is assumed that there are many other "Concrete" types... not just the one.
Here are my questions/concerns:
1. Am I "off my rocker" for using
an approach like this?
2. Are there
any obvious drawbacks/caveats to
using this approach?
3. What about
that "new public T..." in
GenericBase? Good/bad idea? Awkward?
Any feedback or advice would be greatly appreciated. | I don't have any objection to that explicitly as long as you're disciplined enough to only use the generic base class as a helper only and never downcast to it. If you start referencing RealBase and GenericBase and ConcreteClass all over the place things tend to get real tightly coupled really quickly.
As a matter of fact, I would recommend kicking it up a notch and introducing an interface
```
interface IReal {
void DoThatThingYouDo();
}
```
And leaving the base class out of it entirely (basically never reference it except when declaring a derived class). Just a tip that helps me increase the flexibility of my code.
Oh, and if you do use an interface, don't just declare it in the base classes, declare it on the concrete ones:
```
class MyConcrete: BaseClass<MyConcrete>, IReal {
...
}
```
as a reminder, the base class is not important only what it does is important! | Well, we've now got an inheritance tree three levels deep, but you haven't given any particular reason for doing this.
Personally I rarely use inheritance (or rather, rarely design my own inheritance hierarchies beyond implementing interfaces and deriving directly from object). Inheritance is a powerful tool, but one which is difficult to use effectively.
If this gives you some clear advantage over other approaches, that's fine - but I would consider the complexity you're adding for someone reading the code. Do they really want to have to consider three levels of hierarchy, with two properties of the same name? (I would rename GenericBase.Arg to GenericBase.GenericArg or something like that.) | Generics, Inheritance and the new operator | [
"",
"c#",
"generics",
"inheritance",
"oop",
""
] |
Ok, I am not sure I want to use Request Tracker and RTFM, which is a possible solution.
I'd like to have a knowledge base with my bug tracker/todo list , so that when
I solve a problem, I would have a record of its resolution for myself or others later.
What python based solutions are available? | A highly flexible issue tracker in Python I would recommend is "Roundup":
<http://roundup.sourceforge.net/>.
An example of its use can be seen online at <http://bugs.python.org/>. | Try [Trac](http://trac.edgewall.org/) | Looking for knowledge base integrated with bug tracker in python | [
"",
"python",
"knowledge-management",
""
] |
I have an `IEnumerable<T>` and an `IEnumerable<U>` that I want merged into an `IEnumerable<KeyValuePair<T,U>>` where the indexes of the elements joined together in the KeyValuePair are the same. Note I'm not using IList, so I don't have a count or an index for the items I'm merging. How best can I accomplish this? I would prefer a LINQ answer, but anything that gets the job done in an elegant fashion would work as well. | **Note:** As of .NET 4.0, the framework includes a `.Zip` extension method on IEnumerable, documented [here](http://msdn.microsoft.com/en-us/library/dd267698%28v=vs.110%29.aspx). The following is maintained for posterity and for use in .NET framework version earlier than 4.0.
I use these extension methods:
```
// From http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx
public static IEnumerable<TResult> Zip<TFirst, TSecond, TResult>(this IEnumerable<TFirst> first, IEnumerable<TSecond> second, Func<TFirst, TSecond, TResult> func) {
if (first == null)
throw new ArgumentNullException("first");
if (second == null)
throw new ArgumentNullException("second");
if (func == null)
throw new ArgumentNullException("func");
using (var ie1 = first.GetEnumerator())
using (var ie2 = second.GetEnumerator())
while (ie1.MoveNext() && ie2.MoveNext())
yield return func(ie1.Current, ie2.Current);
}
public static IEnumerable<KeyValuePair<T, R>> Zip<T, R>(this IEnumerable<T> first, IEnumerable<R> second) {
return first.Zip(second, (f, s) => new KeyValuePair<T, R>(f, s));
}
```
**EDIT**: after the comments I'm obliged to clarify and fix some things:
* I originally took the first Zip implementation verbatim from [Bart De Smet's blog](http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx)
* Added enumerator disposing (which was also [noted](http://community.bartdesmet.net/blogs/bart/archive/2008/11/03/c-4-0-feature-focus-part-3-intermezzo-linq-s-new-zip-operator.aspx#14059) on Bart's original post)
* Added null parameter checking (also discussed in Bart's post) | As a update to anyone stumbling across this question, .Net 4.0 supports this natively as ex from MS:
```
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
```
[Documentation](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.zip?view=net-5.0):
> The method merges each element of the first sequence with an element that has the same index in the second sequence. If the sequences do not have the same number of elements, the method merges sequences until it reaches the end of one of them. For example, if one sequence has three elements and the other one has four, the result sequence will have only three elements. | How do I merge (or zip) two IEnumerables together? | [
"",
"c#",
".net",
"linq",
"ienumerable",
""
] |
When I create shared libraries, I have a header file (but with no file name extension) in the root of the library source named the same as the library.
So for example, if my library was called libirock.so, then I'd have a file called irock in the project root. This file will include all of the most important headers in the library, so that when the library is to be implemented, all you need to do is use this include line:
```
#include <irock> // Instead of <irock.h>
```
I got the idea from when I saw a compiler warning similar to:
```
#include <string.h> is obsolete, use #include <string> instead
```
Two questions:
1. Is using irock instead of irock.h best practice?
2. Is is correct to use a single header file instead of many headers?
**Course of action**
Thanks for your answers! From the answers, I've decided:
1. Will use `<irock.h>` instead of `<irock>`.
2. I will continue to use a 'primary' header file. | There is nothing in the standard governing "allowed", "prohibited" or "best practices" regarding extensions for filenames.
Use whichever form you prefer. On some platforms there's a convenience factor to having an file extensions for registered types.
For what it's worth `<string.h>` and `<string>` are totally different headers. The C++ namespaced equivalent of `<string.h>` is actually `<cstring>`. | In a single word, no. You'll want to explicitly use irock.h
With the extension in place, it's clear that this is a header file, and any application that uses files based on file extension will correctly know how to interpret your header file. | What is the best practice for a shared library primary header file in C++? | [
"",
"c++",
"header",
"shared-libraries",
""
] |
I am getting this error message when I try to "Add Web Reference" to my ASMX proxy project:
```
**"To be XML serializable, types which inherit from ICollection must have an implementation of Add(System.String) at all levels of their inheritance hierarchy. System.Collections.Specialized.NameValueCollection does not implement Add(System.String)"**
```
I need to pass name-value pairs to my web service and here is what I came up with:
```
public class FileService : System.Web.Services.WebService
{
[WebMethod]
public string UploadFile(byte[] incomingArray
, string FileName
, long FileLengthInBytes
, NameValueCollection nvcMetaData)
```
I now realize I need help changing this (I am new to C# and this part of the .Net framework). If I can get this working, my web service will need to be invoked by ColdFusion (right now I am using an .aspx page for calling the web service). So whatever means I come up with for passing a variable number of NAME-VALUE pairs I need it callable by CF. Thanks in advance. | As an alternative, you can just define a simple NameValue class and receive an array.
```
public class NameValue
{
public string Name{get;set;}
public string Value{get;set;}
}
[WebMethod]
public string UploadFile(byte[] incomingArray
, string FileName
, long FileLengthInBytes
, NameValue[] nvcMetaData)
```
If on the client side you have a NameValueCollection you can easily map to your type. Check the sample I posted in this [question](https://stackoverflow.com/questions/663416/populate-array-of-objects-from-namevaluecollection-in-c/663441#663441) | Unfortunately all of the .NET library dictionary structures are not serializable. I have heard good things about [this code](http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx) - maybe that will help.
Basically what you will be doing with the code I linked is creating a new type that has custom serialization methods that will allow you to serialize a dictionary to XML. If this is the route you choose it would be best to compile this type in its own assembly so that you can share that assembly with the client of your service that way it can be used as a parameter to the service method. | Using NameValueCollection in C# webservice gives not XML serializable error | [
"",
"c#",
"dictionary",
"xml-serialization",
"asmx",
""
] |
I have an imagelist of about 30 images, and 3 images I'd like to be able to overlay on top of the 30 when a TreeNode is in a particular state. I know that a C++ TreeItem can do this with the TVIS\_OVERLAYMASK as such:
```
SetItemState(hItem,INDEXTOOVERLAYMASK(nOverlayIndex), TVIS_OVERLAYMASK);
```
Is there any mechanism to achieve similar results in .NET? | I don't know of a way to do the overlay automatically, but you could do this with an owner drawn tree node. | I see this question is still getting views, so I'll post the implementation of what David suggested.
```
internal class MyTree : TreeView
{
internal MyTree() :
base()
{
// let the tree know that we're going to be doing some owner drawing
this.DrawMode = TreeViewDrawMode.OwnerDrawText;
this.DrawNode += new DrawTreeNodeEventHandler(MyTree_DrawNode);
}
void MyTree_DrawNode(object sender, DrawTreeNodeEventArgs e)
{
// Do your own logic to determine what overlay image you want to use
Image overlayImage = GetOverlayImage();
// you have to move the X value left a bit,
// otherwise it will draw over your node text
// I'm also adjusting to move the overlay down a bit
e.Graphics.DrawImage(overlayImage,
e.Node.Bounds.X - 15, e.Node.Bounds.Y + 4);
// We're done! Draw the rest of the node normally
e.DefaultDraw = true
}
}
``` | TreeNode Image Overlay | [
"",
"c#",
"treeview",
"treenode",
""
] |
In Windows, `JAVA_HOME` must point to the JDK installation folder (so that `JAVA_HOME/bin` contains all executables and `JAVA_HOME/libs` contains all default `jar` libraries).
If I download Sun's JDK bundle and installs it in Linux, it is the same procedure.
However, I need to use Kubuntu's default OpenJDK package. The problem is that all executables are placed in `/usr/bin`. But the jars are placed in `/usr/share/java`. Since they are not under the same `JAVA_HOME` folder I'm having trouble with Grails and maybe there will be trouble with other applications that expect the standard Java structure.
1. If I use:
```
JAVA_HOME=/usr
```
All applications and scripts that want to use any Java executable can use the standard procedure `call $JAVA_HOME/bin/executable`. However, since the jars are in a different place, they are not always found (example: in grails I'm getting `ClassDefNotFound` for `native2ascii`).
2. On the other hand, if I use:
```
JAVA_HOME=/usr/share/java
```
None of the Java executables (`java`, `javac`, etc.) can be found.
So, what is the correct way of handling the `JAVA_HOME` variable in a Debian-based Linux?
Thanks for your help,
Luis | What finally worked for me (Grails now works smoothly) is doing almost like Steve B. has pointed out:
```
JAVA_HOME=/usr/lib/jvm/default-java
```
This way if the user changes the default JDK for the system, `JAVA_HOME` still works.
`default-java` is a symlink to the current JVM. | If you use alternatives to manage multiple java versions, you can set the `JAVA_HOME` based on the symlinked java (or javac) like this:
```
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
``` | What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution? | [
"",
"java",
"grails",
"java-home",
"debian-based",
""
] |
I am very new to regex, and this is way too advanced for me. So I am asking the experts over here.
**Problem**
I would like to retrieve the constants / values from a php define()
```
DEFINE('TEXT', 'VALUE');
```
Basically I would like a regex to be able to return the name of constant, and the value of constant from the above line. Just TEXT and VALUE . Is this even possible?
Why I need it? I am dealing with language file and I want to get all couples (name, value) and put them in array. I managed to do it with str\_replace() and trim() etc.. but this way is long and I am sure it could be made easier with single line of regex.
Note: The VALUE may contain escaped single quotes as well. example:
```
DEFINE('TEXT', 'J\'ai');
```
I hope I am not asking for something too complicated. :)
Regards | For any kind of grammar-based parsing, regular expressions are usually an awful solution. Even smple grammars (like arithmetic) have nesting and it's on nesting (in particular) that regular expressions just fall over.
Fortunately PHP provides a far, far better solution for you by giving you access to the same lexical analyzer used by the PHP interpreter via the [token\_get\_all() function](https://www.php.net/manual/en/function.token-get-all.php). Give it a character stream of PHP code and it'll parse it into tokens ("lexemes"), which you can do a bit of simple parsing on with a pretty simple [finite state machine](http://en.wikipedia.org/wiki/Finite_state_machine).
Run this program (it's run as test.php so it tries it on itself). The file is deliberately formatted badly so you can see it handles that with ease.
```
<?
define('CONST1', 'value' );
define (CONST2, 'value2');
define( 'CONST3', time());
define('define', 'define');
define("test", VALUE4);
define('const5', //
'weird declaration'
) ;
define('CONST7', 3.14);
define ( /* comment */ 'foo', 'bar');
$defn = 'blah';
define($defn, 'foo');
define( 'CONST4', define('CONST5', 6));
header('Content-Type: text/plain');
$defines = array();
$state = 0;
$key = '';
$value = '';
$file = file_get_contents('test.php');
$tokens = token_get_all($file);
$token = reset($tokens);
while ($token) {
// dump($state, $token);
if (is_array($token)) {
if ($token[0] == T_WHITESPACE || $token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) {
// do nothing
} else if ($token[0] == T_STRING && strtolower($token[1]) == 'define') {
$state = 1;
} else if ($state == 2 && is_constant($token[0])) {
$key = $token[1];
$state = 3;
} else if ($state == 4 && is_constant($token[0])) {
$value = $token[1];
$state = 5;
}
} else {
$symbol = trim($token);
if ($symbol == '(' && $state == 1) {
$state = 2;
} else if ($symbol == ',' && $state == 3) {
$state = 4;
} else if ($symbol == ')' && $state == 5) {
$defines[strip($key)] = strip($value);
$state = 0;
}
}
$token = next($tokens);
}
foreach ($defines as $k => $v) {
echo "'$k' => '$v'\n";
}
function is_constant($token) {
return $token == T_CONSTANT_ENCAPSED_STRING || $token == T_STRING ||
$token == T_LNUMBER || $token == T_DNUMBER;
}
function dump($state, $token) {
if (is_array($token)) {
echo "$state: " . token_name($token[0]) . " [$token[1]] on line $token[2]\n";
} else {
echo "$state: Symbol '$token'\n";
}
}
function strip($value) {
return preg_replace('!^([\'"])(.*)\1$!', '$2', $value);
}
?>
```
Output:
```
'CONST1' => 'value'
'CONST2' => 'value2'
'CONST3' => 'time'
'define' => 'define'
'test' => 'VALUE4'
'const5' => 'weird declaration'
'CONST7' => '3.14'
'foo' => 'bar'
'CONST5' => '6'
```
This is basically a finite state machine that looks for the pattern:
```
function name ('define')
open parenthesis
constant
comma
constant
close parenthesis
```
in the lexical stream of a PHP source file and treats the two constants as a (name,value) pair. In doing so it handles nested define() statements (as per the results) and ignores whitespace and comments as well as working across multiple lines.
**Note:** I've deliberatley made it ignore the case when functions and variables are constant names or values but you can extend it to that as you wish.
It's also worth pointing out that PHP is quite forgiving when it comes to strings. They can be declared with single quotes, double quotes or (in certain circumstances) with no quotes at all. This can be (as pointed out by Gumbo) be an ambiguous reference reference to a constant and you have no way of knowing which it is (no guaranteed way anyway), giving you the chocie of:
1. Ignoring that style of strings (T\_STRING);
2. Seeing if a constant has already been declared with that name and replacing it's value. There's no way you can know what other files have been called though nor can you process any defines that are conditionally created so you can't say with any certainty if anything is definitely a constant or not nor what value it has; or
3. You can just live with the possibility that these might be constants (which is unlikely) and just treat them as strings.
Personally I would go for (1) then (3). | This is possible, but I would rather use [get\_defined\_constants()](http://de.php.net/manual/en/function.defined.php). But make sure all your translations have something in common (like all translations starting with T), so you can tell them apart from other constants. | Regex to parse define() contents, possible? | [
"",
"php",
"regex",
""
] |
Is it possible to change the Windows command prompt working directory via Python script?
e.g.
```
>> cd
>> c:\windows\system32
>> make_decision_change_dir.py
>> cd
>> c:\windows
```
I have tried a few things which don't work:
```
import os
os.chdir(path)
```
---
```
import os, subprocess
subprocess.Popen("chdir /D \"%s\"" %path, shell=True)
```
---
```
import os, subprocess
subprocess.Popen("cd \"%s\"" %path, shell=True)
```
---
```
import os, subprocess
subprocess.Popen("CD=\"%s\"" %path, shell=True)
```
As I understand it and observe these operations change the current processes working directory - which is the Python process and not the prompt its executing from.
Thanks.
UPDATE
The path I would want to change to is dynamic (based on what project I am working on, the full path to a build location changes) hence I wanted to code a solution in Python rather than hack around with a Windows batch file.
UPDATE
I ended up hacking a batch file together to do this ;(
Thanks everyone. | I have a Python script to make moving around a file tree easier: [xdir.py](http://nedbatchelder.com/code/utilities/xdir_py.html)
Briefly, I have an xdir.py file, which writes Windows commands to stdout:
```
# Obviously, this should be more interesting..
import sys
print "cd", sys.argv[1]
```
Then an xdir.cmd file:
```
@echo off
python xdir.py %* >%TEMP%\__xdir.cmd
call %TEMP%\__xdir.cmd
```
Then I create a doskey alias:
```
doskey x=xdir.cmd $*
```
The end result is that I can type
```
$ x subdir
```
and change into subdir.
The script I linked to above does much more, including remembering history, maintaining a stack of directories, accepting shorthand for directories, and so on. | I'm not clear what you want to do here. Do you want a python script which you can run from a Windows command prompt which will change the working directory of the Windows command session?
If so, I'm 99.9% sure that's impossible. As you said yourself the `python.exe` process is a separate process from the Windows `cmd.exe` and anything you do in Python won't affect the Command prompt.
There may be something you can do via the Windows API by sending keystrokes to the Windows or something but it would be pretty brittle.
The only two practical options I can think of involve wrapping your Python script in a Batch file:
1. Output your desired directory from the Python script, read the output in your Batch file and CD to it.
2. Start your Python script from a batch file, allow your Python script to start a new `cmd.exe` Window and get the Batch file to close the original Command window. | Changing prompt working directory via Python script | [
"",
"python",
"windows",
"scripting",
""
] |
I'm writing a program under MS Visual C++ 6.0 (yes, I know it's ancient, no there's nothing I can do to upgrade). I'm seeing some behavior that I think is really weird. I have a class with two constructors defined like this:
```
class MyClass
{
public:
explicit MyClass(bool bAbsolute = true, bool bLocation = false) : m_bAbsolute(bAbsolute), m_bLocation(bLocation) { ; }
MyClass(const RWCString& strPath, bool bLocation = false);
private:
bool m_bAbsolute;
bool m_bLocation;
};
```
When I instantiate an instance of this class with this syntax: `MyClass("blah")`, it calls the first constructor. As you can see, I added the `explicit` keyword to it in the hopes that it wouldn't do that... no dice. It would appear to prefer the conversion from `const char *` to `bool` over the conversion to `RWCString`, which has a copy constructor which takes a `const char *`. Why does it do this? I would assume that given two possible choices like this, it would say it's ambiguous. What can I do to prevent it from doing this? If at all possible, I'd like to avoid having to explicitly cast the `strPath` argument to an `RWCString`, as it's going to be used with literals a lot and that's a lot of extra typing (plus a really easy mistake to make). | Explicit will not help here as the constructor is not a part of the implicit conversion, just the recipient.
There's no way to control the preferred order of conversions, but you could add a second constructor that took a const char\*. E.g:
```
class MyClass
{
public:
MyClass(bool bAbsolute = true, bool bLocation = false);
MyClass(const RWCString& strPath, bool bLocation = false);
MyClass(const char* strPath, bool bLocation = false);
private:
bool m_bAbsolute;
bool m_bLocation;
};
``` | Andrew Grant provided the solution. I want to tell you *why* it doesn't work the way you tried. If you have two viable functions for an argument, then the one that matches the argument best is called. The second requires a user-defined conversion, while the first only needs a standard conversion. That is why the compiler prefers the first over the second. | wrong argument conversion preferred when calling function | [
"",
"c++",
"constructor",
"arguments",
"visual-c++-6",
""
] |
I have the need to allocate large blocks of memory with new.
I am stuck with using new because I am writing a mock for the producer side of a two part application. The actual producer code is allocating these large blocks and my code has responsibility to delete them (after processing them).
Is there a way I can ensure my application is capable of allocating such a large amount of memory from the heap? Can I set the heap to a larger size?
My case is 64 blocks of 288000 bytes. Sometimes I am getting 12 to allocate and other times I am getting 27 to allocate. I am getting a std::bad\_alloc exception.
This is: C++, GCC on Linux (32bit). | With respect to *new* in C++/GCC/Linux(32bit)...
It's been a while, and it's implementation dependent, but I believe *new* will, behind the scenes, invoke *malloc()*. *Malloc()*, unless you ask for something exceeding the address space of the process, or outside of specified (*ulimit/getrusage*) limits, won't fail. Even when your system doesn't have enough RAM+SWAP. For example: *malloc(1gig)* on a system with 256Meg of RAM + 0 SWAP will, I believe, succeed.
However, when you go use that memory, the kernel supplies the pages through a lazy-allocation mechanism. At that point, when you first read or write to that memory, if the kernel cannot allocate memory pages to your process, it kills your process.
This can be a problem on a shared computer, when your colleague has a slow core leak. Especially when he starts knocking out system processes.
So the fact that you are seeing std::bad\_alloc exceptions is "interesting".
Now *new* will run the constructor on the allocated memory, touching all those memory pages before it returns. Depending on implementation, it *might* be trapping the out-of-memory signal.
Have you tried this with plain o'l *malloc*?
Have you tried running the "*free*" program? Do you have enough memory available?
As others have suggested, have you checked *limit/ulimit/getrusage()* for hard & soft constraints?
What does your code look like, exactly? I'm guessing *new ClassFoo [ N ]*. Or perhaps *new char [ N ]*.
What is *sizeof(ClassFoo)*? What is *N*?
Allocating 64\*288000 (17.58Meg) should be trivial for most modern machines... Are you running on an embedded system or something otherwise special?
Alternatively, are you linking with a custom *new* allocator? Does your class have its own *new* allocator?
Does your data structure (class) allocate other objects as part of its constructor?
Has someone tampered with your libraries? Do you have multiple compilers installed? Are you using the wrong include or library paths?
Are you linking against stale object files? Do you simply need to recompile your all your source files?
Can you create a trivial test program? Just a couple lines of code that reproduces the bug? Or is your problem elsewhere, and only showing up here?
--
For what it's worth, I've allocated over 2gig data blocks with *new* in 32bit linux under g++. Your problem lies elsewhere. | It's possible that you are being limited by the process' ulimit; run `ulimit -a` and check the virutal memory and data seg size limits. Other than that, can you post your allocation code so we can see what's actually going on? | Allocating large blocks of memory with new | [
"",
"c++",
"memory",
"new-operator",
"bad-alloc",
""
] |
Is there any function to encode HTML strings in T-SQL? I have a legacy database which contains dodgey characters such as '<', '>' etc. I can write a function to replace the characters but is there a better way?
I have an ASP.Net application and when it returns a string it contains characters which cause an error. The ASP.Net application is reading the data from a database table. It does not write to the table itself. | We have a legacy system that uses a trigger and dbmail to send HTML encoded email when a table is entered, so we require encoding within the email generation. I noticed that Leo's version has a slight bug that encodes the & in `<` and `>` I use this version:
```
CREATE FUNCTION HtmlEncode
(
@UnEncoded as varchar(500)
)
RETURNS varchar(500)
AS
BEGIN
DECLARE @Encoded as varchar(500)
--order is important here. Replace the amp first, then the lt and gt.
--otherwise the < will become &lt;
SELECT @Encoded =
Replace(
Replace(
Replace(@UnEncoded,'&','&'),
'<', '<'),
'>', '>')
RETURN @Encoded
END
GO
``` | It's a bit late, but anyway, here the proper ways:
HTML-Encode (HTML encoding = XML encoding):
```
DECLARE @s NVARCHAR(100)
SET @s = '<html>unsafe & safe Utf8CharsDon''tGetEncoded ÄöÜ - "Conex"<html>'
SELECT (SELECT @s FOR XML PATH(''))
```
HTML-encode in a query:
```
SELECT
FIELD_NAME,
(SELECT FIELD_NAME AS [text()] FOR XML PATH('')) AS FIELD_NAME_HtmlENcoded
FROM TABLE_NAME
```
HTML-Decode:
```
SELECT CAST('<root>' + '<root>Test&123' + '</root>' AS XML)
.value(N'(root)[1]', N'varchar(max)');
```
If you want to do it properly, you can use a CLR-stored procedure.
However, it gets a bit complicated, because you can't use the `System.Web`-Assembly in CLR-stored-procedures (so you can't do `System.Web.HttpUtility.HtmlDecode(htmlEncodedStr);`). So you have to write your own `HttpUtility` class, which I wouldn't recommend, especially for decoding.
Fortunately, you can rip `System.Web.HttpUtility` out of the Mono source code (.NET for Linux). Then you can use `HttpUtility` without referencing `System.Web`.
Then you write this CLR-Stored-Procedure:
```
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
//using Microsoft.SqlServer.Types;
namespace ClrFunctionsLibrary
{
public class Test
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString HtmlEncode(SqlString sqlstrTextThatNeedsEncoding)
{
string strHtmlEncoded = System.Web.HttpUtility.HtmlEncode(sqlstrTextThatNeedsEncoding.Value);
SqlString sqlstrReturnValue = new SqlString(strHtmlEncoded);
return sqlstrReturnValue;
}
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlString HtmlDecode(SqlString sqlstrHtmlEncodedText)
{
string strHtmlDecoded = System.Web.HttpUtility.HtmlDecode(sqlstrHtmlEncodedText.Value);
SqlString sqlstrReturnValue = new SqlString(strHtmlDecoded);
return sqlstrReturnValue;
}
// ClrFunctionsLibrary.Test.GetPassword
//[Microsoft.SqlServer.Server.SqlFunction]
//public static SqlString GetPassword(SqlString sqlstrEncryptedPassword)
//{
// string strDecryptedPassword = libPortalSecurity.AperturePortal.DecryptPassword(sqlstrEncryptedPassword.Value);
// SqlString sqlstrReturnValue = new SqlString(sqlstrEncryptedPassword.Value + "hello");
// return sqlstrReturnValue;
//}
public const double SALES_TAX = .086;
// http://msdn.microsoft.com/en-us/library/w2kae45k(v=vs.80).aspx
[SqlFunction()]
public static SqlDouble addTax(SqlDouble originalAmount)
{
SqlDouble taxAmount = originalAmount * SALES_TAX;
return originalAmount + taxAmount;
}
} // End Class Test
} // End Namespace ClrFunctionsLibrary
```
And register it:
```
GO
/*
--http://stackoverflow.com/questions/72281/error-running-clr-stored-proc
-- For unsafe permission
EXEC sp_changedbowner 'sa'
ALTER DATABASE YOUR_DB_NAME SET TRUSTWORTHY ON
GO
*/
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[HtmlEncode]')
AND type IN (N'FN', N'IF', N'TF', N'FS', N'FT') )
DROP FUNCTION [dbo].[HtmlEncode]
GO
IF EXISTS (SELECT * FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[HtmlDecode]')
AND type IN (N'FN', N'IF', N'TF', N'FS', N'FT') )
DROP FUNCTION [dbo].[HtmlDecode]
GO
IF EXISTS (SELECT * FROM sys.assemblies asms
WHERE asms.name = N'ClrFunctionsLibrary' AND is_user_defined = 1 )
DROP ASSEMBLY [ClrFunctionsLibrary]
GO
-- http://msdn.microsoft.com/en-us/library/ms345101.aspx
CREATE ASSEMBLY [ClrFunctionsLibrary]
AUTHORIZATION [dbo]
FROM 'D:\username\documents\visual studio 2010\Projects\ClrFunctionsLibrary\ClrFunctionsLibrary\bin\Debug\ClrFunctionsLibrary.dll'
WITH PERMISSION_SET = UNSAFE --EXTERNAL_ACCESS --SAFE
;
GO
CREATE FUNCTION [dbo].[HtmlDecode](@value [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS
-- [AssemblyName].[Namespace.Class].[FunctionName]
EXTERNAL NAME [ClrFunctionsLibrary].[ClrFunctionsLibrary.Test].[HtmlDecode]
GO
CREATE FUNCTION [dbo].[HtmlEncode](@value [nvarchar](max))
RETURNS [nvarchar](max) WITH EXECUTE AS CALLER
AS
-- [AssemblyName].[Namespace.Class].[FunctionName]
EXTERNAL NAME [ClrFunctionsLibrary].[ClrFunctionsLibrary.Test].[HtmlEncode]
GO
/*
EXEC sp_CONFIGURE 'show advanced options' , '1';
GO
RECONFIGURE;
GO
EXEC sp_CONFIGURE 'clr enabled' , '1'
GO
RECONFIGURE;
GO
EXEC sp_CONFIGURE 'show advanced options' , '0';
GO
RECONFIGURE;
*/
```
Afterwards, you can use it like normal functions:
```
SELECT
dbo.HtmlEncode('helloäÖühello123') AS Encoded,
dbo.HtmlDecode('helloäÖühello123') AS Decoded
```
Anybody who just copy-pastes, please note that for efficiency reasons, you would use
```
public const double SALES_TAX = 1.086;
// http://msdn.microsoft.com/en-us/library/w2kae45k(v=vs.80).aspx
[SqlFunction()]
public static SqlDouble addTax(SqlDouble originalAmount)
{
return originalAmount * SALES_TAX;
}
```
if you'd use this function in production.
See here for the edited mono classes:
<http://pastebin.com/pXi57iZ3>
<http://pastebin.com/2bfGKBte>
You need to define `NET_2_0` in the build options
 | HTML Encoding in T-SQL? | [
"",
"asp.net",
"sql",
"t-sql",
""
] |
On Windows, the Java preferences, which you access in your application from java.util.prefs.Preferences are stored in the registry. Where are those stored on Mac OS X? | From [Apple Developer Connection](http://developer.apple.com/documentation/Java/Conceptual/Java14Development/05-CoreJavaAPIs/CoreJavaAPIs.html#//apple_ref/doc/uid/TP40001902-210728-TPXREF143):
> The preferences files generated by the
> Preferences API are named
> `com.apple.java.util.prefs`. The
> user’s preferences file is stored in
> their home directory
> (`~/Library/Preferences/`). The system
> preferences are stored in
> `/Library/Preferences/` and are only
> persisted to disk if the user is an
> administrator. | Also, note that if the preference is nested enough, it won't directly be in `com.apple.java.util.prefs`, but rather in its own file. For instance, if you have a node `/a/b/c`, the key/value pairs for that node will be stored in `a.b.c.plist`.
The file will be either in `~/Library/Preferences/` or `/Library/Preferences/`, as for the `com.apple.java.util.prefs` file. | Where are Java preferences stored on Mac OS X? | [
"",
"java",
"macos",
"preferences",
""
] |
This may be a strange question, but do 'try-catch' blocks add any more to memory in a server environment than just running a particular block of code. For example, if I do a print stack trace, does the JVM hold on to more information. Or is more information retained on the heap?
```
try {
... do something()
} catch(Exception e) {
e.printStackTrace();
}
... do something()
``` | The exception will hae a reference to the stack trace. printStackTrace will allocate more memory as it formats that stack trace into something pretty.
The try catch block will likely result in a largely static code/data segment but not in run time memory allocations | The important here is as soon the exception variable 'e' is no longer reachable (ie, out of scope) it becomes eligible for memory collection. | Exception handling and memory | [
"",
"java",
"memory",
"exception",
""
] |
I´m reading a file in Python where each record is separated by an empty new line. If the file ends in two or more new lines, the last record is processed as expected, but if the file ends in a single new line it´s not processed. Here´s the code:
```
def fread():
record = False
for line in open('somefile.txt'):
if line.startswith('Record'):
record = True
d = SomeObject()
# do some processing with line
d.process(line)
if not line.strip() and record:
yield d
record = False
for record in fread():
print(record)
```
In this data sample, everything works as expected ('---' is an empty line):
> Record 1
> data a
> data b
> data c
> \n
> Record 2
> data a
> data b
> data c
> \n
> \n
But in this, the last record isn´t returned:
> Record 1
> data a
> data b
> data c
> \n
> Record 2
> data a
> data b
> data c
> \n
How can I preserve the last new line from the file to get the last record?
PS.: I´m using the term "preserve" as I couldn´t find a better name.
Thanks.
**Edit**
The original code was a stripped version, just to illustrate the problem, but it seems that I stripped too much. Now I posted all function´s code.
A little more explanation: The object `SomeObject` is created for each record in the file and the records are separated by empty new lines. At the end of the record it yields back the object so I can use it (save to a db, compare to another objects, etc).
The main problem when the file ends in a single new line, the last record isn´t yielded. It seems that Python does not read the last line when it´s blank. | The way it's written now probably doesn't work anyway; with `d = SomeObject()` inside your loop, a new SomeObject is being created for every line. Yet, if I understand correctly, what you want is for all of the lines in between empty lines to contribute to that one object. You could do something like this instead:
```
def fread():
d = None
for line in open('somefile.txt'):
if d is None:
d = SomeObject()
if line.strip():
# do some processing
else:
yield d
d = None
if d: yield d
```
This isn't great code, but it does work; that last object that misses its empty line is yielded when the loop is done. | You might find a slight twist in a more classically pythonic direction improves the predicability of the code:
```
def fread():
for line in open('text.txt'):
if line.strip():
d = SomeObject()
yield d
raise StopIteration
for record in fread():
print record
```
The preferred way to end a generator in Python, though often not strictly necessary, is with the StopIteration exception. Using `if line.strip()` simply means that you'll do the yield if there's anything remaining in line after stripping whitespace. The construction of SomeObject() can be anywhere... I just happened to move it in case construction of SomeObject was expensive, or had side-effects that shouldn't happen if the line is empty.
EDIT: I'll leave my answer here for posterity's sake, but DNS below got the original intent right, where several lines contribute to the same SomeObject() record (which I totally glossed over). | Preserving last new line when reading a file | [
"",
"python",
"file",
""
] |
PROBLEM:
C:\>**cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /link/out:hello.dll**
> 'cl' is not recognized as an internal
> or external command,
> operable program or batch file.
I am using Visual Studio Prof Edi 2008.
1. What PATH should I set for this command to work?
2. How to execute above command using the IDE?
NOTE:I am studying [this](http://en.wikibooks.org/wiki/Python_Programming/Extending_with_C).
---
```
C:\>cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /li
nk/out:hello.dll
'cl' is not recognized as an internal or external command,
operable program or batch file.
C:\>PATH="C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe"
C:\>cl
'cl' is not recognized as an internal or external command,
operable program or batch file.
C:\>PATH="C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe"
C:\>cl /LD hellomodule.c /Ic:\Python24\include c:\Python24\libs\python24.lib /li
nk/out:hello.dll
'cl' is not recognized as an internal or external command,
operable program or batch file.
C:\>
```
--- | You can set up the environment by using
C:\Program Files\Microsoft Visual Studio 9.0\VC\vcvarsall.bat | Can you be a bit more specific with your question? What exactly is not working? Can it not find the program, does the compile fail, etc ...
The only immediate issue I can see is that the command line can't resolve the CL command. Try including the full path to the cl.exe binary. This is the relevant path on my machine.
```
C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.exe
```
**EDIT**
When using the path environment variable, you must set it to a path, not an application. Change your path code to
```
set PATH=%PATH%;C:\Program Files\Microsoft Visual Studio 9.0\VC\bin
```
As for the inability to load mspdb80.dll, I'm worried messing with your environment variables may have contributed to this problem. Restart your cmd.exe shell and add the line I specified above and retry. If you still get the error with mspdb80.dll you may need to repair your Visual Studio installation.
**EDIT2**
Definitely looks like the PATH environment variable is messing up the load path for mspdb80.dll. This thread has a bunch of solutions for this problem
<http://social.msdn.microsoft.com/Forums/en-US/Vsexpressinstall/thread/2a3c57c5-de79-43e6-9769-35043f732d68/> | HELP VS8 Command line to IDE? | [
"",
"c++",
"visual-studio",
"visual-studio-2008",
"command-line",
"ide",
""
] |
I trying to use a "`.h`" file from Windows SDK in a .NET language (maybe C#), but without success. This header exposes some Windows Media player functionality through COM. If I use Win32 C++, I can use it with no problems, so I thought that I could use Managed C++ as a "Bridge" to expose it to C#.
The header file is the `subscriptionservices.h` that comes with Windows Media Player SDK 11 (part of Windows SDK 6).
Is that possible? How could I use that header file in a .NET Application?
Thanks,
Eduardo Cobuci | You can use PInvoke to Interop with Win32. If you are trying to use a COM object you should be able to add a reference to the project. Have you looked at [this article?](http://www.codeproject.com/KB/cs/wmp_pinvoke.aspx)
More practically you need to understand the kind of work that you are doing. If you are going to be doing lots of pointer arithmetic then I would recommend managed c++. If not C#. Good luck. | If there is a particular snippet of code or types that you are looking to use from the header file, you can paste them into the PInvoke Interop Assistant and get the C# code generated for you.
<http://www.codeplex.com/clrinterop/Release/ProjectReleases.aspx?ReleaseId=14120> | Using a C++ header with .NET language | [
"",
".net",
"c++",
"com",
"interop",
"windows-media-player",
""
] |
I'd like to create a Dictionary object, with string Keys, holding values which are of a generic type. I imagine that it would look something like this:
```
Dictionary<string, List<T>> d = new Dictionary<string, List<T>>();
```
And enable me to add the following:
```
d.Add("Numbers", new List<int>());
d.Add("Letters", new List<string>());
```
I know that I can do it for a list of strings, for example, using this syntax:
```
Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
d.Add("Key", new List<string>());
```
but I'd like to do it for a generic list if possible...
**2 questions then:**
1. Is it possible?
2. What's the syntax? | EDIT: Now I've reread the question...
You can't do this, but a custom collection would handle it to some extent. You'd basically have a generic `Add` method:
```
public void Add<T>(string key, List<T> list)
```
(The collection itself *wouldn't* be generic - unless you wanted to make the key type generic.)
You couldn't *extract* values from it in a strongly typed manner though, because the compiler won't know which type you've used for a particular key. If you make the key the type itself, you end with a *slightly* better situation, but one which still isn't supported by the existing collections. That's the situation my original answer was responding to.
EDIT: Original answer, when I hadn't quite read the question correctly, but which may be informative anyway...
No, you can't make one type argument depend on another, I'm afraid. It's just one of the things one might want to express in a generic type system but which .NET's constraints don't allow for. There are always going to be such problems, and the .NET designers chose to keep generics *relatively* simple.
However, you can write a collection to enforce it fairly easily. I have [an example in a blog post](http://codeblog.jonskeet.uk/2008/10/08/mapping-from-a-type-to-an-instance-of-that-type.aspx) which only keeps a single value, but it would be easy to extend that to use a list. | Would something like this work?
```
public class GenericDictionary
{
private Dictionary<string, object> _dict = new Dictionary<string, object>();
public void Add<T>(string key, T value) where T : class
{
_dict.Add(key, value);
}
public T GetValue<T>(string key) where T : class
{
return _dict[key] as T;
}
}
```
Basically it wraps all the casting behind the scenes for you. | Can I Create a Dictionary of Generic Types? | [
"",
"c#",
"generics",
""
] |
If I am evaluating a Python string using eval(), and have a class like:
```
class Foo(object):
a = 3
def bar(self, x): return x + a
```
What are the security risks if I do not trust the string? In particular:
1. Is `eval(string, {"f": Foo()}, {})` unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?
2. Is `eval(string, {}, {})` unsafe? That is, can I reach os or sys entirely from builtins like len and list?
3. Is there a way to make builtins not present at all in the eval context?
There are some unsafe strings like "[0] \* 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.
Obviously, `eval(string)` without custom dictionaries is unsafe in most cases. | You cannot secure eval with a blacklist approach like this. See [Eval really is dangerous](http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html) for examples of input that will segfault the CPython interpreter, give access to any class you like, and so on. | `eval()` will allow malicious data to compromise your entire system, kill your cat, eat your dog and make love to your wife.
There was recently a thread about how to do this kind of thing safely on the python-dev list, and the conclusions were:
* It's really hard to do this properly.
* It requires patches to the python interpreter to block many classes of attacks.
* Don't do it unless you really want to.
Start here to read about the challenge: <http://tav.espians.com/a-challenge-to-break-python-security.html>
What situation do you want to use eval() in? Are you wanting a user to be able to execute arbitrary expressions? Or are you wanting to transfer data in some way? Perhaps it's possible to lock down the input in some way. | Security of Python's eval() on untrusted strings? | [
"",
"python",
"security",
"eval",
""
] |
Currently I have some code that is being generated dynamically. In other words, a C# .cs file is created dynamically by the program, and the intention is to include this C# file in another project.
The challenge is that I would like to generate a .DLL file instead of generating a C# .cs file so that it could be referenced by any kind of .NET application (not only C#) and therefore be more useful. | ```
using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = "AutoGen.dll";
CompilerResults results = icc.CompileAssemblyFromSource(parameters, yourCodeAsString);
```
Adapted from <http://support.microsoft.com/kb/304655> | The non-deprecated way of doing it (using .NET 4.0 as previous posters mentioned):
```
using System.CodeDom.Compiler;
using System.Reflection;
using System;
public class J
{
public static void Main()
{
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = "AutoGen.dll";
CompilerResults r = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromSource(parameters, "public class B {public static int k=7;}");
//verify generation
Console.WriteLine(Assembly.LoadFrom("AutoGen.dll").GetType("B").GetField("k").GetValue(null));
}
}
``` | Generating DLL assembly dynamically at run time | [
"",
"c#",
".net",
"dll",
"code-generation",
""
] |
In relation to [my previous question](https://stackoverflow.com/questions/578593/castle-windsor-will-my-transient-component-be-garbage-collected), I need to check whether a component that will be instantiated by Castle Windsor, can be garbage collected after my code has finished using it. I have tried the suggestion in the answers from the previous question, but it does not seem to work as expected, at least for my code. So I would like to write a unit test that tests whether a specific object instance can be garbage collected after some of my code has run.
Is that possible to do in a reliable way ?
**EDIT**
I currently have the following test based on Paul Stovell's answer, which succeeds:
```
[TestMethod]
public void ReleaseTest()
{
WindsorContainer container = new WindsorContainer();
container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
container.AddComponentWithLifestyle<ReleaseTester>(LifestyleType.Transient);
Assert.AreEqual(0, ReleaseTester.refCount);
var weakRef = new WeakReference(container.Resolve<ReleaseTester>());
Assert.AreEqual(1, ReleaseTester.refCount);
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.AreEqual(0, ReleaseTester.refCount, "Component not released");
}
private class ReleaseTester
{
public static int refCount = 0;
public ReleaseTester()
{
refCount++;
}
~ReleaseTester()
{
refCount--;
}
}
```
Am I right assuming that, based on the test above, I can conclude that Windsor will not leak memory when using the NoTrackingReleasePolicy ? | This is what I normally do:
```
[Test]
public void MyTest()
{
WeakReference reference;
new Action(() =>
{
var service = new Service();
// Do things with service that might cause a memory leak...
reference = new WeakReference(service, true);
})();
// Service should have gone out of scope about now,
// so the garbage collector can clean it up
GC.Collect();
GC.WaitForPendingFinalizers();
Assert.IsNull(reference.Target);
}
```
NB: There are very, very few times where you should call GC.Collect() in a production application. But testing for leaks is one example of where it's appropriate. | Use [dotMemory Unit](https://www.jetbrains.com/dotmemory/unit/) framework (it's free)
```
[TestMethod]
public void ReleaseTest()
{
// arrange
WindsorContainer container = new WindsorContainer();
container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();
container.AddComponentWithLifestyle<ReleaseTester>(LifestyleType.Transient);
var target = container.Resolve<ReleaseTester>()
// act
target = null;
// assert
dotMemory.Check(memory =>
Assert.AreEqual(
0,
memory.GetObjects(where => where.Type.Is<ReleaseTester>().ObjectsCount,
"Component not released");
}
``` | How can I write a unit test to determine whether an object can be garbage collected? | [
"",
"c#",
".net",
"unit-testing",
"garbage-collection",
""
] |
I have a function in C# that is being called in F#, passing its parameters in a `Microsoft.FSharp.Collections.List<object>`.
How am I able to get the items from the F# List in the C# function?
**EDIT**
I have found a 'functional' style way to loop through them, and can pass them to a function as below to return C# System.Collection.List:
```
private static List<object> GetParams(Microsoft.FSharp.Collections.List<object> inparams)
{
List<object> parameters = new List<object>();
while (inparams != null)
{
parameters.Add(inparams.Head);
inparams = inparams.Tail;
}
return inparams;
}
```
**EDIT AGAIN**
The F# List, as was pointed out below, is Enumerable, so the above function can be replaced with the line;
```
new List<LiteralType>(parameters);
```
Is there any way, however, to reference an item in the F# list by index? | In general, avoid exposing F#-specific types (like the F# 'list' type) to other languages, because the experience is not all that great (as you can see).
An F# list is an IEnumerable, so you can create e.g. a System.Collections.Generic.List from it that way pretty easily.
There is no efficient indexing, as it's a singly-linked-list and so accessing an arbitrary element is O(n). If you do want that indexing, changing to another data structure is best. | In my C#-project I made extension methods to convert lists between C# and F# easily:
```
using System;
using System.Collections.Generic;
using Microsoft.FSharp.Collections;
public static class FSharpInteropExtensions {
public static FSharpList<TItemType> ToFSharplist<TItemType>(this IEnumerable<TItemType> myList)
{
return Microsoft.FSharp.Collections.ListModule.of_seq<TItemType>(myList);
}
public static IEnumerable<TItemType> ToEnumerable<TItemType>(this FSharpList<TItemType> fList)
{
return Microsoft.FSharp.Collections.SeqModule.of_list<TItemType>(fList);
}
}
```
Then use just like:
```
var lst = new List<int> { 1, 2, 3 }.ToFSharplist();
``` | Retrieving items from an F# List passed to C# | [
"",
"c#",
".net",
"f#",
""
] |
I have an RTF file that I need to display to a user. I know that I need to convert it if I want to display it in the browser. I would like to be able to convert it to JPG so that I can take advantage of other code that I am using that uses ImageMagick to convert JPG to PDF. ImageMagick will convert a PDF to a JPG, but not an RTF :( I am using PHP on a windows box.
\*\*\*\*Update\*\*\*\*
I have figured out how to convert the RTF to PDF and then I use ImageMagick to convert it to JPG for display. I don't like the fact that I have to go to PDF first, but it works so I am going to stick with it. Thanks to all that have responded. | Perhaps you could convert the RTF to PDF then to JPG. Sure thats more work than going straight from RTF to JPG but it might be an acceptable short term workaround for today. | This might require more that one tool.....
for the rtf to pdf
<http://www.linuxquestions.org/questions/linux-software-2/convert-rtf-to-pdf-263247/>
<http://www.linuxforums.org/forum/linux-applications/141953-looking-convert-rtf-pdf-utility.html>
As for the PDF to JPG
you can try convert(linux)...ImageMagick | doe anyone know of a free tool or how to convert an rtf to a jpg | [
"",
"php",
"rtf",
"jpeg",
""
] |
I draw a triangle using line. How can I fill color on it? So far I can only success color the line but not fill the color.
```
public void paintComponent(Graphics g){
super.paintComponents(g);
int k=0;
for (j=0 ; j < numOfLines; j++){ // the values of numOfLines retrieved from other method.
g.setColor(Color.green);
g.drawLine(x[k], x[k+1], x[k+2], x[k+3]);
k = k+4; //index files
}
``` | Make a [`Polygon`](http://java.sun.com/javase/6/docs/api/java/awt/Polygon.html) from the vertices and fill that instead, by calling [`fillPolygon(...)`](http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html#fillPolygon(java.awt.Polygon)):
```
// A simple triangle.
x[0]=100; x[1]=150; x[2]=50;
y[0]=100; y[1]=150; y[2]=150;
n = 3;
Polygon p = new Polygon(x, y, n); // This polygon represents a triangle with the above
// vertices.
g.fillPolygon(p); // Fills the triangle above.
``` | You need to specify the vertices of your polygon (in this case, a triangle) and pass to `fillPolygon():`
```
public void paint(Graphics g)
{
int xpoints[] = {25, 145, 25, 145, 25};
int ypoints[] = {25, 25, 145, 145, 25};
int npoints = 5;
g.fillPolygon(xpoints, ypoints, npoints);
}
``` | How to fill color on triangle | [
"",
"java",
"geometry",
"drawing",
""
] |
I'm concatenating a string that sometimes is long enough for it not to fit in a label control. How can i make it autoscroll to the rightside so i always see the end of the string? | While I'm sure there are ways of doing, I have to ask, why? I think it would look and/or work very badly and probably confuse the user.
Why not have the text get trimmed with an ellipse (...) at the end and show a tooltip on the label?
```
using System.Windows.Forms;
var label = new Label();
label.AutoSize = false;
label.AutoEllipsis = true;
label.Text = "This text will be too long to display all together.";
var labelToolTip = new ToolTip();
labelToolTip.SetToolTip(label, label.Text);
```
Now the tooltip will show the full text when the user hovers over it. Since the text in the label will be truncated and end in an ellipse, the user should know to hover over for more info (usually the standard way). | The [`TextAlign`](http://msdn.microsoft.com/en-us/library/system.windows.forms.label.textalign.aspx) property allows you to specify the alignment. If you right-justify it with this, the right side of the text will always be visible. However, if you want it to be left or center justified and still have the behavior you describe, I suspect you will need to perform some measurement using [`Graphics.MeasureString`](http://msdn.microsoft.com/en-us/library/system.drawing.graphics.measurestring.aspx) to determine if the text fits and change the alignment dynamically. | C# have end of text priorities | [
"",
"c#",
"textbox",
"label",
""
] |
Is there a way to compare two `DateTime` variables but to disregard the Time part.
The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.
I want to compare `12/3/89 12:43:34` and `12/3/89 11:22:12` and have it disregard the actual time of day so both of these are considered the same.
I guess I can set all the times of day to `00:00:00` before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.
I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this? | try using the `Date` property on the `DateTime` Object...
```
if(dtOne.Date == dtTwo.Date)
....
``` | For a true comparison, you can use:
```
dateTime1.Date.CompareTo(dateTime2.Date);
``` | How to compare only Date without Time in DateTime types? | [
"",
"c#",
".net",
"database",
"entity-framework",
""
] |
How do I get a [`PriorityQueue`](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html) to sort on what I want it to sort on?
Also, is there a difference between the [`offer`](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html#offer-E-) and [`add`](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html#add-E-) methods? | Use the constructor overload which takes a `Comparator<? super E> comparator` and pass in a comparator which compares in the appropriate way for your sort order. If you give an example of how you want to sort, we can provide some sample code to implement the comparator if you're not sure. (It's pretty straightforward though.)
As has been said elsewhere: `offer` and `add` are just different interface method implementations. In the JDK source I've got, `add` calls `offer`. Although `add` and `offer` have *potentially* different behaviour in general due to the ability for `offer` to indicate that the value can't be added due to size limitations, this difference is irrelevant in `PriorityQueue` which is unbounded.
Here's an example of a priority queue sorting by string length:
```
// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;
public class Test {
public static void main(String[] args) {
Comparator<String> comparator = new StringLengthComparator();
PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
queue.add("short");
queue.add("very long indeed");
queue.add("medium");
while (queue.size() != 0) {
System.out.println(queue.remove());
}
}
}
// StringLengthComparator.java
import java.util.Comparator;
public class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String x, String y) {
// Assume neither string is null. Real code should
// probably be more robust
// You could also just return x.length() - y.length(),
// which would be more efficient.
if (x.length() < y.length()) {
return -1;
}
if (x.length() > y.length()) {
return 1;
}
return 0;
}
}
```
Here is the output:
> short
>
> medium
>
> very long indeed | ## Java 8 solution
We can use `lambda expression` or `method reference` introduced in Java 8. In case we have some String values stored in the Priority Queue (having capacity 5) we can provide inline comparator (based on length of String) :
**Using lambda expression**
```
PriorityQueue<String> pq=
new PriorityQueue<String>(5,(a,b) -> a.length() - b.length());
```
**Using Method reference**
```
PriorityQueue<String> pq=
new PriorityQueue<String>(5, Comparator.comparing(String::length));
```
Then we can use any of them as:
```
public static void main(String[] args) {
PriorityQueue<String> pq=
new PriorityQueue<String>(5, (a,b) -> a.length() - b.length());
// or pq = new PriorityQueue<String>(5, Comparator.comparing(String::length));
pq.add("Apple");
pq.add("PineApple");
pq.add("Custard Apple");
while (pq.size() != 0)
{
System.out.println(pq.remove());
}
}
```
This will print:
```
Apple
PineApple
Custard Apple
```
To reverse the order (to change it to max-priority queue) simply change the order in inline comparator or use `reversed` as:
```
PriorityQueue<String> pq = new PriorityQueue<String>(5,
Comparator.comparing(String::length).reversed());
```
We can also use `Collections.reverseOrder`:
```
PriorityQueue<Integer> pqInt = new PriorityQueue<>(10, Collections.reverseOrder());
PriorityQueue<String> pq = new PriorityQueue<String>(5,
Collections.reverseOrder(Comparator.comparing(String::length))
```
So we can see that `Collections.reverseOrder` is overloaded to take comparator which can be useful for custom objects. The `reversed` actually uses `Collections.reverseOrder`:
```
default Comparator<T> reversed() {
return Collections.reverseOrder(this);
}
```
## offer() vs add()
As per the [doc](https://docs.oracle.com/javase/7/docs/api/java/util/Queue.html)
> The offer method inserts an element if possible, otherwise returning
> false. This differs from the Collection.add method, which can fail to
> add an element only by throwing an unchecked exception. The offer
> method is designed for use when failure is a normal, rather than
> exceptional occurrence, for example, in fixed-capacity (or "bounded")
> queues.
When using a capacity-restricted queue, offer() is generally preferable to add(), which can fail to insert an element only by throwing an exception. And [PriorityQueue](https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html) is an unbounded priority queue based on a priority heap. | How do I use a PriorityQueue? | [
"",
"java",
"priority-queue",
""
] |
I came across this strange code snippet which compiles fine:
```
class Car
{
public:
int speed;
};
int main()
{
int Car::*pSpeed = &Car::speed;
return 0;
}
```
**Why** does C++ have this pointer to a non-static data member of a class? **What** is the use of this strange pointer in real code? | It's a "pointer to member" - the following code illustrates its use:
```
#include <iostream>
using namespace std;
class Car
{
public:
int speed;
};
int main()
{
int Car::*pSpeed = &Car::speed;
Car c1;
c1.speed = 1; // direct access
cout << "speed is " << c1.speed << endl;
c1.*pSpeed = 2; // access via pointer to member
cout << "speed is " << c1.speed << endl;
return 0;
}
```
As to *why* you would want to do that, well it gives you another level of indirection that can solve some tricky problems. But to be honest, I've never had to use them in my own code.
**Edit:** I can't think off-hand of a convincing use for pointers to member data. Pointer to member functions can be used in pluggable architectures, but once again producing an example in a small space defeats me. The following is my best (untested) try - an Apply function that would do some pre &post processing before applying a user-selected member function to an object:
```
void Apply( SomeClass * c, void (SomeClass::*func)() ) {
// do hefty pre-call processing
(c->*func)(); // call user specified function
// do hefty post-call processing
}
```
The parentheses around `c->*func` are necessary because the `->*` operator has lower precedence than the function call operator. | This is the simplest example I can think of that conveys the rare cases where this feature is pertinent:
```
#include <iostream>
class bowl {
public:
int apples;
int oranges;
};
int count_fruit(bowl * begin, bowl * end, int bowl::*fruit)
{
int count = 0;
for (bowl * iterator = begin; iterator != end; ++ iterator)
count += iterator->*fruit;
return count;
}
int main()
{
bowl bowls[2] = {
{ 1, 2 },
{ 3, 5 }
};
std::cout << "I have " << count_fruit(bowls, bowls + 2, & bowl::apples) << " apples\n";
std::cout << "I have " << count_fruit(bowls, bowls + 2, & bowl::oranges) << " oranges\n";
return 0;
}
```
The thing to note here is the pointer passed in to count\_fruit. This saves you having to write separate count\_apples and count\_oranges functions. | What is a pointer to class data member "::*" and what is its use? | [
"",
"c++",
"class",
"pointers",
"c++-faq",
""
] |
I have been using this method to filter my queries:
```
Create PROCEDURE [dbo].[pGetTask]
@showCompletedTasks bit = 1
,@showInProgressTasks bit = 1
,@taskID int = null
,@projectID int = null
,@applicationID int = null
,@clientID int = null
... Snip ...
where
a.clientID = isnull(@clientID, a.clientID)
and a.applicationID = isnull(@applicationID, a.applicationID)
and p.projectID = isnull(@projectID, p.projectID)
and t.taskID = isnull(@taskID, t.taskID)
and curr.complete = case @showCompletedTasks when 0 then 0 else curr.complete end
and curr.complete = case @showInProgressTasks when 0 then 1 else curr.complete end
```
This actually slows my queries by 2 seconds on a 664 row result set. The SQL tuning advisor isn't much help, so I figure this is not the right way to do this. Is there a right way, besides a ton of if statements? | Assuming you have properly indexed the table that the select is on, and these fields are part of the index, my guess is that it would be the calls to isnull. I would change them to this:
```
(@clientID is null or a.clientID = @clientId) and ...
```
As for the case statements, indexes on bit fields are pointless, so there's not much to do there. | Check your indexes & statistics. That seems a little slow. The other option would be to do a dynamic query essentially build a string representing your sql and execute it using sp\_ExecuteSql (or Exec statement)
# Edit
You could try and combine your two cases but I doubt it will have effect on performance of the query. It would look better though...
Although I'm not sure your query is right (Which is hard to say without more info) but shouldn't there be an or clause between the cases your trying to provide two states to return and by having separate params I assume I can ask for Only Complete, Only Not Complete or both...in this case you need an Or | Best way to filter queries by parameter? | [
"",
"sql",
"t-sql",
""
] |
I'm working with C++ unmanaged, the problem that I have happens when I call a method that returns an LPVOID.
```
LPVOID MyMethod(...);
```
The problem is that this method sometimes returns a Bad Ptr and I want to know if there is a way of detecting this, if the value returned is a Bad Ptr.
I have tried asking if it is NULL with no luck.
The only way in which I realize if the result is a Bad Ptr is while I'm debugging, I have tried some different ways but still unable to do it. | No, there is no easy way to determine if a pointer is bad.
Windows does have IsBadReadPtr, IsBadWritePtr. These functions are inherently flawed - they only determine if a function is readable or writable in your address space at the moment of the call. They can also be the cause of [security](http://blogs.msdn.com/LarryOsterman/archive/2004/05/18/134471.aspx) [issues](http://blogs.msdn.com/oldnewthing/archive/2006/09/27/773741.aspx) and should never be used.
The main issue is that there is no way to differentiate between a "bad" pointer that is still accessible to your process, and a good pointer.
For instance,
```
int g[5];
int somethingElse;
void* GetPointer()
{
return &g[5]; // Whoops, off by one.
}
```
&g[5] is probably a valid pointer in your process, and might be pointing to somethingElse, you'll be able to access it without crashing but writing to it will corrupt your state. | Your real problem is that you're calling a function that returns bad pointers. Do you have access to its source code? 90% of the time I've encountered problems like this, it's because either:
1) The function is returning a pointer to the stack; e.g.,
```
char a[10];
...
return a;
```
2) The function is returning a pointer that was never assigned valid memory to begin with:
```
char* foo; // Invalid pointer
...
return foo;
```
3) The function is returning a pointer that was already deleted (or free'd):
```
char* foo = new char[10];
...
delete[] foo;
return foo;
```
You really need to find the real problem, rather than work around it. | How to validate LPVOID to <Bad Ptr> | [
"",
"c++",
""
] |
I'm trying to use jQuery and JSON with a C# Web Service that I wrote. No matter what, the following code will only output in XML.
**Webservice Code**
```
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld() {
return "Hello World!";
}
```
I also have these attributes assigned to the class
```
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
```
**jQuery Code**
```
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ScheduleComputerDS.asmx/HelloWorld",
data: "{}",
dataType: "jsonp",
success: function(data) {
alert(data);
}
});
```
The ASMX page always returns as content type "text/xml". Anything I'm missing?
**EDITS:** In response to a couple answers:
If I have the datatype as just "json" the content is still XML and jQuery also will not call my callback function. If I add the "&callback=?" to the url, IIS throws a HTTP 500 error.
My class does inherit from "System.Web.Services.WebService".
From doing some research on your guys answers, it looks like I do need to mess with WCF. Unfortunately the JSON that is returned is more designed for MS Ajax and is a lot of useless bloat for my use. I may look into an open source library like Jayrock or something similar.
Thanks for all your help! | As far as I know, the ScriptService attribute just allows the service to automatically create a JavaScript proxy (by appending /js to the endpoint address - ScheduleComputerDS.asmx/js in your case). It does not allow you to call the operations on the service the way you're trying to do.
You could instead use a RESTful WCF service (which requires .NET 3.5) which you can access by sending a properly shaped URI via an HTTP GET. | I think there's a typo:
```
dataType: "jsonp",
```
Should be:
```
dataType: "json",
``` | C# Web Service won't output JSON, only XML | [
"",
"c#",
"jquery",
"web-services",
"json",
""
] |
I have a Java applet consisting of a wizard-like form with three steps. At the final step, the user can click a "finish" button. I want that button to cause the web browser to navigate to a specific URL.
**Question:** Is there a way to cause the browser to navigate to a specific URL, in such a way that it will work across all modern browsers? My specific browser requirements are FF3+, IE7+, Safari 3+, and Opera 9+. I am using Java 1.5. | From the applet you can simply get the applet context and call [showDocument(url)](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL)).
This will navigate away from the current page to the specified URL:
```
getAppletContext().showDocument(url);
```
Additionally you can pass a [target](http://java.sun.com/javase/6/docs/api/java/applet/AppletContext.html#showDocument(java.net.URL,%20java.lang.String)) parameter.
To visit a relative URL you can use:
```
URL url = new URL(getCodeBase().getProtocol(),
getCodeBase().getHost(),
getCodeBase().getPort(),
"/next.html");
getAppletContext().showDocument(url);
```
These work in every major browser since Java version 1.1. | You could initiate the wizard from within JavaScript and have the applet return the execution flow to the JavaScript caller on clicking the 'Finish' button. Once you are in JavaScript you could then navigate to a new location, either by doing a form post or by doing changing the window.location property.
In the worst case, you could examine the use of [LiveConnect](http://java.sun.com/products/plugin/1.3/docs/jsobject.html), but I would touch it with a 10 foot pole.
---
**Update on LiveConnect**
The original LiveConnect seems to be limited by nature to browsers running on Windows, and will probably work only on NN and IE. [Some of those bugs have been fixed recently](https://developer.mozilla.org/en/LiveConnect), but browser compatibility will continue to be an issue. | How can I cause the browser to navigate to a given URL from a Java applet? | [
"",
"java",
"cross-platform",
"applet",
"cross-browser",
""
] |
I doubt this is possible, but I was curious if you could have more than 2 items (key,value) in a dictionary. Maybe a key and 2 values. Is there a collection object that does allow this? What I am actually trying to do is to store a key and a value for the key and another value to hold the count of how many times the key has been found. For example, I may have a for loop that goes through a list of colors and each color has a unique value. As I go through the list, I not only want to store the color, the unique value of the color in a dictionary, but also store how many times red occurred in the list.
I put in the following declaration and now I am tyring to figure out how I can test to see if it contains the value already and if it does not, add it to the list with a count of 1 and if it does, increment the count. After I post the declaration, I will post how I was doing it with just one dictionary.
```
Dictionary<string, Dictionary<int,int>> colors =
new Dictionary<string, Dictionary<int,int>>();
```
Here is code of how I was handling it before:
```
Dictionary<string, int> colors = new Dictionary<string, int>();
foreach (Color color in ColorList)
{
if (colors.ContainsKey(color.ToString()))
colors[color]++;
else
colors.Add(color, 1);
}
``` | Could you perhaps have a dictionary of a struct that would keep track of the color and the number of times it occurred?
Edit: As suggested elsewhere, this could also be accomplished by building your own small custom class. Would essentially work in the same fashion. | You could make a simple Tuple class, such as a Triple. It's essentially a generically keyed dictionary but holds an additional object. It's pretty common for this scenario, people have made libraries that extend it out for 4 to 10 objects. Here's an example:
```
public struct Triple<X, Y, Z>
{
public X First;
public Y Second;
public Z Third;
public Triple(X x, Y y, Z z)
{
First = x;
Second = y;
Third = z;
}
}
```
And then use it like so:
```
var myTriple = new Triple<string, Color, int>(
"key",
myColor,
count
)
```
, | Can you have more than 2 items in a Dictionary collection or another type of collection? | [
"",
"c#",
"collections",
""
] |
For example. there are 3 variables, 1 is a must, 2 and 3 are eithers so 3 can be false as long as 1 and 2 are true, 2 can be false as long as 1 and 3 are true.
```
if(xmlhttp.responseText.indexOf("type:SearchList~")>=0 && (obj == "hDrop" || obj == "iDrop")){
}
```
Isn't working for me
Can anyone spot the problem? | No problem with your script that I can spot. This very simple test validates it:
```
var a = "yes";
var b = "no2";
var c = true;
alert(c && (a == "yes" || b == 'no'));
```
Check the values of 'obj'. Is it a string? | I built a truth table of your conditions:
```
1 2 3 R
-------
0 X X 0
1 0 0 0
1 1 X 1
1 X 1 1
```
This resolves to 1 && (2 || 3), so something else is wrong. | And Or stacking conditions in Javascript (if $1 && ($2 || $3)) | [
"",
"javascript",
"conditional-statements",
""
] |
In vs2008, C# build events are configuration-specific.
Looking for ideas on how to make my build event run only when doing a Release build.
Ideas? | Unfortunately the C# projects do not support anything like this that I have found. I have had to resort to writing makefiles in certain situations to get around this. You could also write a batch file or a simple program that accepts a parameter then call it like this from the build event:
```
custom.exe $(ConfigurationName)
``` | ok, along Brian's line, I'm doing this:
```
if "$(ConfigurationName)" == "Release" do_something
```
and it appears to work | How do you make configuration-specific C# build events in VS2008 | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"build-process",
""
] |
If I have run a long line in IPython, and try and recall it (using the up-arrow) or backspace beyond the start of the current line, it displays incorrectly (all smushed into one line)
For example, in the following session I wrote a long line `[1]`, entered a somewhat-blank line `[2]`, then up-arrowed twice to get the `print` statement on line `[3]`, and the following happened:

Happens in both iTerm and Terminal.app.. I had a similar problem with regular terminal sessions, which was fixed by properly terminating colour codes, but I'm not sure how to fix it with IPython | Aha! I had an old version of the Python readline module - installing the latest from <http://ipython.scipy.org/dist/> and it works perfectly!
```
sudo easy_install http://ipython.scipy.org/dist/readline-2.5.1-py2.5-macosx-10.5-i386.egg
``` | Got this problem on Snow Leopard. Installing a new version of readline from <http://pypi.python.org/pypi/readline/> fixes it:
```
sudo easy_install http://pypi.python.org/packages/2.6/r/readline/readline-2.6.4-py2.6-macosx-10.6-universal.egg
``` | Line-wrapping problems with IPython shell | [
"",
"python",
"terminal",
"ipython",
""
] |
I have a medical database that keeps different types of data on patients: examinations, lab results, x-rays... each type of record exists in a separate table. I need to present this data on one table to show the patient's history with a particular clinic.
My question: what is the best way to do it? Should I do a `SELECT` from each table where the patient ID matches, order them by date, and then keep them in some artificial list-like structure (ordered by date)? Or is there a better way of doing this?
I'm using WPF and SQL Server 2008 for this app. | As others have said, JOIN is the way you'd normally do this. However, if there are multiple rows in one table for a patient then there's a chance you'll get data in some columns repeated across multiple rows, which often you don't want. In that case it's sometimes easier to use UNION or UNION ALL.
Let's say you have two tables, `examinations` and `xrays`, each with a PatientID, a Date and some extra details. You could combine them like this:
```
SELECT PatientID, ExamDate [Date], ExamResults [Details]
FROM examinations
WHERE PatientID = @patient
UNION ALL
SELECT PatientID, XrayDate [Date], XrayComments [Details]
FROM xrays
WHERE PatientID = @patient
```
Now you have one big result set with PatientID, Date and Details columns. I've found this handy for "merging" multiple tables with similar, but not identical, data. | Use a [JOIN](http://w3schools.com/sql/sql_join.asp) to get data from several tables. | Best way of acquiring information from several database tables | [
"",
"c#",
"wpf",
"sql-server-2008",
"merge",
""
] |
I have a base class and a derived class. Each class has an .h file and a .cpp file.
I am doing dynamic\_cast of the base class object to the derived class in the following code:
h files:
```
class Base
{
public:
Base();
virtual ~Base();
};
class Derived : public Base
{
public:
Derived(){};
void foo();
};
class Another
{
public:
Another(){};
void bar(Base* pointerToBaseObject);
};
```
cpp files:
```
Base::Base()
{
//do something....
}
Base::~Base()
{
//do something....
}
void Derived::foo()
{
Another a;
a.bar(this);
}
void Another::bar(Base* pointerToBaseObject)
{
dynamic_cast<Derived*>(pointerToBaseObject)
}
```
From some strange reason, the casting fails (returns NULL). However, the casting succeeds if I move the implementation of Derived class's constructor from .h to the .cpp file.
What can cause it?
The compiler is gcc 3.1, on Linux-SUSE. BTW, I see this behavior only on this platform, and the same code works fine in Visual Studio. | The code, as posted, shouldn't fail, provided you have a virtual function in the base class (as litb pointed out).
But I believe every current compiler generates a "Base class is not polymorphic" kind of error if you hadn't, so that probably won't be the problem.
The only thing I can think of is that due to some weird bug everything gets inlined and no vtable gets generated. But if you put the constructor in the C++ file, the compiler decides not to inline everything, triggering the creation of a vtable, causing your cast to work.
But this is very wild guesswork, and I don't think any compiler would have such a mistake in it (?)
If you want a definite answer, post more code. And the compiler / platform used.
EDIT: Seeing the updated code
I think you should at least derive Derived from Base ;) (I suppose that's a typo)
But after seeing the code, the only thing I can think of is that gcc (wrongly) inlines everything and doesn't generate a vtable for Derived. For what it's worth, this runs fine compiled with gcc 4.0
3.1 is over 7 years old by now... if there's any possibility to upgrade I'd go for it. | Do you have any virtual function in Base? It won't work otherwise. If nothing else, make its dtor virtual.
Don't know whether it was already asked by the other guy that deleted his answer, but i believe it was something different: Are you doing the dynamic\_cast from the bases' constructor? If so, that won't work. The compiler will think that the Base is the most derived type, similar to when you call a virtual function and it ends up calling the version of the Base. | dynamic_cast fails | [
"",
"c++",
"dynamic-cast",
""
] |
Hey all. I am working on a project for school where we are given the .class file but not the source to include in our code. I am using Eclipse, and I want to include the file in my project so I can instantiate objects from it and use it.
The file is TokenizerImpl.class, and I want to use it like this:
`TokenizerImpl tokenizer = new TokenizerImpl(foo);`
I put the file in my project folder, and Eclipse says that "TokenizeImpl cannot be resolved as a type", which I assume means it cannot find the class or source. I tried putting it in the "bin" folder of the project and got the same error. Google search and SO search didn't seem to answer this, so I will give it a shot. How do I do this, oh wise ones?
Edit: Oh dear, I found the problem was something else entirely. These solutions worked fine, but I just forgot to create the Tokenizer interface that TokenizerImpl implements. Doh. Thanks for all your help though, I did learn a lot about eclipse. | You can add a directory containing the class files to the Eclipse project, only if it is inside one of your Eclipse projects, either in a generated directory or in one you have created.
This can be done by adding the class folder to the Java build path of the application. You can set this in the Project properties, by visiting Java Build Path -> Libraries -> Add Class Folder. Keep in mind, that you will have to specify the root folder containing the class files in their packages.
Therefore, if you wish to have the compiler access com.stackoverflow.Example.class present in the classes directory under project A (but not in the build path of project A), then you should add 'classes' as a class folder, and not classes/com/stackoverflow as a class folder. | Project -> Properties -> Java Build Path -> Libraries -> Add External Class Folder
The folder must contain a package hierarchy, i.e. if your class is really foo.bar.TokenizerImpl it must be in the subdirectory foo/bar. | How do I include .class files in my project in Eclipse? (Java) | [
"",
"java",
"eclipse",
"class",
""
] |
I have a Python module with nothing but regular global functions. I need to call it from another business-domain scripting environment that can only call out to C DLLs. Is there anyway to build my Python modules so that to other code it can be called like a standard C function that's exported from a DLL? This is for a Windows environment. I'm aware of IronPython, but as far as I know it can only build .NET Assemblies, which are not callable as C DLL functions. | Take a look at [this](http://www.codeproject.com/KB/cpp/embedpython_1.aspx) Codeproject article. One way would be wrap your python functions in a C dll and expose this to the callee.
COM is a binary protocol to solve this issue. But you will have to wrap this python dll in a COM wrapper. And add some code on the calling side as well. | The standard solution is to embed the Python interpreter (which is already a C DLL) in your application.
<https://docs.python.org/extending/windows.html#using-dlls-in-practice>
<http://docs.python.org/extending/embedding.html> | Is there a way to build a C-like DLL from a Python module? | [
"",
"python",
""
] |
I am still new to C# and I've been struggling with various issues on arrays. I've got an array of metadata objects (name value pairs) and I would like to know how to create only the number of "InputProperty" objects that I truly need. In this loop I've arbitrarily set the number of elements to 20 and I try to bail out when the entry becomes null but the web service on the receiving end of this does not like any null elements passed to it:
```
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
InputProperty[] ip = new InputProperty[20]; // how to make this "dynamic"
int i;
for (i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
update.Items = ip;
return update;
}
```
In summary, say I only have 3 namevalue pairs in the above input array? Rather than allocate 20 elements for the array called ip, how can code this so ip is only as big as it needs to be. The update object is passed across another webservice so serialization is important (i.e. I can't use namevaluecollection, etc.).
p.s. Is the only way to followup on a posted question through the "add comments" facility? | If you don't want to use a `List`, `ArrayList`, or other dynamically-sized collection and then convert to an array (that's the method I'd recommend, by the way), then you'll have to allocate the array to its maximum possible size, keep track of how many items you put in it, and then create a new array with just those items in it:
```
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
InputProperty[] ip = new InputProperty[20]; // how to make this "dynamic"
int i;
for (i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
if (i < nvPairs.Length)
{
// Create new, smaller, array to hold the items we processed.
update.Items = new InputProperty[i];
Array.Copy(ip, update.Items, i);
}
else
{
update.Items = ip;
}
return update;
}
```
An alternate method would be to always assign `update.Items = ip;` and then resize if necessary:
```
update.Items = ip;
if (i < nvPairs.Length)
{
Array.Resize(update.Items, i);
}
```
It's less code, but will likely end up doing the same amount of work (i.e. creating a new array and copying the old items). | ```
InputProperty[] ip = new InputProperty[nvPairs.Length];
```
Or, you can use a list like so:
```
List<InputProperty> list = new List<InputProperty>();
InputProperty ip = new (..);
list.Add(ip);
update.items = list.ToArray();
```
Another thing I'd like to point out, in C# you can delcare your int variable use in a for loop right inside the loop:
```
for(int i = 0; i<nvPairs.Length;i++
{
.
.
}
```
And just because I'm in the mood, here's a cleaner way to do this method IMO:
```
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
var ip = new List<InputProperty>();
foreach(var nvPair in nvPairs)
{
if (nvPair == null) break;
var inputProp = new InputProperty
{
Name = "udf:" + nvPair.Name,
Val = nvPair.Value
};
ip.Add(inputProp);
}
update.Items = ip.ToArray();
return update;
}
``` | How to set array length in c# dynamically | [
"",
"c#",
"arrays",
"object",
"array-initialize",
""
] |
I'm trying to debug portions of the current application I'm working on, however when I try and check the value of a property/variable I get the error:
`Cannot evaluate expression because a thread is stopped at a point where garbage collection is impossible, possibly because the code is optimized.`
This is just a regular ASP.NET project. In some portions of the application I can view the properties and variables perfectly fine. I haven't figured out what's different about the blocks of code that I can and can not see the values of the variables in. | The problem was [documented](http://blogs.msdn.com/rmbyers/archive/2008/08/16/Func_2D00_eval-can-fail-while-stopped-in-a-non_2D00_optimized-managed-method-that-pushes-more-than-256-argument-bytes-.aspx) on an MSDN blog, as being a size limitation of certain types in certain situations, more details in the link. I believe it was 256 bytes and/or the total size/count of the number of arguments passed to a function. Sorry to say there does not seem to be a quick fix, but hopefully the MSDN blog entry will help you identify a way to solve your problem. | This article, [Rules of Funceval](http://blogs.msdn.com/b/jmstall/archive/2005/11/15/funceval-rules.aspx) gives a number of reasons why this can occur. If debugging is turned on and optimisation turned off already, there doesn't seem to be much else you can do about this problem. | Unable to view values of variables while debugging | [
"",
"c#",
".net",
"asp.net",
""
] |
I have a big content slideshow kinda page that I'm making that is starting to use a lot of event triggers. Also about half of them use the livequery plugin.
Will I see speed increases by unloading these events between slides so only the active slide has bound events?
Also is the native livequery significantly faster then the livequery plugin?(cause it's certainly less functional)
Also would something like this:
<http://dev.jquery.com/attachment/ticket/2698/unload.js>
unbind livequery events as well?
I really just need to know how long it takes to unload/load an event listener vs how many cycles they are really eating up if I leave them running. Also any information on live events would be awesome. | If by "native `liveQuery`" you mean [`live()`](http://docs.jquery.com/Events/live), then yes, `live()` is significantly faster than `liveQuery()`. The latter uses `setInterval` to periodically query the entire document tree for new elements while the former uses [event delegation](http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/).
Event delegation wins handsdown. In a nutshell, `live()` will have *one* handler on the `document` per event type registered (eg, `click`), no matter how many selectors you call `live()` with.
As for your other question, it sounds like you are binding to each slide's elements and want to know if unbinding and binding again is performant? I would say WRT memory, yes. WRT CPU cycles, no.
To be clear, with the `liveQuery()` approach CPU will never sleep. | I need more details to offer actual code, but you might want to look into [Event Delegation](http://developer.yahoo.com/yui/examples/event/event-delegation.html):
> Event delegation refers to the use of a single event listener on a parent object to listen for events happening on its children (or deeper descendants). Event delegation allows developers to be sparse in their application of event listeners while still reacting to events as they happen on highly specific targets. This proves to be a key strategy for maintaining high performance in event-rich web projects, where the creation of hundreds of event listeners can quickly degrade performance.
A quick, basic example:
Say you have a DIV with images, like this:
```
<div id="container">
<img src="happy.jpg">
<img src="sad.jpg">
<img src="laugh.jpg">
<img src="boring.jpg">
</div>
```
But instead of 4 images, you have 100, or 200. You want to bind a click event to images so that X action is performed when the user clicks on it. Most people's first code might look like this:
```
$('#container img').click(function() {
performAction(this);
});
```
This is going to bind a crapload of event handlers that will bog down the performance of your page. With Event Delegation, you can do something like this:
```
$('#container').click(function(e) {
if($(e.target)[0].nodeName.toUpperCase() == 'IMG') {
performAction(e.target);
}
});
```
This will only bind 1 event to the actual container, you can then figure out what was clicked by using the event's `target` property and delegate accordingly. This is still kind of a pain, though, and you can actually get this significant performance improvement without doing all this by using jQuery's [`live`](http://docs.jquery.com/Events/live) function:
```
$('#container img').live('click', function() {
performAction(this);
});
```
Hope this helps. | jquery unbinding events speed increases | [
"",
"javascript",
"jquery",
""
] |
Just come to polishing my application and making it resume after the user has left. When the application restores I get an IllegalThreadStateException, which is quite annoying. This problem is present in the example google gives of [Lunar Lander](http://developer.android.com/guide/samples/LunarLander/index.html). Has anyone found a way to restore working when using surfaceView? | I believe this arises from a disparity in how the Surface and the Activity are handled. When you leave the LunarLander application the surface is destroyed (invoking surfaceDestroyed) but the Activity is only paused (invoking onPause). When the Activity is resumed the surface is created (invoking surfaceCreated) and it attempts to start the drawing thread again.
This means that creating the Thread happens with the Activity's lifecycle and destroying the thread happens with the SurfaceView's lifecycle, which do not always correspond, thus the IllegalThreadStateException. The solution would be to tie the thread to one lifecycle or the other, not both.
I think [this thread](https://stackoverflow.com/questions/672325/android-regaining-focus-using-surfaceview) proposes a possible solution, though I don't know if it works. | In my own test, I create the drawing thread in the surfaceCreated() method, and this solves the issue completely. This is my method implementation:
```
@Override
public void surfaceCreated(SurfaceHolder arg0) {
_thread = new DrawThread(getHolder());
_thread.setRunning(true);
_thread.start();
}
``` | Android IllegalThreadStateException in LunarLander | [
"",
"java",
"android",
"surfaceview",
"illegalstateexception",
""
] |
I found a function in a PHP page that calculates the number of miles between 2 points, but it's faulty. It's supposed to work with google maps, but the difference in distances are ranging from 1.3 to 1.65 times further in google maps(which is more accurate).
Here's the function:
```
$M = 69.09 * rad2deg(acos(sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($lon1 - $lon2))));
```
I find it to be a bit complicated and I don't know that much about geometry to know wheter or not this is correct.
Can someone with a bit more knowhow take a look at this and see what's wrong with it? | Maybe you are comparing the 'distance as the crow flies' (direct line between two points) with driving distance?
Also, [see this post](https://stackoverflow.com/questions/407989/calculating-distance-between-zip-codes-in-php) for calculating distance between two points in PHP. | You're looking for the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to calculate distance between two points that you have longitude and latitude for.
A straightforward implementation of it in Javascript [can be found here](http://www.movable-type.co.uk/scripts/latlong.html), which should be easy to convert to PHP. | math related PHP question + latitude | [
"",
"php",
"google-maps",
"geolocation",
"distance",
""
] |
Hello I'm writing a little project in c++ where I would like to have some classes that does some work, I wrote the interfaces and the implementation of the classes.
The thing that surprises me is that I cannot have a simple class without a main(), I would like to have a class that once instantiated, It's methods can be called, do things, but I don't need (nor want) a main() in the class implementation.
Here's an example I have in my head of what I'd like to have:
file animal.h:
```
class animal
{
public:
animal();
~animal();
public:
int method1(int arg1);
private:
int var1;
};
```
file animal.cpp:
```
#include "animal.h"
animal::animal(){...}
animal::~animal(){...}
int animal::method1(int arg1){return var1;}
}
```
And I would like to call the animal class form another file and have it work, something like this:
file app.cpp:
```
#include <neededlib>
#include "animal.h"
int main()
{
animal dog;
cout << dog.method1(42);
return 0;
}
```
But compiler give me
```
/usr/lib/gcc/i686-pc-linux-gnu/4.3.3/../../../crt1.o: In function _start:
"(.text+0x18): undefined reference to `main`"
collect2: ld returned 1 exit status
```
for animal.cpp, but I don't need a main there, or do I need it?
Where Am I wrong? | > but I don't need (nor want) a main() in the class implementation.
The function `main` is your entry-point. That is where execution begins. You need to have one and only one such function.
> But compiler give me "undefined reference to main" for animal.cpp, but I don't need a main there, or do I need it?
Now, your problem looks like you have not *linked* the compiled forms of `app.cpp` and `animal.cpp`.
> I'm not so strong in Makefiles, I used something like g++ animal.h -o animal and g++ animal.cpp but it gives me the error above
You don't compile headers. So don't use: `g++ animal.h`
When you compiled the animal.cpp separately, g++ created an object file. You will also need to compile the `app.cpp` because you *do need* the `main`. Once you compile the `app.cpp` file you will have to link it with the `animal` object file created earlier. But if these did not get linked in, specially, the file containing the `main` function you will hit the error you are getting now.
However, `g++` takes care of what I have described above. Try something like this:
```
g++ animal.cpp app.cpp -o test
```
This will create an executable called `test` and you can run your application using:
```
./test
``` | First, this is wrong: `animal dog = new animal();`
You either need
```
animal * dog = new animal();
cout << dog->method1(42);
delete animal;
```
or preferably just
```
animal dog;
```
Second, you need to link together the object files produced by compiling your two source .cpp files.
```
gcc -o animal animal.cpp app.cpp
```
should do the trick, if you're using gcc. | c++ class why need main? | [
"",
"c++",
"class",
"program-entry-point",
""
] |
I have several MS Access queries (in views and stored procedures) that I am converting to SQL Server 2000 (T-SQL). Due to Access's limitations regarding sub-queries, and or the limitations of the original developer, many views have been created that function only as sub-queries for other views.
I don't have a clear business requirements spec, except to 'do what the Access application does', and half a page of notes on reports/CSV extracts, but the Access application doesn't even do what I suspect is required properly.
I, therefore, have to take a bottom up approach, and 'copy' the Access DB to T-SQL, where I would normally have a better understanding of requirements and take a top down approach, creating new queries to satisfy well defined requirements.
Is there a method I can follow in doing this? Do I spread it all out and spend a few days 'grokking' it, or do I continue just copying the Access views and adopt an evolutionary approach to optimising the querying? | Work out what access does with the queries, and then use this knowledge to check that you've transferred it properly. Only once you've done this can you think about refactoring. I'd start with slow queries and then go from there: work out what indexes you need and then progressively rewrite. This way you can deliver as soon as you've proved that you moved everything successfully (even if it is potentially a bit slower). That's much better than not being able to deliver at all because problem X came along. | I'd probably start with the Access database, exercise the queries in situ and see what the resultset is. Often you can understand what the query accomplishes and then work back to your own design to accomplish it. (To be thorough, you'll need to understand the intent pretty completely anyway.) And that sounds like the best statement of requirements you're going to get - "Just like it's implemented now."
Other than that, You're approach is the best I can think of. Once they are in SQL Server, just start testing and grokking. | How do I 'refactor' SQL Queries? | [
"",
"sql",
"sql-server",
"t-sql",
"database-design",
"refactoring",
""
] |
main.h
```
extern int array[100];
```
main.c
```
#include "main.h"
int array[100] = {0};
int main(void)
{
/* do_stuff_with_array */
}
```
In the main.c module, the array is defined, and declared. Does the act of also having the extern statement included in the module, cause any problems?
I have always visualized the extern statement as a command to the linker to "look elsewhere for the actual named entity. It's not in here.
What am I missing?
Thanks.
Evil. | The correct interpretation of `extern` is that you tell something to the **compiler**. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.
To avoid exposure of names (variables, functions, ..) outside of a specific object (file), you would have to use `static`. | yea, it's harmless. In fact, I would say that this is a pretty standard way to do what you want.
As you know, it just means that any .c file that includes main.h will also be able to see `array` and access it. | Is this extern harmless? | [
"",
"c++",
"c",
"extern",
""
] |
I am creating an ASHX that returns XML however it expects a path when I do
```
XmlWriter writer = XmlWriter.Create(returnXML, settings)
```
But returnXML is just an empty string right now (guess that won't work), however I need to write the XML to something that I can then send as the response text. I tried XmlDocument but it gave me an error expecting a string. What am I missing here? | If you really want to write into memory, pass in a `StringWriter` or a `StringBuilder` like this:
```
using System;
using System.Text;
using System.Xml;
public class Test
{
static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteStartElement("element");
writer.WriteString("content");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
}
Console.WriteLine(builder);
}
}
```
If you want to write it directly to the response, however, you could pass in `HttpResponse.Output` which is a `TextWriter` instead:
```
using (XmlWriter writer = XmlWriter.Create(Response.Output, settings))
{
// Write into it here
}
``` | Something was missing on my side: flushing the XmlWriter's buffer:
```
static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder, settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("root");
writer.WriteStartElement("element");
writer.WriteString("content");
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
}
Console.WriteLine(builder);
}
``` | Possible to write XML to memory with XmlWriter? | [
"",
"c#",
"asp.net",
"xml",
"xmlwriter",
""
] |
By default, RHEL5.x64 comes with 5.1.6 - pretty old. I'm looking for a more up to date version, 5.2.8, or even the latest 5.2.9 (as of March 2009). Ideally, a Yum/RPM-based solution, for transparent upgrades (when I plan).
How do you upgrade the default for an up-to-date version? | I've elected to go for the Zend-CE solution, installed with YUM (default on rhel5). It's not perfect, the admin-dashboard security leaves something to be desired, and enabling it to be used for php-cli needs at least a manual removale of the old php-cli package + a symlink to the new, but otherwise, its not complicated. | [Oracle have some up-to-date PHP RPMs](http://oss.oracle.com/projects/php/), but not in a repository that I can see. You could try asking [Christopher Jones](http://blogs.oracle.com/opal/2009/03/php_529_rpms_for_rhel_are_avai.html) if he would be interested in building repository metadata for them?
There are also versions in the [CentOS testing repository](http://wiki.centos.org/AdditionalResources/Repositories), and Remi Collet has PHP 5.2.9 in his [repository](http://blog.famillecollet.com/pages/Config-en) (read his [announcement](http://blog.famillecollet.com/post/2009/03/01/php-5.2.9-1)). | Php 5 on RedHat Enterprise Linux 5 | [
"",
"php",
"redhat",
"rhel5",
""
] |
how can i make a tcp (ive heard it called a listener?) server (simplicity is optional at this point) that can recieve data from a client thats connected as well as send data back to that individual client (more multiple clients)?
ive done several tutorials but i could not get any of them to work or they did not do what i was hoping they would do. anyway, any help is most appreciated. | There are samples all over the web, what is it that they are not doing dor you?
Basic sample
<http://www.codeproject.com/KB/IP/socketsincsharp.aspx>
Proper server sample
<http://www.codeproject.com/KB/IP/AsyncSocketServerandClien.aspx> | You could either manually use a `Socket` or for a more high level view, use [`TcpListener` class](http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(VS.71).aspx). | C#: how do i make a listening/tcp server? | [
"",
"c#",
"visual-studio-2008",
""
] |
I have some code for validating date below:
```
function validateForm() {
var errFound = 0;
//var patt_date = new RegExp("^((((19|20)(([02468][048])|([13579][26]))-02-29))|((20[0-9][0-9])|(19[0-9][0-9]))-((((0[1-9])|(1[0-2]))-((0[1-9])|(1\d)|(2[0-8])))|((((0[13578])|(1[02]))-31)|(((0[1,3-9])|(1[0-2]))-(29|30)))))$");
var patt_date = new RegExp("^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$");
if (patt_date.test(document.getElementById("datefrom").value) == false){errFound = errFound + 1;document.getElementById("datefrom").className = "error";}
if (errFound > 0)
alert('Please correct red colored field!');
else
return true;
return false;
}
```
Above code should work with YYYY-MM-DD format, but fail to validate date such as **"2009-02-29"**
The commented code should work **(//var patt\_date = new RegExp...)**, it can catch **"2009-02-29"**,
but it ruin the validation when i put invalid data and try to correct it, it keeps complain there something wrong with form value after i had correct them (especially on form with multiple input)
Maybe someone can fix the current regex?
---
**Edited**, what i want just a simple replacement for above regexp, mean a new regexp pattern not the whole new method to validate date
And for reference, i simply grab the regexp pattern from:
<http://www.regexlib.com/REDetails.aspx?regexp_id=694> and
<http://www.regexlib.com/REDetails.aspx?regexp_id=933>
Tested with **2009-02-29**, 1st link work & 2nd not. Again the problem was only the 2nd regexp didn't detect value **2009-02-29** as invalid while 1st can (but it ruin my code? so it's must be there something wrong with it).
Thanks,
Dels | Don't do the whole date validation with a regular expression, that's really pushing the limits of what regexps were designed for. I would suggest this procedure instead:
1. Check date against regexp `/^\d{4}-\d{2}-\d{2}$/`
2. Extract year, month, and day using `substr()` and convert to integers
3. Use some `if` statements to validate the integers. Like so:
```
if (month == 2) {
if (day == 29) {
if (year % 4 != 0 || year % 100 == 0 && year % 400 != 0) {
// fail
}
}
else if (day > 28) {
// fail
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
if (day > 30) {
// fail
}
}
else {
if (day > 31) {
// fail
}
```
(That could certainly be written more concisely) Alternatively, you could probably perform this validation using Javascript's `Date` class - you might have to do something like parsing the date, converting it back to a string, and checking if the two strings are equal. (I'm not a Javascript expert) | I kinda agree with David on this... Regex matches should not be used as an exclusive criterion to decide if the passed date is, in fact, valid. The usual procedure in Javascript validation involves a few steps :
a. The first step is to ensure that the passed string matches *expected* date formats by matching it against a Regex. The following may be a stricter Regex pattern.
```
// Assuming that the only allowed separator is a forward slash.
// Expected format: yyyy-mm-dd
/^[12][90][\d][\d]-[0-3]?[\d]-[01]?[\d]$/
```
b. The second step is to parse the string into a Date object which returns the no. of milliseconds since 1970. Use this number as a parameter for the Date constructor.
c. Since JS automatically rolls over the passed date to the nearest valid value, you still cannot be certain if the Date object created matches that which was passed. To determine if this happened, the best way is to split the passed string according to the separator and compare individual date components:
```
// d is the created Date object as explained above.
var arrDateParts = inputDate.split("-");
if ((d.getFullYear() == arrDateParts[0]) && (d.getMonth() == arrDateParts[1]) && (d.getDate() == arrDateParts[2]))
return true;
else
return false;
``` | javascript regexp, validating date problem | [
"",
"javascript",
"regex",
"validation",
""
] |
I am reading a table A and inserting the date in Table B (both tables are of same structure except primary key data type). In Table B, Primary key is int whereas in Table A it is UniqueIdentifier.
INSERT INTO TableB
(ID, Names, Address)
(select ID, Names, Address from TableA)
Now how can i insert int type incremental value (1,2,3,so on) in TableB instead of uniqueidentifier from TableA using above script.
Help? | Why not change Table B so that the primary key is an identity which auto-increments? | Go to the table properties, select the ID field, under "Identity specification", set "Identity Increment" = 1, "Identity Seed" = 1. By doing that, the ID becomes auto incremental...
Then your insert statement would be something like:
`INSERT INTO TableB (Names, Address) (select Names, Address from TableA)` | How to insert sequential numbers in primary key using select subquery? | [
"",
"sql",
"sql-server",
""
] |
I often see legacy code checking for `NULL` before deleting a pointer, similar to,
```
if (NULL != pSomeObject)
{
delete pSomeObject;
pSomeObject = NULL;
}
```
Is there any reason to checking for a `NULL` pointer before deleting it? What is the reason for setting the pointer to `NULL` afterwards? | It's perfectly "safe" to delete a null pointer; it effectively amounts to a no-op.
The reason you might want to check for null before you delete is that trying to delete a null pointer could indicate a bug in your program.
*Edit*
**NOTE**: if you overload the delete operator, it may no longer be "safe" to `delete NULL` | The C++ standard guarantees that it is legal to use a null pointer in a *delete-expression* (§8.5.2.5/2). However, it is *unspecified* whether this will call a deallocation function (`operator delete` or `operator delete[]`; §8.5.2.5/7, note).
If a default deallocation function (i.e. provided by the standard library) is called with a null pointer, then the call has no effect (§6.6.4.4.2/3).
But it is unspecified what happens if the deallocation function is not provided by the standard library — i.e. what happens when we overload `operator delete` (or `operator delete[]`).
A competent programmer would handle null pointers accordingly *inside* the deallocation function, rather than before the call, as shown in OP’s code.Likewise, setting the pointer to `nullptr`/`NULL` after the deletion only serves very limited purpose. Some people like to do this in the spirit of [defensive programming](https://en.wikipedia.org/wiki/Defensive_programming): it will make program behaviour slightly more predictable in the case of a bug: accessing the pointer after deletion will result in a null pointer access rather than a access to a random memory location. Although both operations are undefined behaviour, the behaviour of a null pointer access is a lot more predictable in practice (it most often results in a direct crash rather than memory corruption). Since memory corruptions are especially hard to debug, resetting deleted pointers aids debugging.
— Of course this is treating the symptom rather than the cause (i.e. the bug). **You should treat resetting pointers as code smell.** Clean, modern C++ code will make memory ownership clear and statically checked (by using smart pointers or equivalent mechanisms), and thus provably avoid this situation.
### Bonus: An explanation of overloaded `operator delete`:
`operator delete` is (despite its name) a function that may be overloaded like any other function. This function gets called internally for every call of `operator delete` with matching arguments. The same is true for `operator new`.
Overloading `operator new` (and then also `operator delete`) makes sense in some situations when you want to control precisely how memory is allocated. Doing this isn't even very hard, but a few precautions must be made to ensure correct behaviour. Scott Meyers describes this in great detail *Effective C++*.
For now, let's just say that we want to overload the global version of `operator new` for debugging. Before we do this, one short notice about what happens in the following code:
```
klass* pobj = new klass;
// … use pobj.
delete pobj;
```
What actually happens here? Well the above can be roughly translated to the following code:
```
// 1st step: allocate memory
klass* pobj = static_cast<klass*>(operator new(sizeof(klass)));
// 2nd step: construct object in that memory, using placement new:
new (pobj) klass();
// … use pobj.
// 3rd step: call destructor on pobj:
pobj->~klass();
// 4th step: free memory
operator delete(pobj);
```
Notice step 2 where we call `new` with a slightly odd syntax. This is a call to so-called *placement `new`* which takes an address and constructs an object at that address. This operator can be overloaded as well. In this case, it just serves to call the constructor of the class `klass`.
Now, without further ado here's the code for an overloaded version of the operators:
```
void* operator new(size_t size) {
// See Effective C++, Item 8 for an explanation.
if (size == 0)
size = 1;
cerr << "Allocating " << size << " bytes of memory:";
while (true) {
void* ret = custom_malloc(size);
if (ret != 0) {
cerr << " @ " << ret << endl;
return ret;
}
// Retrieve and call new handler, if available.
new_handler handler = set_new_handler(0);
set_new_handler(handler);
if (handler == 0)
throw bad_alloc();
else
(*handler)();
}
}
void operator delete(void* p) {
cerr << "Freeing pointer @ " << p << "." << endl;
custom_free(p);
}
```
This code just uses a custom implementation of `malloc`/`free` internally, as do most implementations. It also creates a debugging output. Consider the following code:
```
int main() {
int* pi = new int(42);
cout << *pi << endl;
delete pi;
}
```
It yielded the following output:
```
Allocating 4 bytes of memory: @ 0x100160
42
Freeing pointer @ 0x100160.
```
Now, this code does something fundamentally different than the standard implementation of `operator delete`: **It didn't test for null pointers!** The compiler doesn't check this so the above code compiles but it may give nasty errors at run-time when you try to delete null pointers.
However, as I said before, this behaviour is actually unexpected and a library writer **should** take care to check for null pointers in the `operator delete`. This version is much improved:
```
void operator delete(void* p) {
if (p == 0) return;
cerr << "Freeing pointer @ " << p << "." << endl;
free(p);
}
```
In conclusion, although a sloppy implementation of `operator delete` may require explicit null checks in the client code, this is non-standard behaviour and should only be tolerated in legacy support (*if at all*). | Is there any reason to check for a NULL pointer before deleting? | [
"",
"c++",
"pointers",
"null",
"delete-operator",
""
] |
Maybe the most typical example is the JDBC closing done wrong way and not handling the possible exceptions correctly. I am very curious to see other examples you have seen - preferably web application related.
So, are there any common leak patterns in Java? | The two key "effective leak" patterns in my experience are:
* Statics and singletons which gradually grow over time. This could include caches, poorly implemented and used connection pools, dictionaries of "every user we've seen since startup" etc
* References from long-lived objects to objects which were *intended* to be short-lived. In C# this can happen with events, and the equivalent observer pattern could give the same sort of effect in Java. Basically if you ask one object (the observer) to watch another (the source) then you usually end up with a reference *from* the source *to* the observer. That can end up being the only "live" reference, but it'll live as long as the source.
* Permgen leaks if you keep generating new code dynamically. I'm on rockier ground here, but I'm pretty sure I've run into problems this way. It's possible this was partly due to JRE bugs which have since been fixed - it's been too long since it happened for me to remember for sure.
* Unit tests which hold onto state can last longer than you might expect because JUnit will hold onto the testcase instances. Again I can't remember the details, but sometimes this makes it worth having explicit "variable nulling" in the teardown, anachronistic as that looks.
I can't say that I've regularly found memory leaks to be a problem in Java (or .NET) though. | I wouldn't say it's common - leaks are very rare in Java - but I've seen a leak due to keeping a reference to a non-static inner class which didn't use the outer instance, but held a reference to it anyway. | Common Java memory/reference leak patterns? | [
"",
"java",
"memory-leaks",
"reference",
"garbage-collection",
""
] |
We've written a WCF service to be used by a Java shop, who is using CXF to generate the adapters. We're not that familiar with Java, but have exposed the service using basicHttpBinding, SSL, and basic authentication. Integration tests show that a .NET client can consume the service just fine. However, the Java shop is having trouble consuming the service. Specifically, they getthe following JAXB error: Two declarations cause a collision in the ObjectFactory class. This is usually caused if 2 operations have the same name and namespace when CXF attempts to create adapter classes.
We can't find any type or operation names that should cause any sort of collision. We have made sure that all custom types specify a namespace, and tempuri.org is not specified anywhere in the WSDL. The Java shop suspects the error is because the generated WSDL contains <xsd:import elements.
So, my questions:
* Is there any better way than CXF for the Java shop consume the WCF service? Project Tango looks interesting, but I don't know enough to tell them to consider using it. Is CXF a defacto standard in Java?
* BasicHttpBinding/SSL/Basic Auth are MS recommended for interop scenarios, but the client still seems to have interop problems. Should we consider other bindings or settings to make this easier to consume?
* Is there a way to configure WCF to always output a single WDSL with no schema imports? | The "Two declarations cause a collision in the ObjectFactory class" error message usually has nothing to do with imports. That's a JAXB error message that is usually caused by having multiple elements or similar that cause the generated field names to be the same. For example, if you have elements like:
<element name="Foo" .../>
and
<element name="foo" .../>
That can cause that error. Another is using thing like hyphens and underscores and such that are usually eliminated+capped:
<element name="doFoo" .../>
and
<element name="do\_foo" .../>
With 2.1.4, you can TRY running the wsdl2java with the -autoNameResolution flag. That SOMETIMES helps with this, but not always. Unfortunately, the information that JAXB gives in these cases is nearly worthless and lots of times it's just trial and error to find the conflicting types. :-( | I am deep into Java & WCF interoperability. As someone else said you need to flatten your WSDL if you are working with file based WSDL. However I use Netbeans 6.5 and if you point to a real url like <http://myservice/?wsdl> , Netbeans can cope easily with the default wsdl generated by WCF.
In real life other things you need to consider is service versioning, optional datamembers (doesn't go well in java, so I suggest to make all datamembers IsRequired=true), order etc.
The real tough thing to get going was security. I had to make mutual certificate authentication working and it still has some issues. | What is the best way to expose a WCF service so that it can be easily consumed from Java/CXF? | [
"",
"java",
"wcf",
"cxf",
""
] |
I'm trying to figure out how to automatically link the email addresses contained in a simple text from the db when it's printed in the page, using php.
Example, now I have:
```
Lorem ipsum dolor email@foo.com sit amet
```
And I would like to convert it (on the fly) to:
```
Lorem ipsum dolor <a href="mailto:email@foo.com">email@foo.com</a> sit amet
``` | You will need to use regex:
```
<?php
function emailize($text)
{
$regex = '/(\S+@\S+\.\S+)/';
$replace = '<a href="mailto:$1">$1</a>';
return preg_replace($regex, $replace, $text);
}
echo emailize ("bla bla bla e@mail.com bla bla bla");
?>
```
Using the above function on sample text below:
```
blalajdudjd user@example.com djjdjd
```
will be turned into the following:
```
blalalbla <a href="mailto:user@example.com">user@example.com</a> djjdjd
``` | Try this version:
```
function automail($str){
//Detect and create email
$mail_pattern = "/([A-z0-9_-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
$str = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $str);
return $str;
}
```
---
Update 31/10/2015: Fix for email address like `abc.def@xyz.com`
```
function detectEmail($str)
{
//Detect and create email
$mail_pattern = "/([A-z0-9\._-]+\@[A-z0-9_-]+\.)([A-z0-9\_\-\.]{1,}[A-z])/";
$str = preg_replace($mail_pattern, '<a href="mailto:$1$2">$1$2</a>', $str);
return $str;
}
``` | Automatically create email link from a static text | [
"",
"php",
"email",
"url",
"hyperlink",
""
] |
What is the best way to embed Login Form into several pages in Zend Framework?
Currently I have two controllers, LoginController for separate login form
and IndexController for actions on index page.
I need to include Login Form into index page to let users log in both from the front page and from Login page.
My current solution is to make IndexController extend LoginController, but I have to make some adjustments to the code of both controllers (e.g. call parent::IndexAction from inside child indexAction to render login form and various redirects should be updated too).
Is it OK implement "multi-page" login with such a controller inharitance?
What is the best practice? | Action helpers may help you <http://devzone.zend.com/article/3350-Action-Helpers-in-Zend-Framework> | i also recommend you moving most of your code into the user model instead of the controller.
I think "thin controllers, Fat models" pattern is more expendable and maintainable then extending controllers.
I also use the extending a generic login controller for my aplications, but the generic controller just has a functions that gets the inputs and sends them to the model and redirects or sends an error to the view. | Best way to embed Login Form in Zend Framework pages | [
"",
"php",
"zend-framework",
"composition",
""
] |
Let's say I have these two arrays:
```
var array1 = new[] {"A", "B", "C"};
var array2 = new[] {"A", "C", "D"};
```
I would like to get the differences between the two. I know I could write this in just a few lines of code, but I want to make sure I'm not missing a built in language feature or a LINQ extension method.
Ideally, I would end up with the following three results:
* Items not in array1, but are in array2 ("D")
* Items not in array2, but are in array1 ("B")
* Items that are in both | If you've got LINQ available to you, you can use [`Except`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.except.aspx) and [`Distinct`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx). The sets you asked for in the question are respectively:
```
- array2.Except(array1)
- array1.Except(array2)
- array1.Intersect(array2)
``` | from the [MSDN 101 LINQ samples](http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#except1)....
```
public void Linq52() {
int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };
IEnumerable<int> aOnlyNumbers = numbersA.Except(numbersB);
Console.WriteLine("Numbers in first array but not second array:");
foreach (var n in aOnlyNumbers) {
Console.WriteLine(n);
}
}
``` | Getting the "diff" between two arrays in C#? | [
"",
"c#",
"arrays",
""
] |
I know that `WIN32` denotes win32 compilation but what is `_WIN32` used for? | `WIN32` is a name that you could use and even define in your own code and so might clash with Microsoft's usage. `_WIN32` is a name that is reserved for the implementor (in this case Microsoft) because it begins with an underscore and an uppercase letter - you are not allowed to define reserved names in your own code, so there can be no clash. | To elaborate (Neil Butterworth and blue.tuxedo have already given the correct answer):
* `WIN32` is defined by the SDK or the build environment, so it does not use the implementation reserved namespace
* `_WIN32` is defined by the **compiler** so it uses the underscore to place it in the implementation-reserved namespace
You'll find a similar set of dual defines with nearly identical names and similar uses such as `_UNICODE`/`UNICODE`, `_DEBUG`/`DEBUG`, or maybe `_DLL`/`DLL` (I think that only the UNICODE ones get much of any use in their different versions). Though sometimes in these cases (like `_UNICODE`), instead of the underscore version being defined *by* the compiler, they are used to control what the CRT headers do:
* `_UNICODE` tells the CRT headers that CRT names which can be either Unicode or ANSI (such as `_tcslen()` should map to the wide character variant (`wcslen()`)
* `UNICODE` does something similar for the SDK (maps Win32 APIs to their "`W`" variants)
Essentially the versions with the underscore are controlled by or used by the compiler team, the versions without the underscore are controlled/used by teams outside of the compiler. Of course, there's probably going to be a lot overlap due to compatibility with past versions and just general mistakes by one team or the other.
I find it confusing as hell - and find that they are used nearly interchangeably in user code (usually, when you see one defined, you'll see the other defined in the same place, because if you need one you need the other). Personally, I think that you should *use* the versions without the underscore (unless you're writing the compiler's runtime) and make sure they both get defined (whether via hearers or compiler switches as appropriate) when you're defining one.
---
Note that the SDK will define `_WIN32` when building for the Mac because the compiler doesn't, kind of overstepping it's bounds. I'm not sure what projects use a Win32 API an a compiler targeting the Mac - maybe some version of Office for the Mac or something. | What's the difference between the WIN32 and _WIN32 defines in C++ | [
"",
"c++",
"c-preprocessor",
""
] |
i'm using the mshtml dll to develop a helper to ie,
i'm trying to get the position of an htmll element,
i have an object with type of HTMLAnchorElementClass
when i'm trying to get his style.posTop value i get a null ref exception
is there a better way to do it?
maybe other cast?
please help | Here's an example I found (the way you're obtaining a reference to your element object is probably different, but take a look at this anyway:
```
Element = <however your get your element>;
//--- Determine real element size and position relative to the main page.
int ElementLeft = Element.offsetLeft;
int ElementTop = Element.offsetTop;
mshtml.IHTMLElement TmpElem = Element.offsetParent;
while (TmpElem != null)
{
ElementLeft = ElementLeft + TmpElem.offsetLeft;
ElementTop = ElementTop + TmpElem.offsetTop;
TmpElem = TmpElem.offsetParent;
}
``` | Try
```
element.offsetTop
element.offsetLeft
``` | get an html element top and left properties data | [
"",
"c#",
"html",
"mshtml",
""
] |
I'm experimenting with [CS-Script](http://www.csscript.net/) and my problem is that each time I run a script the console window is automatically closed when the script exits. How can I prevent this from happening? | If you don't want to change the script itself then open a command window and execute the script from the command line. The only reason the console closes after the script completes is because it was created by the script itself. The script will not close a console that you opened. | I don't how you call it but you can always call it with `"Ctrl + R" > cmd.exe /k [your command]` or `Console.ReadLine()` in your script. | Prevent command prompt from closing automatically (CS Script) | [
"",
"c#",
"scripting",
"command-prompt",
""
] |
Anyone know how to combine PHP prepared statements with LIKE? i.e.
`"SELECT * FROM table WHERE name LIKE %?%";` | The % signs need to go in the variable that you assign to the parameter, instead of in the query.
I don't know if you're using mysqli or PDO, but with PDO it would be something like:
```
$st = $db->prepare("SELECT * FROM table WHERE name LIKE ?");
$st->execute(array('%'.$test_string.'%'));
```
For `mysqli` user the following.
```
$test_string = '%' . $test_string . '%';
$st->bind_param('s', $test_string);
$st->execute();
``` | You can use the concatenation operator of your respective sql database:
```
# oracle
SELECT * FROM table WHERE name LIKE '%' || :param || '%'
# mysql
SELECT * from table WHERE name LIKE CONCAT('%', :param, '%')
```
I'm not familar with other databases, but they probably have an equivalent function/operator. | Combine PHP prepared statments with LIKE | [
"",
"php",
"sql-like",
""
] |
I have a C# winforms app that runs a macro in another program. The other program will continually pop up windows and generally make things look, for lack of a better word, crazy. I want to implement a cancel button that will stop the process from running, but I cannot seem to get the window to stay on top. How do I do this in C#?
Edit: I have tried `TopMost = true;` , but the other program keeps popping up its own windows over top. Is there a way to send my window to the top every n milliseconds?
Edit: The way I solved this was by adding a system tray icon that will cancel the process by double-clicking on it. The system tray icon does no get covered up. Thank you to all who responded. I read the article on why there is not a 'super-on-top' window... it logically does not work. | `Form.TopMost` will work unless the other program is creating topmost windows.
There is no way to create a window that is not covered by new topmost windows of another process. Raymond Chen [explained](https://devblogs.microsoft.com/oldnewthing/20050607-00/?p=35413) why. | I was searching to make my WinForms application "Always on Top" but setting "TopMost" did not do anything for me. I knew it was possible because WinAmp does this (along with a host of other applications).
What I did was make a call to "user32.dll." I had no qualms about doing so and it works great. It's an option, anyway.
First, import the following namespace:
```
using System.Runtime.InteropServices;
```
Add a few variables to your class declaration:
```
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
```
Add prototype for user32.dll function:
```
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
```
Then in your code (I added the call in Form\_Load()), add the call:
```
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
```
[Reference][1]
[1]: http://www.c-sharpcorner.com/uploadfile/kirtan007/make-form-stay-always-on-top-of-every-window/ | How to make a window always stay on top in .Net? | [
"",
"c#",
".net",
"winforms",
""
] |
I would like to have a text input form with a submit button that goes to paypal, upon payment the contents of the form should go in a mysql database..
This sounds trivial, but I'm having such a hard time with paypal's IPN.
Can anyone point in me in the right direction?
Thanks! | PayPal has some sample code on their website. However the bigger problem you'll face is that the user will probably want a real-time response. This is usually done by processing the PDT data that is submitted to your site when the user clicks the link to return to your site. At some point later PayPal will post to your IPN url similar data. You need to avoid processing the data twice.
Also the data in question is only PayPal's data about the transaction. It does not contain arbitrary data. You should probably record the customer's order before sending them to paypal, or else look for a pass-through variable. For example, when creating a billing agreement, there is a variable called `custom` which is passed back to you as you created it. You can store an order id or whatever you want in that variable. Be careful to validate its contents to make sure it's still correct for the transaction details. | You don't, and can't, get the entire contents of the form back from Paypal. What you will get is a postback to the address you sent in the "return" field. The best way to pass arbitrary information through the process from your form to the postback is in the "item\_number" field (preferably by using it as an ID in your database linked to whatever information you want to track). | Simple Paypal IPN examples? | [
"",
"php",
"paypal",
"paypal-ipn",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.