Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I want to create a c# application with multiple windows that are all transparent with some text on.
The tricky part is making these forms sit on top of the desktop but under the desktop icons. Is this possible?
|
Just making the window transparent is very straight forward:
```
this.BackColor = Color.Fuchsia;
this.TransparencyKey = Color.Fuchsia;
```
You can do something like this to make it so you can still interact with the desktop or anything else under your window:
```
public const int WM_NCHITTEST = 0x84;
public const int HTTRANSPARENT = -1;
protected override void WndProc(ref Message message)
{
if ( message.Msg == (int)WM_NCHITTEST )
{
message.Result = (IntPtr)HTTRANSPARENT;
}
else
{
base.WndProc( ref message );
}
}
```
|
Thanks for the tips Jeff. Its still not quite what I'm after. I would effectively like the window to appear as if it was part of the desktop so icons could sit on top of my form.
Maybe there is a different way to do it. Can I actually draw text and graphics directly on to the desktop?
|
Transparent form on the desktop
|
[
"",
"c#",
"winforms",
"window",
"desktop",
""
] |
In order to perform a case-sensitive search/replace on a table in a SQL Server 2000/2005 database, you must use the correct collation.
How do you determine whether the default collation for a database is case-sensitive, and if it isn't, how to perform a case-sensitive search/replace?
|
```
SELECT testColumn FROM testTable
WHERE testColumn COLLATE Latin1_General_CS_AS = 'example'
SELECT testColumn FROM testTable
WHERE testColumn COLLATE Latin1_General_CS_AS = 'EXAMPLE'
SELECT testColumn FROM testTable
WHERE testColumn COLLATE Latin1_General_CS_AS = 'eXaMpLe'
```
Don't assume the default collation will be case sensitive, just specify a case sensitive one every time (using the correct one for your language of course)
|
If you have **different cases** of the same word **in the same field**, and only want to **replace specific cases**, then you can use collation in your `REPLACE` function:
```
UPDATE tableName
SET fieldName =
REPLACE(
REPLACE(
fieldName COLLATE Latin1_General_CS_AS,
'camelCase' COLLATE Latin1_General_CS_AS,
'changedWord'
),
'CamelCase' COLLATE Latin1_General_CS_AS,
'ChangedWord'
)
```
This will result in:
```
This is camelCase 1 and this is CamelCase 2
```
becoming:
```
This is changedWord 1 and this is ChangedWord 2
```
|
How do I perform a case-sensitive search and replace in SQL 2000/2005?
|
[
"",
"sql",
"sql-server-2005",
"sql-server-2000",
"collation",
""
] |
In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.
I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. **I've narrowed it down to cake using this auto model feature instead of throwing and error**! So i have no idea what's wrong!
Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful!
|
**Cake 1.2**
It's a hack and it's ugly cus you need to edit core cake files but this is how i do it:
\cake\libs\class\_registry.php : line 127ish
```
if (App::import($type, $plugin . $class)) {
${$class} =& new $class($options);
} elseif ($type === 'Model') {
/* Print out whatever debug info we have then exit */
pr($objects);
die("unable to find class $type, $plugin$class");
/* We don't want to base this on the app model */
${$class} =& new AppModel($options);
}
```
**Cake 2**
Costa recommends changing $strict to true in the init function on line 95 of `Cake\Utility\ClassRegistry.php`
[See Cake Api Docs for init](http://api.cakephp.org/2.3/class-ClassRegistry.html#_init)
[ClassRegistry.php - init function](https://github.com/cakephp/cakephp/blob/c989624f8053f28d2ac37f5e84dc436965235177/lib/Cake/Utility/ClassRegistry.php#L96)
|
There's always the possibility to actually create the model file and set var $useTable = false.
If this is not what you're asking for and the model and its associations actually do exist, but Cake seems to be unable to find them, you'll have to triple check the names of all models and their class names in both the actual model definition and in the association definitions.
AFAIK you can't disable the auto modelling.
|
Disable Cakephp's Auto Model "feature"
|
[
"",
"php",
"cakephp",
"model",
"cakephp-1.2",
""
] |
How would I design and organize tests for the concrete methods of an abstract class? Specifically in .NET.
|
You have to create a subclass that implements the abstract methods (with empty methods), but none of the concrete ones. This subclass should be for testing only (it should never go into your production code). Just ignore the overridden abstract methods in your unit tests and concentrate on the concrete methods.
|
Use Rhino Mocks, it can generate implementations of the abstract class at runtime and you can call the non-abstract methods.
|
Testing Abstract Class Concrete Methods
|
[
"",
"c#",
".net",
"unit-testing",
""
] |
If I have a `std::vector` or `std::map` variable, and I want to see the contents, it's a big pain to see the nth element while debugging. Is there a plugin, or some trick to making it easier to watch STL container variables while debugging `(VS2003/2005/2008)`?
|
For vectors, this [thread](http://social.msdn.microsoft.com/forums/en-US/vsdebug/thread/c09f4fe4-4783-4dbb-8d36-85489fa2a4ae) on the msdn forums has a code snippet for setting a watch on a vector index that might help.
|
If you want to watch more than one element at the same time, you can append a comma and the number of elements as so:
`(v._Myfirst)[startIndex], count`
However, note that count must be a constant, it cannot be the result of another expression.
|
Inspecting STL containers in Visual Studio debugging
|
[
"",
"c++",
"visual-studio",
"debugging",
"stl",
""
] |
I'm having a problem with an application hanging and giving me the default "Please tell Microsoft about this problem" popup, instead of the "unhandled exception" dialog in the application.
In the application code, the Application.ThreadException and AppDomain.CurrentDomain.UnhandledException are both redirected to a method which writes an error log to disk, saves a screenshot to disk, and shows a friendly dialog box.
But when this error occurs, none of those three things happen. All I get is this in the event viewer:
*EventType clr20e3, P1 myapp.exe, P2 4.0.0.0, P3 47d794d4, P4 mscorlib, P5 2.0.0.0, P6 471ebc5b, P7 15e5, P8 27, P9 system.argumentoutofrange, P10 NIL*
Given that the error only seems to happen after the application has been running for several hours, I wonder if it may be a memory-leak problem. I've searched a bit for "clr20e3" but only managed to find ASP.Net stuff. My application is Windows Forms (.Net 2.0) exe, using quite a few assemblies - in both C# and some unmanaged C++.
I guess that it could also be an error in the error handling method - As some answers suggest, I may try logging at the start of error handler (but given that that is pretty much what I do anyway...).
Any help solving this problem would be much appreciated - whether it is solutions, or suggestions in how to find out what the root cause of the problem is.
UPDATE: The root cause of the original bug was accessing an array with a negative index (that was the system.argumentoutofrange). Why this was not trapped is a bit of a mystery to me, but given than both exceptions were sent to the same handling code, I wonder if there may not have been a condition where (for example) both were invoked and fought over a resource (the log file, for example)?
I managed to prove this much by doing an EventLog.WriteEntry before anything else in the error handling code. Having now added a flag to prevent re-entry in the error handling, I no longer appear to have a problem...
|
Just shooting in the dark here - is it possible that the ArgumentOutOfRangeException is actually thrown from your exception *handler*?
Additionally, you didn't say what type of application is in question -- Application.ThreadException only affects WinForms threads, so if this isn't a GUI application it's useless. (See the remarks section in the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx))
|
Have you checked whether the `ArgumentOutOfRangeException` is thrown from your handler itself? May be worthwhile doing a simple write to the event log or trace at the entry of your exception handler and confirm you're actually hitting it.
***Edit:*** Information to writing to the event log can be found at:
<http://support.microsoft.com/kb/307024>
|
Exception getting past Application.ThreadException and AppDomain.CurrentDomain.UnhandledException
|
[
"",
"c#",
"exception",
""
] |
Do you know any grid control compatible with .NET and Mono?
DataGridView seems to be quite buggy on Mono, and GTK# controls depends on GTK+ so you need to install it in windows machines where, usually, it's not present.
|
You might want to try out the preview of Mono 2.0. DataGridView is vastly better in this version, though there are still several places where it is still lacking.
<http://mono.ximian.com/monobuild/preview/download-preview/>
|
I tried mono 1.9.1 (Mono 2.0 beta) and had some problems with sorting, generated columns, and some nasty exceptions.
|
Grid controls compatible with .NET and Mono?
|
[
"",
"c#",
"datagrid",
"controls",
"mono",
""
] |
Here's my issue: I need to close a process, already running, from a C# program.
The problem is that the process now runs as an icon (minimized to taskbar), and unless the user opens it at least once (which will never happen on unattended machines), it'll never
have a main window.
The other requirement that I have is that the application be **closed** not **killed**. I need it to write it's memory buffers to disk - and killing it causes data loss.
Here's what I tried so far:
```
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.ToLower().StartsWith("myapp"))
{
if (proc.MainWindowHandle.ToInt32() != 0)
{
proc.CloseMainWindow();
proc.Close();
//proc.Kill(); <--- not good!
}
}
}
```
I've added the **if** clause, after discovering that **MainWindowHandle == 0** when the window was minimized. Removing the **if** doesn't help. Neither the **CloseMainWindow()** nor the **Close()** work. The **Kill()** does, but as mentioned above - it's not what I need.
Any idea would be accepted, including the use of arcane Win32 API functions :)
|
Here are some answers and clarifications:
**rpetrich**:
Tried your method before and the problem is, I don't know the window name, it differs from user to user, version to version - just the exe name remains constant. All I have is the process name. And as you can see in the code above the MainWindowHandle of the process is 0.
**Roger**:
Yes, I did mean the taskbar notification area - thanks for the clarification.
I *NEED* to call PostQuitMessage. I just don't know how, given a processs only, and not a Window.
**Craig**:
I'd be glad to explain the situation: the application has a command line interface, allowing you to specify parameters that dictate what it would do and where will it save the results. But once it's running, the only way to stop it and get the results is right-click it in the tray notification are and select 'exit'.
Now my users want to script/batch the app. They had absolutely no problem starting it from a batch (just specify the exe name and and a bunch of flags) but then got stuck with a running process. Assuming no one will change the process to provide an API to stop it while running (it's quite old), I need a way to artificially close it.
Similarly, on unattended computers, the script to start the process can be started by a task scheduling or operations control program, but there's no way to shut the process down.
Hope that clarifies my situation, and again, thanks everyone who's trying to help!
|
This should work:
```
[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr FindWindow(string className, string windowName);
[DllImport("user32.dll", CharSet=CharSet.Auto)]
private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
private const int WM_CLOSE = 0x10;
private const int WM_QUIT = 0x12;
public void SearchAndDestroy(string windowName)
{
IntPtr hWnd = FindWindow(null, windowName);
if (hWnd == IntPtr.Zero)
throw new Exception("Couldn't find window!");
SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
}
```
Since some windows don't respond to `WM_CLOSE`, `WM_QUIT` might have to be sent instead. These declarations should work on both 32bit and 64bit.
|
Closing a minimized/iconized process from C#
|
[
"",
"c#",
"winapi",
"process",
"kill",
""
] |
I use to run
```
$s =~ s/[^[:print:]]//g;
```
on Perl to get rid of non printable characters.
In Python there's no POSIX regex classes, and I can't write [:print:] having it mean what I want. I know of no way in Python to detect if a character is printable or not.
What would you do?
EDIT: It has to support Unicode characters as well. The string.printable way will happily strip them out of the output.
curses.ascii.isprint will return false for any unicode character.
|
Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The *unicodedata* module is quite helpful for this, especially the *unicodedata.category()* function. See [Unicode Character Database](http://www.unicode.org/reports/tr44/#General_Category_Values) for descriptions of the categories.
```
import unicodedata, re, itertools, sys
all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
```
For Python2
```
import unicodedata, re, sys
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))
control_char_re = re.compile('[%s]' % re.escape(control_chars))
def remove_control_chars(s):
return control_char_re.sub('', s)
```
For some use-cases, additional categories (e.g. all from the *control* group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:
* `Cc` (control): 65
* `Cf` (format): 161
* `Cs` (surrogate): 2048
* `Co` (private-use): 137468
* `Cn` (unassigned): 836601
***Edit** Adding suggestions from the comments.*
|
As far as I know, the most pythonic/efficient method would be:
```
import string
filtered_string = filter(lambda x: x in string.printable, myStr)
```
|
Stripping non printable characters from a string in python
|
[
"",
"python",
"string",
"non-printable",
""
] |
I've been working on this for a few days now, and I've found several solutions but none of them incredibly simple or lightweight. The problem is basically this: We have a cluster of 10 machines, each of which is running the same software on a multithreaded ESB platform. I can deal with concurrency issues between threads on the same machine fairly easily, but what about concurrency on the same data on different machines?
Essentially the software receives requests to feed a customer's data from one business to another via web services. However, the customer may or may not exist yet on the other system. If it does not, we create it via a web service method. So it requires a sort of test-and-set, but I need a semaphore of some sort to lock out the other machines from causing race conditions. I've had situations before where a remote customer was created twice for a single local customer, which isn't really desirable.
Solutions I've toyed with conceptually are:
1. Using our fault-tolerant shared file system to create "lock" files which will be checked for by each machine depending on the customer
2. Using a special table in our database, and locking the whole table in order to do a "test-and-set" for a lock record.
3. Using Terracotta, an open source server software which assists in scaling, but uses a hub-and-spoke model.
4. Using EHCache for synchronous replication of my in-memory "locks."
I can't imagine that I'm the only person who's ever had this kind of problem. How did you solve it? Did you cook something up in-house or do you have a favorite 3rd-party product?
|
you might want to consider using [Hazelcast](http://www.hazelcast.com) distributed locks. Super lite and easy.
```
java.util.concurrent.locks.Lock lock = Hazelcast.getLock ("mymonitor");
lock.lock ();
try {
// do your stuff
}finally {
lock.unlock();
}
```
Hazelcast - Distributed Queue, Map, Set, List, Lock
|
We use Terracotta, so I would like to vote for that.
I've been following Hazelcast and it looks like another promising technology, but can't vote for it since I've not used it, and knowing that it uses a P2P based system at its heard, I really would not trust it for large scaling needs.
But I have also heard of Zookeeper, which came out of Yahoo, and is moving under the Hadoop umbrella. If you're adventurous trying out some new technology this really has lots of promise since it's very lean and mean, focusing on just coordination. I like the vision and promise, though it might be too green still.
* <http://www.terracotta.org>
* <http://wiki.apache.org/hadoop/ZooKeeper>
* <http://www.hazelcast.com>
|
Distributed Concurrency Control
|
[
"",
"java",
"concurrency",
"load-balancing",
"scaling",
"terracotta",
""
] |
Is there a portable, not patent-restricted way to play compressed sound files in C# / .Net? I want to play short "jingle" sounds on various events occuring in the program.
[System.Media.SoundPlayer](http://msdn.microsoft.com/en-us/library/system.media.soundplayer.aspx) can handle only WAV, but those are typically to big to embed in a downloadable apllication. MP3 is protected with patents, so even if there was a fully managed decoder/player it wouldn't be free to redistribute. The best format available would seem to be OGG Vorbis, but I had no luck getting any C# Vorbis libraries to work (I managed to extract a raw PCM with [csvorbis](https://github.com/mono/csvorbis) but I don't know how to play it afterwards).
I neither want to distribute any binaries with my application nor depend on P/Invoke, as the project should run at least on Windows and Linux. I'm fine with bundling .Net assemblies as long as they are license-compatible with GPL.
[this question is a follow up to a [mailing list discussion on mono-dev](http://lists.ximian.com/pipermail/mono-devel-list/2007-June/023863.html) mailing list a year ago]
|
I finally revisited this topic, and, using help from [BrokenGlass on writing WAVE header](https://stackoverflow.com/a/7152153/3205), updated csvorbis. I've added an [OggDecodeStream](https://github.com/mono/csvorbis/blob/master/OggDecoder/OggDecodeStream.cs) that can be passed to `System.Media.SoundPlayer` to simply play any (compatible) Ogg Vorbis stream. Example usage:
```
using (var file = new FileStream(oggFilename, FileMode.Open, FileAccess.Read))
{
var player = new SoundPlayer(new OggDecodeStream(file));
player.PlaySync();
}
```
'Compatible' in this case means 'it worked when I tried it out'. The decoder is fully managed, works fine on Microsoft .Net - at the moment, there seems to be a regression in Mono's `SoundPlayer` that causes distortion.
Outdated:
~~`System.Diagnostics.Process.Start("fullPath.mp3");`~~
I am surprised but the [method Dinah mentioned](https://stackoverflow.com/questions/35896/how-can-i-play-compressed-sound-files-in-c-in-a-portable-way#35987) actually works. However, I was thinking about playing short "jingle" sounds on various events occurring in the program, I don't want to launch user's media player each time I need to do a 'ping!' sound.
As for the code project link - this is unfortunately only a P/Invoke wrapper.
|
> I neither want to distribute any
> binaries with my application nor
> depend on P/Invoke, as the project
> should run at least on Windows and
> Linux. I'm fine with bundling .Net
> assemblies as long as they are
> license-compatible with GPL.
Unfortunatly its going to be impossible to avoid distributing binaries, or avoid P/Invoke. The .net class libraries use P/Invoke underneath anyway, the managed code has to communicate with the unmanage operating system API at some point, in order to do anything.
Converting the OGG file to PCM should be possible in Managed code, but because there is no Native Support for Audio in .net, you really have 3 options:
1. Call an external program to play the sound (as suggested earlier)
2. P/Invoke a C module to play the sound
3. P/Invoke the OS APIs to play the sound.
(4.) If you're only running this code on windows you could probably just use DirectShow.
P/Invoke can be used in a cross platform way
<http://www.mono-project.com/Interop_with_Native_Libraries#Library_Names>
Once you have your PCM data (using a OGG C Lib or Managed Code, something like this <http://www.robburke.net/mle/mp3sharp/> of course there are licencing issues with MP3), you will need a way to play it, unfortunatly .net does not provide any direct assess to your sound card or methods to play streaming audio. You could convert the ogg files to PCM at startup, and then use System.Media.SoundPlayer, to play the wav files generated. The current method Microsoft suggests uses P/Invoke to access Sound playing API in the OS <http://msdn.microsoft.com/en-us/library/ms229685.aspx>
A cross platform API to play PCM sound is OpenAL and you should be able to play (PCM) sound using the c# bindings for OpenAL at www.taoframework.com, you will unfortunatly need to copy a number of DLL and .so files with your application in order for it to work when distributed, but this is, as i've explained earlier unavoidable.
|
How can I play compressed sound files in C# in a portable way?
|
[
"",
"c#",
".net",
"mono",
"audio",
"oggvorbis",
""
] |
It's [shown](http://www.codeproject.com/KB/cs/csharpcasts.aspx) that 'as' casting is much faster than prefix casting, but what about 'is' reflection? How bad is it? As you can imagine, searching for 'is' on Google isn't terribly effective.
|
There are a few options:
1. The **classic cast**: `Foo foo = (Foo)bar`
2. The **`as` cast operator**: `Foo foo = bar as Foo`
3. The **`is` test**: `bool is = bar is Foo`
---
1. The **classic cast** needs to check if `bar` can be safely cast to `Foo` (quick), and then actually do it (slower), or throw an exception (really slow).
2. The **`as` operator** needs to check if `bar` can be cast, then do the cast, or if it cannot be safely cast, then it just returns `null`.
3. The **`is` operator** just checks if `bar` can be cast to Foo, and return a `boolean`.
The **`is`** test is quick, because it only does the first part of a full casting operation. The **`as`** operator is quicker than a classic cast because doesn't throw an exception if the cast fails (which makes it good for situations where you legitimately expect that the cast might fail).
If you just need to know if the variable `bar`is a `Foo` then use the **`is`** operator, **BUT**, if you're going to test if `bar` is a `Foo`, and if so, **then cast it**, then you should use the **`as`** operator.
Essentially every cast needs to do the equivalent of an `is` check internally to begin with, in order to ensure that the cast is valid. So if you do an `is` check followed by a full cast (either an `as` cast, or with the classic cast operator) you are effectively doing the `is` check twice, which is a slight extra overhead.
|
The way I learned it is that this:
```
if (obj is Foo) {
Foo f = (Foo)obj;
f.doSomething();
}
```
is slower than this:
```
Foo f = obj as Foo;
if (f != null) {
f.doSomething();
}
```
Is it slow enough to matter? Probably not, but it's such a simple thing to pay attention for, that you might as well do it.
|
What are the performance characteristics of 'is' reflection in C#?
|
[
"",
"c#",
"reflection",
""
] |
I'm doing some web scraping and sites frequently use HTML entities to represent non ascii characters. Does Python have a utility that takes a string with HTML entities and returns a unicode type?
For example:
I get back:
```
ǎ
```
which represents an "ǎ" with a tone mark. In binary, this is represented as the 16 bit 01ce. I want to convert the html entity into the value `u'\u01ce'`
|
The standard lib’s very own HTMLParser has an undocumented function unescape() which does exactly what you think it does:
up to Python 3.4:
```
import HTMLParser
h = HTMLParser.HTMLParser()
h.unescape('© 2010') # u'\xa9 2010'
h.unescape('© 2010') # u'\xa9 2010'
```
Python 3.4+:
```
import html
html.unescape('© 2010') # u'\xa9 2010'
html.unescape('© 2010') # u'\xa9 2010'
```
|
Python has the [htmlentitydefs](https://docs.python.org/2/library/htmllib.html#module-htmlentitydefs) module, but this doesn't include a function to unescape HTML entities.
Python developer Fredrik Lundh (author of elementtree, among other things) has such a function [on his website](http://effbot.org/zone/re-sub.htm#unescape-html), which works with decimal, hex and named entities:
```
import re, htmlentitydefs
##
# Removes HTML or XML character references and entities from a text string.
#
# @param text The HTML (or XML) source text.
# @return The plain text, as a Unicode string, if necessary.
def unescape(text):
def fixup(m):
text = m.group(0)
if text[:2] == "&#":
# character reference
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
else:
# named entity
try:
text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
except KeyError:
pass
return text # leave as is
return re.sub("&#?\w+;", fixup, text)
```
|
Convert XML/HTML Entities into Unicode String in Python
|
[
"",
"python",
"html",
"entities",
""
] |
I have a legacy C++ module that offers encryption/decryption using the openssl library (DES encryption). I'm trying to translate that code into java, and I don't want to rely on a DLL, JNI, etc...
C++ code looks like:
```
des_string_to_key(reinterpret_cast<const char *>(key1), &initkey);
des_string_to_key(reinterpret_cast<const char *>(key2), &key);
key_sched(&key, ks);
// ...
des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
return base64(reinterpret_cast<const unsigned char *>(encrypted_buffer), strlen(encrypted_buffer));
```
Java code looks like:
```
Cipher ecipher;
try {
ecipher = Cipher.getInstance("DES");
SecretKeySpec keySpec = new SecretKeySpec(key, "DES");
ecipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] utf8 = password.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch {
// ...
}
```
So I can do DES encryption in Java pretty easily, but how can I get the same result as with the above code with methods that are completely different? What bothers me in particular is the fact that the C++ version uses 2 keys while the Java version uses only 1 key.
The answer about DES in CBC mode is quite satisfying but I can't get it to work yet.
Here are more details about the original code:
unsigned char key1[10]= {0};
unsigned char key2[50]= {0};
```
int i;
for (i=0;i<8;i++)
key1[i] = 31+int((i*sqrt((double)i*5)))%100;
key1[9]=0;
for (i=0;i<48;i++)
key2[i] = 31+int((i*i*sqrt((double)i*2)))%100;
key2[49]=0;
...
// Initialize encrypted buffer
memset(encrypted_buffer, 0, sizeof(encrypted_buffer));
// Add begin Text and End Text to the encrypted message
std::string input;
const char beginText = 2;
const char endText = 3;
input.append(1,beginText);
input.append(bufferToEncrypt);
input.append(1,endText);
// Add padding
tmp.assign(desPad(input));
des_ncbc_encrypt(reinterpret_cast<const unsigned char *>(tmp.c_str()),
reinterpret_cast< unsigned char *>(encrypted_buffer), tmp.length(), ks, &initkey,
DES_ENCRYPT);
...
```
From what I've read, the key should be 56 (or 64, it's not clear to me) bits long, but here it's 48 bytes long.
|
I'm not an OpenSSL expert, but I'd guess the C++ code is using DES in CBC mode thus needing an IV (that's what the initKey probably is, and that's why you think you need two keys). If I'm right, you need to change your Java code to use DES in CBC mode too, then the Java code too will require an encryption key and an IV.
|
Also, keep in mind that you really shouldn't use sun.misc.\* classes in your code. This could break in other VMs as these are not public APIs. Apache Commons Codecs (among others) have implementations of Base64 that don't bear this problem.
I'm not really sure why single DES would ever use multiple keys. Even if you were using Triple-DES, I believe you would use a single key (with more bytes of data) rather than using separate keys with the Java Cryptography API.
|
Using openssl encryption with Java
|
[
"",
"java",
"encryption",
"openssl",
""
] |
Working on a project at the moment and we have to implement soft deletion for the majority of users (user roles). We decided to add an `is_deleted='0'` field on each table in the database and set it to `'1'` if particular user roles hit a delete button on a specific record.
For future maintenance now, each `SELECT` query will need to ensure they do not include records `where is_deleted='1'`.
Is there a better solution for implementing soft deletion?
Update: I should also note that we have an Audit database that tracks changes (field, old value, new value, time, user, ip) to all tables/fields within the Application database.
|
You could perform all of your queries against a view that contains the `WHERE IS_DELETED='0'` clause.
|
I would lean towards a `deleted_at` column that contains the **datetime of when the deletion took place**. Then you get a little bit of free metadata about the deletion. For your `SELECT` just get rows `WHERE deleted_at IS NULL`
|
What is the best way to implement soft deletion?
|
[
"",
"sql",
"database",
"database-design",
"backup",
""
] |
I create a new Button object but did not specify the `command` option upon creation. Is there a way in Tkinter to change the command (onclick) function after the object has been created?
|
Though [Eli Courtwright's](https://stackoverflow.com/questions/68327/change-command-method-for-tkinter-button-in-python#68455) program will work fine¹, what you really seem to want though is just a way to reconfigure after instantiation any attribute which you could have set when you instantiated². How you do so is by way of the configure() method.
```
from Tkinter import Tk, Button
def goodbye_world():
print "Goodbye World!\nWait, I changed my mind!"
button.configure(text = "Hello World!", command=hello_world)
def hello_world():
print "Hello World!\nWait, I changed my mind!"
button.configure(text = "Goodbye World!", command=goodbye_world)
root = Tk()
button = Button(root, text="Hello World!", command=hello_world)
button.pack()
root.mainloop()
```
¹ "fine" if you use only the mouse; if you care about tabbing and using [Space] or [Enter] on buttons, then you will have to implement (duplicating existing code) keypress events too. Setting the `command` option through `.configure` is much easier.
² the only attribute that can't change after instantiation is `name`.
|
Sure; just use the `bind` method to specify the callback after the button has been created. I've just written and tested the example below. You can find a nice tutorial on doing this at <http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm>
```
from Tkinter import Tk, Button
root = Tk()
button = Button(root, text="Click Me!")
button.pack()
def callback(event):
print "Hello World!"
button.bind("<Button-1>", callback)
root.mainloop()
```
|
Change command Method for Tkinter Button in Python
|
[
"",
"python",
"user-interface",
"tkinter",
""
] |
I'm getting a random unreproducible Error when initializing a `JSplitPane` in with JDK 1.5.0\_08. Note that this does not occur every time, but about 80% of the time:
```
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.KeyStroke
at java.util.TreeMap.compare(TreeMap.java:1093)
at java.util.TreeMap.put(TreeMap.java:465)
at java.util.TreeSet.add(TreeSet.java:210)
at javax.swing.plaf.basic.BasicSplitPaneUI.installDefaults(BasicSplitPaneUI.java:364)
at javax.swing.plaf.basic.BasicSplitPaneUI.installUI(BasicSplitPaneUI.java:300)
at javax.swing.JComponent.setUI(JComponent.java:652)
at javax.swing.JSplitPane.setUI(JSplitPane.java:350)
at javax.swing.JSplitPane.updateUI(JSplitPane.java:378)
at javax.swing.JSplitPane.<init>(JSplitPane.java:332)
at javax.swing.JSplitPane.<init>(JSplitPane.java:287)
...
```
Thoughts? I've tried cleaning and rebuilding my project so as to minimize the probability of corrupted class files.
Looking at [JDK-6434148 : ClassCastException thrown while running SwingSet2 demo](https://bugs.java.com/bugdatabase/view_bug?bug_id=6434148), this seems to be a JDK bug. Any known workarounds? None are listed on the bug entry page.
|
After doing some searching in the [Java Bug Database](https://bugs.java.com/bugdatabase/), this looks like this might be a JDK bug that was only fixed in JDK 6.
See [JDK-6434148 : ClassCastException thrown while running SwingSet2 demo](https://bugs.java.com/bugdatabase/view_bug?bug_id=6434148).
|
Same exception had got thrown when i had upgraded java verion and db visualizer dint support jre7. and since
Support for Java 7 was introduced in DbVisualizer 8.0 for Windows and Linux/UNIX.
Support for Java 7 on Mac OS X was introduced in DbVisualizer 9.1.
So Solution that worked for me :
**Windows/Unix/Linux:**
In the DbVisualizer installation directory there is an .install4j directory,
In this directory create a file named pref\_jre.cfg if it doesn't already exist,
Open the file in a text editor,
Add the complete path to the root directory for the Java installation you want to use.
Example: C:\Program Files\Java\jre7
|
Getting java.lang.ClassCastException: javax.swing.KeyStroke when creating a JSplitPane
|
[
"",
"java",
"swing",
"java-5",
"jsplitpane",
""
] |
What's the best way for determining whether the user's browser can view PDF files?
Ideally, it shouldn't matter on the browser or the operating system.
Is there a specific way of doing it in ASP.NET, or would the answer be just JavaScript?
|
Neither, none, don't try.
Re [dawnerd](https://stackoverflow.com/questions/76179/how-to-determine-if-the-users-browser-can-view-pdf-files#76220): Plug-in detection is not the right answer. I do not have a PDF plugin installed in my browser (Firefox on Ubuntu), yet I am able to view PDF files using the operating system's document viewer (which is not Acrobat Reader).
Today, any operating system that can run a web browser can view PDF files out of the box.
If a specific system does not have a PDF viewer installed and the browser configured to use it, that likely means that either it's a hand-made install of Windows, a very trimmed down alternate operating system, or something really retro.
It is reasonable to assume that in any of those situation the user will know what a PDF file is and either deliberately choose not to be able to view them or know how to install the required software.
If I am deluding myself, I would love to have it explained to me in which way I am wrong.
|
A quick google search [found this](http://www.oreillynet.com//cs/user/view/cs_msg/9920). Useful for all kinds of plugins.
|
How to determine if the user's browser can view PDF files
|
[
"",
"asp.net",
"javascript",
"pdf",
"browser",
""
] |
I want to do this:
```
e.className = t;
```
Where t is the name of a style I have defined in a stylesheet.
|
If `e` is a reference to a DOM element and you have a class like this: `.t {color:green;}` then you want reference the class name as a string:
```
e.className = 't';
```
|
Yes, that works (with the class name as a string, as jonah mentioned). Also, you can set style attributes directly on an object, using the [DOM Level 2 Style](http://www.w3.org/TR/DOM-Level-2-Style/) interface. e.g.,
```
button.style.fontFamily = "Verdana, Arial, sans-serif";
```
where `button` is (presumably) a button object. :-)
|
Can an element's CSS class be set via JavaScript?
|
[
"",
"javascript",
"css",
""
] |
I have a Cocoa app that uses a WebView to display an HTML interface. How would I go about calling an Objective-C method from a Javascript function within the HTML interface?
|
This is documented at [developer.apple.com](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/JavaScriptFromObjC.html).
|
Being rather green, Apple's documentation is pretty unusable for me, so I made a proof of concept of calling Objective C methods from javascript and vice versa in Cocoa, though the latter was much easier.
First make sure you have your webview as the setFrameLoadDelegate:
```
[testWinWebView setFrameLoadDelegate:self];
```
You need to tell the webview to watch for a specific object as soon as it's loaded:
```
- (void)webView:(WebView *)sender didClearWindowObject:(WebScriptObject *)windowScriptObject forFrame:(WebFrame *)frame {
//add the controller to the script environment
//the "ObjCConnector" object will now be available to JavaScript
[windowScriptObject setValue:self forKey:@"ObjCConnector"];
}
```
Then the business of the communication:
```
// a few methods to log activity
- (void)acceptJavaScriptFunctionOne:(NSString*) logText {
NSLog(@"acceptJavaScriptFunctionOne: %@",logText);
}
- (void)acceptJavaScriptFunctionTwo:(NSString*) logText {
NSLog(@"acceptJavaScriptFunctionTwo: %@",logText);
}
//this returns a nice name for the method in the JavaScript environment
+(NSString*)webScriptNameForSelector:(SEL)sel {
NSLog(@"%@ received %@ with sel='%@'", self, NSStringFromSelector(_cmd), NSStringFromSelector(sel));
if(sel == @selector(acceptJavaScriptFunctionOne:))
return @"functionOne"; // this is what you're sending in from JS to map to above line
if(sel == @selector(acceptJavaScriptFunctionTwo:))
return @"functionTwo"; // this is what you're sending in from JS to map to above line
return nil;
}
//this allows JavaScript to call the -logJavaScriptString: method
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)sel {
NSLog(@"isSelectorExcludedFromWebScript: %@", NSStringFromSelector(sel));
if(sel == @selector(acceptJavaScriptFunctionOne:) ||
sel == @selector(acceptJavaScriptFunctionTwo:))
return NO;
return YES;
}
```
The key is that if you have multiple methods you'd like to call, you need to have them all excluded in the isSelectorExcludedFromWebScript method, and you need the javascript call to map out to the ObjC method in webScriptNameForSelector.
Full project proof of concept file:
<https://github.com/bytestudios/JS-function-and-ObjC-method-connector>
|
How to call an Objective-C method from Javascript in a Cocoa/WebKit app?
|
[
"",
"javascript",
"objective-c",
"cocoa",
"webkit",
""
] |
first question here. I'm developing a program in C# (.NET 3.5) that displays files in a listview. I'd like to have the "large icon" view display the icon that Windows Explorer uses for that filetype, otherwise I'll have to use some existing code like this:
```
private int getFileTypeIconIndex(string fileName)
{
string fileLocation = Application.StartupPath + "\\Quarantine\\" + fileName;
FileInfo fi = new FileInfo(fileLocation);
switch (fi.Extension)
{
case ".pdf":
return 1;
case ".doc": case ".docx": case ".docm": case ".dotx":case ".dotm": case ".dot":case ".wpd": case ".wps":
return 2;
default:
return 0;
}
}
```
The above code returns an integer that is used to select an icon from an imagelist that I populated with some common icons. It works fine but I'd need to add every extension under the sun! Is there a better way? Thanks!
|
You might find the use of [Icon.ExtractAssociatedIcon](http://msdn.microsoft.com/en-us/library/system.drawing.icon.extractassociatedicon.aspx) a much simpler (an managed) approach than using SHGetFileInfo. But watch out: two files with the same extension may have different icons.
|
The file icons are held in the registry. It's a little convoluted but it works something like
* Take the file extension and lookup
the registry entry for it, for
example .DOC Get the default value
for that registry setting,
"Word.Document.8"
* Now lookup that
value in the registry.
* Look at the
default value for the "Default Icon"
registry key, in this case,
C:\Windows\Installer{91120000-002E-0000-0000-0000000FF1CE}\wordicon.exe,1
* Open the file and get the icon,
using any number after the comma as
the indexer.
There is some sample code at on [CodeProject](http://www.codeproject.com/KB/cs/GetFileTypeAndIcon.aspx?display=Print)
|
How can I get the filetype icon that Windows Explorer shows?
|
[
"",
"c#",
"winforms",
""
] |
I'm writing a C parser using PLY, and recently ran into a problem.
This code:
```
typedef int my_type;
my_type x;
```
Is correct C code, because my\_type is defined as a type previously to
being used as such. I handle it by filling a type symbol table in the
parser that gets used by the lexer to differentiate between types and
simple identifiers.
However, while the type declaration rule ends with SEMI (the ';' token), PLY shifts the token `my_type` from the second line before deciding it's done with the first one. Because of this, I have no chance to pass the update in the type symbol table to the lexer and it
sees my\_type as an identifier and not a type.
Any ideas for a fix ?
The full code is at: <http://code.google.com/p/pycparser/source/browse/trunk/src/c_parser.py>
Not sure how I can create a smaller example out of this.
**Edit:**
Problem solved. See my solution below.
|
With [some help](http://groups.google.com/group/ply-hack/tree/browse_frm/thread/cf31e8334801eabd/b9cdf4a6682635c1?rnum=1&_done=%2Fgroup%2Fply-hack%2Fbrowse_frm%2Fthread%2Fcf31e8334801eabd%3F#doc_5c415da045e77a6e) from Dave Beazley (PLY's creator), my problem was solved.
The idea is to use special sub-rules and do the actions in them. In my case, I split the `declaration` rule to:
```
def p_decl_body(self, p):
""" decl_body : declaration_specifiers init_declarator_list_opt
"""
# <<Handle the declaration here>>
def p_declaration(self, p):
""" declaration : decl_body SEMI
"""
p[0] = p[1]
```
`decl_body` is always reduced before the token after SEMI is shifted in, so my action gets executed at the correct time.
|
Not sure why you're doing that level of analysis in your lexer.
Lexical analysis should probably be used to separate the input stream into lexical tokens (number, line-change, keyword and so on). It's the parsing phase that should be doing that level of analysis, including table lookups for typedefs and such.
That's the way I've always separated the duties between lexx and yacc, my tools of choice.
|
PLY: Token shifting problem in C parser
|
[
"",
"python",
"parsing",
"yacc",
"ply",
""
] |
When I enter an object into the DB with Linq-to-SQL can I get the id that I just inserted without making another db call? I am assuming this is pretty easy, I just don't know how.
|
After you commit your object into the db the object receives a value in its ID field.
So:
```
myObject.Field1 = "value";
// Db is the datacontext
db.MyObjects.InsertOnSubmit(myObject);
db.SubmitChanges();
// You can retrieve the id from the object
int id = myObject.ID;
```
|
When inserting the generated ID is saved into the instance of the object being saved (see below):
```
protected void btnInsertProductCategory_Click(object sender, EventArgs e)
{
ProductCategory productCategory = new ProductCategory();
productCategory.Name = “Sample Category”;
productCategory.ModifiedDate = DateTime.Now;
productCategory.rowguid = Guid.NewGuid();
int id = InsertProductCategory(productCategory);
lblResult.Text = id.ToString();
}
//Insert a new product category and return the generated ID (identity value)
private int InsertProductCategory(ProductCategory productCategory)
{
ctx.ProductCategories.InsertOnSubmit(productCategory);
ctx.SubmitChanges();
return productCategory.ProductCategoryID;
}
```
reference: <http://blog.jemm.net/articles/databases/how-to-common-data-patterns-with-linq-to-sql/#4>
|
Can I return the 'id' field after a LINQ insert?
|
[
"",
"c#",
".net",
"linq",
"linq-to-sql",
""
] |
I have a text file on my local machine that is generated by a daily Python script run in cron.
I would like to add a bit of code to have that file sent securely to my server over SSH.
|
You can call the [`scp`](https://en.wikipedia.org/wiki/Secure_copy) bash command (it copies files over [SSH](https://en.wikipedia.org/wiki/Secure_Shell)) with [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run):
```
import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "joe@srvr.net:/path/to/foo.bar"])
```
If you're creating the file that you want to send in the same Python program, you'll want to call `subprocess.run` command outside the `with` block you're using to open the file (or call `.close()` on the file first if you're not using a `with` block), so you know it's flushed to disk from Python.
You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).
|
To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the [Paramiko](https://github.com/paramiko/paramiko) library, you would do something like this:
```
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(server, username=username, password=password)
sftp = ssh.open_sftp()
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
```
(You would probably want to deal with unknown hosts, errors, creating any directories necessary, and so on).
|
How to copy a file to a remote server in Python using SCP or SSH?
|
[
"",
"python",
"ssh",
"automation",
"scp",
""
] |
Here's a problem I've been trying to solve at work. I'm not a database expert, so that perhaps this is a bit sophomoric. All apologies.
I have a given database D, which has been duplicated on another machine (in a perhaps dubious manner), resulting in database D'. It is my task to check that database D and D' are in fact exactly identical.
The problem, of course, is what to actually do if they are not. For this purpose, my thought was to run a symmetric difference on each corresponding table and see the differences.
There is a "large" number of tables, so I do not wish to run each symmetric difference by hand. How do I then implement a symmetric difference "function" (or stored procedure, or whatever you'd like) that can run on arbitrary tables without having to explicitly enumerate the columns?
This is running on Windows, and your hedge fund will explode if you don't follow through. Good luck.
|
My first reaction is to suggest duplicating to the other machine again in a non-dubious manner.
If that is not an option, perhaps some of the tools available from [Red Gate](http://www.red-gate.com/products/index.htm) could do what you need.
(I am in no way affliated with Red Gate, just remember Joel mentioning how good their tools were on the podcast.)
|
Here is the solution. The example data is from the ReportServer database that comes with SSRS 2008 R2, but you can use it on any dataset:
```
SELECT s.name, s.type
FROM
(
SELECT s1.name, s1.type
FROM syscolumns s1
WHERE object_name(s1.id) = 'executionlog2'
UNION ALL
SELECT s2.name, s2.type
FROM syscolumns s2
WHERE object_name(s2.id) = 'executionlog3'
) AS s
GROUP BY s.name, s.type
HAVING COUNT(s.name) = 1
```
|
Implement symmetric difference in SQL Server?
|
[
"",
"sql",
"sql-server",
""
] |
I just installed Ubuntu 8.04 and Eclipse.
I made a very simple Hello World program in order to ensure that everything is running smoothly. When I attempted to use the Scanner class for acquiring some user input I got a very odd error.
My code:
```
import java.util.Scanner;
class Test {
public static void main (String [] args) {
Scanner sc = new Scanner(System.in);
System.out.println("hi");
}
}
```
Error message
```
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Scanner cannot be resolved to a type
Scanner cannot be resolved to a type
at test.main(test.java:5)
```
|
The Scanner class is new in Java 5. I do not know what Hardy's default Java environment is, but it is not Sun's and therefore may be outdated.
I recommend installing the package sun-java6-jdk to get the most up-to-date version, then telling Eclipse to use it.
|
It could also be that although you are have JDK 1.5 or higher, the project has some specific settings set that tell it to compile as 1.4. You can test this via Project >> Properties >> Java Compiler and ensure the "Compiler Compliance Level" is set to 1.5 or higher.
|
Scanner cannot be resolved to a type
|
[
"",
"java",
"eclipse",
"ubuntu",
""
] |
I want to port data from one server's database to another server's database.
The databases are both on a different mssql 2005 server.
Replication is probably not an option since the destination database is generated from scratch on a [time interval] basis.
Preferebly I would do something like
```
insert *
from db1/table1
into db2/table2
where rule1 = true
```
It's obvious that connection credentials would go in somehwere in this script.
|
I think what you want to do is create a linked server as per [this webarchive snapshot of msdn article from 2015](http://web.archive.org/web/20150628090613/https://msdn.microsoft.com/en-us/library/aa213778(SQL.80).aspx) or [this article from learn.microsoft.com](https://learn.microsoft.com/en-us/sql/relational-databases/linked-servers/create-linked-servers-sql-server-database-engine?view=sql-server-ver15). You would then select using a 4 part object name eg:
```
Select * From ServerName.DbName.SchemaName.TableName
```
|
You can use Open Data Source Like this :
```
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
EXEC sp_configure 'Ad Hoc Distributed Queries', 1
GO
RECONFIGURE
GO
SELECT *
FROM OPENDATASOURCE('SQLOLEDB',
'Data Source=<Ip Of Your Server>;
User ID=<SQL User Name>;Password=<SQL password>').<DataBase name>.<SchemaName>.<Table Or View Name>
Go
```
|
Cross-server SQL
|
[
"",
"sql",
"sql-server",
"t-sql",
"linked-server",
"cross-server",
""
] |
Okay, I've seen but haven't programmed in C# before. You can assume I'm competent in C++, and advanced in C (for what good that'll do me). I understand inheritance, polymorphism, etc so OO concepts aren't going to be a huge problem.
Let's say I've been given a task to prototype a quick and dirty program that won't be much different than what I could do in access in a short time.
* It'll have a DB with 5-6 tables (mostly small, a few with have several thousand rows but only 4 or so columns, etc)
* I'll need to have forms generated dynamically from one of the DBs
* The results of the forms will be stored in another table
* The DB isn't multiuser
Basically your run of the mill access app... except without access. I'm sure I can muddle my way through and create horrendously bad code, but I'm equally sure lots of people here can give me a push in the right direction (tutorials, wizards, info, differences and killers moving from C/C++ to C#, etc).
Is there a simple DB I can plug in to get started aside from mdb, or is that the best choice for this particular nail? I'm aiming for a quick and dependency-less install.
Thanks!
-Adam
|
It sounds like for this app, you could use [Microsoft Dynamic Data](http://www.asp.net/dynamicdata/) or [Castle Active Record](http://www.castleproject.org/activerecord/index.html), and have the application working a few minutes after you finished the database. These tools connect to a database and generate forms for inputing data. Take a look at them.
Access is probably your best choice for database. MS Sql 2005/2008 Express would also work well, but that would require an install.
|
If you're programming in C#, Visual Studio comes with an added install for SQL Server Express. If you're looking to get something up quick and dirty, it would pretty easy to leverage that database in building your app.
|
Quick C# prototype program with simple DB
|
[
"",
"c#",
"database",
"prototype",
""
] |
Greetings.
I'm looking for a way to parse a number of XML files in a particular directory with ASP.NET (C#). I'd like to be able to return content from particular elements, but before that, need to find those that have a certain value between an element.
Example XML file 1:
```
<file>
<title>Title 1</title>
<someContent>Content</someContent>
<filter>filter</filter>
</file>
```
Example XML file 2:
```
<file>
<title>Title 2</title>
<someContent>Content</someContent>
<filter>filter, different filter</filter>
</file>
```
Example case 1:
Give me all XML that has a filter of 'filter'.
Example case 2:
Give me all XML that has a title of 'Title 1'.
Looking, it seems this should be possible with LINQ, but I've only seen examples on how to do this when there is one XML file, not when there are multiples, such as in this case.
I would prefer that this be done on the server-side, so that I can cache on that end.
Functionality from any version of the .NET Framework can be used.
Thanks!
~James
|
If you are using .Net 3.5, this is extremely easy with LINQ:
```
//get the files
XElement xe1 = XElement.Load(string_file_path_1);
XElement xe2 = XElement.Load(string_file_path_2);
//Give me all XML that has a filter of 'filter'.
var filter_elements1 = from p in xe1.Descendants("filter") select p;
var filter_elements2 = from p in xe2.Descendants("filter") select p;
var filter_elements = filter_elements1.Union(filter_elements2);
//Give me all XML that has a title of 'Title 1'.
var title1 = from p in xe1.Descendants("title") where p.Value.Equals("Title 1") select p;
var title2 = from p in xe2.Descendants("title") where p.Value.Equals("Title 1") select p;
var titles = title1.Union(title2);
```
This can all be written shorthand and get you your results in just 4 lines total:
```
XElement xe1 = XElement.Load(string_file_path_1);
XElement xe2 = XElement.Load(string_file_path_2);
var _filter_elements = (from p1 in xe1.Descendants("filter") select p1).Union(from p2 in xe2.Descendants("filter") select p2);
var _titles = (from p1 in xe1.Descendants("title") where p1.Value.Equals("Title 1") select p1).Union(from p2 in xe2.Descendants("title") where p2.Value.Equals("Title 1") select p2);
```
These will all be IEnumerable lists, so they are super easy to work with:
```
foreach (var v in filter_elements)
Response.Write("value of filter element" + v.Value + "<br />");
```
LINQ rules!
|
You might want to create your own iterator class that iterate over those files.
Say, make a XMLContentEnumerator : IEnumerable. that would iterate over files in a specific directory and parse its content, and then you would be able to make a normal LINQ filtering query such as:
```
var xc = new XMLContentEnumerator(@"C:\dir");
var filesWithHello = xc.Where(x => x.title.Contains("hello"));
```
I don't have the environment to provide a full example, but this should give some ideas.
|
Parse multiple XML files with ASP.NET (C#) and return those with particular element
|
[
"",
"c#",
"asp.net",
"xml",
""
] |
Does anybody have experience of a decent J2SE (preferably at least Java JDK 1.5-level) Java Virtual Machine for Windows Mobile 6? If you know of any CLDC VMs, I'm also interested because even that would be better than what we [currently have](http://www.nsicom.com/Default.aspx?tabid=138) for the platform.
|
Yes, I've tried doing things with Java on Windows Mobile. I tried really hard. The best advise I can give you is: Stop right now, and start using .NET Compact Framework.
Anyway, the two 'good' JVMs for WM are [IBM-J9](http://www-01.ibm.com/software/wireless/weme/) and NSICom Creme, which still are both terribile to work with. You've already seen Creme - IBM-J9 isn't much better. They are slow, clumsy, not native looking and hard to install for end users. Also don't ever think of doing exotic things like dialing a phonenumber or even launching another application. If you really want to try, there's an evaluation version of J9 available [here](http://www-128.ibm.com/developerworks/websphere/zones/wireless/weme_eval_runtimes.html?S_CMP=rnav). (which is identical to the full version).
I'm not against Java in any way, but on Windows Mobile i recommend saving the trouble and using C#.
|
Honestly I searched a while and there no decent JVM for windows mobile. The best bet I think is this : <http://www2s.biglobe.ne.jp/~dat/java/project/jvm/index_en.html> but it's JDK 1.3 compliant the last time I checked.
|
Windows Mobile 6 J2SE-scale JVM implementation
|
[
"",
"windows-mobile",
"java-me",
"java",
""
] |
I am working on a project where the requirement is to have a date calculated as being the last Friday of a given month. I think I have a solution that only uses standard Java, but I was wondering if anyone knew of anything more concise or efficient. Below is what I tested with for this year:
```
for (int month = 0; month < 13; month++) {
GregorianCalendar d = new GregorianCalendar();
d.set(d.MONTH, month);
System.out.println("Last Week of Month in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + d.getLeastMaximum(d.WEEK_OF_MONTH));
d.set(d.DAY_OF_WEEK, d.FRIDAY);
d.set(d.WEEK_OF_MONTH, d.getActualMaximum(d.WEEK_OF_MONTH));
while (d.get(d.MONTH) > month || d.get(d.MONTH) < month) {
d.add(d.WEEK_OF_MONTH, -1);
}
Date dt = d.getTime();
System.out.println("Last Friday of Last Week in " + d.getDisplayName(d.MONTH, Calendar.LONG, Locale.ENGLISH) + ": " + dt.toString());
}
```
|
Based on [marked23's](https://stackoverflow.com/questions/76223/get-last-friday-of-month-in-java#76437) suggestion:
```
public Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month + 1, 1 );
cal.add( Calendar.DAY_OF_MONTH, -( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 1 ) );
return cal.getTime();
}
```
|
Let Calendar.class do its magic for you ;)
```
pCal.set(GregorianCalendar.DAY_OF_WEEK,Calendar.FRIDAY);
pCal.set(GregorianCalendar.DAY_OF_WEEK_IN_MONTH, -1);
```
|
Get Last Friday of Month in Java
|
[
"",
"java",
"date",
"calendar",
""
] |
As the title says, how can I find the current operating system in python?
|
I usually use [`sys.platform`](https://docs.python.org/3/library/sys.html#sys.platform) to get the platform. `sys.platform` will distinguish between linux, other unixes, and OS X, while `os.name` is "`posix`" for all of them.
For much more detailed information, use the [platform module](https://docs.python.org/3/library/platform.html#module-platform). This has cross-platform functions that will give you information on the machine architecture, OS and OS version, version of Python, etc. Also it has os-specific functions to get things like the particular linux distribution.
|
If you want user readable data but still detailed, you can use [platform.platform()](http://docs.python.org/library/platform.html#platform.platform)
```
>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'
```
`platform` also has some other useful methods:
```
>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'
```
Here's a few different possible calls you can make to identify where you are, linux\_distribution and dist seem to have gone from recent python versions, so they have a wrapper function here.
```
import platform
import sys
def linux_distribution():
try:
return platform.linux_distribution()
except:
return "N/A"
def dist():
try:
return platform.dist()
except:
return "N/A"
print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))
```
The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: <https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version>
e.g. Solaris on sparc gave:
```
Python version: ['2.6.4 (r264:75706, Aug 4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')
```
or MacOS on M1
```
Python version: ['2.7.16 (default, Dec 21 2020, 23:00:36) ', '[GCC Apple LLVM 12.0.0 (clang-1200.0.30.4) [+internal-os, ptrauth-isa=sign+stri']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: Darwin
machine: arm64
platform: Darwin-20.3.0-arm64-arm-64bit
uname: ('Darwin', 'Nautilus.local', '20.3.0', 'Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101', 'arm64', 'arm')
version: Darwin Kernel Version 20.3.0: Thu Jan 21 00:06:51 PST 2021; root:xnu-7195.81.3~1/RELEASE_ARM64_T8101
mac_ver: ('10.16', ('', '', ''), 'arm64')
```
|
How can I find the current OS in Python?
|
[
"",
"python",
"cross-platform",
"platform-specific",
""
] |
I'd like to implement a simple class (in Java) that would allow me to register and deregister strings, and on the basis of the current set of strings auto-complete a given string. So, the interface would be:
* void add(String)
* void remove(String)
* String complete(String)
What's the best way to do this in terms of algorithms and data-structures?
|
you should consider to use a PATRICIA trie for the data structure. Search for 'patricia trie' on google and you'll find a lot of information...
|
The datastructure you are after is called a Ternary Search Tree.
There's a great JavaWorld example at www.javaworld.com/javaworld/jw-02-2001/jw-0216-ternary.html
|
How to implement a simple auto-complete functionality?
|
[
"",
"java",
"autocomplete",
""
] |
What experience have you had with introducing a Ribbon style control to legacy MFC applications?
I know it exists in the new VC2008 Feature Pack, but changing compilers from VC2005 is a big deal for our source base and integration to our environment, Intel FORTRAN, ClearCase, many 3rd libraries.
There are quiet a few different commerical implementations, most focusing on C#/VB .NET, and only a few for native C++ MFC.
I have read all the usual reviews found by Google most are quiet old now, so I am interested to here from people who have actually done it, been through the pain barrier, released a legacy application with VC2005 and a Ribbon UI.
We currently use a very old version of Stingray Objective Toolkit to provide our MFC extensions like customizable toolbars and docking windows etc.
---
Any one used [Prof-UIS](http://www.prof-uis.com/), compared to the other commercial ones its relatively cheap, unlimited developer licensing is a 10th the cost of the others.
Are there any free, open source or L-GPL'd ones available?
|
In my projects I'm using the MFC Feature Pack in Visual Studio 2008, which is based on code from [BCGSoft](http://www.bcgsoft.com). Their BCGControlBar Library Professional Edition includes a ribbon control and is compatible with Visual Studio 2005.
I'm not aware of any open source ribbon control libraries for C++, though.
|
We use [Codejock](http://www.codejock.com/). It's not cheap, but I guess I've come to find that good controls usually are :-). They are fairly responsive in the tech support department (although we haven't had need to use that recently). We are buidling a whole suite of tools using these controls and have always had what we've needed, including the ability build the office 2007 style ribbon.
|
Whats the best Ribbon UI control to retro fit to a legacy MFC application build with VC2005?
|
[
"",
"c++",
"user-interface",
"mfc",
"ribbon",
"stingray",
""
] |
How do you stop the designer from auto generating code that sets the value for public properties on a user control?
|
Use the DesignerSerializationVisibilityAttribute on the properties that you want to hide from the designer serialization and set the parameter to Hidden.
```
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public string Name
{
get;
set;
}
```
|
Add the following attributes to the property in your control:
```
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
```
|
How do you stop the Designer generating code for public properties on a User Control?
|
[
"",
"c#",
"winforms",
""
] |
I have a database with names in it such as John Doe etc. Unfortunately some of these names contain quotes like Keiran O'Keefe. Now when I try and search for such names as follows:
```
SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'
```
I (understandably) get an error.
How do I prevent this error from occurring. I am using Oracle and PLSQL.
|
The escape character is ', so you would need to replace the quote with two quotes.
For example,
`SELECT * FROM PEOPLE WHERE SURNAME='O'Keefe'`
becomes
`SELECT * FROM PEOPLE WHERE SURNAME='O''Keefe'`
That said, it's probably incorrect to do this yourself. Your language may have a function to escape strings for use in SQL, but an even better option is to use parameters. Usually this works as follows.
Your SQL command would be :
`SELECT * FROM PEOPLE WHERE SURNAME=?`
Then, when you execute it, you pass in "O'Keefe" as a parameter.
Because the SQL is parsed before the parameter value is set, there's no way for the parameter value to alter the structure of the SQL (and it's even a little faster if you want to run the same statement several times with different parameters).
I should also point out that, while your example just causes an error, you open youself up to a lot of other problems by not escaping strings appropriately. See <http://en.wikipedia.org/wiki/SQL_injection> for a good starting point or the following classic [xkcd comic](http://xkcd.com/327/).

|
Oracle 10 solution is
```
SELECT * FROM PEOPLE WHERE SURNAME=q'{O'Keefe}'
```
|
How do I deal with quotes ' in SQL
|
[
"",
"sql",
"oracle",
""
] |
So, I have willfully kept myself a Java n00b until recently, and my first real exposure brought about a minor shock: Java does not have C# style properties!
Ok, I can live with that. However, I can also swear that I have seen property getter/setter code in Java in one codebase, but I cannot remember where. How was that achieved? Is there a language extension for that? Is it related to NetBeans or something?
|
There is a "standard" pattern for getters and setters in Java, called [Bean properties](http://docs.oracle.com/javase/tutorial/javabeans/writing/properties.html). Basically any method starting with `get`, taking no arguments and returning a value, is a property getter for a property named as the rest of the method name (with a lowercased start letter). Likewise `set` creates a setter of a void method with a single argument.
For example:
```
// Getter for "awesomeString"
public String getAwesomeString() {
return awesomeString;
}
// Setter for "awesomeString"
public void setAwesomeString( String awesomeString ) {
this.awesomeString = awesomeString;
}
```
Most Java IDEs will generate these methods for you if you ask them (in Eclipse it's as simple as moving the cursor to a field and hitting `Ctrl`-`1`, then selecting the option from the list).
For what it's worth, for readability you can actually use `is` and `has` in place of `get` for boolean-type properties too, as in:
```
public boolean isAwesome();
public boolean hasAwesomeStuff();
```
|
I am surprised that no one mentioned [project lombok](http://projectlombok.org/)
Yes, currently there are no properties in java. There are some other missing features as well.
But luckily we have [project lombok](http://projectlombok.org/) that is trying to improve the situation. It is also getting more and more popular every day.
So, if you're using lombok:
```
@Getter @Setter int awesomeInteger = 5;
```
This code is going to generate `getAwesomeInteger` and `setAwesomeInteger` as well. So it is quite similar to [C# auto-implemented properties](http://msdn.microsoft.com/en-us/library/bb384054.aspx).
You can get more info about lombok getters and setters [here](http://projectlombok.org/features/GetterSetter.html).
You should definitely check out [other features](http://projectlombok.org/features/index.html) as well.
My favorites are:
* [val](http://projectlombok.org/features/val.html)
* [NoArgsConstructor, RequiredArgsConstructor, AllArgsConstructor](http://projectlombok.org/features/Constructor.html)
* [Logs!](http://projectlombok.org/features/Log.html)
Lombok is well-integrated with IDEs, so it is going to show generated methods like if they existed (suggestions, class contents, go to declaration and refactoring).
The only problem with lombok is that other programmers might not know about it. You can always [delombok](http://projectlombok.org/features/delombok.html) the code but that is rather a workaround than a solution.
|
(no) Properties in Java?
|
[
"",
"java",
"getter-setter",
""
] |
First off: I'm using a rather obscure implementation of javascript embedded as a scripting engine for Adobe InDesign CS3. This implementation sometimes diverges from "standard" javascript, hence my problem.
I'm using [John Resig's jsdiff library](http://ejohn.org/projects/javascript-diff-algorithm/) ([source here](http://ejohn.org/files/jsdiff.js)) to compare selections of text between two documents. jsdiff uses vanilla objects as associative arrays to map a word from the text to another object. (See the "ns" and "os" variables in jsdiff.js, around line 129.)
My headaches start when the word "reflect" comes up in the text. "reflect" is a default, *read-only* property on *all* objects. When jsdiff tries to assign a value on the associative array to ns['reflect'], everything explodes.
My question: is there a way around this? Is there a way to do a hash table in javascript without using the obvious vanilla object?
**Ground rules:** switching scripting engines isn't an option. :)
|
You might be "asking the wrong question" (as Raymond Chen would say); rather than trying to avoid using the vanilla objects, try changing the way the associative array members are named.
The way I'd try to approach this: instead of there being an array member ns["reflect"], change the way that jsdiff builds the arrays so that the member is ns["\_reflect"] or some other variation on that.
|
If the JS implementation you're using supports the hasOwnProperty method for objects, you can use it to test whether a property has explicitly been set for an object or the property is inherited from its prototype. Example:
```
if(object.hasOwnProperty('testProperty')){
// do something
}
```
|
What is a javascript hash table implementation that avoids object namespace collisions?
|
[
"",
"javascript",
"hash",
"diff",
"adobe-indesign",
""
] |
How can I change the width of a textarea form element if I used ModelForm to create it?
Here is my product class:
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
```
And the template code...
```
{% for f in form %}
{{ f.name }}:{{ f }}
{% endfor %}
```
`f` is the actual form element...
|
**The easiest way for your use case is to use CSS**. It's a language meant for defining presentation. Look at the code generated by form, take note of the ids for fields that interest you, and change appearance of these fields through CSS.
Example for `long_desc` field in your ProductForm (when your form does not have a custom prefix):
```
#id_long_desc {
width: 300px;
height: 200px;
}
```
**Second approach** is to pass the `attrs` keyword to your widget constructor.
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
```
It's [described in Django documentation](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs).
**Third approach** is to leave the nice declarative interface of newforms for a while and set your widget attributes in custom constructor.
```
class ProductForm(ModelForm):
long_desc = forms.CharField(widget=forms.Textarea)
short_desc = forms.CharField(widget=forms.Textarea)
class Meta:
model = Product
# Edit by bryan
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
self.fields['long_desc'].widget.attrs['cols'] = 10
self.fields['long_desc'].widget.attrs['rows'] = 20
```
This approach has the following advantages:
* You can define widget attributes for fields that are generated automatically from your model without redefining whole fields.
* It doesn't depend on the prefix of your form.
|
Excellent answer by zuber, but I believe there's an error in the example code for the third approach. The constructor should be:
```
def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
self.fields['long_desc'].widget.attrs['cols'] = 10
self.fields['long_desc'].widget.attrs['cols'] = 20
```
The Field objects have no 'attrs' attributes, but their widgets do.
|
Change the width of form elements created with ModelForm in Django
|
[
"",
"python",
"html",
"django",
"django-forms",
"django-templates",
""
] |
I would like to call Perl script files from my c++ program.
I am not sure that the people I will distribute to will have Perl installed.
Basically I'm looking for a .lib file that I can use that has an Apache like distribution license.
|
You can embed perl into your app.
* [Perl Embedding](http://www.linuxjournal.com/article/2901) by John Quillan
* [C++ wrapper around Perl C API](http://xaxxon.slackworks.com/ep/)
|
I'm [currently](http://news.perlfoundation.org/2008/08/2008q3_grant_proposal_libperl.html) writing a library for embedding Perl in C++, but it's not finished yet. In any case I would recommend against using the EP library. Not only has it not been maintained for years, but is also has some severe architectural deficiencies and is rather limited in its scope. If you are interested in alpha software you can contact me about it, otherwise I'd advice you to use [the](http://perldoc.perl.org/perlembed.html) [raw](http://perldoc.perl.org/perlguts.html) [API](http://perldoc.perl.org/perlapi.html).
|
How can I embed Perl inside a C++ application?
|
[
"",
"c++",
"perl",
""
] |
I have two webapplication, one is a simple authenticationsite which can authenticate the logged in user and **redirects** him then to another site.
Therefore I have to pass ther userId (GUID) to the second application. Currently this is done via the URL but i would like to hide this id.
Has anybody an idea how to do this properly?
[EDIT]: I can't use the Session because of the ApplicationBoundaries (2 different Servers)
|
Pass the GUID through a **session**, best way.
<http://www.w3schools.com/ASP/asp_sessions.asp>
OR, since it's 2 different servers, pass the information by POST method:
<http://www.w3schools.com/aspnet/aspnet_forms.asp>
The other possibility is to store the session state in a database on the local server, and remotely access that database from the other server to see if the user has successfully logged in and within session timelimit.
With that in mind, you can do the entire authentication remotely as well. Remotely connect to the local database from the remote server and check the login credentials from there...that way you will be able to store the session and/or cookie on the remote server.
**I would recommend AGAINST the hidden field proposition**, as it completely counteracts what you are trying to do! You are trying to hide the GUID in the URL but posting the same information in your HTML code! This is not the way to do it.
Best choice is the database option, or if not possible, then use HTTP POST.
|
This sounds like a tricky situation.
There are however several options you can use but it all depends on what your application does.
Let's call WebApp1 your authenticate site, and WebApp2 your distination site once authenticated.
Can WebApp2 not call WebApp1 behind the scenes? (Services)
THe problem with passing this Guid between applications is it's going through clear text, and considering it's a user id, if anyone manages to intercept this they will have access to WebApp2 for life. Whether you pass it in a querystring or form variable, it's still vulnerable.
If you can't use WebApp2 to query WebApp1, you should consider WebApp1 creating a temporary Guid that expires. That would be much safer long term, but as it's clear text is still susceptible to attack. The 2 web apps will also need access to the same data store.
Ultimately, i think the AUthentication Site should be a service which WebApp2 can consume.
Users should login through WebApp2, which will call WebApp1 securely for authentication.
WebApp2 can then manage it's own session.
|
Hiding a queryString in an ASP.NET Webapplication
|
[
"",
"c#",
"asp.net",
"web-services",
""
] |
I am new to all the anonymous features and need some help. I have gotten the following to work:
```
public void FakeSaveWithMessage(Transaction t)
{
t.Message = "I drink goats blood";
}
public delegate void FakeSave(Transaction t);
public void SampleTestFunction()
{
Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage));
}
```
But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried:
```
Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; });
```
and
```
Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; });
```
but these give me
> Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type\*\* compile errors.
What am I doing wrong?
---
Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:
```
public delegate void FakeSave(Transaction t);
Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; }));
```
|
That's a well known error message. Check the link below for a more detailed discussion.
<http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/>
Basically you just need to put a cast in front of your anonymous delegate (your lambda expression).
In case the link ever goes down, here is a copy of the post:
> **They are Anonymous Methods, not
> Anonymous Delegates.**
> Posted on December 22, 2007 by staceyw1
>
> It is not just a talking point because
> we want to be difficult. It helps us
> reason about what exactly is going on.
> To be clear, there is \*no such thing
> as an anonymous delegate. They don’t
> exist (not yet). They are "Anonymous
> Methods" – period. It matters in how
> we think of them and how we talk about
> them. Lets take a look at the
> anonymous method statement "delegate()
> {…}". This is actually two different
> operations and when we think of it
> this way, we will never be confused
> again. The first thing the compiler
> does is create the anonymous method
> under the covers using the inferred
> delegate signature as the method
> signature. It is not correct to say
> the method is "unnamed" because it
> does have a name and the compiler
> assigns it. It is just hidden from
> normal view. The next thing it does
> is create a delegate object of the
> required type to wrap the method. This
> is called delegate inference and can
> be the source of this confusion. For
> this to work, the compiler must be
> able to figure out (i.e. infer) what
> delegate type it will create. It has
> to be a known concrete type. Let
> write some code to see why.
```
private void MyMethod()
{
}
```
> **Does not compile:**
```
1) Delegate d = delegate() { }; // Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type
2) Delegate d2 = MyMethod; // Cannot convert method group ‘MyMethod’ to non-delegate type ‘System.Delegate’
3) Delegate d3 = (WaitCallback)MyMethod; // No overload for ‘MyMethod’ matches delegate ‘System.Threading.WaitCallback’
```
> Line 1 does not compile because the
> compiler can not infer any delegate
> type. It can plainly see the signature
> we desire, but there is no concrete
> delegate type the compiler can see.
> It could create an anonymous type of
> type delegate for us, but it does not
> work like that. Line 2 does not
> compile for a similar reason. Even
> though the compiler knows the method
> signature, we are not giving it a
> delegate type and it is not just going
> to pick one that would happen to work
> (not what side effects that could
> have). Line 3 does not work because
> we purposely mismatched the method
> signature with a delegate having a
> different signature (as WaitCallback
> takes and object).
>
> **Compiles:**
```
4) Delegate d4 = (MethodInvoker)MyMethod; // Works because we cast to a delegate type of the same signature.
5) Delegate d5 = (Action)delegate { }; // Works for same reason as d4.
6) Action d6 = MyMethod; // Delegate inference at work here. New Action delegate is created and assigned.
```
> In contrast, these work. Line 1 works
> because we tell the compiler what
> delegate type to use and they match,
> so it works. Line 5 works for the
> same reason. Note we used the special
> form of "delegate" without the parens.
> The compiler infers the method
> signature from the cast and creates
> the anonymous method with the same
> signature as the inferred delegate
> type. Line 6 works because the
> MyMethod() and Action use same
> signature.
>
> I hope this helps.
>
> Also see:
> <http://msdn.microsoft.com/msdnmag/issues/04/05/C20/>
|
What Mark said.
The problem is that Do takes a Delegate parameter. The compiler can't convert the anonymous methods to Delegate, only a "delegate type" i.e. a concrete type derived from Delegate.
If that Do function had took Action<>, Action<,> ... etc. overloads, you wouldn't need the cast.
|
Convert this delegate to an anonymous method or lambda
|
[
"",
"c#",
".net-3.5",
"delegates",
"lambda",
"anonymous-methods",
""
] |
I'm attempting to use TinyXML to read and save from memory, instead of only reading and saving files to disk.
It seems that the documnent's parse function can load a char \*. But then I need to save the document to a char \* when I'm done with it. Does anyone know about this?
Edit: The printing & streaming functions aren't what I'm looking for. They output in a viewable format, I need the actual xml content.
Edit: Printing is cool.
|
I'm not familiar with TinyXML, but from the documentation it seems that by using operator << to a C++ stream (so you can use [C++ string streams](http://www.cppreference.com/wiki/io/sstream/start)) or a [TiXMLPrinter class](http://www.grinninglizard.com/tinyxmldocs/classTiXmlPrinter.html) you can get an STL string without using a file. See [TinyXML documentation](http://www.grinninglizard.com/tinyxmldocs/index.html) (look for the "Printing" section)
|
Here's some sample code I am using, adapted from the [TiXMLPrinter](http://www.grinninglizard.com/tinyxmldocs/classTiXmlPrinter.html) documentation:
```
TiXmlDocument doc;
// populate document here ...
TiXmlPrinter printer;
printer.SetIndent( " " );
doc.Accept( &printer );
std::string xmltext = printer.CStr();
```
|
TinyXML: Save document to char * or string
|
[
"",
"c++",
"tinyxml",
""
] |
Is there a way (without installing any libraries) of validating XML using a custom DTD in PHP?
|
Take a look at [PHP's DOM](https://www.php.net/dom), especially [DOMDocument::schemaValidate](https://www.php.net/manual/en/domdocument.schemavalidate.php) and [DOMDocument::validate](https://www.php.net/manual/en/domdocument.validate.php).
The example for DOMDocument::validate is fairly simple:
```
<?php
$dom = new DOMDocument;
$dom->Load('book.xml');
if ($dom->validate()) {
echo "This document is valid!\n";
}
?>
```
|
If you have the dtd in a string, you can validate against it by using a [data wrapper](http://php.net/manual/en/wrappers.data.php) for the dtd:
```
$xml = '<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don\'t forget me this weekend!</body>
</note>';
$dtd = '<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>';
$root = 'note';
$systemId = 'data://text/plain;base64,'.base64_encode($dtd);
$old = new DOMDocument;
$old->loadXML($xml);
$creator = new DOMImplementation;
$doctype = $creator->createDocumentType($root, null, $systemId);
$new = $creator->createDocument(null, null, $doctype);
$new->encoding = "utf-8";
$oldNode = $old->getElementsByTagName($root)->item(0);
$newNode = $new->importNode($oldNode, true);
$new->appendChild($newNode);
if (@$new->validate()) {
echo "Valid";
} else {
echo "Not valid";
}
```
|
Validate XML using a custom DTD in PHP
|
[
"",
"php",
"xml",
"validation",
"dtd",
""
] |
I have a table with a "Date" column. Each Date may appear multiple times. How do I select only the dates that appear < k number of times?
|
```
select dates
from table t
group by dates having count(dates) < k ;
```
Hopefully, it works for ORACLE.
HTH
|
```
SELECT * FROM [MyTable] WHERE [Date] IN
(
SELECT [Date]
FROM [MyTable]
GROUP By [Date]
HAVING COUNT(*) < @Max
)
```
See @[SQLMenace] 's response also. It's very similar to this, but depending on your database his JOIN will probably run faster, assuming the optimizer doesn't make the difference moot.
|
SQL Query Help: Selecting Rows That Appear A Certain Number Of Times
|
[
"",
"sql",
"date",
"select",
""
] |
I have done a bit of research into this and it seems that the only way to sort a data bound combo box is to sort the data source itself (a DataTable in a DataSet in this case).
If that is the case then the question becomes what is the best way to sort a DataTable?
The combo box bindings are set in the designer initialize using
```
myCombo.DataSource = this.typedDataSet;
myCombo.DataMember = "Table1";
myCombo.DisplayMember = "ColumnB";
myCombo.ValueMember = "ColumnA";
```
I have tried setting
```
this.typedDataSet.Table1.DefaultView.Sort = "ColumnB DESC";
```
But that makes no difference, I have tried setting this in the control constructor, before and after a typedDataSet.Merge call.
|
If you're using a DataTable, you can use the (DataTable.DefaultView) [DataView.Sort](http://msdn.microsoft.com/en-us/library/system.data.dataview.sort.aspx) property. For greater flexibility you can use the [BindingSource](http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.aspx) component. BindingSource will be the DataSource of your combobox. Then you can change your data source from a DataTable to List without changing the DataSource of the combobox.
> The BindingSource component serves
> many purposes. First, it simplifies
> binding controls on a form to data by
> providing currency management, change
> notification, and other services
> between Windows Forms controls and
> data sources.
|
You can actually sort the [default view](http://msdn.microsoft.com/en-us/library/system.data.datatable.defaultview.aspx) on a DataTable:
```
myDataTable.DefaultView.Sort = "Field1, Field2 DESC";
```
That'll sort any rows you retrieve directly from the DataTable.
|
What is the best way to sort a data bound combo box?
|
[
"",
"c#",
"data-binding",
""
] |
I wanted to "emulate" a popular flash game, Chrontron, in C++ and needed some help getting started. (NOTE: Not for release, just practicing for myself)
```
Basics:
Player has a time machine. On each iteration of using the time machine, a parallel state
is created, co-existing with a previous state. One of the states must complete all the
objectives of the level before ending the stage. In addition, all the stages must be able
to end the stage normally, without causing a state paradox (wherein they should have
been able to finish the stage normally but, due to the interactions of another state,
were not).
```
So, that sort of explains how the game works. You should play it a bit to really
understand what my problem is.
I'm thinking a good way to solve this would be to use linked lists to store each state,
which will probably either be a hash map, based on time, or a linked list that iterates
based on time. I'm still unsure.
ACTUAL QUESTION:
Now that I have some rough specs, I need some help deciding on which data structures to use for this, and why. Also, I want to know what Graphics API/Layer I should use to do this: SDL, OpenGL, or DirectX (my current choice is SDL). And how would I go about implementing parallel states? With parallel threads?
EDIT (To clarify more):
OS -- Windows (since this is a hobby project, may do this in Linux later)
Graphics -- 2D
Language -- C++ (must be C++ -- this is practice for a course next semester)
Q-Unanswered: SDL : OpenGL : Direct X
Q-Answered: Avoid Parallel Processing
Q-Answered: Use STL to implement time-step actions.
```
So far from what people have said, I should:
1. Use STL to store actions.
2. Iterate through actions based on time-step.
3. Forget parallel processing -- period. (But I'd still like some pointers as to how it
could be used and in what cases it should be used, since this is for practice).
```
Appending to the question, I've mostly used C#, PHP, and Java before so I wouldn't describe myself as a hotshot programmer. What C++ specific knowledge would help make this project easier for me? (ie. Vectors?)
|
What you should do is first to read and understand the "fixed time-step" game loop (Here's a good explanation: <http://www.gaffer.org/game-physics/fix-your-timestep>).
Then what you do is to keep a list of list of pairs of frame counter and action. STL example:
```
std::list<std::list<std::pair<unsigned long, Action> > > state;
```
Or maybe a vector of lists of pairs. To create the state, for every action (player interaction) you store the frame number and what action is performed, most likely you'd get the best results if action simply was "key <X> pressed" or "key <X> released":
```
state.back().push_back(std::make_pair(currentFrame, VK_LEFT | KEY_PRESSED));
```
To play back the previous states, you'd have to reset the frame counter every time the player activates the time machine and then iterate through the state list for each previous state and see if any matches the current frame. If there is, perform the action for that state.
To optimize you could keep a list of iterators to where you are in each previous state-list. Here's some *pseudo-code* for that:
```
typedef std::list<std::pair<unsigned long, Action> > StateList;
std::list<StateList::iterator> stateIteratorList;
//
foreach(it in stateIteratorList)
{
if(it->first == currentFrame)
{
performAction(it->second);
++it;
}
}
```
I hope you get the idea...
Separate threads would simply complicate the matter greatly, this way you get the same result every time, which you cannot guarantee by using separate threads (can't really see how that would be implemented) or a non-fixed time-step game loop.
When it comes to graphics API, I'd go with SDL as it's probably the easiest thing to get you started. You can always use OpenGL from SDL later on if you want to go 3D.
|
This sounds very similar to [Braid](http://braid-game.com). You really don't want parallel processing for this - parallel programming is **hard**, and for something like this, performance should not be an issue.
Since the game state vector will grow very quickly (probably on the order of several kilobytes per second, depending on the frame rate and how much data you store), you don't want a linked list, which has a lot of overhead in terms of space (and can introduce big performance penalties due to cache misses if it is laid out poorly). For each parallel timeline, you want a vector data structure. You can store each parallel timeline in a linked list. Each timeline knows at what time it began.
To run the game, you iterate through all active timelines and perform one frame's worth of actions from each of them in lockstep. No need for parallel processing.
|
Making a game in C++ using parallel processing
|
[
"",
"c++",
"opengl",
"graphics",
"directx",
"sdl",
""
] |
Any recommended practices for cleaning up "header spaghetti" which is causing extremely
slow compilation times (Linux/Unix)?
Is there any equvalent to "#pragma once" with GCC?
(found conflicting messages regarding this)
Thanks.
|
Assuming you're familiar with "include guards" (#ifdef at the begining of the header..), an additional way of speeding up build time is by using external include guards.
It was discussed in "[Large Scale C++ Software Design](http://vig.pearsoned.com/store/product/1,1207,store-15080_isbn-0201633620,00.html)". The idea is that classic include guards, unlike #pragma once, do not spare you the preprocessor parsing required to ignore the header from the 2nd time on (i.e. it still has to parse and look for the start and end of the include guard. With external include guards you place the #ifdef's around the #include line itself.
So it looks like this:
```
#ifndef MY_HEADER
#include "myheader.h"
#endif
```
and of course within the H file you have the classic include guard
```
#ifndef MY_HEADER
#define MY_HEADER
// content of header
#endif
```
This way the myheader.h file isn't even opened / parsed by the preprocessor, and it can save you a lot of time in large projects, especially when header files sit on shared remote locations, as they sometimes do.
again, it's all in that book. hth
|
If you want to do a complete cleanup and have the time to do it then the best solution is to delete all the #includes in all the files (except for obvious ones e.g. abc.h in abc.cpp) and then compile the project. Add the necessary forward declaration or header to fix the first error and then repeat until you comple cleanly.
This doesn't fix underlying problems that can result in include issues, but it does ensure that the only includes are the required ones.
|
Cleaning up Legacy Code "header spaghetti"
|
[
"",
"c++",
"legacy-code",
""
] |
Is there a way to read a module's configuration ini file?
For example I installed php-eaccelerator (<http://eaccelerator.net>) and it put a `eaccelerator.ini` file in `/etc/php.d`. My PHP installation wont read this `.ini` file because the `--with-config-file-scan-dir` option wasn't used when compiling PHP. Is there a way to manually specify a path to the ini file somewhere so PHP can read the module's settings?
|
This is just a wild guess, but try to add all the directives from eaccelerator.ini to php.ini. First create a `<?php phpinfo(); ?>` and check where it's located.
For example, try this:
```
[eAccelerator]
extension="eaccelerator.so"
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmp"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"
```
Another thing you could do is set all the settings on run-time using ini\_set(). I am not sure if that works though or how effective that is. :) I am not familiar with eAccelerator to know for sure.
|
The standard way in this instance is to copy the relevant .ini lines to the bottom of the php.ini file. There is no 'include "file.ini"' functionality in the php.ini file itself.
You can't do it at run time either, since the extension has already been initialised by then.
|
PHP parse configuration ini files
|
[
"",
"php",
"apache",
""
] |
Once again one of those: "Is there an easier built-in way of doing things instead of my helper method?"
So it's easy to get the underlying type from a nullable type, but how do I get the nullable version of a .NET type?
So I have
```
typeof(int)
typeof(DateTime)
System.Type t = something;
```
and I want
```
int?
DateTime?
```
or
```
Nullable<int> (which is the same)
if (t is primitive) then Nullable<T> else just T
```
Is there a built-in method?
|
Here is the code I use:
```
Type GetNullableType(Type type) {
// Use Nullable.GetUnderlyingType() to remove the Nullable<T> wrapper if type is already nullable.
type = Nullable.GetUnderlyingType(type) ?? type; // avoid type becoming null
if (type.IsValueType)
return typeof(Nullable<>).MakeGenericType(type);
else
return type;
}
```
|
I have a couple of methods I've written in my utility library that I've heavily relied on. The first is a method that converts any Type to its corresponding Nullable<Type> form:
```
/// <summary>
/// [ <c>public static Type GetNullableType(Type TypeToConvert)</c> ]
/// <para></para>
/// Convert any Type to its Nullable<T> form, if possible
/// </summary>
/// <param name="TypeToConvert">The Type to convert</param>
/// <returns>
/// The Nullable<T> converted from the original type, the original type if it was already nullable, or null
/// if either <paramref name="TypeToConvert"/> could not be converted or if it was null.
/// </returns>
/// <remarks>
/// To qualify to be converted to a nullable form, <paramref name="TypeToConvert"/> must contain a non-nullable value
/// type other than System.Void. Otherwise, this method will return a null.
/// </remarks>
/// <seealso cref="Nullable<T>"/>
public static Type GetNullableType(Type TypeToConvert)
{
// Abort if no type supplied
if (TypeToConvert == null)
return null;
// If the given type is already nullable, just return it
if (IsTypeNullable(TypeToConvert))
return TypeToConvert;
// If the type is a ValueType and is not System.Void, convert it to a Nullable<Type>
if (TypeToConvert.IsValueType && TypeToConvert != typeof(void))
return typeof(Nullable<>).MakeGenericType(TypeToConvert);
// Done - no conversion
return null;
}
```
The second method simply reports whether a given Type is nullable. This method is called by the first and is useful separately:
```
/// <summary>
/// [ <c>public static bool IsTypeNullable(Type TypeToTest)</c> ]
/// <para></para>
/// Reports whether a given Type is nullable (Nullable< Type >)
/// </summary>
/// <param name="TypeToTest">The Type to test</param>
/// <returns>
/// true = The given Type is a Nullable< Type >; false = The type is not nullable, or <paramref name="TypeToTest"/>
/// is null.
/// </returns>
/// <remarks>
/// This method tests <paramref name="TypeToTest"/> and reports whether it is nullable (i.e. whether it is either a
/// reference type or a form of the generic Nullable< T > type).
/// </remarks>
/// <seealso cref="GetNullableType"/>
public static bool IsTypeNullable(Type TypeToTest)
{
// Abort if no type supplied
if (TypeToTest == null)
return false;
// If this is not a value type, it is a reference type, so it is automatically nullable
// (NOTE: All forms of Nullable<T> are value types)
if (!TypeToTest.IsValueType)
return true;
// Report whether TypeToTest is a form of the Nullable<> type
return TypeToTest.IsGenericType && TypeToTest.GetGenericTypeDefinition() == typeof(Nullable<>);
}
```
The above IsTypeNullable implementation works like a champ every time, but it's slightly verbose and slow in its last code line. The following code body is the same as above for IsTypeNullable, except the last code line is simpler and faster:
```
// Abort if no type supplied
if (TypeToTest == null)
return false;
// If this is not a value type, it is a reference type, so it is automatically nullable
// (NOTE: All forms of Nullable<T> are value types)
if (!TypeToTest.IsValueType)
return true;
// Report whether an underlying Type exists (if it does, TypeToTest is a nullable Type)
return Nullable.GetUnderlyingType(TypeToTest) != null;
```
Enjoy!
Mark
P.S. - About "nullability"
I should repeat a statement about nullability I made in a separate post, which applies directly to properly addressing this topic. That is, I believe the focus of the discussion here should not be how to check to see if an object is a generic Nullable type, but rather whether one can assign a value of null to an object of its type. In other words, I think we should be determining whether an object type is nullable, not whether it is Nullable. The difference is in semantics, namely the practical reasons for determining nullability, which is usually all that matters.
In a system using objects with types possibly unknown until run-time (web services, remote calls, databases, feeds, etc.), a common requirement is to determine whether a null can be assigned to the object, or whether the object might contain a null. Performing such operations on non-nullable types will likely produce errors, usually exceptions, which are very expensive both in terms of performance and coding requirements. To take the highly-preferred approach of proactively avoiding such problems, it is necessary to determine whether an object of an arbitrary Type is capable of containing a null; i.e., whether it is generally 'nullable'.
In a very practical and typical sense, nullability in .NET terms does not at all necessarily imply that an object's Type is a form of Nullable. In many cases in fact, objects have reference types, can contain a null value, and thus are all nullable; none of these have a Nullable type. Therefore, for practical purposes in most scenarios, testing should be done for the general concept of nullability, vs. the implementation-dependent concept of Nullable. So we should not be hung up by focusing solely on the .NET Nullable type but rather incorporate our understanding of its requirements and behavior in the process of focusing on the general, practical concept of nullability.
|
How do I convert a System.Type to its nullable version?
|
[
"",
"c#",
".net",
""
] |
Is it possible to use .htaccess to process all six digit URLs by sending them to a script, but handle every other invalid URL as an error 404?
For example:
```
http://mywebsite.com/132483
```
would be sent to:
```
http://mywebsite.com/scriptname.php?no=132483
```
but
```
http://mywebsite.com/132483a or
http://mywebsite.com/asdf
```
would be handled as a 404 error.
I presently have this working via a custom PHP 404 script but it's kind of kludgy. Seems to me that .htaccess might be a more elegant solution, but I haven't been able to figure out if it's even possible.
|
```
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteRule ^([0-9]{6})$ scriptname.php?no=$1 [L]
</IfModule>
```
To preserve the clean URL
```
http://mywebsite.com/132483
```
while serving scriptname.php use only [L].
Using [R=301] will redirect you to your scriptname.php?no=xxx
You may find this useful <http://www.addedbytes.com/download/mod_rewrite-cheat-sheet-v2/pdf/>
|
In your htaccess file, put the following
```
RewriteEngine On
RewriteRule ^([0-9]{6})$ /scriptname.php?no=$1 [L]
```
The first line turns the mod\_rewrite engine on. The () brackets put the contents into $1 - successive () would populate $2, $3... and so on. The [0-9]{6} says look for a string precisely 6 characters long containing only characters 0-9.
The [L] at the end makes this the last rule - if it applies, rule processing will stop.
Oh, the ^ and $ mark the start and end of the incoming uri.
Hope that helps!
|
Is it possible to use .htaccess to send six digit number URLs to a script but handle all other invalid URLs as 404s?
|
[
"",
"php",
".htaccess",
"redirect",
""
] |
I have two threads, one updating an int and one reading it. This is a statistic value where the order of the reads and writes is irrelevant.
My question is, do I need to synchronize access to this multi-byte value anyway? Or, put another way, can part of the write be complete and get interrupted, and then the read happen.
For example, think of a value = 0x0000FFFF that gets incremented value of 0x00010000.
Is there a time where the value looks like 0x0001FFFF that I should be worried about? Certainly the larger the type, the more possible something like this to happen.
I've always synchronized these types of accesses, but was curious what the community thinks.
|
At first one might think that reads and writes of the native machine size are atomic but there are a number of issues to deal with including cache coherency between processors/cores. Use atomic operations like Interlocked\* on Windows and the equivalent on Linux. C++0x will have an "atomic" template to wrap these in a nice and cross-platform interface. For now if you are using a platform abstraction layer it may provide these functions. [ACE](http://www.cse.wustl.edu/~schmidt/ACE.html) does, see the class template [ACE\_Atomic\_Op](http://www.dre.vanderbilt.edu/~schmidt/DOC_ROOT/ACE/ace/Atomic_Op.inl).
|
Boy, what a question. The answer to which is:
> Yes, no, hmmm, well, it depends
It all comes down to the architecture of the system. On an IA32 a correctly aligned address will be an atomic operation. Unaligned writes might be atomic, it depends on the caching system in use. If the memory lies within a single L1 cache line then it is atomic, otherwise it's not. The width of the bus between the CPU and RAM can affect the atomic nature: a correctly aligned 16bit write on an 8086 was atomic whereas the same write on an 8088 wasn't because the 8088 only had an 8 bit bus whereas the 8086 had a 16 bit bus.
Also, if you're using C/C++ don't forget to mark the shared value as volatile, otherwise the optimiser will think the variable is never updated in one of your threads.
|
Are C++ Reads and Writes of an int Atomic?
|
[
"",
"c++",
"multithreading",
"synchronization",
"atomic",
""
] |
I am working through the book Learning WCF by Michele Bustamante, and trying to do it using Visual Studio C# Express 2008. The instructions say to use WCF project and item templates, which are not included with VS C# Express. There *are* templates for these types included with Visual Studio Web Developer Express, and I've tried to copy them over into the right directories for VS C# Express to find, but the IDE doesn't find them. Is there some registration process? Or config file somewhere?
|
If you have both Visual Web Developer (VWD) 2008 and Visual C# (VC#) 2008 installed you can copy templates between them. The VWD template files live in (by default):
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress
```
The VC# templates live in:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress
```
Simply copy the templates between the two directories, they might not match exactly but they should be close enough to make sense, for instance I copied the project templates from VC# into VWD by copying files from:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress\ProjectTemplates\1033
```
into:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress\ProjectTemplates\CSharp\Windows\1033
```
The templates won't appear straight away in the template browser. For VWD you need to run:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VWDExpress.exe /installvstemplates
```
For VC# you run:
```
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\VCSExpress.exe /installvstemplates
```
|
If you are a student you could get the full Visual Studio 2008 from [DreamSpark](http://dreamspark.com) for free.
|
How to add WCF templates to Visual Studio Express?
|
[
"",
"c#",
"visual-studio",
"visual-studio-2008",
"wcf",
"visual-studio-express",
""
] |
I maintain an old PC-only application written in Delphi 7. Although Delphi has served me very well in the past I now only use it for this one application and find my skills with the language diminishing. Its syntax is too different from my 'day job' languages of Java/Ruby so it takes me longer to get into the groove of writing new code, plus it is so old I have not used many **interface**s so the code is not managed which seems ancient to me now!
Many of my users are moving to Vista which may run the app in compatibility mode or may have GPF problems depending on how their PC is configured by their IT department, so I have to do some maintenance on the application. I'm wondering if I should jump to a more familiar stack.
Is there an automated tool that will do the legwork of converting the code base to C#, leaving me to concentrate on the conversion on any non-standard components? I'm using an embedded database component called [AbsoluteDatabase](http://www.componentace.com/bde_replacement_database_delphi_absolute_database.htm) which is BDE compatible and using standard SQL throughout, and a native Delphi HTML browser component which can be swapped out with something from the Microsoft world.
How good are these conversion tools?
|
I am not aware of any automated tools for making that conversion. Personally I would suggest you stick with Delphi, maybe just upgrade to a new version. I have seen a couple code DOM's that attempt to convert from Delphi to C#, but that doesn't address the library issue.
CodeGear (formally Borland) has a tool for [going from C# to Delphi](http://dn.codegear.com/article/32338) that works OK. I would assume the tools that go the other direction will work the same (requiring a lot of editing). Here is a Swedish tool that works on the same CodeDOM principle to go from [Delphi to C#](http://w1.311.telia.com/~u31115556/desc/programs.htm#BabbelFisken) (and a number of other languages). There are others, I just can't find them right now.
Another option would be to upgrade to a more resent version of Delphi for .NET and port your code to .NET that way. Once you get it working in Delphi for .NET (which will be pretty easy, except for the embedded DB, unless they have a .NET version) you can use [.NET Reflector](http://www.red-gate.com/products/reflector/) and [File Disassembler](http://www.denisbauer.com/NETTools/FileDisassembler.aspx) reverse the IL to C#. You will still be using the VCL, but you can use C# instead of Object pascal.
Another similar solution would be to port it to [Oxygene by RemObjects](http://remobjects.com/oxygene). I believe they have a Delphi Win32 migration path to WinForms. Then use [.NET Reflector](http://www.red-gate.com/products/reflector/) and [File Disassembler](http://www.denisbauer.com/NETTools/FileDisassembler.aspx) reverse the IL to C#.
In short, no easy answers. Language migration is easier then library migration. A lot of it depends on what 3rd party components you used (beyond AbsoluteDatabase) and if you made any Windows API calls directly in your application.
Another completely different option would be too look for an off shore team to maintain the application. They can probably do so cheaply. You could find someone domestically, but it would cost you more no doubt (although with the sagging dollar and poor job market you never know . . . )
Good luck!
|
There has been a scientific report of a successfull transformation of a 1.5 million line Delphi Project to C# by John Brant. He wrote a Delphi parser, a C# generator and lots of transformation rules on the AST. Gradually extending the set of rules, doing a daily build, lots of unit tests, and some rewriting of difficult Delphi parts allowed him with a team of 4, among which some of the original developers, with deep Delphi & C# knowledge, to migrate the software in 18 months. John Brant being the original developer of the refactoring browser and the SmaCC compiler construction kit, you are unlikely to be able to go that fast
|
What tools exist to convert a Delphi 7 application to C# and the .Net framework?
|
[
"",
"c#",
"delphi",
"migration",
""
] |
Is there an easy way to convert a string from csv format into a string[] or list?
I can guarantee that there are no commas in the data.
|
```
string[] splitString = origString.Split(',');
```
*(Following comment not added by original answerer)*
**Please keep in mind that this answer addresses the SPECIFIC case where there are guaranteed to be NO commas in the data.**
|
String.Split is just not going to cut it, but a Regex.Split may - Try this one:
```
using System.Text.RegularExpressions;
string[] line;
line = Regex.Split( input, ",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
```
Where 'input' is the csv line. This will handle quoted delimiters, and should give you back an array of strings representing each field in the line.
|
asp.net Convert CSV string to string[]
|
[
"",
"c#",
"string",
"csv",
""
] |
What is the reason browsers do not correctly recognize:
```
<script src="foobar.js" /> <!-- self-closing script element -->
```
Only this is recognized:
```
<script src="foobar.js"></script>
```
Does this break the concept of XHTML support?
Note: This statement is correct at least for all IE (6-8 beta 2).
|
The non-normative appendix ‘HTML Compatibility Guidelines’ of the XHTML 1 specification says:
[С.3. Element Minimization and Empty Element Content](http://www.w3.org/TR/xhtml1/#C_3)
> Given an empty instance of an element whose content model is not `EMPTY` (for example, an empty title or paragraph) do not use the minimized form (e.g. use `<p> </p>` and not `<p />`).
[XHTML DTD](http://www.w3.org/TR/xhtml1/dtds.html#a_dtd_XHTML-1.0-Strict) specifies script elements as:
```
<!-- script statements, which may include CDATA sections -->
<!ELEMENT script (#PCDATA)>
```
|
To add to what Brad and squadette have said, the self-closing XML syntax `<script />` actually **is** correct XML, but for it to work in practice, your web server also needs to send your documents as properly formed XML with an XML mimetype like `application/xhtml+xml` in the HTTP Content-Type header (and *not* as `text/html`).
However, sending an XML mimetype will cause your pages not to be parsed by IE7, which only likes `text/html`.
From [w3](http://www.w3.org/TR/xhtml-media-types/):
> In summary, 'application/xhtml+xml'
> SHOULD be used for XHTML Family
> documents, and the use of 'text/html'
> SHOULD be limited to HTML-compatible
> XHTML 1.0 documents. 'application/xml'
> and 'text/xml' MAY also be used, but
> whenever appropriate,
> 'application/xhtml+xml' SHOULD be used
> rather than those generic XML media
> types.
I puzzled over this a few months ago, and the only workable (compatible with FF3+ and IE7) solution was to use the old `<script></script>` syntax with `text/html` (HTML syntax + HTML mimetype).
If your server sends the `text/html` type in its HTTP headers, even with otherwise properly formed XHTML documents, FF3+ will use its HTML rendering mode which means that `<script />` will not work (this is a change, Firefox was previously less strict).
This will happen regardless of any fiddling with `http-equiv` meta elements, the XML prolog or doctype inside your document -- Firefox branches once it gets the `text/html` header, that determines whether the HTML or XML parser looks inside the document, and the HTML parser does not understand `<script />`.
|
Why don't self-closing script elements work?
|
[
"",
"javascript",
"html",
"internet-explorer",
"xhtml",
""
] |
When I am working in .NET 2.0 projects with the newest version of ReSharper (4.1) I am getting warnings about using the var keyword and lambadas etc.. Any idea how I can disable this only for .NET 2.0 projects?
|
Indeed, you can use C# 3.0 compiler features when targeting .NET 2.0, except extension methods and default LINQ implementations, which are located in newer assemblies. But if you need to co-operate with VS2005 users, you can open Properties view for a given project (not Project Properties, but Edit \ Properties Window, or F4) and select desired language level.
|
You can actually use var in 2.0 projects. It's syntactical sugar and the compiler works with it. Check out this for more info.
<http://weblogs.asp.net/shahar/archive/2008/01/23/use-c-3-features-from-c-2-and-net-2-0-code.aspx>
|
ReSharper giving C# 3.0 Code Inspection Warnings to .NET 2.0 Projects
|
[
"",
"c#",
".net",
"visual-studio",
"asp.net-2.0",
"resharper",
""
] |
In Python specifically, how do variables get shared between threads?
Although I have used `threading.Thread` before I never really understood or saw examples of how variables got shared. Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?
I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem.
|
In Python, everything is shared, except for function-local variables (because each function call gets its own set of locals, and threads are always separate function calls.) And even then, only the variables themselves (the names that refer to objects) are local to the function; objects themselves are always global, and anything can refer to them.
The `Thread` object for a particular thread is not a special object in this regard. If you store the `Thread` object somewhere all threads can access (like a global variable) then all threads can access that one `Thread` object. If you want to atomically modify *anything* that another thread has access to, you have to protect it with a lock. And all threads must of course share this very same lock, or it wouldn't be very effective.
If you want actual thread-local storage, that's where `threading.local` comes in. Attributes of `threading.local` are not shared between threads; each thread sees only the attributes it itself placed in there. If you're curious about its implementation, the source is in [\_threading\_local.py](https://github.com/python/cpython/blob/master/Lib/_threading_local.py) in the standard library.
|
Consider the following code:
```
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread, local
data = local()
def bar():
print("I'm called from", data.v)
def foo():
bar()
class T(Thread):
def run(self):
sleep(random())
data.v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
```
```
>> T().start(); T().start()
I'm called from Thread-2
I'm called from Thread-1
```
Here threading.local() is used as a quick and dirty way to pass some data from run() to bar() without changing the interface of foo().
Note that using global variables won't do the trick:
```
#/usr/bin/env python
from time import sleep
from random import random
from threading import Thread
def bar():
global v
print("I'm called from", v)
def foo():
bar()
class T(Thread):
def run(self):
global v
sleep(random())
v = self.getName() # Thread-1 and Thread-2 accordingly
sleep(1)
foo()
```
```
>> T().start(); T().start()
I'm called from Thread-2
I'm called from Thread-2
```
Meanwhile, if you could afford passing this data through as an argument of foo() - it would be a more elegant and well-designed way:
```
from threading import Thread
def bar(v):
print("I'm called from", v)
def foo(v):
bar(v)
class T(Thread):
def run(self):
foo(self.getName())
```
But this is not always possible when using third-party or poorly designed code.
|
What is "thread local storage" in Python, and why do I need it?
|
[
"",
"python",
"multithreading",
"thread-local",
""
] |
I'm trying to automate a gdb session using the `--command` flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:
```
set args /home/shlomi/conf/bugs/kde/font-break.txt
b IA__FcFontMatch
r
```
However, I'm getting the following:
```
shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb...
GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0)
Copyright (C) 2008 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law. Type "show copying"
and "show warranty" for details.
This GDB was configured as "i586-mandriva-linux-gnu"...
(no debugging symbols found)
Function "IA__FcFontMatch" not defined.
Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal]
```
So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load?
I recall that I was able to do something, but cannot recall what.
|
Replying to myself, I'd like to give the answer that someone gave me on IRC:
```
(gdb) apropos pending
actions -- Specify the actions to be taken at a tracepoint
set breakpoint -- Breakpoint specific settings
set breakpoint pending -- Set debugger's behavior regarding pending breakpoints
show breakpoint -- Breakpoint specific settings
show breakpoint pending -- Show debugger's behavior regarding pending breakpoints
```
And so **set breakpoint pending on** does the trick; it is used in `cmds.gdb` like e.g.
```
set breakpoint pending on
break <source file name>:<line number>
```
|
OT: In terminal it would look like this to debug Caja in one line:
```
gdb -ex "set breakpoint pending on" -ex "break gdk_x_error" -ex run --args caja --sync
```
|
How to set breakpoints on future shared libraries with a command flag
|
[
"",
"c++",
"c",
"linux",
"unix",
"gdb",
""
] |
Python gives us the ability to create 'private' methods and variables within a class by prepending double underscores to the name, like this: `__myPrivateMethod()`. How, then, can one explain this
```
>>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
>>> obj.myPublicMethod()
public method
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
What's the deal?!
I'll explain this a little for those who didn't quite get that.
```
>>> class MyClass:
... def myPublicMethod(self):
... print 'public method'
... def __myPrivateMethod(self):
... print 'this is private!!'
...
>>> obj = MyClass()
```
I create a class with a public method and a private method and instantiate it.
Next, I call its public method.
```
>>> obj.myPublicMethod()
public method
```
Next, I try and call its private method.
```
>>> obj.__myPrivateMethod()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__myPrivateMethod'
```
Everything looks good here; we're unable to call it. It is, in fact, 'private'. Well, actually it isn't. Running `dir()` on the object reveals a new magical method that Python creates magically for all of your 'private' methods.
```
>>> dir(obj)
['_MyClass__myPrivateMethod', '__doc__', '__module__', 'myPublicMethod']
```
This new method's name is always an underscore, followed by the class name, followed by the method name.
```
>>> obj._MyClass__myPrivateMethod()
this is private!!
```
So much for encapsulation, eh?
In any case, I'd always heard Python doesn't support encapsulation, so why even try? What gives?
|
The name scrambling is used to ensure that subclasses don't accidentally override the private methods and attributes of their superclasses. It's not designed to prevent deliberate access from outside.
For example:
```
>>> class Foo(object):
... def __init__(self):
... self.__baz = 42
... def foo(self):
... print self.__baz
...
>>> class Bar(Foo):
... def __init__(self):
... super(Bar, self).__init__()
... self.__baz = 21
... def bar(self):
... print self.__baz
...
>>> x = Bar()
>>> x.foo()
42
>>> x.bar()
21
>>> print x.__dict__
{'_Bar__baz': 21, '_Foo__baz': 42}
```
Of course, it breaks down if two different classes have the same name.
|
When I first came from Java to Python I **hated** this. It scared me to death.
Today it might just be the one thing **I love most** about Python.
I love being on a platform, where people trust each other and don't feel like they need to build impenetrable walls around their code. In strongly encapsulated languages, if an API has a bug, and you have figured out what goes wrong, you may still be unable to work around it because the needed method is private. In Python the attitude is: "sure". If you think you understand the situation, perhaps you have even read it, then all we can say is "good luck!".
Remember, encapsulation is not even weakly related to "security", or keeping the kids off the lawn. It is just another pattern that should be used to make a code base easier to understand.
|
Why are Python's 'private' methods not actually private?
|
[
"",
"python",
"encapsulation",
"information-hiding",
""
] |
I am looking for a better solution than what we currently have to deal with **unexpected production errors**, without reinventing the wheel.
A larger number of our products are WinForm and WPF applications that are installed at remote sites. Inevitably unexpected errors occur, from NullReferenceExceptions to 'General network errors'. Thus ranging from programmer errors to environment problems.
Currently all these unhandled exceptions are logged using log4net and then emailed back to us for **analysis**. However we found that sometimes these error 'reports' contain too little information to identify the problem.
In these reports we need information such as:
1. Application name
2. Application Version
3. Workstation
4. Maybe a screen shot
5. Exception details
6. Operating system
7. Available RAM
8. Running processes
9. And so on...
I don't really want to re-invent the wheel by developing this from scratch. Components that are required:
1. Error collection (details as mentioned above)
2. Error 'sender' (Queuing required if DB or Internet is unavailable)
3. Error database
4. Analysis and reporting of these errors. E.g. 10 most frequent errors or timeouts occur between 4:00PM and 5:00PM. How do the errors compare between version x and y?
Note:
We looked at [SmartAssembly](http://www.smartassembly.com) as a possible solution but although close it didn't quite met our needs and I was hoping to hear what other developers do and if some alternatives exist.
**Edit:** Thanks for the answers so far. Maybe I wasn't clear in my original question, the problem is not how to catch all unhanded exceptions but rather how to deal with them and to create a reporting engine (analysis) around them.
|
I'd suggest Jeff Atwood's article on [User Friendly Exception Handling](http://www.codeproject.com/KB/exception/ExceptionHandling.aspx), which does most of what you ask already (Application Info, Screenshot, Exception Details, OS, Logging to text files and Emailing), and contains the source code so you add the extra stuff you need.
|
You can attach to the unhandled exception event and log it/hit a webservice/etc.
```
[STAThread]
static void Main()
{
Application.ThreadException += new ThreadExceptionEventHandler(OnUnhandledException);
Application.Run(new FormStartUp());
}
static void OnUnhandledException(object sender, ThreadExceptionEventArgs t)
{
// Log
}
```
I also found this code snippet using AppDomain instead of ThreadException:
```
static class EntryPoint {
[MTAThread]
static void Main() {
// Add Global Exception Handler
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(OnUnhandledException);
Application.Run(new Form1());
}
// In CF case only, ALL unhandled exceptions come here
private static void OnUnhandledException(Object sender,
UnhandledExceptionEventArgs e) {
Exception ex = e.ExceptionObject as Exception;
if (ex != null) {
// Can't imagine e.IsTerminating ever being false
// or e.ExceptionObject not being an Exception
SomeClass.SomeStaticHandlingMethod(ex, e.IsTerminating);
}
}
}
```
Here is some documentation on it: [AppDomain Unhandled Exception](http://hoser.lander.ca/PermaLink.aspx?guid=4d6820a1-c059-44bc-8b2e-84b2c6a61a39)
Outside of just handling it yourself, there isn't really a generic way to do this that is reusable, it really needs to be integrated with the interface of the application properly, but you could setup a webservice that takes application name, exception, and all that good stuff and have a centralized point for all your apps.
|
What is the best way to collect/report unexpected errors in .NET Window Applications?
|
[
"",
"c#",
".net",
"error-handling",
"reporting",
""
] |
Looking at the source of urllib2 it looks like the easiest way to do it would be to subclass HTTPRedirectHandler and then use build\_opener to override the default HTTPRedirectHandler, but this seems like a lot of (relatively complicated) work to do what seems like it should be pretty simple.
|
Here is the [Requests](http://docs.python-requests.org/en/latest/) way:
```
import requests
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code, r.headers['Location'])
```
|
[Dive Into Python](https://linux.die.net/diveintopython/html/http_web_services/redirects.html) has a good chapter on handling redirects with urllib2. Another solution is [httplib](https://docs.python.org/2/library/httplib.html).
```
>>> import httplib
>>> conn = httplib.HTTPConnection("www.bogosoft.com")
>>> conn.request("GET", "")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
301 Moved Permanently
>>> print r1.getheader('Location')
http://www.bogosoft.com/new/location
```
|
Is there an easy way to request a URL in python and NOT follow redirects?
|
[
"",
"python",
"http",
"redirect",
""
] |
I've got C# code that accesses MySQL through ODBC.
It creates a transaction, does a few thousand insert commands, and then commits.
Now my question is how many "round trips", so to speak, happen against the DB server? I mean, does it simply transmit every insert command to the DB server, or does it cache/buffer them and send them in batches? And is this configurable in any way?
|
MySQL has an extended SQL style that can be used, where mass inserts are put in several at a time:
```
INSERT INTO `table` (`id`, `event`) VALUES (1, 94263), (2, 75015), (3, 75015);
```
I will usually collect a few hundred insert-parts into a string before running the SQL query itself. This will reduce the overhead of parsing and communication by batching them yourself.
|
There is no limit on the number of rows per se; The limit is on the number of bytes transferred to the server.
You could build the bulk insert up to the number of bytes specified in 'max allowed packet'. If I wanted to use the least amount of inserts I would try that.
|
MySQL transaction with thousands of Inserts - how many "round trips" does it take?
|
[
"",
"sql",
"mysql",
"database",
""
] |
I have C# winforms application that needs to start an external exe from time to time, but I do not wish to start another process if one is already running, but rather switch to it.
So how in C# would I so this in the example below?
```
using System.Diagnostics;
...
Process foo = new Process();
foo.StartInfo.FileName = @"C:\bar\foo.exe";
foo.StartInfo.Arguments = "Username Password";
bool isRunning = //TODO: Check to see if process foo.exe is already running
if (isRunning)
{
//TODO: Switch to foo.exe process
}
else
{
foo.Start();
}
```
|
This should do it for ya.
[Check Processes](http://www.dreamincode.net/code/snippet1541.htm)
```
//Namespaces we need to use
using System.Diagnostics;
public bool IsProcessOpen(string name)
{
//here we're going to get a list of all running processes on
//the computer
foreach (Process clsProcess in Process.GetProcesses()) {
//now we're going to see if any of the running processes
//match the currently running processes. Be sure to not
//add the .exe to the name you provide, i.e: NOTEPAD,
//not NOTEPAD.EXE or false is always returned even if
//notepad is running.
//Remember, if you have the process running more than once,
//say IE open 4 times the loop thr way it is now will close all 4,
//if you want it to just close the first one it finds
//then add a return; after the Kill
if (clsProcess.ProcessName.Contains(name))
{
//if the process is found to be running then we
//return a true
return true;
}
}
//otherwise we return a false
return false;
}
```
|
You can use LINQ as well,
```
var processExists = Process.GetProcesses().Any(p => p.ProcessName.Contains("<your process name>"));
```
|
How do I find out if a process is already running using c#?
|
[
"",
"c#",
"winforms",
"external-process",
""
] |
I'm considering Altova MapForce (or something similar) to produce either XSLT and/or a Java or C# class to do the translation. Today, we pull data right out of the database and manually build an XML string that we post to a webservice.
Should it be db -> (internal)XML -> XSLT -> (External)XML? What do you folks do out there in the wide world?
|
I would use one of the out-of-the-box XML serialization classes to do your internal XML generation, and then use XSLT to transform to the external XML. You might generate a schema as well to enforce that the translation code (whatever will drive your XSLT translation) continues to get the XML it is expecting for translation in case of changes to the object breaks things.
There are a number of XSLT editors on the market that will help you do the mappings, but I prefer to just use a regular XML editor.
|
ya, I think you're heading down the right path with MapForce. If you don't want to write code to preform the actual transformation, MapForce can do that for you also. THis may be better long term b/c it's less code to maintain.
Steer clear of more expensive options (e.g. BizTalk) unless you really need to B2B integration and orchestration.
|
Mapping internal data elements to external vendors' XML schema
|
[
"",
"c#",
"xml",
"xslt",
"mapping",
"coldfusion",
""
] |
We just started running in to an odd problem with a FileSystemWatcher where the call to Dispose() appears to be hanging. This is code that has been working without any problems for a while but we just upgraded to .NET3.5 SP1 so I'm trying to find out if anyone else has seen this behavior. Here is the code that creates the FileSystemWatcher:
```
if (this.fileWatcher == null)
{
this.fileWatcher = new FileSystemWatcher();
}
this.fileWatcher.BeginInit();
this.fileWatcher.IncludeSubdirectories = true;
this.fileWatcher.Path = project.Directory;
this.fileWatcher.EnableRaisingEvents = true;
this.fileWatcher.NotifyFilter = NotifyFilters.Attributes;
this.fileWatcher.Changed += delegate(object s, FileSystemEventArgs args)
{
FileWatcherFileChanged(args);
};
this.fileWatcher.EndInit();
```
The way this is being used is to update the state image of a TreeNode object (adjusted slightly to remove business specific information):
```
private void FileWatcherFileChanged(FileSystemEventArgs args)
{
if (this.TreeView != null)
{
if (this.TreeView.InvokeRequired)
{
FileWatcherFileChangedCallback d = new FileWatcherFileChangedCallback(FileWatcherFileChanged);
this.TreeView.Invoke(d, new object[]
{
args
});
}
else
{
switch (args.ChangeType)
{
case WatcherChangeTypes.Changed:
if (String.CompareOrdinal(this.project.FullName, args.FullPath) == 0)
{
this.StateImageKey = GetStateImageKey();
}
else
{
projectItemTreeNode.StateImageKey = GetStateImageKey();
}
break;
}
}
}
}
```
Is there something we're missing or is this an anomoly from .NET3.5 SP1?
|
Just a thought... Any chance there's a deadlock issue here?
You're calling TreeView.Invoke, which is a blocking call. If a filesystem change happens just as you're clicking whatever button causes the FileSystemWatcher.Dispose() call, your FileWatcherFileChanged method will get called on a background thread and call TreeView.Invoke, which will block until your form thread can process the Invoke request. However, your form thread would be calling FileSystemWatcher.Dispose(), which probably doesn't return until all pending change requests are processed.
Try changing the .Invoke to .BeginInvoke and see if that helps. That may help point you in the right direction.
Of course, it could also be a .NET 3.5SP1 issue. I'm just speculating here based on the code you provided.
|
Scott, we've occasionally seen issues with control.Invoke in .NET 2. Try switching to control.BeginInvoke and see if that helps.
Doing that will allow the FileSystemWatcher thread to return immediately. I suspect your issue is somehow that the control.Invoke is blocking, thus causing the FileSystemWatcher to freeze upon dispose.
|
FileSystemWatcher Dispose call hangs
|
[
"",
"c#",
".net",
"winforms",
"filesystemwatcher",
""
] |
A coworker has been struggling with this problem.
The desired result is an installable plugin for Notes that will add a button emails with attachments that will let users save the attachment to a document management system.
Finding documentation on doing this for Notes has been an uphill battle to say the least.
Writing the actual java to do the work isn't a problem, but figuring out how to extend Notes is.
So, is there a way to add a button/icon to the toolbar, or is it just a matter of adding a new toolbar? If we add a new toolbar then can we make it only visible (or just grey it out otherwise) when no email is open?
|
Both Lotus Notes 8+ and Lotus Symphony use the IBM Lotus Expeditor Toolkit.
If you get the Lotus Symphony SDK [here](http://symphony.lotus.com/software/lotus/symphony/developers.nsf/home).
Their are one or two examples dealing with adding button's to the symphony toolbar.
They should translate almost identically to Notes.
Good Luck,
Brian Gianforcaro
|
I had to do this once in Notes for a plugin I was developing. What I ended up doing was editing the Notes template in the designer, and then writing some LotusScript behind it that called a .NET class via a DLL. So when you clicked the button, it triggered the event in the LotusScript, and then called the DLL, and passed the item information to it.
I should also note that it was a freakin' bear to figure out because Notes documentation is terrible.
|
How do you add a button to the email message window toolbar in Lotus Notes 8.5+?
|
[
"",
"java",
"eclipse",
"lotus-notes",
""
] |
Given the following JSON Date representation:
```
"\/Date(1221644506800-0700)\/"
```
How do you deserialize this into it's JavaScript Date-type form?
I've tried using MS AJAX JavaScrioptSerializer as shown below:
```
Sys.Serialization.JavaScriptSerializer.deserialize("\/Date(1221644506800-0700)\/")
```
However, all I get back is the literal string date.
|
Provided you know the string is definitely a date I prefer to do this :
```
new Date(parseInt(value.replace("/Date(", "").replace(")/",""), 10))
```
|
Bertrand LeRoy, who worked on ASP.NET Atlas/AJAX, [described the design of the JavaScriptSerializer DateTime output](http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx) and revealed the origin of the mysterious leading and trailing forward slashes. He made this recommendation:
> run a simple search for "\/Date((\d+))\/" and replace with "new Date($1)" before the eval
> (but after validation)
I implemented that as:
```
var serializedDateTime = "\/Date(1271389496563)\/";
document.writeln("Serialized: " + serializedDateTime + "<br />");
var toDateRe = new RegExp("^/Date\\((\\d+)\\)/$");
function toDate(s) {
if (!s) {
return null;
}
var constructor = s.replace(toDateRe, "new Date($1)");
if (constructor == s) {
throw 'Invalid serialized DateTime value: "' + s + '"';
}
return eval(constructor);
}
document.writeln("Deserialized: " + toDate(serializedDateTime) + "<br />");
```
This is very close to the many of the other answers:
* Use an anchored RegEx as Sjoerd Visscher did -- don't forget the ^ and $.
* Avoid string.replace, and the 'g' or 'i' options on your RegEx. "/Date(1271389496563)//Date(1271389496563)/" shouldn't work at all.
|
Deserializing Client-Side AJAX JSON Dates
|
[
"",
"c#",
"asp.net",
"json",
"ajax",
"date",
""
] |
I have the following code:
```
string prefix = "OLD:";
Func<string, string> prependAction = (x => prefix + x);
prefix = "NEW:";
Console.WriteLine(prependAction("brownie"));
```
Because the compiler replaces the prefix variable with a closure "NEW:brownie" is printed to the console.
Is there an easy way to prevent the compiler from lifting the prefix variable whilst still making use of a lambda expression? I would like a way of making my Func work identically to:
```
Func<string, string> prependAction = (x => "OLD:" + x);
```
The reason I need this is I would like to serialize the resulting delegate. If the prefix variable is in a non-serializable class the above function will not serialize.
The only way around this I can see at the moment is to create a new serializable class that stores the string as a member variable and has the string prepend method:
```
string prefix = "NEW:";
var prepender = new Prepender {Prefix = prefix};
Func<string, string> prependAction = prepender.Prepend;
prefix = "OLD:";
Console.WriteLine(prependAction("brownie"));
```
With helper class:
```
[Serializable]
public class Prepender
{
public string Prefix { get; set; }
public string Prepend(string str)
{
return Prefix + str;
}
}
```
This seems like a lot of extra work to get the compiler to be "dumb".
|
I see the underlying problem now. It is deeper than I first thought. Basically the solution is to modify the expression tree before serializing it, by replacing all subtrees that do not depend on the parameters with constant nodes. This is apparently called "funcletization".
There is an explanation of it [here](http://social.msdn.microsoft.com/Forums/en-US/67f63b9a-ea44-4428-aea0-5dcdb61e918b/binding-lambdas-when-they-are-closures).
|
Just make another closure...
Say, something like:
```
var prepend = "OLD:";
Func<string, Func<string, string>> makePrepender = x => y => (x + y);
Func<string, string> oldPrepend = makePrepender(prepend);
prepend = "NEW:";
Console.WriteLine(oldPrepend("Brownie"));
```
Havn't tested it yet as I don't have access to VS at the moment, but normally, this is how I solve such problem.
|
Prevent .NET from "lifting" local variables
|
[
"",
"c#",
".net",
"lambda",
""
] |
I want to recreate the stickiness and snapping of windows, like it is implemented in Winamp.
The basic premise is, when you drag a window and it comes close to another one, it will snap to it and will stick. When you move it the two will move together.
I need it for a MDI application.
|
You could read this article and try to adopt it for your program:
[Sticky Windows - How to make your (top-level) forms to stick one to the other or to the screen](http://www.codeproject.com/KB/cs/stickywindows.aspx)
The class presented in the article inherits from *System.Windows.Forms.NativeWindow*, thus no inheritance is required in order to make your class "Stick-able".
|
I have created a [magnet forms component](https://github.com/edoreshef/magnet-winforms) that also supports joint move of "glued" forms. I hope it helps.
Disclaimer: I don't know how well will it works with MDI projects.
|
Anyone familiar with a good "sticky windows" library for Winforms?
|
[
"",
"c#",
".net",
"winforms",
"user-interface",
""
] |
I need to write a function that receives a property as a parameter and execute its getter.
If I needed to pass a function/delegate I would have used:
```
delegate RET FunctionDelegate<T, RET>(T t);
void func<T, RET>(FunctionDelegate function, T param, ...)
{
...
return function.Invoke(param);
}
```
Is there a similar way to define a property so that I could invoke it's getter and/or setter in the function code?
|
You can use reflection, you can get a MethodInfo object for the get/set accessors and call it's Invoke method.
The code example assumes you have both a get and set accessors and you really have to add error handling if you want to use this in production code:
For example to get the value of property Foo of object obj you can write:
```
value = obj.GetType().GetProperty("Foo").GetAccessors()[0].Invoke(obj,null);
```
to set it:
```
obj.GetType().GetProperty("Foo").GetAccessors()[1].Invoke(obj,new object[]{value});
```
So you can pass obj.GetType().GetProperty("Foo").GetAccessors()[0] to your method and execute it's Invoke method.
an easier way is to use anonymous methods (this will work in .net 2.0 or later), let's use a slightly modified version of your code example:
```
delegate RET FunctionDelegate<T, RET>(T t);
void func<T, RET>(FunctionDelegate<T,RET> function, T param, ...)
{
...
return function(param);
}
```
for a property named Foo of type int that is part of a class SomeClass:
```
SomeClass obj = new SomeClass();
func<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj);
```
|
You can also write something like:
```
static void Method<T, U>(this T obj, Expression<Func<T, U>> property)
{
var memberExpression = property.Body as MemberExpression;
//getter
U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);
//setter
obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);
}
```
and example of invocation:
```
DbComputerSet cs = new DbComputerSet();
cs.Method<DbComputerSet, string>(set => set.Code);
```
|
How to pass a generic property as a parameter to a function?
|
[
"",
"c#",
"generics",
""
] |
Earlier today a question was asked regarding [input validation strategies in web apps](https://stackoverflow.com/questions/110458/what-percentage-of-my-time-will-be-spent-in-user-input-verfication-during-web-d).
The top answer, at time of writing, suggests in `PHP` just using `htmlspecialchars` and `mysql_real_escape_string`.
My question is: Is this always enough? Is there more we should know? Where do these functions break down?
|
When it comes to database queries, always try and use prepared parameterised queries. The `mysqli` and `PDO` libraries support this. This is infinitely safer than using escaping functions such as `mysql_real_escape_string`.
Yes, `mysql_real_escape_string` is effectively just a string escaping function. It is not a magic bullet. All it will do is escape dangerous characters in order that they can be safe to use in a single query string. However, if you do not sanitise your inputs beforehand, then you will be vulnerable to certain attack vectors.
Imagine the following SQL:
```
$result = "SELECT fields FROM table WHERE id = ".mysql_real_escape_string($_POST['id']);
```
You should be able to see that this is vulnerable to exploit.
Imagine the `id` parameter contained the common attack vector:
```
1 OR 1=1
```
There's no risky chars in there to encode, so it will pass straight through the escaping filter. Leaving us:
```
SELECT fields FROM table WHERE id= 1 OR 1=1
```
Which is a lovely SQL injection vector and would allow the attacker to return all the rows.
Or
```
1 or is_admin=1 order by id limit 1
```
which produces
```
SELECT fields FROM table WHERE id=1 or is_admin=1 order by id limit 1
```
Which allows the attacker to return the first administrator's details in this completely fictional example.
Whilst these functions are useful, they must be used with care. You need to ensure that all web inputs are validated to some degree. In this case, we see that we can be exploited because we didn't check that a variable we were using as a number, was actually numeric. In PHP you should widely use a set of functions to check that inputs are integers, floats, alphanumeric etc. But when it comes to SQL, heed most the value of the prepared statement. The above code would have been secure if it was a prepared statement as the database functions would have known that `1 OR 1=1` is not a valid literal.
As for `htmlspecialchars()`. That's a minefield of its own.
There's a real problem in PHP in that it has a whole selection of different html-related escaping functions, and no clear guidance on exactly which functions do what.
Firstly, if you are inside an HTML tag, you are in real trouble. Look at
```
echo '<img src= "' . htmlspecialchars($_GET['imagesrc']) . '" />';
```
We're already inside an HTML tag, so we don't need < or > to do anything dangerous. Our attack vector could just be `javascript:alert(document.cookie)`
Now resultant HTML looks like
```
<img src= "javascript:alert(document.cookie)" />
```
The attack gets straight through.
It gets worse. Why? because `htmlspecialchars` (when called this way) only encodes double quotes and not single. So if we had
```
echo "<img src= '" . htmlspecialchars($_GET['imagesrc']) . ". />";
```
Our evil attacker can now inject whole new parameters
```
pic.png' onclick='location.href=xxx' onmouseover='...
```
gives us
```
<img src='pic.png' onclick='location.href=xxx' onmouseover='...' />
```
In these cases, there is no magic bullet, you just have to santise the input yourself. If you try and filter out bad characters you will surely fail. Take a whitelist approach and only let through the chars which are good. Look at the [XSS cheat sheet](http://ha.ckers.org/xss.html) for examples on how diverse vectors can be
Even if you use `htmlspecialchars($string)` outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors.
The most effective you can be is to use the a combination of mb\_convert\_encoding and htmlentities as follows.
```
$str = mb_convert_encoding($str, 'UTF-8', 'UTF-8');
$str = htmlentities($str, ENT_QUOTES, 'UTF-8');
```
Even this leaves IE6 vulnerable, because of the way it handles UTF. However, you could fall back to a more limited encoding, such as ISO-8859-1, until IE6 usage drops off.
For a more in-depth study to the multibyte problems, see <https://stackoverflow.com/a/12118602/1820>
|
In addition to Cheekysoft's excellent answer:
* Yes, they will keep you safe, but only if they're used absolutely correctly. Use them incorrectly and you will still be vulnerable, and may have other problems (for example data corruption)
* Please use parameterised queries instead (as stated above). You can use them through e.g. PDO or via a wrapper like PEAR DB
* Make sure that magic\_quotes\_gpc and magic\_quotes\_runtime are off at all times, and never get accidentally turned on, not even briefly. These are an early and deeply misguided attempt by PHP's developers to prevent security problems (which destroys data)
There isn't really a silver bullet for preventing HTML injection (e.g. cross site scripting), but you may be able to achieve it more easily if you're using a library or templating system for outputting HTML. Read the documentation for that for how to escape things appropriately.
In HTML, things need to be escaped differently depending on context. This is especially true of strings being placed into Javascript.
|
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
|
[
"",
"php",
"security",
"xss",
"sql-injection",
""
] |
Spring DA helps in writing DAOs. When using iBATIS as the persistence framework, and extending SqlMapClientDaoSupport, a SqlMapClient mock should be set for the DAO, but I can't do it. SqlMapClientTemplate is not an interface and EasyMock cannot creates a mock for it.
|
DAO and unit tests do not get along well !
That does not make sense to mock anything in a component that does not hold any business logic and is focused on database access.
You should try instead to write an integration test. Take a look at the spring reference documentation, chapter 8.3 : <http://static.springframework.org/spring/docs/2.5.x/reference/testing.html>
|
This exact reason is why I don't extend from `SqlMapClientDaoSupport`. Instead, I inject a dependency to the `SqlMapClientTemplate` (typed as the interface `SqlMapClientOperations`). Here's a Spring 2.5 example:
```
@Component
public class MyDaoImpl implements MyDao {
@Autowired
public SqlMapClientOperations template;
public void myDaoMethod(BigInteger id) {
int rowcount = template.update("ibatisOperationName", id);
}
}
```
|
How to unit test a DAO that is extending SqlMapClientDaoSupport
|
[
"",
"java",
"spring",
"ibatis",
"easymock",
""
] |
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.
Say, I have a 2D list:
```
li = [[0,1,2],[3,4,5],[6,7,8]]
```
I would like to merge this either into one long list
```
li2 = [0,1,2,3,4,5,6,7,8]
```
or into a string with separators:
```
s = "0,1,2,3,4,5,6,7,8"
```
Really, I'd like to know how to do both.
|
Like so:
```
[ item for innerlist in outerlist for item in innerlist ]
```
Turning that directly into a string with separators:
```
','.join(str(item) for innerlist in outerlist for item in innerlist)
```
Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:
```
for innerlist in outerlist:
for item in innerlist:
...
```
|
Try that:
```
li=[[0,1,2],[3,4,5],[6,7,8]]
li2 = [ y for x in li for y in x]
```
You can read it like this:
Give me the list of every ys.
The ys come from the xs.
The xs come from li.
To map that in a string:
```
','.join(map(str,li2))
```
|
How do I merge a 2D array in Python into one string with List Comprehension?
|
[
"",
"python",
"list-comprehension",
""
] |
```
class Tag(models.Model):
name = models.CharField(maxlength=100)
class Blog(models.Model):
name = models.CharField(maxlength=100)
tags = models.ManyToManyField(Tag)
```
Simple models just to ask my question.
I wonder how can i query blogs using tags in two different ways.
* Blog entries that are tagged with "tag1" or "tag2":
`Blog.objects.filter(tags_in=[1,2]).distinct()`
* Blog objects that are tagged with "tag1" and "tag2" : **?**
* Blog objects that are tagged with exactly "tag1" and "tag2" and nothing else : **??**
---
Tag and Blog is just used for an example.
|
You could use Q objects for #1:
```
# Blogs who have either hockey or django tags.
from django.db.models import Q
Blog.objects.filter(
Q(tags__name__iexact='hockey') | Q(tags__name__iexact='django')
)
```
Unions and intersections, I believe, are a bit outside the scope of the Django ORM, but its possible to to these. The following examples are from a Django application called called [django-tagging](http://code.google.com/p/django-tagging/) that provides the functionality. [Line 346 of models.py](http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#346):
For part two, you're looking for a union of two queries, basically
```
def get_union_by_model(self, queryset_or_model, tags):
"""
Create a ``QuerySet`` containing instances of the specified
model associated with *any* of the given list of tags.
"""
tags = get_tag_list(tags)
tag_count = len(tags)
queryset, model = get_queryset_and_model(queryset_or_model)
if not tag_count:
return model._default_manager.none()
model_table = qn(model._meta.db_table)
# This query selects the ids of all objects which have any of
# the given tags.
query = """
SELECT %(model_pk)s
FROM %(model)s, %(tagged_item)s
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
AND %(model_pk)s = %(tagged_item)s.object_id
GROUP BY %(model_pk)s""" % {
'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
'model': model_table,
'tagged_item': qn(self.model._meta.db_table),
'content_type_id': ContentType.objects.get_for_model(model).pk,
'tag_id_placeholders': ','.join(['%s'] * tag_count),
}
cursor = connection.cursor()
cursor.execute(query, [tag.pk for tag in tags])
object_ids = [row[0] for row in cursor.fetchall()]
if len(object_ids) > 0:
return queryset.filter(pk__in=object_ids)
else:
return model._default_manager.none()
```
For part #3 I believe you're looking for an intersection. See [line 307 of models.py](http://code.google.com/p/django-tagging/source/browse/trunk/tagging/models.py#307)
```
def get_intersection_by_model(self, queryset_or_model, tags):
"""
Create a ``QuerySet`` containing instances of the specified
model associated with *all* of the given list of tags.
"""
tags = get_tag_list(tags)
tag_count = len(tags)
queryset, model = get_queryset_and_model(queryset_or_model)
if not tag_count:
return model._default_manager.none()
model_table = qn(model._meta.db_table)
# This query selects the ids of all objects which have all the
# given tags.
query = """
SELECT %(model_pk)s
FROM %(model)s, %(tagged_item)s
WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
AND %(model_pk)s = %(tagged_item)s.object_id
GROUP BY %(model_pk)s
HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
'model': model_table,
'tagged_item': qn(self.model._meta.db_table),
'content_type_id': ContentType.objects.get_for_model(model).pk,
'tag_id_placeholders': ','.join(['%s'] * tag_count),
'tag_count': tag_count,
}
cursor = connection.cursor()
cursor.execute(query, [tag.pk for tag in tags])
object_ids = [row[0] for row in cursor.fetchall()]
if len(object_ids) > 0:
return queryset.filter(pk__in=object_ids)
else:
return model._default_manager.none()
```
|
I've tested these out with Django 1.0:
The "or" queries:
```
Blog.objects.filter(tags__name__in=['tag1', 'tag2']).distinct()
```
or you could use the Q class:
```
Blog.objects.filter(Q(tags__name='tag1') | Q(tags__name='tag2')).distinct()
```
The "and" query:
```
Blog.objects.filter(tags__name='tag1').filter(tags__name='tag2')
```
I'm not sure about the third one, you'll probably need to drop to SQL to do it.
|
Union and Intersect in Django
|
[
"",
"python",
"django",
"django-models",
"django-views",
"tagging",
""
] |
I want the search box on my web page to display the word "Search" in gray italics. When the box receives focus, it should look just like an empty text box. If there is already text in it, it should display the text normally (black, non-italics). This will help me avoid clutter by removing the label.
BTW, this is an on-page [Ajax](http://en.wikipedia.org/wiki/Ajax_%28programming%29) search, so it has no button.
|
Another option, if you're happy to have this feature only for newer browsers, is to use the support offered by HTML 5's **placeholder** attribute:
```
<input name="email" placeholder="Email Address">
```
In the absence of any styles, in Chrome this looks like:
[](https://i.stack.imgur.com/tZcmY.png)
You can try demos out [here](http://diveintohtml5.info/examples/input-placeholder.html) and in *[HTML5 Placeholder Styling with CSS](http://davidwalsh.name/html5-placeholder-css)*.
Be sure to check the [browser compatibility of this feature](http://caniuse.com/#feat=input-placeholder). Support in Firefox was added in 3.7. Chrome is fine. Internet Explorer only added support in 10. If you target a browser that does not support input placeholders, you can use a jQuery plugin called [jQuery HTML5 Placeholder](https://github.com/mathiasbynens/jquery-placeholder), and then just add the following JavaScript code to enable it.
```
$('input[placeholder], textarea[placeholder]').placeholder();
```
|
That is known as a textbox watermark, and it is done via JavaScript.
* <http://naspinski.net/post/Text-Input-Watermarks-using-Javascript-(IE-Compatible).aspx>
or if you use jQuery, a much better approach:
* <http://digitalbush.com/projects/watermark-input-plugin/>
* or [code.google.com/p/jquery-watermark](http://code.google.com/p/jquery-watermark)
|
How do I make an HTML text box show a hint when empty?
|
[
"",
"javascript",
"html",
""
] |
I want to add a *column* to an existing legacy *database* and write a *procedure* by which I can assign each record a different value. Something like adding a *column* and autogenerate the data for it.
Like, if I add a new *column* called "ID" (number) I want to then initialize a unique value to each of the records. So, my ID *column* will have records from say `1 to 1000`.
How do I do that?
|
This will depend on the database but for SQL Server, this could be achieved as follows:
```
alter table Example
add NewColumn int identity(1,1)
```
|
It would help if you posted what SQL database you're using. For MySQL you probably want auto\_increment:
```
ALTER TABLE tableName ADD id MEDIUMINT NOT NULL AUTO_INCREMENT KEY
```
Not sure if this applies the values retroactively though. If it doesn't you should just be able to iterate over your values with a stored procedure or in a simple program (as long as no one else is writing to the database) and set use the `LAST_INSERT_ID()` function to generate the id value.
|
Add a column to existing table and uniquely number them on MS SQL Server
|
[
"",
"sql",
"sql-server",
""
] |
I understand the main function of the lock key word from MSDN
> lock Statement (C# Reference)
>
> The lock keyword marks a statement
> block as a critical section by
> obtaining the mutual-exclusion lock
> for a given object, executing a
> statement, and then releasing the
> lock.
When should the lock be used?
For instance it makes sense with multi-threaded applications because it protects the data. But is it necessary when the application does not spin off any other threads?
Is there performance issues with using lock?
I have just inherited an application that is using lock everywhere, and it is single threaded and I want to know should I leave them in, are they even necessary?
Please note this is more of a general knowledge question, the application speed is fine, I want to know if that is a good design pattern to follow in the future or should this be avoided unless absolutely needed.
|
> When should the lock be used?
A lock should be used to protect shared resources in multithreaded code. Not for anything else.
> But is it necessary when the application does not spin off any other threads?
Absolutely not. It's just a time waster. However do be sure that you're not implicitly using system threads. For example if you use asynchronous I/O you may receive callbacks from a random thread, not your original thread.
> Is there performance issues with using lock?
Yes. They're not very big in a single-threaded application, but why make calls you don't need?
> ...if that is a good design pattern to follow in the future[?]
Locking everything willy-nilly is a terrible design pattern. If your code is cluttered with random locking and then you do decide to use a background thread for some work, you're likely to run into deadlocks. Sharing a resource between multiple threads requires careful design, and the more you can isolate the tricky part, the better.
|
All the answers here seem right: locks' usefulness is to block threads from acessing locked code concurrently. However, there are many subtleties in this field, one of which is that locked blocks of code are automatically marked as **critical regions** by the Common Language Runtime.
The effect of code being marked as critical is that, if the entire region cannot be entirely executed, the runtime may consider that your entire Application Domain is potentially jeopardized and, therefore, unload it from memory. To quote [MSDN](http://msdn.microsoft.com/en-us/library/system.threading.thread.begincriticalregion.aspx "Thread.BeginCriticalRegion Method (System.Threading)"):
> For example, consider a task that attempts to allocate memory while holding a lock. If the memory allocation fails, aborting the current task is not sufficient to ensure stability of the AppDomain, because there can be other tasks in the domain waiting for the same lock. If the current task is terminated, other tasks could be deadlocked.
Therefore, even though your application is single-threaded, this may be a hazard for you. Consider that one method in a locked block throws an exception that is eventually not handled within the block. Even if the exception is dealt as it bubbles up through the call stack, your critical region of code didn't finish normally. And who knows how the CLR will react?
For more info, read [this article on the perils of Thread.Abort()](http://tdanecker.blogspot.com/2007/08/do-never-ever-use-threadabort.html "Thomas Danecker's Blog: Do never-ever use Thread.Abort!").
|
lock keyword in C#
|
[
"",
"c#",
"multithreading",
"design-patterns",
"locking",
""
] |
I have Java and Flash client applications. What is the best way for the two to communicate without special Flash-specific servers such as BlazeDS or Red5? I am looking for a light client-only solution.
|
Well, you can make http requests from flash to any url... so if your java server has a point where it can listen to incoming requests and process XML or JSON, your flash client can just make the request to that url. BlazeDS and Red5 just aim to make it simpler by handling the translation for you making it possible to call the server-side functions transparently.
|
Are they running in a browser (applet and SWF), or are they standalone apps?
If they're running in a browser then you can use javascript. Both Flash and Java are can access javascript. It's fragile, but it works.
If they're running as actual applications then you can have Java open a socket connection on some port. Then Flash can connect to that and they can send XML data back and forth.
I've done both of these, so I know they both work. The javascript thing is fragile, but the socket stuff has worked great.
|
Communicating between Java and Flash without a Flash-specific server
|
[
"",
"java",
"flash",
""
] |
I have an action like this:
```
public class News : System.Web.Mvc.Controller
{
public ActionResult Archive(int year)
{
/ *** /
}
}
```
With a route like this:
```
routes.MapRoute(
"News-Archive",
"News.mvc/Archive/{year}",
new { controller = "News", action = "Archive" }
);
```
The URL that I am on is:
```
News.mvc/Archive/2008
```
I have a form on this page like this:
```
<form>
<select name="year">
<option value="2007">2007</option>
</select>
</form>
```
Submitting the form should go to News.mvc/Archive/2007 if '2007' is selected in the form.
This requires the form 'action' attribute to be "News.mvc/Archive".
However, if I declare a form like this:
```
<form method="get" action="<%=Url.RouteUrl("News-Archive")%>">
```
it renders as:
```
<form method="get" action="/News.mvc/Archive/2008">
```
Can someone please let me know what I'm missing?
|
You have a couple problems, I think.
First, your route doesn't have a default value for "year", so the URL "/News.mvc/Archive" is actually not valid for routing purposes.
Second, you're expect form values to show up as route parameters, but that's not how HTML works. If you use a plain form with a select and a submit, your URLs will end up having "?year=2007" on the end of them. This is just how GET-method forms are designed to work in HTML.
So you need to come to some conclusion about what's important.
* If you want the user to be able to select something from the dropdown and that changes the submission URL, then you're going to have to use Javascript to achieve this (by intercepting the form submit and formulating the correct URL).
* If you're okay with /News.mvc/Archive?year=2007 as your URL, then you should remove the {year} designator from the route entirely. You can still leave the "int year" parameter on your action, since form values will also populate action method parameters.
|
I think I've worked out why - the route includes {year} so the generated routes always will too..
If anyone can confirm this?
|
ASP.NET MVC Preview 4 - Stop Url.RouteUrl() etc. using existing parameters
|
[
"",
"c#",
"asp.net-mvc",
"forms",
"routes",
""
] |
The first language I learnt was PHP, but I have more recently picked up Python. As these are all 'high-level' languages, I have found them a bit difficult to pick up. I also tried to learn Objective-C but I gave up.
So, what language should I learn to bridge between Python to C
|
It's not clear why you need a bridge language. Why don't you start working with C directly? C is a very simple language itself. I think that hardest part for C learner is pointers and everything else related to memory management. Also C lang is oriented on structured programming, so you will need to learn how to implement data structures and algorithms without OOP goodness. Actually, your question is pretty hard, usually people go from low level langs to high level and I can understand frustration of those who goes in other direction.
|
The best place to start learning C is the book "The C Programming Language" by Kernighan and Ritchie.
You will recognise a lot of things from PHP, and you will be surprised how much PHP (and Perl, Python etc) do for you.
Oh and you also will need a C compiler, but i guess you knew that.
|
What language should I learn as a bridge to C (and derivatives)
|
[
"",
"python",
"c",
""
] |
Is there any **simple algorithm** to determine the likeliness of 2 names representing the same person?
I'm not asking for something of the level that Custom department might be using. Just a simple algorithm that would tell me if 'James T. Clark' is most likely the same name as 'J. Thomas Clark' or 'James Clerk'.
If there is an algorithm in `C#` that would be great, but I can translate from any language.
|
I've faced similar problem and tried to use Levenstein distance first, but it did not work well for me. I came up with an algorithm that gives you "similarity" value between two strings (higher value means more similar strings, "1" for identical strings). This value is not very meaningful by itself (if not "1", always 0.5 or less), but works quite well when you throw in Hungarian Matrix to find matching pairs from two lists of strings.
Use like this:
```
PartialStringComparer cmp = new PartialStringComparer();
tbResult.Text = cmp.Compare(textBox1.Text, textBox2.Text).ToString();
```
The code behind:
```
public class SubstringRange {
string masterString;
public string MasterString {
get { return masterString; }
set { masterString = value; }
}
int start;
public int Start {
get { return start; }
set { start = value; }
}
int end;
public int End {
get { return end; }
set { end = value; }
}
public int Length {
get { return End - Start; }
set { End = Start + value;}
}
public bool IsValid {
get { return MasterString.Length >= End && End >= Start && Start >= 0; }
}
public string Contents {
get {
if(IsValid) {
return MasterString.Substring(Start, Length);
} else {
return "";
}
}
}
public bool OverlapsRange(SubstringRange range) {
return !(End < range.Start || Start > range.End);
}
public bool ContainsRange(SubstringRange range) {
return range.Start >= Start && range.End <= End;
}
public bool ExpandTo(string newContents) {
if(MasterString.Substring(Start).StartsWith(newContents, StringComparison.InvariantCultureIgnoreCase) && newContents.Length > Length) {
Length = newContents.Length;
return true;
} else {
return false;
}
}
}
public class SubstringRangeList: List<SubstringRange> {
string masterString;
public string MasterString {
get { return masterString; }
set { masterString = value; }
}
public SubstringRangeList(string masterString) {
this.MasterString = masterString;
}
public SubstringRange FindString(string s){
foreach(SubstringRange r in this){
if(r.Contents.Equals(s, StringComparison.InvariantCultureIgnoreCase))
return r;
}
return null;
}
public SubstringRange FindSubstring(string s){
foreach(SubstringRange r in this){
if(r.Contents.StartsWith(s, StringComparison.InvariantCultureIgnoreCase))
return r;
}
return null;
}
public bool ContainsRange(SubstringRange range) {
foreach(SubstringRange r in this) {
if(r.ContainsRange(range))
return true;
}
return false;
}
public bool AddSubstring(string substring) {
bool result = false;
foreach(SubstringRange r in this) {
if(r.ExpandTo(substring)) {
result = true;
}
}
if(FindSubstring(substring) == null) {
bool patternfound = true;
int start = 0;
while(patternfound){
patternfound = false;
start = MasterString.IndexOf(substring, start, StringComparison.InvariantCultureIgnoreCase);
patternfound = start != -1;
if(patternfound) {
SubstringRange r = new SubstringRange();
r.MasterString = this.MasterString;
r.Start = start++;
r.Length = substring.Length;
if(!ContainsRange(r)) {
this.Add(r);
result = true;
}
}
}
}
return result;
}
private static bool SubstringRangeMoreThanOneChar(SubstringRange range) {
return range.Length > 1;
}
public float Weight {
get {
if(MasterString.Length == 0 || Count == 0)
return 0;
float numerator = 0;
int denominator = 0;
foreach(SubstringRange r in this.FindAll(SubstringRangeMoreThanOneChar)) {
numerator += r.Length;
denominator++;
}
if(denominator == 0)
return 0;
return numerator / denominator / MasterString.Length;
}
}
public void RemoveOverlappingRanges() {
SubstringRangeList l = new SubstringRangeList(this.MasterString);
l.AddRange(this);//create a copy of this list
foreach(SubstringRange r in l) {
if(this.Contains(r) && this.ContainsRange(r)) {
Remove(r);//try to remove the range
if(!ContainsRange(r)) {//see if the list still contains "superset" of this range
Add(r);//if not, add it back
}
}
}
}
public void AddStringToCompare(string s) {
for(int start = 0; start < s.Length; start++) {
for(int len = 1; start + len <= s.Length; len++) {
string part = s.Substring(start, len);
if(!AddSubstring(part))
break;
}
}
RemoveOverlappingRanges();
}
}
public class PartialStringComparer {
public float Compare(string s1, string s2) {
SubstringRangeList srl1 = new SubstringRangeList(s1);
srl1.AddStringToCompare(s2);
SubstringRangeList srl2 = new SubstringRangeList(s2);
srl2.AddStringToCompare(s1);
return (srl1.Weight + srl2.Weight) / 2;
}
}
```
Levenstein distance one is much simpler (adapted from <http://www.merriampark.com/ld.htm>):
```
public class Distance {
/// <summary>
/// Compute Levenshtein distance
/// </summary>
/// <param name="s">String 1</param>
/// <param name="t">String 2</param>
/// <returns>Distance between the two strings.
/// The larger the number, the bigger the difference.
/// </returns>
public static int LD(string s, string t) {
int n = s.Length; //length of s
int m = t.Length; //length of t
int[,] d = new int[n + 1, m + 1]; // matrix
int cost; // cost
// Step 1
if(n == 0) return m;
if(m == 0) return n;
// Step 2
for(int i = 0; i <= n; d[i, 0] = i++) ;
for(int j = 0; j <= m; d[0, j] = j++) ;
// Step 3
for(int i = 1; i <= n; i++) {
//Step 4
for(int j = 1; j <= m; j++) {
// Step 5
cost = (t.Substring(j - 1, 1) == s.Substring(i - 1, 1) ? 0 : 1);
// Step 6
d[i, j] = System.Math.Min(System.Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost);
}
}
// Step 7
return d[n, m];
}
}
```
|
Sounds like you're looking for a phonetic-based algorithms, such as [soundex](http://en.wikipedia.org/wiki/Soundex), [NYSIIS](http://en.wikipedia.org/wiki/New_York_State_Identification_and_Intelligence_System), or [double metaphone](http://en.wikipedia.org/wiki/Double_Metaphone). The first actually *is* what several government departments use, and is trivial to implement (with many implementations readily [available](http://www.google.com/search?q=soundex+c%23)). The second is a slightly more complicated and more precise version of the first. The latter-most works with some non-English names and alphabets.
[Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) is a definition of distance between two arbitrary strings. It gives you a distance of 0 between identical strings and non-zero between different strings, which might also be useful if you decide to make a custom algorithm.
|
Comparing names
|
[
"",
"c#",
"string",
"comparison",
""
] |
In what order are the following parameters tested (in C++)?
```
if (a || b && c)
{
}
```
I've just seen this code in our application and I hate it, I want to add some brackets to just clarify the ordering. But I don't want to add the brackets until I know I'm adding them in the right place.
***Edit: Accepted Answer & Follow Up***
This link has more information, but it's not totally clear what it means. It seems || and && are the same precedence, and in that case, they are evaluated left-to-right.
<http://msdn.microsoft.com/en-us/library/126fe14k.aspx>
|
From [here](http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm):
```
a || (b && c)
```
This is the default precedence.
|
[<http://www.cppreference.com/wiki/operator_precedence]> (Found by googling "C++ operator precedence")
That page tells us that &&, in group 13, has higher precedence than || in group 14, so the expression is equivalent to a || (b && c).
Unfortunately, the wikipedia article [<http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Operator_precedence]> disagrees with this, but since I have the C89 standard on my desk and it agrees with the first site, I'm going to revise the wikipedia article.
|
C++ Binary operators order of precedence
|
[
"",
"c++",
"binary-operators",
""
] |
We're living in a golden age of databases, with numerous high quality commercial and free databases. This is great, but the downside is there's not a simple obvious choice for someone who needs a database for his next project.
* What are the constraints/criteria you use for selecting a database?
* How well do the various databases you've used meet those constraints/criteria?
* What special features do the databases have?
* Which databases do you feel comfortable recommending to others?
etc...
|
I would think first on what the system requirements are for data access, data security, scalability, performance, disconnected scenarios, data transformation, data sizing.
On the other side, consider also the experience and background of developers, operators, platform administrators.
You should also think on what constraints you have regarding programming languages, operating systems, memory footprint, network bandwidth, hardware.
Last, but not least, you have to think about business issues like budget for licences, support, operation.
After all those considerations you should end up with just a couple of options and the selection should be easier.
In other words, select the technology that suits the best the constraints and needs of your organization and project.
I certainly think that you are right on saying that it is not an obvious choice given the wide number of alternatives, but this is the only way I think you can narrow them to the ones that are really feasible for your project.
|
My selection criteria (mainly programming centric):
* Maintenance: How are updates/hotfixes installed?
* Transaction control: How it is implemented
* Are Stored Procedures supported?
* Can you use exception handling in Stored Procedures?
* Costs
* As a benefit: Can you use recursion on Stored Procedures? (E.g. in SQL Server 2000 the recursion stops after 32 passes IIRC)
|
How to select an SQL database?
|
[
"",
"sql",
"database",
""
] |
Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.
Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning.
First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version.
So I added the define for `_BIND_TO_CURRENT_VCLIBS_VERSION=1` to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this.
I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors.
Running the app still gets the following error:
> > The application failed to initialize properly (0xc0150002). Click on OK to terminate the application.
None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message).
Any one had any similar problem with SP1?
Options:
* Find the problem and fix it so it works as it should (preferred)* Install the redist* dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!)
**Edit:** I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error:
> c:\Program Files\...\...\X.exe
>
> This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
Has no-one else had to deal with this issue?
**Edit:** Just for grins, I downloaded and ran the vcredist\_x86.exe for VS2008SP1 on my test machine. ***It*** works. With the SP1 DLLs. And my RTM linked app. But **NOT** in a private side-by-side distribution that worked pre-SP1.
|
I have battled this problem myself last week and consider myself somewhat of an expert now ;)
I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put
```
#define _BIND_TO_CURRENT_MFC_VERSION 1
#define _BIND_TO_CURRENT_CRT_VERSION 1
```
into *every* project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.
There are more flags that define what versions to bind to; it's documented on <http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx> . As an alternative to the lines above, you can also put
```
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1
```
which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).
Then, check what the embedded manifest says. Download XM Resource Editor: <http://www.wilsonc.demon.co.uk/d10resourceeditor.htm>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.
What I found is that in many cases, *both* versions were included in the manifest. This means that some libraries use the sp1 version and others don't.
A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the `_BIND_TO_CURRENT_CRT_VERSION` preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.
Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.
|
To understand the problem, I think it is important to realize that there are **four version numbers involved**:
* (A) The version of the VC header files to which the .exe is compiled.
* (B) The version of the manifest file that is embedded in the resources section of that .exe. By default, this manifest file is automatically generated by Visual Studio.
* (C) The version of the VC .DLLs (part of the side-by-side assembly) you copy in the same directory as the .exe.
* (D) The version of the VC manifest files (part of the side-by-side assembly) you copy in the same directory as the .exe.
There are two versions of the VC 2008 DLL's in the running:
* v1: 9.0.21022.8
* v2: 9.0.30729.4148
For clarity, I'll use the v1/v2 notation. The following table shows a number of possible situations:
```
Situation | .exe (A) | embedded manifest (B) | VC DLLs (C) | VC manifests (D)
-----------------------------------------------------------------------------
1 | v2 | v1 | v1 | v1
2 | v2 | v1 | v2 | v2
3 | v2 | v1 | v2 | v1
4 | v2 | v2 | v2 | v2
```
The results of these situations when running the .exe on a clean Vista SP1 installation are:
* Situation 1: a popup is shown, saying: "The procedure entry point XYZXYZ could not be located in the dynamic link library".
* Situation 2: nothing seems to happen when running the .exe, but the following event is logged in Windows' "Event Viewer / Application log":
Activation context generation failed for "C:\Path\file.exe".Error in manifest or policy file "C:\Path\Microsoft.VC90.CRT.MANIFEST" on line 4. Component identity found in manifest does not match the identity of the component requested. Reference is Microsoft.VC90.CRT,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="9.0.21022.8". Definition is Microsoft
* Situation 3: everything seems to work fine. This is [remicles2's solution](https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/1567715#1567715).
* Situation 4: this is [how it should be done](https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/70808#70808). Regrettably, as Roel indicates, it can be rather hard to implement.
Now, my situation (and I think it is the same as [crashmstr's](https://stackoverflow.com/users/1441/crashmstr)) is nr 1. The problem is that Visual Studio for one reason or another generates client code (A) for v2, but for one reason or another, generates a v1 manifest file (B). I have no idea where version (A) can be configured.
**Note** that this whole explanation is still in the context of [private assemblies](http://msdn.microsoft.com/en-us/library/aa375674%28VS.85%29.aspx).
**Update**: finally I start to understand what is going on. Apparently, [Visual Studio generates client code (A) for v2 by default](https://stackoverflow.com/questions/2289593/how-to-select-the-version-of-the-vc-2008-dlls-the-application-should-be-linked-to/2289740#2289740), contrary to what I've read on some Microsoft blogs. The \_BIND\_TO\_CURRENT\_VCLIBS\_VERSION flag only selects the version in the generated manifest file (B), but this version will be ignored when running the application.
## Conclusion
An .exe that is compiled by Visual Studio 2008 links to the newest versions of the VC90 DLLs by default. You can [use the \_BIND\_TO\_CURRENT\_VCLIBS\_VERSION flag](https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/70808#70808) to control which version of the VC90 libraries will be generated in the manifest file. This indeed avoids situation 2 where you get the error message "manifest does not match the identity of the component requested". It also explains why situation 3 works fine, as even without the \_BIND\_TO\_CURRENT\_VCLIBS\_VERSION flag the application is linked to the newest versions of the VC DLLs.
The situation is even weirder with public side-by-side assemblies, where vcredist was run, putting the VC 9.0 DLLs in the Windows SxS directory. Even if the .exe's manifest file states that the old versions of the DLLs should be used (this is the case when the \_BIND\_TO\_CURRENT\_VCLIBS\_VERSION flag is not set), Windows **ignores** this version number by default! Instead, Windows will use a newer version if present on the system, except [when an "application configuration file"](https://stackoverflow.com/questions/2289593/how-to-select-the-version-of-the-vc-2008-dlls-the-application-should-be-linked-to/2289740#2289740) is used.
Am I the only one who thinks this is confusing?
So **in summary**:
* For private assemblies, use the \_BIND\_TO\_CURRENT\_VCLIBS\_VERSION flag in the .exe's project and *all* dependent .lib projects.
* For public assemblies, this is not required, as Windows will automatically select the correct version of the .DLLs from the SxS directory.
|
App does not run with VS 2008 SP1 DLLs, previous version works with RTM versions
|
[
"",
"c++",
"visual-studio-2008",
"mfc",
""
] |
There's something very unsatisfactory about this code:
```
/*
Given a command string in which the first 8 characters are the command name
padded on the right with whitespace, construct the appropriate kind of
Command object.
*/
public class CommandFactory {
public Command getCommand(String cmd) {
cmdName = cmd.subString(0,8).trim();
if(cmdName.equals("START")) {
return new StartCommand(cmd);
}
if(cmdName.equals("END")) {
return new EndCommand(cmd);
}
// ... more commands in more if blocks here
// else it's a bad command.
return new InvalidCommand(cmd);
}
}
```
I'm unrepentant about the multiple exit points - the structure is clear. But I'm not happy about the series of near-identical if statements. I've considered making a Map of Strings to Commands:
```
commandMap = new HashMap();
commandMap.put("START",StartCommand.class);
// ... etc.
```
... then using Reflection to make instances of the appropriate class looked up from the Map. However while conceptually elegant, this involves a fair amount of Reflection code that whoever inherits this code might not appreciate - although that cost might be offset by the benefits. All the lines hardcoding values into the commandMap smell almost as bad as the if block.
Even better would be if the factory's constructor could scan the classpath for subclasses of Command, query them for String representations, and automatically add them them to its repertoire.
So - how should I go about refactoring this?
I guess some of the frameworks out there give me this kind of thing for free. Let's assume I'm not in a position to migrate this stuff into such a framework.
|
Your map of strings to commands I think is good. You could even factor out the string command name to the constructor (i.e. shouldn't StartCommand know that its command is "START"?) If you could do this, instantiation of your command objects is much simpler:
```
Class c = commandMap.get(cmdName);
if (c != null)
return c.newInstance();
else
throw new IllegalArgumentException(cmdName + " is not as valid command");
```
Another option is to create an `enum` of all your commands with links to the classes (assume all your command objects implement `CommandInterface`):
```
public enum Command
{
START(StartCommand.class),
END(EndCommand.class);
private Class<? extends CommandInterface> mappedClass;
private Command(Class<? extends CommandInterface> c) { mappedClass = c; }
public CommandInterface getInstance()
{
return mappedClass.newInstance();
}
}
```
since the toString of an enum is its name, you can use `EnumSet` to locate the right object and get the class from within.
|
How about the following code:
```
public enum CommandFactory {
START {
@Override
Command create(String cmd) {
return new StartCommand(cmd);
}
},
END {
@Override
Command create(String cmd) {
return new EndCommand(cmd);
}
};
abstract Command create(String cmd);
public static Command getCommand(String cmd) {
String cmdName = cmd.substring(0, 8).trim();
CommandFactory factory;
try {
factory = valueOf(cmdName);
}
catch (IllegalArgumentException e) {
return new InvalidCommand(cmd);
}
return factory.create(cmd);
}
}
```
The `valueOf(String)` of the enum is used to find the correct factory method. If the factory doesn't exist it will throw an `IllegalArgumentException`. We can use this as a signal to create the `InvalidCommand` object.
An extra benefit is that if you can make the method `create(String cmd)` public if you would also make this way of constructing a Command object compile time checked available to the rest of your code. You could then use `CommandFactory.START.create(String cmd`) to create a Command object.
The last benefit is that you can easily create a list of all available command in your Javadoc documentation.
|
Refactoring Java factory method
|
[
"",
"java",
"factory",
""
] |
I wrote a simple web service in C# using SharpDevelop (which I just got and I love).
The client wanted it in VB, and fortunately there's a Convert To VB.NET feature. It's great. Translated all the code, and it builds. (I've been a "Notepad" guy for a long time, so I may seem a little old-fashioned.)
But I get this error when I try to load the service now.
```
Parser Error Message: Could not load type 'flightinfo.Soap' from assembly 'flightinfo'.
Source Error:
Line 1: <%@ WebService Class="flightinfo.Soap,flightinfo" %>
```
I have deleted the bins and rebuilt, and I have searched google (and stackoverflow). I have scoured the project files for any remnants of C#.
Any ideas?
|
In VB.NET, namespace declarations are relative to the default namespace of the project. So if the default namespace for the project is set to X.Y, everithyng between `Namespace Z` and `End Namespace` will be in the X.Y.Z namespace.
In C# you have to provide the full namespace name, regardless of the default namespace of the project.
So if the C# project had the default namespace X.Y, the CS files would still include the `namespace X.Y` declaration. After converting to VB, if both the default namespace and the namespace declarations in the files stay the same you end up with classes in the X.Y.X.Y namespace.
So in your case, the Soap class is now in the flightinfo.flightinfo namespace. Thus there are three possible solutions:
* change the asmx file to
* remove the default namespace from the project
* remove the namespace declarations from the vb files
|
The problem may be cause by VB.NET & C# projects using different naming conventions for project assemblies and how the project namespace is used. At least that's were I would start looking.
|
"Could not load type" in web service converted to VB.NET
|
[
"",
"c#",
"vb.net",
"web-services",
"translation",
"sharpdevelop",
""
] |
I have an internal enterprise app that currently consumes 10 different web services. They're consumed via old style "Web References" instead of using WCF.
The problem I'm having is trying to work with the other teams in the company who are authoring the services I'm consuming. I found I needed to capture the exact SOAP messages that I'm sending and receiving. I did this by creating a new attribute that extends SoapExtensionAttribute. I then just add that attribute to the service method in the generated Reference.cs file. This works, but is painful for two reasons. First, it's a generated file so anything I do in there can be overwritten. Second, I have to remember to remove the attribute before checking in the file.
**Is There a better way to capture the exact SOAP messages that I am sending and receiving?**
|
This seems to be a common question, as I just asked it and was told to look [here](https://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet).
You don't have to edit the generated `Reference.cs`. You can reference the extension in your application's `app.config`.
|
Is this a webapp?
Place your SoapExtension code in a HTTPModule, and inject the SOAP envelope into the HTTPOutput stream.
That way, when in debug mode, I picture something like a collapsible div on the top of the page that lists all SOAP communication for that page.
|
Soap logging in .net
|
[
"",
"c#",
"web-services",
"soap",
""
] |
I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: *[www.gallup.com](http://www.gallup.com)* and *[www.rassmussenreports.com](http://www.rassmussenreports.com)*
I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)
Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations.
And this is my problem. At the end of the test I have an array in a single variable that looks something like this:
```
[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0]
```
The program currently produces one array for each correct simulation. *I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?*
How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.
Code testing for McCain:
```
test = []
while x < 5:
test = round(100*random.random())
mctest.append(test)
x = x +1
mctestavg = (mctest[0] + mctest[1] + mctest[2])/3
#mcavg is real data
if mctestavg == mcavg[2]:
mcwork = mctest
```
How do I repeat without creating multiple mcwork vars?
|
Would something like this work?
```
from random import randint
mcworks = []
for n in xrange(NUM_ITERATIONS):
mctest = [randint(0, 100) for i in xrange(5)]
if sum(mctest[:3])/3 == mcavg[2]:
mcworks.append(mctest) # mcavg is real data
```
In the end, you are left with a list of valid `mctest` lists.
What I changed:
* Used a [list comprehension](https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000) to build the data instead of a for loop
* Used `random.randint` to get random integers
* Used [slices](http://docs.python.org/tut/node5.html) and `sum` to calculate the average of the first three items
* (To answer your actual question :-) ) Put the results in a list `mcworks`, instead of creating a new variable for every iteration
|
Are you talking about doing this?
```
>>> a = [ ['a', 'b'], ['c', 'd'] ]
>>> a[1]
['c', 'd']
>>> a[1][1]
'd'
```
|
Storing multiple arrays in Python
|
[
"",
"python",
"arrays",
""
] |
I have an AST derived from the ANTLR Parser Generator for Java. What I want to do is somehow construct a control flow graph of the source code, where each statement or expression is a unique Node. I understand there must be some recursiveness to this identification, I was wondering what you would suggest as the best option and if ANTLR has a toolset I can use for this job.
Cheers,
Chris
---
EDIT - My main concern is to get a control flow graph(CFG) from the AST. This way I can get a tree representation of the source. To clarify, both the source code and the implementation language is Java.
|
Usually CFGs are computed on a lower-level representation (e.g. JVM bytecode). Someone did [a thesis](http://www.ssw.uni-linz.ac.at/General/Staff/TW/Wuerthinger06Bachelor.pdf) on such things a few years ago. There might be a helpful way described in there for how to get at that representation.
Since your source and target languages are the same, there's no code generation step -- you're already done! However, now you get to walk the AST. At each node of the AST, you have to ask yourself: is this a "jumping" instruction or not? Method calls and if statements are examples of jumping instructions. So are loop constructs (such as `for` and `while`). Instructions such as addition and multiplication are non-jumping.
First associate with each java statement a node in the CFG, along with an entry and exit node. As a first approximation, walk the tree and:
1. if the current statement is a method call, figure out where the entry node is for the corresponding body of that method call, and make an edge pointing from the current statement to that entry node. if the statement is a method return, enumerate the places that could have called it and add an edge to those.
2. for each non-jumping statement, make an edge between it and the next statement.
This will give you *some kind* of CFG. The procedure is slightly hairy in step 2 because the method called may be declared in a library, and not elsewhere in the AST -- if so, either don't make an edge or make an edge to a special node representing the entry to that library method.
Does this make sense?
|
Producing a full control flow graph that really takes into account all the language
issues is harder than it looks. Not only do you have to identify what
appears to be the "basic blocks", but you have to identify function calls
(sort of easy, but identifying the *target* might be harder),
where behind-the-scenes operations such as class initializers can happen.
and to worry about the points where exceptions can occur
and where control goes if an exception does occur.
If you examine most languages carefully, they will also be
clear about ordering of evaluation of computations in expressions,
and this matters if you have two side-effects in an expression;
the control flow should reflect the order (or the non-order,
if it isn't defined).
Maybe you only want an abstraction of the control flow
having the basic blocks and the conditionals. That's
obviously a bit easier.
In either case (simple CFG or full CFG), you need to walk the AST,
at each point having a reference to possible control flow targets
(e.g., for most cases, such as IF statements, there are two flow targets:
the THEN and ELSE clauses). At each node, link that node to the
appropriate control flow target, possibly replacing the flow targets
(e.g., when you encounter an IF).
To do this for the full language semantics of Java (or C) is quite
a lot of work. You may want to simply use a tool that computes this
off-the-shelf.
See <http://www.semanticdesigns.com/Products/DMS/FlowAnalysis.html>
for what this really looks like, coming out of our tools.
|
Get Control flow graph from Abstract Syntax Tree
|
[
"",
"java",
"parsing",
"abstract-syntax-tree",
"control-flow",
""
] |
I'm wandering myself what component is the best for displaying fast search results in swing. I want to create something like this, make a text field where user can enter some text, during his entering I'll improve in back end fast search on database, and I want to show data bellow the text box, and he will be able to browse the results and on pres enter result will be displayed in table. So my question is is there any component which already have this logic for displaying?
Or is it's not, what is the best way to implement that.
This search will be something what ajax gives me on web, same logic same look and feel, if it's possible on desktop application.
|
Are you looking for something like an AutoComplete component for Java Swing?
[SwingX](https://swingx.dev.java.net/) has such a component. See [here](http://javadesktop.org/swinglabs/build/weekly/latest/swingx-HEAD/javadoc/org/jdesktop/swingx/autocomplete/AutoCompleteDecorator.html) for the JavaDoc. It has a lot of utility methods to do various things, i.e. auto-completing a text box from the contents of a JList.
|
I strongly, strongly recommend that you take a look at [Glazed Lists](http://publicobject.com/glazedlists/) - this is one of the finer open source Java libraries out there, and it makes the bulk of what you are asking about super easy.
|
Fast search in java swing applications?
|
[
"",
"java",
"swing",
"search",
""
] |
Using the method `Application.Restart()` in C# should restart the current application: but it seems that this is not always working.
Is there a reason for this Issue, can somebody tell me, why it doesn't work all the time?
|
There could be a lot of reasons for this. It's not that the method doesn't work; rather, many times programmers forget that they've put something in their code that would stop the application from automatically shutting down, or starting up. Two examples:
* The Closing event on a form can stop an app's shutdown
* If you're doing checking for an already-running process, the old one may not be closing fast enough to allow the new one to start up.
Check your code for gotchas like that. If you're seeing this behaviour within a blank application, then that's more likely to be a problem with the actual function than your code.
Check Microsoft's sourcecode of [application restart](https://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/Application.cs,de3600ec6a11dcac).
|
In my case (NO single-instance), where
```
Application.Restart();
```
didn't work,
```
System.Diagnostics.Process.Start(Application.ExecutablePath);
Application.Exit();
```
did the job!
|
Why is Application.Restart() not reliable?
|
[
"",
"c#",
".net",
""
] |
I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):
```
Connection conn = dataSource.getConnection();
try{
PreparedStatement stmt = conn.prepareStatement();
//initialize the statement
stmt.execute();
ResultSet rs = stmt.getResultSet();
//get data
}finally{
conn.close();
}
```
The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:
```
finally{
try{
rs.close()
}catch(SqlException se){
//log it
}
try{
stmt.close();
}catch(SqlException se){
//log it
}
conn.close();
}
```
But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.
Did you have troubles with ResultSets and Statements not being closed when the Connection is closed?
I found only [this](http://www.theserverside.com/discussions/thread.tss?thread_id=41036) and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.
|
One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the `connection.close()` would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.
|
I've had problems with unclosed ResultSets in Oracle, even though the connection was closed. The error I got was
```
"ORA-01000: maximum open cursors exceeded"
```
So: Always close your ResultSet!
|
ResultSet not closed when connection closed?
|
[
"",
"java",
"jdbc",
"findbugs",
""
] |
I want to compare 2 arrays of objects in JavaScript code. The objects have 8 total properties, but each object will not have a value for each, and the arrays are never going to be any larger than 8 items each, so maybe the brute force method of traversing each and then looking at the values of the 8 properties is the easiest way to do what I want to do, but before implementing, I wanted to see if anyone had a more elegant solution. Any thoughts?
|
EDIT: You cannot overload operators in current, common browser-based implementations of JavaScript interpreters.
To answer the original question, one way you could do this, and mind you, this is a bit of a hack, simply [serialize the two arrays to JSON](https://github.com/douglascrockford/JSON-js/blob/master/json2.js) and then compare the two JSON strings. That would simply tell you if the arrays are different, obviously you could do this to *each* of the objects within the arrays as well to see which ones were different.
Another option is to use a library which has some nice facilities for comparing objects - I use and recommend [**MochiKit**](http://www.mochikit.com/).
---
**EDIT:** [The answer kamens gave](https://stackoverflow.com/questions/27030/comparing-arrays-of-objects-in-javascript#27932) deserves consideration as well, since a single function to compare two given objects would be much smaller than any library to do what I suggest (although my suggestion would certainly work well enough).
Here is a naïve implemenation that may do just enough for you - be aware that there are potential problems with this implementation:
```
function objectsAreSame(x, y) {
var objectsAreSame = true;
for(var propertyName in x) {
if(x[propertyName] !== y[propertyName]) {
objectsAreSame = false;
break;
}
}
return objectsAreSame;
}
```
The assumption is that both objects have the same exact list of properties.
Oh, and it is probably obvious that, for better or worse, I belong to the only-one-return-point camp. :)
|
As serialization doesn't work generally (only when the order of properties matches: `JSON.stringify({a:1,b:2}) !== JSON.stringify({b:2,a:1})`) you have to check the count of properties and compare each property as well:
```
const objectsEqual = (o1, o2) =>
Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => o1[p] === o2[p]);
const obj1 = { name: 'John', age: 33};
const obj2 = { age: 33, name: 'John' };
const obj3 = { name: 'John', age: 45 };
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false
```
If you need a deep comparison, you can call the function recursively:
```
const obj1 = { name: 'John', age: 33, info: { married: true, hobbies: ['sport', 'art'] } };
const obj2 = { age: 33, name: 'John', info: { hobbies: ['sport', 'art'], married: true } };
const obj3 = { name: 'John', age: 33 };
const objectsEqual = (o1, o2) =>
typeof o1 === 'object' && Object.keys(o1).length > 0
? Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => objectsEqual(o1[p], o2[p]))
: o1 === o2;
console.log(objectsEqual(obj1, obj2)); // true
console.log(objectsEqual(obj1, obj3)); // false
```
Then it's easy to use this function to compare objects in arrays:
```
const arr1 = [obj1, obj1];
const arr2 = [obj1, obj2];
const arr3 = [obj1, obj3];
const arraysEqual = (a1, a2) =>
a1.length === a2.length && a1.every((o, idx) => objectsEqual(o, a2[idx]));
console.log(arraysEqual(arr1, arr2)); // true
console.log(arraysEqual(arr1, arr3)); // false
```
|
Comparing Arrays of Objects in JavaScript
|
[
"",
"javascript",
"arrays",
"comparison",
"array-of-dict",
""
] |
My JavaScript is pretty nominal, so when I saw this construction, I was kind of baffled:
```
var shareProxiesPref = document.getElementById("network.proxy.share_proxy_settings");
shareProxiesPref.disabled = proxyTypePref.value != 1;
```
Isn't it better to do an if on `proxyTypePref.value`, and then declare the var inside the result, only if you need it?
(Incidentally, I also found this form very hard to read in comparison to the normal usage. There were a set of two or three of these conditionals, instead of doing a single if with a block of statements in the result.)
---
**UPDATE:**
The responses were very helpful and asked for more context. The code fragment is from Firefox 3, so you can see the code here:
<http://mxr.mozilla.org/firefox/source/browser/components/preferences/connection.js>
Basically, when you look at the **Connect** preferences window in Firefox, clicking the proxy **modes** (radio buttons), causes various form elements to enable|disable.
|
It depends on the context of this code. If it's running on page load, then it would be better to put this code in an if block.
But, if this is part of a validation function, and the field switches between enabled and disabled throughout the life of the page, then this code sort of makes sense.
It's important to remember that setting disabled to false also alters page state.
|
> (Incidentally, I also found this form very hard to read in comparison to the normal usage.
Not necessarily, although that was my first thought, too. A code should always emphasize its function, especially if it has side effects. If the writer's intention was to emphasize the assignment to `sharedProxiesPref.disabled` then hey, roll with it. On the other hand, it could have been clearer that the action taking place here is to disable the object, in which case the conditional block would have been better.
|
Javascript: declaring a variable before the conditional result?
|
[
"",
"javascript",
""
] |
I'm looking for something that will show me the size of each folder within my main folder recursively.
This is a [LAMP](http://en.wikipedia.org/wiki/LAMP_%28software_bundle%29) server with a CGI-Bin so most any PHP script should work or anything that will work in the CGI-Bin.
My hosting company does not provide an interface for me to see which folders are consuming the most amount of space. I don't know of anything on the Internet and did a few searches however I came up with no results.
Something implementing graphs ([GD](http://en.wikipedia.org/wiki/GD_Graphics_Library)/[ImageMagick](http://en.wikipedia.org/wiki/ImageMagick)) would be best but not required.
My host supports only Perl in the CGI-BIN.
|
Strange, I came up on Google with [many relevant results](http://www.google.com.au/search?hl=en&q=php+directory+size&btnG=Google+Search&meta=) and [this one](http://www.go4expert.com/forums/showthread.php?t=290) is probably the most complete.
> The function "getDirectorySize" will
> ignore link/shorcuts to
> files/directory. The function
> "sizeFormat" will suffix the size with
> bytes,KB,MB or GB accordingly.
## Code
```
function getDirectorySize($path)
{
$totalsize = 0;
$totalcount = 0;
$dircount = 0;
if ($handle = opendir ($path))
{
while (false !== ($file = readdir($handle)))
{
$nextpath = $path . '/' . $file;
if ($file != '.' && $file != '..' && !is_link ($nextpath))
{
if (is_dir ($nextpath))
{
$dircount++;
$result = getDirectorySize($nextpath);
$totalsize += $result['size'];
$totalcount += $result['count'];
$dircount += $result['dircount'];
}
elseif (is_file ($nextpath))
{
$totalsize += filesize ($nextpath);
$totalcount++;
}
}
}
}
closedir ($handle);
$total['size'] = $totalsize;
$total['count'] = $totalcount;
$total['dircount'] = $dircount;
return $total;
}
function sizeFormat($size)
{
if($size<1024)
{
return $size." bytes";
}
else if($size<(1024*1024))
{
$size=round($size/1024,1);
return $size." KB";
}
else if($size<(1024*1024*1024))
{
$size=round($size/(1024*1024),1);
return $size." MB";
}
else
{
$size=round($size/(1024*1024*1024),1);
return $size." GB";
}
}
```
## Usage
```
$path="/httpd/html/pradeep/";
$ar=getDirectorySize($path);
echo "<h4>Details for the path : $path</h4>";
echo "Total size : ".sizeFormat($ar['size'])."<br>";
echo "No. of files : ".$ar['count']."<br>";
echo "No. of directories : ".$ar['dircount']."<br>";
```
## Output
```
Details for the path : /httpd/html/pradeep/
Total size : 2.9 MB
No. of files : 196
No. of directories : 20
```
|
If you have shell access you can run the command
```
$ du -h
```
or perhaps use this, if PHP is configured to allow execution:
```
<?php $d = escapeshellcmd(dirname(__FILE__)); echo nl2br(`du -h $d`) ?>
```
|
Get the Directory sizes on a Remote Host with a PHP script
|
[
"",
"php",
"hosting",
"cgi",
""
] |
I have some domain logic implemented in a number of POJOs. I want to write a Swing user interface to allow the user to initiate and see the results of various domain actions.
What's the best pattern/framework/library for communications between the UI and the domain? This boils down into:
* the UI being able to convert a user gesture into a domain action
* the domain being able to send state/result information back to the UI for display purposes
I'm aware of MVC as a broad concept and have fiddled with the Observer pattern (whose Java implementation has some drawbacks if I understand correctly), but I'm wondering if there's an accepted best practise for this problem?
|
Definitely MVC - something like this [example](http://www.leepoint.net/notes-java/GUI/structure/40mvc.html) which clearly splits things out. The problem with the Swing examples is that they seem to show the MVC all working within the swing stuff, which does not seem right to me
|
**MVC** is fantastic for an individual widget, however it gets a little unruly when you have `pages` and `forms` with lots of widgets.
One thing that might be worth looking into (and I'm not endorsing it, I haven't actually used it, just implemented something very similar for myself) is the [Beans Binding Framework (JSR295](http://web.archive.org/web/20070618134019/https://beansbinding.dev.java.net/))
|
Best way for a Swing GUI to communicate with domain logic?
|
[
"",
"java",
"user-interface",
"swing",
""
] |
Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.
*edited later to clarify the use case*
An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.
|
Here is another way, seems more direct.
```
object anon = Activator.CreateInstance(existingObject.GetType());
```
|
Yes, there is.
From memory:
```
public static T create<T>(T t)
{
return Activator.CreateInstance<T>();
}
object anon = create(existingAnonymousType);
```
|
Create anonymous object by Reflection in C#
|
[
"",
"c#",
"silverlight",
"reflection",
"anonymous-objects",
""
] |
When a customer logs in to my site, I need to know their account id and their menu id. This lets me know what data they can see on a page and what menu they get. I don't want to have to read this data over and over. Should I store this in a session variable or customize the membership user and membership provider to contain this information?
|
As already suggested, the profile system is super easy.
<http://msdn.microsoft.com/en-us/library/2y3fs9xs.aspx>
|
If you're going to use the profile provider, make sure to check out the "Optimize ASP.NET 2.0 Profile Provider" section of this article if you're running a high-traffic site:
<http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx>
|
Where is the best place to store user related data in asp.net?
|
[
"",
"c#",
"asp.net",
""
] |
```
public static IList<T> LoadObjectListAll<T>()
{
ISession session = CheckForExistingSession();
var cfg = new NHibernate.Cfg.Configuration().Configure();
var returnList = session.CreateCriteria(typeof(T));
var list = returnList.List();
var castList = list.Cast<typeof(T)>();
return castList;
}
```
So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?
|
`T` is not a type nor a `System.Type`. `T` is a type parameter. `typeof(T)` returns the type of `T`. The `typeof` operator does not act on an object, it returns the `Type` object of a type. <http://msdn.microsoft.com/en-us/library/58918ffs.aspx>
@John is correct in answering your direct question. But the NHibernate code there is a little off. You shouldn't be configuring the `ISessionFactory` *after* getting the `ISession`, for example.
```
public static T[] LoadObjectListAll()
{
var session = GetNewSession();
var criteria = session.CreateCriteria(typeof(T));
var results = criteria.List<T>();
return results.ToArray();
}
```
|
I think
```
var castList = list.Cast<typeof(T)>();
```
should be
```
var castList = list.Cast<T>();
```
> @Jon Limjap The most glaring error I can see is
> that an `IList` is definitely different from an `IList<T>`. An `IList` is non-generic
> (e.g., `ArrayList`).
The original question was already using an `IList<T>`. It was removed when someone edited the formatting. Probably a problem with Markdown.
**Fixed now.**
|
IList.Cast<typeof(T)>() returns error, syntax looks ok
|
[
"",
"c#",
".net",
"nhibernate",
".net-3.5",
"syntax",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.