Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have the following file:
```
<html>
<head>
<title></title>
<link rel="css" type="text/css" href="/empty.css" title="css" />
<script type="text/javascript" src="/Prototype"></script>
<script type="text/javascript">
function load_content()
{
var d = new Date();
new Ajax.PeriodicalUpdater('content', '/DOC?'+d.getTime(),
{
method: 'post',
frequency: 5,
onSuccess: function(transport) {
for(i=0; (a = document.getElementsByTagName('link')[i]); i++)
{
if(a.getAttribute('rel') == 'css' && a.getAttribute("type") == 'text/css')
{
a.href = '/CSS?'+d.getTime();
}
}
}
});
}
</script>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
load_content();
</script>
</body>
</html>
```
Note: Ignore the d.getTime() calls...these are just to get around an issue with IE not loading a new page from an AJAX call because it's caching scheme is too aggressive.
Basically, when it reloads the file at /DOC, it is supposed to be setting the current stylesheet to the file at /CSS... both DOC and CSS and constantly changing.
What's weird is that in Chrome it works great. DOC loads up in the "content" div and the stylesheet gets set to CSS and that css is applied to the page. I can change with CSS page and withing 5 seconds, when the page is refreshed, the CSS will be refreshed as well.
But in IE and Firefox, the HTML will load and I can see that the href attribute of the stylesheet link **IS** getting changed to "/CSS + getTime()" but, while the HTML loads, the css is *never* applied to the page. I can even change the content of DOC and it updates, but the css is never even applied. It just stays a style-free page.
Does Firefox and IE not support changing the style sheet reference in this way?
Is there a better way to do this? | Rather than changing the sheet in a single link, try using alternate style sheets. See this link on using alternate style sheets:
<http://www.alistapart.com/articles/alternate/> | The best way to include files via javascript is to insert a new dom element.
```
var a = document.createElement('link');
a.href="inset.css";
a.rel="stylesheet";
document.getElementsByTagName("head")[0].appendChild(a);
```
However, obviously the problem you're going to run into though is that firefox and ie will not repaint the canvas once the document is finished loading (and you're using ajax). The way you get around that is by taking the contents of the stylesheets and including them in a style element. This sample code will change the color on the page dynamically.
```
function onLoadFunction() {
var a = document.createElement('style');
a.appendChild(document.createTextNode('body {color: blue;}'));
document.getElementsByTagName("body")[0].appendChild(a);
}
```
When you load a new sheet, just destroy the css inside the style element and replace it. | Dynamically changing stylesheet path not working in IE and Firefox | [
"",
"javascript",
"css",
"ajax",
""
] |
I understand passing in a function to another function as a callback and having it execute, but I'm not understanding the best implementation to do that. I'm looking for a very basic example, like this:
```
var myCallBackExample = {
myFirstFunction : function( param1, param2, callback ) {
// Do something with param1 and param2.
if ( arguments.length == 3 ) {
// Execute callback function.
// What is the "best" way to do this?
}
},
mySecondFunction : function() {
myFirstFunction( false, true, function() {
// When this anonymous function is called, execute it.
});
}
};
```
In myFirstFunction, if I do return new callback(), then it works and executes the anonymous function, but that doesn't seem like the correct approach to me. | You can just say
```
callback();
```
Alternately you can use the `call` method if you want to adjust the value of `this` within the callback.
```
callback.call( newValueForThis);
```
Inside the function `this` would be whatever `newValueForThis` is. | You should check if the callback exists, and is an executable function:
```
if (callback && typeof(callback) === "function") {
// execute the callback, passing parameters as necessary
callback();
}
```
A lot of libraries (jQuery, dojo, etc.) use a similar pattern for their asynchronous functions, as well as node.js for all async functions (nodejs usually passes `error` and `data` to the callback). Looking into their source code would help! | Getting a better understanding of callback functions in JavaScript | [
"",
"javascript",
"function",
"callback",
""
] |
I have a VB5 (non .net) project that I would like to upgrade to a c# project. Has anyone have any suggestions on methods or free tools that are avalible to help me with this.
Thanks
Brad | You are better off with a straight rewrite. | What I would suggest is first convert the project to VB6. It'll be much easier to go forward from there. There are a number of tools to help you do this. There is [VBMigration Partner](http://www.vbmigration.com/) and there is [vbto](http://www.vbto.net/). I've not tried either so YMMV.
If costs are a constraint you could try this: there is a wizard in Visual Studio that will attempt to upgrade VB6 to VB.NET. It's not 100% accurate and you WILL have to write code for things VB.NET does not support such as control arrays, etc. Once the code is in VB.NET you can use a tool like [SharpDevelop](http://icsharpcode.net) to convert the VB.NET to C#. It'll be a bit tedious but i suppose all roads, no matter how convoluted, lead to Rome. | How do I convert VB5 project to a c# project | [
"",
"c#",
"vb6-migration",
"vb5",
""
] |
Is there any condition where finally might not run in java? Thanks. | from the [Sun Tutorials](http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html)
> Note: If the JVM exits while the try
> or catch code is being executed, then
> the finally block may not execute.
> Likewise, if the thread executing the
> try or catch code is interrupted or
> killed, the finally block may not
> execute even though the application as
> a whole continues.
I don't know of any other ways the finally block wouldn't execute... | [System.exit](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html#exit(int)) shuts down the Virtual Machine.
> Terminates the currently running Java
> Virtual Machine. The argument serves
> as a status code; by convention, a
> nonzero status code indicates abnormal
> termination.
>
> This method calls the `exit` method in
> class `Runtime`. This method never
> returns normally.
```
try {
System.out.println("hello");
System.exit(0);
}
finally {
System.out.println("bye");
} // try-finally
```
"bye" does not print out in above code. | Does a finally block always run? | [
"",
"java",
"finally",
""
] |
I've just started playing with Guice, and a use-case I can think of is that in a test I just want to override a single binding. I think I'd like to use the rest of the production level bindings to ensure everything is setup correctly and to avoid duplication.
So imagine I have the following Module
```
public class ProductionModule implements Module {
public void configure(Binder binder) {
binder.bind(InterfaceA.class).to(ConcreteA.class);
binder.bind(InterfaceB.class).to(ConcreteB.class);
binder.bind(InterfaceC.class).to(ConcreteC.class);
}
}
```
And in my test I only want to override InterfaceC, while keeping InterfaceA and InterfaceB in tact, so I'd want something like:
```
Module testModule = new Module() {
public void configure(Binder binder) {
binder.bind(InterfaceC.class).to(MockC.class);
}
};
Guice.createInjector(new ProductionModule(), testModule);
```
I've also tried the following, with no luck:
```
Module testModule = new ProductionModule() {
public void configure(Binder binder) {
super.configure(binder);
binder.bind(InterfaceC.class).to(MockC.class);
}
};
Guice.createInjector(testModule);
```
Does anyone know if it's possible to do what I want or am I completely barking up the wrong tree??
--- Follow up:
It would seem I can achieve what I want if I make use of the @ImplementedBy tag on the interface and then just provide a binding in the test case, which works nicely when there is a 1-1 mapping between the interface and implementation.
Also, after discussing this with a colleague it would seem we'd head down the road of overriding an entire module and ensuring we have our modules defined correctly. This seems like it might cause a problem though where a binding is misplaced in a module and needs to be moved, thus possibly breaking a load of tests as bindings may no longer be available to be overriden. | This might not be the answer you're looking for, but if you're writing unit tests, you probably shouldn't be using an injector and rather be injecting mock or fake objects by hand.
On the other hand, if you really want to replace a single binding, you could use `Modules.override(..)`:
```
public class ProductionModule implements Module {
public void configure(Binder binder) {
binder.bind(InterfaceA.class).to(ConcreteA.class);
binder.bind(InterfaceB.class).to(ConcreteB.class);
binder.bind(InterfaceC.class).to(ConcreteC.class);
}
}
public class TestModule implements Module {
public void configure(Binder binder) {
binder.bind(InterfaceC.class).to(MockC.class);
}
}
Guice.createInjector(Modules.override(new ProductionModule()).with(new TestModule()));
```
See details in the [Modules documentation](https://google.github.io/guice/api-docs/3.0/javadoc/com/google/inject/util/Modules.html#override(com.google.inject.Module...)).
But as the javadoc for `Modules.overrides(..)` recommends, you should design your modules in such a way that you don't need to override bindings. In the example you gave, you could accomplish that by moving the binding of `InterfaceC` to a separate module. | Why not to use inheritance? You can override your specific bindings in `overrideMe` method, leaving shared implementations in `configure` method.
```
public class DevModule implements Module {
public void configure(Binder binder) {
binder.bind(InterfaceA.class).to(TestDevImplA.class);
overrideMe(binder);
}
protected void overrideMe(Binder binder){
binder.bind(InterfaceC.class).to(ConcreteC.class);
}
};
public class TestModule extends DevModule {
@Override
public void overrideMe(Binder binder) {
binder.bind(InterfaceC.class).to(MockC.class);
}
}
```
And finally create your injector this way:
```
Guice.createInjector(new TestModule());
``` | Overriding Binding in Guice | [
"",
"java",
"unit-testing",
"guice",
""
] |
So I'm trying to build a script that automagically prepends valid column names with its appropriate table prefix (e.g. "t." or "r.")
```
$t_columns = array('id', 'name', 'label');
$r_columns = array('related_value');
```
INPUT:
```
id > 1 AND (name = 'Hello' OR label IN ('World', 'Planet name AND label')) AND (related_value > 1 AND related_value < 50)
```
OUTPUT:
```
t.id > 1 AND (t.name = 'Hello' OR t.label IN ('World', 'Planet name AND label')) AND (r.related_value > 1 AND r.related_value < 50)
```
Notice how you can't do a normal **str\_replace**. What would be the simplest code (I'm guessing **preg\_replace**) to ensure that all table names are properly prepended? | This can be done in a lot of ways, and also using regex. I'd personally use an array approach. First of all, I'd define the mangling table this way:
```
$table = array(
'id' => 't.id',
'name' => 't.name',
'label' => 't.label',
'related_value' => 'r.related_value'
);
```
This will make a lot easier the str\_replace() call:
```
function mangling(&$v, $k, $table)
{
if (($k & 1) == 0)
$v = str_replace(array_keys($table), array_values($table), $v);
}
$spans = explode("'", ' ' . $input);
array_walk($spans, 'mangling', $table);
$output = implode("'", $spans);
``` | After a few seconds' thinking, here's how I'd tackle it:
Walk through the string, char by char, looking for single quotes, but skipping over escaped characters. The stuff between two unescaped single quotes (i.e. the strings) would be replaced with an unique token, and put into an associative array, with that token as the key, and the original string as the value.
Now that we have the strings out of the way, do a `str_replace()` (or `preg_replace()`, if you insist) for the known column names. I'd probably construct the column names into an associative array, with the table's alias as the key, and the value as an enumerated array containing the column names. This way, the replacement could be automated.
Once the table names are filled in, just do a `str_replace()` for the tokens, to replace the original strings back to their places, and you're done.
I'm sure someone might whip an super-awesome (and probably next to unmaintainable) regexp to do all this in one hit. But I prefer to use regexps only in situations where regular expressions are actually the right tool, not where a CFL would be more suitable. | PHP/RegEx - Logic for prepending table names | [
"",
"php",
"regex",
"logic",
""
] |
I'm trying to write a C# program, where when a user enters some data into a text box and clicks on a "save" button, the information is stored in some sort of file that when the program is opened the next time around, the information is automatically loaded in.
I'm using Visual C# express. What's the best way to do this without requiring some sort of database like MySQL or MSSQL or Access?
If the only way or easiest way is a database, I'd rather use Access. If so, does the user of the program need Access installed for my program to run on their computer? What if I go with another database?
p.s.
I forgot to mention, I'd rather the user not be able to access this file and read the contents easily. Text file without encryption would be easy to open. Any way to encrypt this? Also, if I use a delimiter like ':', then that means the user cannot use that character. So any other way?
Thanks! | Make your user data serializable by adding the keyword:
```
[Serializable]
```
above your data structure. When you load the dialog box, load your serialized structure from disk, and when you leave the dialog, save the data structure.
From a style standpoint, you should probably not have the dialog box change data until the dialog box is closed (if it's modal).
To save:
```
private bool Save(String inFileName, MyObject inObject){
try {
FileStream theStream = File.Open(inFileName, FileMode.Create);
BinaryFormatter theFormatter = new BinaryFormatter();
theFormatter.Serialize(theStream, inObject);//add it to the end there
theStream.Dispose();
theStream.Close();
} catch{
return false;
}
return true;
}
```
To Load:
```
private MyObject Read(String inFileName){
MyObject theReturn = null;
try {
FileStream theStream = File.Open(inFileName, FileMode.Open, FileAccess.Read);
BinaryFormatter theFormatter = new BinaryFormatter();
theReturn = (CImageData)theFormatter.Deserialize(theStream);//add it to the end there
theStream.Dispose();
theStream.Close();
}
catch {
return null;
}
return theReturn;
}
```
You can also use 'using' on a stream, but this code is pretty straightforward, I think. It also means that you can add more items into MyObject.
Edit: For encryption, you can add in AES or something similar. That might be overkill for you, and saving the file as binary may make it readable by something like notepad, but not easily editable. Here's a lengthy explanation on real encryption:
<http://msdn.microsoft.com/en-us/magazine/cc164055.aspx> | [Sql Compact Edition](http://www.microsoft.com/Sqlserver/2005/en/us/compact.aspx) would hide the data from being easily accessible (and its free). You can also password protect a CE database. A SQL CE database is contained completely in an .SDF file, like Access, so you can copy the .sdf file around and not have to worry about network connectivity, etc. | C# Storage of User Entered Data | [
"",
"c#",
"data-storage",
""
] |
I've been programming opengl using glut as my window handler, lately i've been thinking if there are any advantages to switching to an alternate window handler such as wxWidgets or qt.
Are there any major differences at all or is it just a matter of taste? Since glut provides some additional functions for opengl-programming beyond the window handling features, would there be a point in combining an additional toolkit with glut? | I can only speak from experiential of using QT:
Once you have the basic structure set up then it is a simple case of doing what you have always done: for example, the project I am working on at the moment has an open gl widget embedded in the window.
This widget has functions such as initializeGL, resize...paintGL etc. Advantages include the ability to pass variables to an from the other windows / widgets etc. QT also has additional functions for handelling mouse clicks and stuff (great for 2d stuff, 32d stuff requires some more complex maths) | You need to move from glut as soon as you want more complex controls and dialogs etc.
QT has an excellent [openGL widget](http://doc.trolltech.com/4.4/qglwidget.html) there is also an interesting article in the newsletter about [drawing controls ontop of GL](http://doc.trolltech.com/qq/qq26-openglcanvas.html) to give cool WPF style effects.
wxWidgets also comes with an [opengl example](http://www.wxwidgets.org/docs/tutorials/opengl.htm) but I don't have much experience of it. | window handlers for opengl | [
"",
"c++",
"opengl",
"graphics",
"3d",
"glut",
""
] |
The [Java documentation](https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html) says:
> it is not possible for two invocations of synchronized methods on the same object to interleave.
What does this mean for a static method? Since a static method has no associated object, will the synchronized keyword lock on the class, instead of the object? | > Since a static method has no associated object, *will the synchronized keyword lock on the class, instead of the object?*
Yes. :) | Just to add a little detail to Oscar's (pleasingly succinct!) answer, the relevant section on the Java Language Specification is [8.4.3.6, 'synchronized Methods'](http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.4.3.6):
> A synchronized method acquires a monitor ([§17.1](https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.1)) before it executes. For a class (static) method, the monitor associated with the Class object for the method's class is used. For an instance method, the monitor associated with this (the object for which the method was invoked) is used. | Java synchronized static methods: lock on object or class | [
"",
"java",
"class",
"static",
"methods",
"synchronized",
""
] |
Currently, we're using the following version numbering scheme for our C# winforms project:
"Major Release"."Minor Release"."Iteration Number"."Build Number within that Iteration"
We wanted to be able to identify the iteration number and the build number within that iteration just by looking at the version number.
In the past, we had done something like:"Major Release"."Minor Release"."Sequential Build Number from 1.0". For example, "4.0.648" would mean there were 648 builds since 1.0 - but this information is fairly useless and anecdotal, which is why we changed to reflect iterations and builds within iterations.
So considering this new agile version numbering, we now have the problem where a different product group would like to make changes in their iteration for our project. In this instance, the version number would not make sense, because their iteration and build numbers do not correspond. For example, my project's last build was 1.0.5.1 indicating the 1st build of iteration 5. Now this other project that in it's 3rd iteration would like to make changes to my project and rebuild.
How should I cope with this situation? How do you do version numbering in your agile project? | I track the agile projects' iteration, not the software projects' iteration. If a late starter side project joins after another project it will therefore init with the current agile project iteration, and there will be no misalignment.
It should not be possible for a technical project outside of the agile project's domain to interact with a project within the domain. That would be a PM failure of the process and should be eliminated in all cases where a shared code base is in use with branching, to be patched into the trunk as a cleanup step after the project completion. | Personally, I think that the release versioning I've liked the best is to do away with the whole `major.minor` stuff altogether. I think that this is only really feasible for internal applications, but for that, it makes life a lot easier.
Typically, if you're developing internally facing applications, I've noticed that the business never actually cares about what major/minor version they are using. Instead, they tend to want to know a) when is the next release and b) what's going to be in or out - and that's about it. Trying to keep the fact that you're working on `FOO-4.34.0.1-a` and `BAR-3.19.4.1` when nobody cares only serves to complicate communication.
At a prior group, we didn't really have major releases other than a project kickoff. Every release was as 'major' as the prior one.
As a result, I think that they did the sensible thing and instead communicated to the business as `PROJECT_RELEASENUM`. The release number incremented by '1' everytime we did a release, with patches as `PROJECT_RELEASENUM_PATCHNUM`, which also incremented by '1'.
It works well with the notion that development is done as a continual series of sprints until the business has all of the functionality that they need (which in practice never happens - there's always *something* more that they want). Business owners understood it, developers could communicate it, and it lent itself naturally to the continual development model we had. | How do you do version numbering in an agile project? | [
"",
"c#",
"agile",
"versioning",
""
] |
I want to cancel this operation if the user selects a specific item because I don't want to force the user to open the dropdown again.
Can this be done? | Why are you putting that item into the drop down list if you will not allow the user to select it? Can you modify your design to provide a more useful user interface? | Maybe you could just use [ListBox](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.aspx) control? Preventing combobox closing is imho a bad UI design idea... | Cancel ComboBox dropdown closing | [
"",
"c#",
"winforms",
"combobox",
""
] |
I did the following to upper case the first letter in each word but it's only working on the first word. Could someone explain why?
```
static void Main(string[] args)
{
string s = "how u doin the dnt know about medri sho min shan ma baref shu";
string a = tocap(s);
Console.WriteLine(a);
}
public static string tocap(string s)
{
if (s.Length == 1) return s.ToUpper();
string s1;
string s2;
s1 = s.Substring(0, 1).ToUpper();
s2 = s.Substring(1).ToLower();
return s1+s2;
}
``` | I guess you'll get this better if you understand actually what you're doing:
```
public static string tocap(string s)
{
// This says: "if s length is 1 then returned converted in upper case"
// for instance if s = "a" it will return "A". So far the function is ok.
if (s.Length == 1) return s.ToUpper();
string s1;
string s2;
// This says: "from my string I want the FIRST letter converted to upper case"
// So from an input like s = "oscar" you're doing this s1 = "O"
s1 = s.Substring(0, 1).ToUpper();
// finally here you're saying: "for the rest just give it to me all lower case"
// so for s= "oscar"; you're getting "scar" ...
s2 = s.Substring(1).ToLower();
// and then return "O" + "scar" that's why it only works for the first
// letter.
return s1+s2;
}
```
Now what you have to do is to change you're algorithm ( and then your code ) to do WHAT you intend to do
You can either "split" your string in parts where an space is found, OR you can go for each character and when you find an space you know the following letter will be the beginning of the word isn't ?
Try this algorithm-psudo code
```
inside_space = false // this flag will tell us if we are inside
// a white space.
for each character in string do
if( character is white space ) then
inside_space = true // you're in an space...
// raise your flag.
else if( character is not white space AND
inside_space == true ) then
// this means you're not longer in a space
// ( thus the beginning of a word exactly what you want )
character = character.toUper() // convert the current
// char to upper case
inside_space = false; // turn the flag to false
// so the next won't be uc'ed
end
// Here you just add your letter to the string
// either white space, upercased letter or any other.
result = result + character
end // for
```
Think about it.
You'll be doing what you want:
* Go letter by letter and
* if you're in a space you put a flag,
* when you're no longer in space then you are in the beginning of a word, the action to take is convert it to uppercase.
* For the rest you just append the letter to the result.
When you're learning to program it is better to start doing the "algorithm" in a paper and once you know it will do what you want, pass it to the programming language in turn. | Since no professor would accept this solution, I feel fine letting anyone googling this know that you can just use [ToTitleCase](http://msdn.microsoft.com/en-us/library/system.globalization.textinfo.totitlecase.aspx) | Why is only the first word capitalizing when using the tocap() function? | [
"",
"c#",
"string",
""
] |
How would I go about programmatically changing the desktop background in Mac OS X? I'd like to use python, but I'm interested in any way possible. Could I hook up to Terminal and call a certain command? | From python, if you have [appscript](http://appscript.sourceforge.net/) installed (`sudo easy_install appscript`), you can simply do
```
from appscript import app, mactypes
app('Finder').desktop_picture.set(mactypes.File('/your/filename.jpg'))
```
Otherwise, this applescript will change the desktop background
```
tell application "Finder"
set desktop picture to POSIX file "/your/filename.jpg"
end tell
```
You can run it from the command line using [`osascript`](http://developer.apple.com/DOCUMENTATION/DARWIN/Reference/ManPages/man1/osascript.1.html), or from Python using something like
```
import subprocess
SCRIPT = """/usr/bin/osascript<<END
tell application "Finder"
set desktop picture to POSIX file "%s"
end tell
END"""
def set_desktop_background(filename):
subprocess.Popen(SCRIPT%filename, shell=True)
``` | If you are doing this for the current user, you can run, from a shell:
```
defaults write com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
```
Or, as root, for another user:
```
/usr/bin/defaults write /Users/joeuser/Library/Preferences/com.apple.desktop Background '{default = {ImageFilePath = "/Library/Desktop Pictures/Black & White/Lightning.jpg"; };}'
chown joeuser /Users/joeuser/Library/Preferences/com.apple.desktop.plist
```
You will of course want to replace the image filename and user name.
The new setting will take effect when the Dock starts up -- either at login, or, when you
```
killall Dock
```
[Based on [a posting elsewhere](http://forums.macrumors.com/showpost.php?p=7237192&postcount=18), and based on information from [Matt Miller's answer](https://stackoverflow.com/questions/431205/how-can-i-programatically-change-the-background-in-mac-os-x/431273#431273).] | How can I programmatically change the background in Mac OS X? | [
"",
"python",
"image",
"macos",
""
] |
Some loading routines in my program takes to long to complete. I want a quick small snippet for checking how long a function took to execute. By small I mean "preferably without 3rd party libraries".
Maybe something as simple as taking the system time?
```
start = current_system_time()
load_something()
delta = current_system_time()-start
log_debug("load took "+delta)
```
**Edit:** Target OS in question is Windows. | Your answer: Yes
Caveat: That **WON'T** work in multihtreaded code or multiple core machines, you need a robust wall-clock timer.
So I recommend you use omp's wallclock. OMP is included with VC and GCC, and most compilers and its a standard you don't need to worry about disappearing
```
#include <omp.h>
// Starting the time measurement
double start = omp_get_wtime();
// Computations to be measured
...
// Measuring the elapsed time
double end = omp_get_wtime();
// Time calculation (in seconds)
``` | ```
#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
namespace win32 {
#include <windows.h>
}
class timer
{
win32::LARGE_INTEGER start_time_;
public:
timer() { QueryPerformanceCounter( &start_time_ ); }
void restart() { QueryPerformanceCounter( &start_time_ ); }
double elapsed() const
{
win32::LARGE_INTEGER end_time, frequency;
QueryPerformanceCounter( &end_time );
QueryPerformanceFrequency( &frequency );
return double( end_time.QuadPart - start_time_.QuadPart )
/ frequency.QuadPart;
}
};
#else
#include <ctime>
class timer
{
clock_t _start_time;
public:
timer() { _start_time = clock(); }
void restart() { _start_time = clock(); }
double elapsed() const
{
return double(clock() - _start_time) / CLOCKS_PER_SEC;
}
};
#endif
template< typename Func >
double measure_time( Func f )
{
timer t;
f();
return t.elapsed();
}
``` | Looking for benchmarking code snippet (c++) | [
"",
"c++",
"windows",
"time",
"benchmarking",
""
] |
I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the table?
(SQL answers preferable over clicking about in the GUI of the management studio.) | Not sure why no one suggested but I use `sp_fkeys` to query foreign keys for a given table:
```
EXEC sp_fkeys 'TableName'
```
You can also specify the schema:
```
EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo'
```
Without specifying the schema, the [docs](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql) state the following:
> If pktable\_owner is not specified, the default table visibility rules
> of the underlying DBMS apply.
>
> In SQL Server, if the current user owns a table with the specified
> name, that table's columns are returned. If pktable\_owner is not
> specified and the current user does not own a table with the specified
> pktable\_name, the procedure looks for a table with the specified
> pktable\_name owned by the database owner. If one exists, that table's
> columns are returned. | This gives you:
* The FK itself itself
* Schema that the FK belongs to
* The "*referencing table*" or the table that has the FK
* The "*referencing column*" or the column inside referencing table that points to the FK
* The "*referenced table*" or the table that has the key column that your FK is pointing to
* The "*referenced column*" or the column that is the key that your FK is pointing to
Code below:
```
SELECT obj.name AS FK_NAME,
sch.name AS [schema_name],
tab1.name AS [table],
col1.name AS [column],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id AND col2.object_id = tab2.object_id
``` | How can I list all foreign keys referencing a given table in SQL Server? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm adding some encryption methods to a class library (C# 2.0) and would like to know the best place to put the pass phrase, salt value and initialisation vector required. Is it a really bad idea just to hard-code these into the DLL, or should I be be encoding them and storing them somewhere else?
Thanks.
**Edit:** Further info - encryption required for personal info in database (addresses, phone numbers etc..), no bank/medical type info so solution doesn't need to be too hard-core. Class library will be used on a server for a web-app, encryption methods to be used in the data layer. | If you're using public key encryption, then you'll want to freely distribute the public key (most likely) and keep access to the private key highly restricted (only on storage media that you know are secure). Either way, it is typical to store keys as base64-encoded strings in XML files. The RSACryptoServiceProvider class has built-in capability to do this, I believe. | If you hard-code you initialisation vector and key into the DLL, then you really may as well forgo encryption altogether. If you could tell us a bit more about the reason you're using encryption here and how the data needs to be accessed precisely, perhaps I can suggest how you can make it secure.
EDIT: You'll probably want to use public key encryption for this purpose (the RSA algorithm specifically, as it's known to be secure, and is implemented fully in the .NET framework). It's asymmetric, which means that it requires a different key to encrypt (public) and decrypt (private) data. Although I'm still not totally sure how your system works, I suspect you'll just need to restrict access to the private key to just those people who are able to view the database information - you certainly don't want to store it at the same location as the database. Public key can essentially be given to anyone, as it just allows you to encrypt data to be put in the database (assuming write-access to the database is properly restricted). Anyway here are some links to get you started:
* [Implementing RSA in C#](https://stackoverflow.com/questions/384401/implementing-rsa-in-c)
* <http://www.dotnetspider.com/resources/692-RSA-Encryption-C.aspx>
* <http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider.aspx>
Hope that helps. | Best way to 'hide' pass phrases, init vectors etc.. for encryption in a class library | [
"",
"c#",
"security",
"dll",
"encryption",
""
] |
Imagine I am doing something like this:
```
void *p = malloc (1000);
*((char*)p) = some_opcode;
*((char*)p+1) = another_opcode; // for the sake of the example: the opcodes are ok
....
etc...
```
How can I define a function pointer to call p as if it was a function? (i'm using VC++ 2008 express).
Thanks | A comment wasn't enough space. Joe\_Muc is correct. You should not stuff code into memory obtained by `malloc` or `new`. You will run into problems if you change the page properties of pages that Windows allocates.
This isn't a problem becuase using VirtualAlloc() and the related WIn32 APIs is every easy: call [VirtualAlloc(](http://msdn.microsoft.com/en-us/library/aa366887.aspx)) and set the `flProtect` to `[PAGE_EXECUTE_READWRITE][2]`
Note, you should probably do three allocations, one guard page, the pages you need for your code, then another guard page. This will give you a little protection from bad code.
Also wrap calls to your generated code with [structured exception handling](http://msdn.microsoft.com/en-us/library/ms680657(VS.85).aspx).
Next, the Windows X86 ABI (calling conventions) are not well documented (I know, I've looked). There is some info [here](http://support.microsoft.com/kb/100832), [here](http://msdn.microsoft.com/en-us/library/aa235439(VS.60).aspx), [here](http://www.agner.org/optimize/calling_conventions.pdf) The best way to see how things work is to look at code generated by the compiler. This is easy to do with the [`\FA` switches](http://msdn.microsoft.com/en-us/library/367y26c6(VS.80).aspx) ( there are four of them).
You can find the 64-bit calling conventions [here](http://msdn.microsoft.com/en-us/library/ms794533.aspx).
Also, you can still obtain Microsoft's Macro Assembler [MASM here](http://www.microsoft.com/downloads/details.aspx?familyid=7A1C9DA0-0510-44A2-B042-7EF370530C64&displaylang=en). I recommend writing your machine code in MASM and look at its output, then have your machine code generator do similar things.
[Intel's](http://www.intel.com/products/processor/manuals/index.htm) and [AMD's](http://www.amd.com/us-en/Processors/TechnicalResources/0,,30_182_739_15343,00.html) processor manuals are good references - get them if you don't have them. | Actually, malloc probably won't cut it. On Windows you probably need to call something like [VirtualAlloc](<http://msdn.microsoft.com/en-us/library/aa366887(VS.85).aspx)> in order to get an executable page of memory.
Starting small:
```
void main(void)
{
char* p = (char*)VirtualAlloc(NULL, 4096, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
p[0] = (char)0xC3; // ret
typedef void (*functype)();
functype func = (functype)p;
(*func)();
}
```
The next step for playing nice with your code is to preserve the EBP register. This is left as an exercise. :-)
After writing this, I ran it with malloc and it also worked. That may be because I'm running an admin account on Windows 2000 Server. Other versions of Windows may actually need the VirtualAlloc call. Who knows. | calling code stored in the heap from vc++ | [
"",
"c++",
"pointers",
"assembly",
"function-pointers",
"opcode",
""
] |
Well I tried to figure out is this possible in any way. Here is code:
```
a=function(text)
{
var b=text;
if (!arguments.callee.prototype.get)
arguments.callee.prototype.get=function()
{
return b;
}
else
alert('already created!');
}
var c=new a("test"); // creates prototype instance of getter
var d=new a("ojoj"); // alerts already created
alert(c.get()) // alerts test
alert(d.get()) // alerts test from context of creating prototype function :(
```
As you see I tried to create prototype getter. For what? Well if you write something like this:
```
a=function(text)
{
var b=text;
this.getText=function(){ return b}
}
```
... everything should be fine.. but in fact every time I create object - i create getText function that uses memory. I would like to have one prototypical function lying in memory that would do the same... Any ideas?
EDIT:
I tried solution given by Christoph, and it seems that its only known solution for now. It need to remember id information to retrieve value from context, but whole idea is nice for me :) Id is only one thing to remember, everything else can be stored once in memory. In fact you could store a lot of private members this way, and use anytime only one id. Actually this is satisfying me :) (unless someone got better idea).
```
someFunc = function()
{
var store = new Array();
var guid=0;
var someFunc = function(text)
{
this.__guid=guid;
store[guid++]=text;
}
someFunc.prototype.getValue=function()
{
return store[this.__guid];
}
return someFunc;
}()
a=new someFunc("test");
b=new someFunc("test2");
alert(a.getValue());
alert(b.getValue());
``` | JavaScript traditionally did not provide a mechanism for property hiding ('private members').
As JavaScript is lexically scoped, you could always simulate this on a per-object level by using the constructor function as a closure over your 'private members' and defining your methods in the constructor, but this won't work for methods defined in the constructor's prototype property.
Of course, there are ways to work around this, but I wouldn't recommend it:
```
Foo = (function() {
var store = {}, guid = 0;
function Foo() {
this.__guid = ++guid;
store[guid] = { bar : 'baz' };
}
Foo.prototype.getBar = function() {
var privates = store[this.__guid];
return privates.bar;
};
Foo.prototype.destroy = function() {
delete store[this.__guid];
};
return Foo;
})();
```
This will store the 'private' properties in another object seperate from your `Foo` instance. Make sure to call `destroy()` after you're done wih the object: otherwise, you've just created a memory leak.
---
**edit 2015-12-01:** ECMAScript6 makes improved variants that do not require manual object destruction possible, eg by using a [WeakMap](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) or preferably a [Symbol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol), avoiding the need for an external store altogether:
```
var Foo = (function() {
var bar = Symbol('bar');
function Foo() {
this[bar] = 'baz';
}
Foo.prototype.getBar = function() {
return this[bar];
};
return Foo;
})();
``` | With modern browsers adopting some ES6 technologies, you can use `WeakMap` to get around the GUID problem. This works in IE11 and above:
```
// Scope private vars inside an IIFE
var Foo = (function() {
// Store all the Foos, and garbage-collect them automatically
var fooMap = new WeakMap();
var Foo = function(txt) {
var privateMethod = function() {
console.log(txt);
};
// Store this Foo in the WeakMap
fooMap.set(this, {privateMethod: privateMethod});
}
Foo.prototype = Object.create(Object.prototype);
Foo.prototype.public = function() {
fooMap.get(this).p();
}
return Foo;
}());
var foo1 = new Foo("This is foo1's private method");
var foo2 = new Foo("This is foo2's private method");
foo1.public(); // "This is foo1's private method"
foo2.public(); // "This is foo2's private method"
```
`WeakMap` won't store references to any `Foo` after it gets deleted or falls out of scope, and since it uses objects as keys, you don't need to attach GUIDs to your object. | Javascript private member on prototype | [
"",
"javascript",
"prototype",
"private",
""
] |
How does the code looks that would create an object of class:
```
string myClass = "MyClass";
```
Of the above type, and then call
```
string myMethod = "MyMethod";
```
On that object? | * Use [`Type.GetType(string)`](http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx) to get the type object.
* Use [`Activator.CreateInstance(Type)`](http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx) to create an instance.
* Use [`Type.GetMethod(string)`](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx) to retrieve a method.
* Use [`MethodBase.Invoke(object, object[])`](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx) to invoke the method on the object
Example, but with no error checking:
```
using System;
using System.Reflection;
namespace Foo
{
class Test
{
static void Main()
{
Type type = Type.GetType("Foo.MyClass");
object instance = Activator.CreateInstance(type);
MethodInfo method = type.GetMethod("MyMethod");
method.Invoke(instance, null);
}
}
class MyClass
{
public void MyMethod()
{
Console.WriteLine("In MyClass.MyMethod");
}
}
}
```
Each step needs careful checking - you may not find the type, it may not have a parameterless constructor, you may not find the method, you may invoke it with the wrong argument types.
One thing to note: Type.GetType(string) needs the assembly-qualified name of the type unless it's in the currently executing assembly or mscorlib. | I've created a library which simplifies dynamic object creation and invocation using .NET you can download the library and the code in google code: [Late Binding Helper](http://code.google.com/p/latebindinghelper/)
In the project you will find a [Wiki page with the usage](http://code.google.com/p/latebindinghelper/wiki/Usage), or you can also check this [article in CodeProject](http://www.codeproject.com/KB/cs/LateBindingHelper.aspx)
Using my library, your example will look like this:
```
IOperationInvoker myClass = BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass");
myClass.Method("MyMethod").Invoke();
```
Or even shorter:
```
BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass")
.Method("MyMethod")
.Invoke();
```
It uses a fluent interface, and truly simplifies this kind of operations. I hope you could find it useful. | How to do dynamic object creation and method invocation in .NET 3.5 | [
"",
"c#",
".net",
"dynamic",
"clr",
"invocation",
""
] |
I have a forum on a website I master, which gets a daily dose of pron spam. Currently I delete the spam and block the IP. But this does not work very well. The list of blocked IP's is growing quickly, but so is the number of spam posts in the forum.
The forum is entirely my own code. It is built in PHP and MySQL.
What are some concrete ways of stopping the spam?
**Edit**
The thing I forgot to mention is that the forum needs to be open for unregistered users to post. Kinda like a blog comment. | In a guestbook app I wrote, I implemented two features which prevent most of the spam:
* Don't allow POST as the first request in a session
* Require a valid HTTP Refer(r)er when posting | One way that I know which works is to use JavaScript before submitting the form. For example, to change the method from GET to POST. ;) Spambots are lousy at executing JavaScript. Of course, this also means that non-Javascript people will not be able to use your site... if you care about them that is. ;) (Note: I don't) | How do I protect my forum against spam? | [
"",
"php",
"mysql",
"forum",
"spam-prevention",
""
] |
I have a console application that contains quite a lot of threads. There are threads that monitor certain conditions and terminate the program if they are true. This termination can happen at any time.
I need an event that can be triggered when the program is closing so that I can cleanup all of the other threads and close all file handles and connections properly. I'm not sure if there is one already built into the .NET framework, so I'm asking before I write my own.
I was wondering if there was an event along the lines of:
```
MyConsoleProgram.OnExit += CleanupBeforeExit;
``` | I am not sure where I found the code on the web, but I found it now in one of my old projects. This will allow you to do cleanup code in your console, e.g. when it is abruptly closed or due to a shutdown...
```
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
enum CtrlType
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig)
{
switch (sig)
{
case CtrlType.CTRL_C_EVENT:
case CtrlType.CTRL_LOGOFF_EVENT:
case CtrlType.CTRL_SHUTDOWN_EVENT:
case CtrlType.CTRL_CLOSE_EVENT:
default:
return false;
}
}
static void Main(string[] args)
{
// Some biolerplate to react to close window event
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
...
}
```
**Update**
For those not checking the comments it seems that this particular solution does **not** work well (or at all) on **Windows 7**. The following [thread](http://social.msdn.microsoft.com/Forums/en/windowscompatibility/thread/abf09824-4e4c-4f2c-ae1e-5981f06c9c6e) talks about this | Full working example, works with ctrl-c, closing the windows with X and kill:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace TestTrapCtrlC {
public class Program {
static bool exitSystem = false;
#region Trap application termination
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(EventHandler handler, bool add);
private delegate bool EventHandler(CtrlType sig);
static EventHandler _handler;
enum CtrlType {
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT = 1,
CTRL_CLOSE_EVENT = 2,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT = 6
}
private static bool Handler(CtrlType sig) {
Console.WriteLine("Exiting system due to external CTRL-C, or process kill, or shutdown");
//do your cleanup here
Thread.Sleep(5000); //simulate some cleanup delay
Console.WriteLine("Cleanup complete");
//allow main to run off
exitSystem = true;
//shutdown right away so there are no lingering threads
Environment.Exit(-1);
return true;
}
#endregion
static void Main(string[] args) {
// Some boilerplate to react to close window event, CTRL-C, kill, etc
_handler += new EventHandler(Handler);
SetConsoleCtrlHandler(_handler, true);
//start your multi threaded program here
Program p = new Program();
p.Start();
//hold the console so it doesn’t run off the end
while (!exitSystem) {
Thread.Sleep(500);
}
}
public void Start() {
// start a thread and start doing some processing
Console.WriteLine("Thread started, processing..");
}
}
}
``` | Capture console exit C# | [
"",
"c#",
".net",
"events",
"console",
"exit",
""
] |
Is there a way to use the DPAPI (Data Protection Application Programming Interface) on Windows XP with Python?
I would prefer to use an existing module if there is one that can do it. Unfortunately I haven't been able to find a way with Google or Stack Overflow.
**EDIT:** I've taken the example code pointed to by "dF" and tweaked it into a standalone library which can be simply used at a high level to crypt and decrypt using DPAPI in user mode. Simply call dpapi.cryptData(text\_to\_encrypt) which returns an encrypted string, or the reverse decryptData(encrypted\_data\_string), which returns the plain text. Here's the library:
```
# DPAPI access library
# This file uses code originally created by Crusher Joe:
# http://article.gmane.org/gmane.comp.python.ctypes/420
#
from ctypes import *
from ctypes.wintypes import DWORD
LocalFree = windll.kernel32.LocalFree
memcpy = cdll.msvcrt.memcpy
CryptProtectData = windll.crypt32.CryptProtectData
CryptUnprotectData = windll.crypt32.CryptUnprotectData
CRYPTPROTECT_UI_FORBIDDEN = 0x01
extraEntropy = "cl;ad13 \0al;323kjd #(adl;k$#ajsd"
class DATA_BLOB(Structure):
_fields_ = [("cbData", DWORD), ("pbData", POINTER(c_char))]
def getData(blobOut):
cbData = int(blobOut.cbData)
pbData = blobOut.pbData
buffer = c_buffer(cbData)
memcpy(buffer, pbData, cbData)
LocalFree(pbData);
return buffer.raw
def Win32CryptProtectData(plainText, entropy):
bufferIn = c_buffer(plainText, len(plainText))
blobIn = DATA_BLOB(len(plainText), bufferIn)
bufferEntropy = c_buffer(entropy, len(entropy))
blobEntropy = DATA_BLOB(len(entropy), bufferEntropy)
blobOut = DATA_BLOB()
if CryptProtectData(byref(blobIn), u"python_data", byref(blobEntropy),
None, None, CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)):
return getData(blobOut)
else:
return ""
def Win32CryptUnprotectData(cipherText, entropy):
bufferIn = c_buffer(cipherText, len(cipherText))
blobIn = DATA_BLOB(len(cipherText), bufferIn)
bufferEntropy = c_buffer(entropy, len(entropy))
blobEntropy = DATA_BLOB(len(entropy), bufferEntropy)
blobOut = DATA_BLOB()
if CryptUnprotectData(byref(blobIn), None, byref(blobEntropy), None, None,
CRYPTPROTECT_UI_FORBIDDEN, byref(blobOut)):
return getData(blobOut)
else:
return ""
def cryptData(text):
return Win32CryptProtectData(text, extraEntropy)
def decryptData(cipher_text):
return Win32CryptUnprotectData(cipher_text, extraEntropy)
``` | I have been using `CryptProtectData` and `CryptUnprotectData` through ctypes, with the code from
<http://article.gmane.org/gmane.comp.python.ctypes/420>
and it has been working well. | Also, pywin32 implements CryptProtectData and CryptUnprotectData in the win32crypt module. | Using DPAPI with Python? | [
"",
"python",
"windows",
"security",
"encryption",
"dpapi",
""
] |
From some old c++ code im trying to use a com dll, it works fine when the dll is registered, but it crahses if the dll isnt registered.
// Initialize COM.
HRESULT hr = CoInitialize(NULL);
IGetTestPtr ptest(\_\_uuidof(tester));
*"Use method from the dll"*
// Uninitialize COM.
CoUninitialize();
Is it anyway to check if the dll has been registered, before calling IGetTestPtr ptest(\_\_uuidof(tester))?
Or what is the correct way to prevent the crash? | Calling CreateInstance on your object will return an HRESULT that can be tested for success:
```
IGetTestPtr p = null;
HRESULT hRes = p.CreateInstance( __uuidof(tester) );
bool bSuccess = SUCCEEDED(hRes);
```
This assumes you've created an interface wrapper around your type library using Visual Studio, where COM Smart Pointers are used in the interface (this gives you the CreateInstance method). | If the COM class is not registered then CoCreateInstance will return REGDB\_E\_CLASSNOTREG. You should check for general success or failure by using the SUCCEEDED() or FAILED() macros. You also need to create the object properly - see MDSN for an [introduction to COM](http://msdn.microsoft.com/en-us/library/ms680573(VS.85).aspx). For example:
```
HRESULT hr = CoInitialize(NULL);
if (SUCCEEDED(hr))
{
IGetTestPtr ptr = NULL;
hr = CoCreateInstance(CLSID_MyObjectNULL, CLSCTX_INPROC_SERVER, IID_IMyInterface, ptr)
if (SUCCEEDED(hr))
{
Do something with your COM object
...
// Don't forget to release your interface pointer or the object will leak
ptr->Release();
}
hr = CoUninitialize();
}
return hr;
``` | How to prevent crashing if com dll isnt registered | [
"",
"c++",
"com",
""
] |
I'm trying to create a DataGridTableStyle object so that I can control the column widths of a DataGrid. I've created a BindingSource object bound to a List. Actually it's bound to an anonymous type list created though Linq in the following manner (variable names changed for clarity of what I'm doing):
```
List<myType> myList = new List<myType>(someCapacity);
.
...populate the list with query from database...
.
var query = from i in myList
select new
{
i.FieldA,
i.FieldB,
i.FieldC
};
myBindingSource.DataSource = query;
myDataGrid.DataSource = myBindingSource;
```
Then I create a DataGridTableStyle object and add it to the datagrid. However, it never applies my table style properties I set up because I can't seem set the proper myDataGridTableStyle.MappingName property.
I've searched Google for about 1/2 an hour and keep seeing links to the same question throughout a bunch of different forums (literally the same text, like someone just copied and pasted the question... I hate that...). Anyway, none of the suggestions work, just like the guy says on all the other sites.
So does anybody here know what I need to set the MappingName property to in order to have my TableStyle actually work properly? Where can I grab the name from? (It can't be blank... that only works with a BindingSource that is bound to a DataTable or SqlCeResultSet etc.).
I'm thinking it could be an issue with me using Linq to create an anonymous, more specialized version of the objects with only the fields I need. Should I just try to bind the BindingSource directly to the List object? Or maybe even bind the DataGrid directly to the List object and skip the binding source altogether.
Thanks
PS - C#, Compact Framework v3.5
UPDATE:
I've posted an answer below that solved my problem. Whether or not it's the best approach, it did work. Worth a peek if you're having the same issue I had. | I've found the way to make this work. I'll break it out into sections...
---
```
List<myType> myList = new List<myType>(someCapacity);
.
...populate the list with query from database...
.
```
---
```
DataGridTableStyle myDataGridTableStyle = new DatGridtTableStyle();
DataGridTextBoxColumn colA = new DataGridTextBoxColumn();
DataGridTextBoxColumn colB = new DataGridTextBoxColumn();
DataGridTextBoxColumn colC = new DataGridTextBoxColumn();
colA.MappingName = "FieldA";
colA.HeaderText = "Field A";
colA.Width = 50; // or whatever;
colB.MappingName = "FieldB";
.
... etc. (lather, rinse, repeat for each column I want)
.
myDataGridTableStyle.GridColumnStyles.Add(colA);
myDataGridTableStyle.GridColumnStyles.Add(colB);
myDataGridTableStyle.GridColumnStyles.Add(colC);
```
---
```
var query = from i in myList
select new
{
i.FieldA,
i.FieldB,
i.FieldC
};
myBindingSource.DataSource = query.ToList(); // Thanks Marc Gravell
// wasn't sure what else to pass in here, but null worked.
myDataGridTableStyle.MappingName = myBindingSource.GetListName(null);
myDataGrid.TableStyles.Clear(); // Recommended on MSDN in the code examples.
myDataGrid.TablesStyles.Add(myDataGridTableStyle);
myDataGrid.DataSource = myBindingSource;
```
---
So basically, the DataGridTableStyle.MappingName needs to know what type of object it is mapping to. Since my object is an anonymous type (created with Linq), I don't know what it is until runtime. After I bind the list of the anonymous type to the binding source, **I can use BindingSource.GetListName(null) to get the string representation of the anonymous type.**
One thing to note. If I just bound the myList (which is type "myType") directly to the binding source, I could have just used the string "myType" as the value for DataGridTableStyle.MappingName.
Hopefully this is useful to other people! | Just to add to the collection of answers already on this page....
I was just frustrated with this same issue trying to develop my fist application using windows forms and compact framework (For Windows Mobile 6.5).
What I found out, through Marc Gravell's comment above is that indeed is possible to get the run time MappingName inspecting the properties of the DataGrid. Doing this I found out that when binding my `List<MyType>` directly to the DataSource property of the DataGrid, the DataGrid was actually looking for a DataGridTableStyle with the MappingName of
```
"List`1"
```
instead of any combination of `List<MyType>` or `MyType`...
So... by putting "List`1" in the Mapping name on the DataGridTableStyle Collection Editor (at design time), I was able to customize the columns and other properties without having to create them all at run time.
I just hope this adds some more to the answers already provided. Thank you all for providing me with the guidelines. | How do you get the proper mapping name from a binding source bound to a List<T>, or an anonymous type, to use on a DataGridTableStyle? | [
"",
"c#",
"datagrid",
"compact-framework",
"bindingsource",
"datagridtablestyle",
""
] |
One of the biggest annoyances I find in Python is the inability of the `re` module to save its state without explicitly doing it in a match object. Often, one needs to parse lines and if they comply a certain regex take out values from them by the same regex. I would like to write code like this:
```
if re.match('foo (\w+) bar (\d+)', line):
# do stuff with .group(1) and .group(2)
elif re.match('baz whoo_(\d+)', line):
# do stuff with .group(1)
# etc.
```
But unfortunately it's impossible to get to the matched object of the previous call to `re.match`, so this is written like this:
```
m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
else:
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
```
Which is rather less convenient and gets really unwieldy as the list of `elif`s grows longer.
A hackish solution would be to wrap the re.match and re.search in my own objects that keep state somewhere. Has anyone used this? Are you aware of semi-standard implementations (in large frameworks or something)?
What other workarounds can you recommend?
Or perhaps, am I just misusing the module and could achieve my needs in a cleaner way?
Thanks in advance | Trying out some ideas...
It looks like you would ideally want an expression with side effects. If this were allowed in Python:
```
if m = re.match('foo (\w+) bar (\d+)', line):
# do stuff with m.group(1) and m.group(2)
elif m = re.match('baz whoo_(\d+)', line):
# do stuff with m.group(1)
elif ...
```
... then you would clearly and cleanly be expressing your intent. But it's not. If side effects were allowed in nested functions, you could:
```
m = None
def assign_m(x):
m = x
return x
if assign_m(re.match('foo (\w+) bar (\d+)', line)):
# do stuff with m.group(1) and m.group(2)
elif assign_m(re.match('baz whoo_(\d+)', line)):
# do stuff with m.group(1)
elif ...
```
Now, not only is that getting ugly, but it's still not valid Python code -- the nested function 'assign\_m' isn't allowed to modify the variable `m` in the outer scope. The best I can come up with is **really** ugly, using nested class which is allowed side effects:
```
# per Brian's suggestion, a wrapper that is stateful
class m_(object):
def match(self, *args):
self.inner_ = re.match(*args)
return self.inner_
def group(self, *args):
return self.inner_.group(*args)
m = m_()
# now 'm' is a stateful regex
if m.match('foo (\w+) bar (\d+)', line):
# do stuff with m.group(1) and m.group(2)
elif m.match('baz whoo_(\d+)', line):
# do stuff with m.group(1)
elif ...
```
But that is **clearly** overkill.
You migth consider using an inner function to allow local scope exits, which allows you to remove the `else` nesting:
```
def find_the_right_match():
# now 'm' is a stateful regex
m = re.match('foo (\w+) bar (\d+)', line)
if m:
# do stuff with m.group(1) and m.group(2)
return # <== exit nested function only
m = re.match('baz whoo_(\d+)', line)
if m:
# do stuff with m.group(1)
return
find_the_right_match()
```
This lets you flatten nesting=(2\*N-1) to nesting=1, but you may have just moved the side-effects problem around, and the nested functions are very likely to confuse most Python programmers.
Lastly, there are side-effect-free ways of dealing with this:
```
def cond_with(*phrases):
"""for each 2-tuple, invokes first item. the first pair where
the first item returns logical true, result is passed to second
function in pair. Like an if-elif-elif.. chain"""
for (cond_lambda, then_lambda) in phrases:
c = cond_lambda()
if c:
return then_lambda(c)
return None
cond_with(
((lambda: re.match('foo (\w+) bar (\d+)', line)),
(lambda m:
... # do stuff with m.group(1) and m.group(2)
)),
((lambda: re.match('baz whoo_(\d+)', line)),
(lambda m:
... # do stuff with m.group(1)
)),
...)
```
And now the code barely even **looks** like Python, let alone understandable to Python programmers (is that Lisp?).
I think the moral of this story is that Python is not optimized for this sort of idiom. You really need to just be a little verbose and live with a large nesting factor of else conditions. | You might like [this module](http://code.activestate.com/recipes/456151/) which implements the wrapper you are looking for. | Python's re module - saving state? | [
"",
"python",
"regex",
""
] |
I want to read, write and create Spreadsheets in the Open Document Format with Java. And I want the resulting Java-program running on a computer without OpenOffice.org or other ODS-capable programs installed. Exists a library to access this format? | Take a look at jOpenDocument:
<http://www.jopendocument.org/documentation.html>
Especially:
<http://www.jopendocument.org/start_spreadsheet_3.html> | jOpenDocument is all you need. | How can I access spreadsheets in the open document format (.ods) with Java? | [
"",
"java",
"spreadsheet",
"odf",
""
] |
I have a Windows Forms (.Net 2.0) app and I have a request to embed some custom images into some textboxes(like the new version of Tortoise does). | I haven't used OwnerDraw on a textbox, but I've used it on other controls such as the listbox and listview and I've seen other people do this with textboxes. I found a tutorial that should point you in the right direction, it's not used for displaying images in the textbox per se, but it could be used for that:
<http://www.codedblog.com/2007/09/17/owner-drawing-a-windowsforms-textbox/>
Hopefully that gets you started at least... | Hmm. Why don't you create a new userControl which has the BackColor of the TextBox. Hide TextBox's Border. Then subscribe to Paint event of the UC and draw the borders to resemble the textbox one. In the Paint Handler you can also draw an image. In the UserControl you can easily set the bounds of any child control such as textbox, or write a custom layout and place the textbox wherever you want. I hope this helps. | Embed image into a textbox | [
"",
"c#",
"winforms",
""
] |
From Joel Spolsky's [article](http://www.joelonsoftware.com/articles/LeakyAbstractions.html) on leaky abstractions:
> [C]ertain SQL queries are thousands of times slower than other logically equivalent queries. A famous example of this is that some SQL servers are dramatically faster if you specify "where a=b and b=c and a=c" than if you only specify "where a=b and b=c" even though the result set is the same.
Does anyone know the details of this? | Obviously, a = b and b = c => a = c - this is related to transitive closure. The point Joel was making is that some SQL servers are poor at optimizing queries, so some of the SQL queries might be written with "extra" qualifiers as in the example.
In this example, remember that a, b and c as above often refer to different tables, and operations like a=b are performed as joins. Suppose the number of entries in table a is 1000, b is 500 and c is 20. Then join of a, b needs 1000x500 row comparisons (this is my dumb example; in practice there might be much better join algorithms that would reduce the complexity a lot), and b,c needs 500x20 comparisons. An optimizing compiler will determine that the join of b,c should be performed first and then the result should be joined on a = b since there are fewer expected rows with b=c. In total there are about 500x20 + 500x1000 comparisons for (b=c) and (a=b) respectively. After that intersections have to be computed between the returned rows (I guess also via joins, but not sure).
Suppose the Sql server could have a logic inference module that would also infer that this means a = c. Then it would probably perform join of b,c and then join of a,c (again this is a hypothetical case). This would take 500x20 + 1000x20 comparisons and after that intersection computations. If expected #(a=c) is lesser (due to some domain knowledge) then the second query will be a lot faster.
Overall my answer has become too long, but this means that SQL query optimization is not a trivial task, and that is why some SQL servers may not do it very well.
More can be found at <http://en.wikipedia.org/wiki/Query_optimizer> or from some expect on databases reading this.
But philosophically speaking, SQL (as an abstraction) was meant to hide all aspects of implementation. It was meant to be declarative (a SQL server can itself use sql query optimization techniques to rephrase the query to make them more efficient). But in the real world it is not so - often the database queries have to be rewritten by humans to make them more efficient.
Overall, the point of the article is that an abstraction can only be so good, and no abstraction is perfect. | Here's a simpler explanation, where everything is all in one table.
Suppose A and C are both indexed, but B is not. If the optimizer can't realize that A = C, then it has to use the non-indexed B for both WHERE conditions.
But if you then tell the server that a=c, it can efficiently apply that filter first and greatly reduce the size of the working set. | SQL question from Joel Spolsky article | [
"",
"sql",
"query-optimization",
""
] |
I appear to have a memory leak in this piece of code. It is a console app, which creates a couple of classes (WorkerThread), each of which writes to the console at specified intervals. The Threading.Timer is used to do this, hence writing to the console is performed in a separate thread (the TimerCallback is called in a seperate thread taken from the ThreadPool). To complicate matters, the MainThread class hooks on to the Changed event of the FileSystemWatcher; when the test.xml file changes, the WorkerThread classes are recreated.
Each time the file is saved, (each time that the WorkerThread and therefore the Timer is recreated), the memory in the Task Manager increases (Mem Usage, and sometimes also VM Size); furthermore, in .Net Memory Profiler (v3.1), the Undisposed Instances of the WorkerThread class increases by two (this may be a red herring though, because I've read that .Net Memory Profiler had a bug whereby it struggled to detect disposed classes.
Anyway, here's the code - does anyone know what's wrong?
**EDIT**: I've moved the class creation out of the FileSystemWatcher.Changed event handler, meaning that the WorkerThread classes are always being created in the same thread. I've added some protection to the static variables. I've also provided threading information to show more clearly what's going on, and have been interchanging using the Timer with using an explicit Thread; however, the memory is still leaking! The Mem Usage increases slowly all the time (is this simply due to extra text in the console window?), and the VM Size increases when I change the file. Here is the latest version of the code:
**EDIT** This appears to be primarily a problem with the console using up memory, as you write to it. There is still a problem with explicitly written Threads increasing the memory usage. See [my answer below](https://stackoverflow.com/questions/483295/memory-leak-while-using-threads/553057#553057).
```
class Program
{
private static List<WorkerThread> threads = new List<WorkerThread>();
static void Main(string[] args)
{
MainThread.Start();
}
}
public class MainThread
{
private static int _eventsRaised = 0;
private static int _eventsRespondedTo = 0;
private static bool _reload = false;
private static readonly object _reloadLock = new object();
//to do something once in handler, though
//this code would go in onStart in a windows service.
public static void Start()
{
WorkerThread thread1 = null;
WorkerThread thread2 = null;
Console.WriteLine("Start: thread " + Thread.CurrentThread.ManagedThreadId);
//watch config
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "../../";
watcher.Filter = "test.xml";
watcher.EnableRaisingEvents = true;
//subscribe to changed event. note that this event can be raised a number of times for each save of the file.
watcher.Changed += (sender, args) => FileChanged(sender, args);
thread1 = new WorkerThread("foo", 10);
thread2 = new WorkerThread("bar", 15);
while (true)
{
if (_reload)
{
//create our two threads.
Console.WriteLine("Start - reload: thread " + Thread.CurrentThread.ManagedThreadId);
//wait, to enable other file changed events to pass
Console.WriteLine("Start - waiting: thread " + Thread.CurrentThread.ManagedThreadId);
thread1.Dispose();
thread2.Dispose();
Thread.Sleep(3000); //each thread lasts 0.5 seconds, so 3 seconds should be plenty to wait for the
//LoadData function to complete.
Monitor.Enter(_reloadLock);
thread1 = new WorkerThread("foo", 10);
thread2 = new WorkerThread("bar", 15);
_reload = false;
Monitor.Exit(_reloadLock);
}
}
}
//this event handler is called in a separate thread to Start()
static void FileChanged(object source, FileSystemEventArgs e)
{
Monitor.Enter(_reloadLock);
_eventsRaised += 1;
//if it was more than a second since the last event (ie, it's a new save), then wait for 3 seconds (to avoid
//multiple events for the same file save) before processing
if (!_reload)
{
Console.WriteLine("FileChanged: thread " + Thread.CurrentThread.ManagedThreadId);
_eventsRespondedTo += 1;
Console.WriteLine("FileChanged. Handled event {0} of {1}.", _eventsRespondedTo, _eventsRaised);
//tell main thread to restart threads
_reload = true;
}
Monitor.Exit(_reloadLock);
}
}
public class WorkerThread : IDisposable
{
private System.Threading.Timer timer; //the timer exists in its own separate thread pool thread.
private string _name = string.Empty;
private int _interval = 0; //thread wait interval in ms.
private Thread _thread = null;
private ThreadStart _job = null;
public WorkerThread(string name, int interval)
{
Console.WriteLine("WorkerThread: thread " + Thread.CurrentThread.ManagedThreadId);
_name = name;
_interval = interval * 1000;
_job = new ThreadStart(LoadData);
_thread = new Thread(_job);
_thread.Start();
//timer = new Timer(Tick, null, 1000, interval * 1000);
}
//this delegate instance does NOT run in the same thread as the thread that created the timer. It runs in its own
//thread, taken from the ThreadPool. Hence, no need to create a new thread for the LoadData method.
private void Tick(object state)
{
//LoadData();
}
//Loads the data. Called from separate thread. Lasts 0.5 seconds.
//
//private void LoadData(object state)
private void LoadData()
{
while (true)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine(string.Format("Worker thread {0} ({2}): {1}", _name, i, Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(50);
}
Thread.Sleep(_interval);
}
}
public void Stop()
{
Console.WriteLine("Stop: thread " + Thread.CurrentThread.ManagedThreadId);
//timer.Dispose();
_thread.Abort();
}
#region IDisposable Members
public void Dispose()
{
Console.WriteLine("Dispose: thread " + Thread.CurrentThread.ManagedThreadId);
//timer.Dispose();
_thread.Abort();
}
#endregion
}
``` | Well, having had some time to look into this again, it appears that the memory leak is a bit of a red herring. *When I stop writing to the console, the memory usage stops increasing*.
However, there is a remaining issue in that every time I edit the test.xml file (which fires the Changed event on the FileSystemWatcher, whose handler sets flags that cause the worker classes to be renewed and therefore threads/timers to be stopped), the memory increases by about 4K, providing that I am using explicit Threads, rather Timers. When I use a Timer, there is no problem. But, given that I would rather use a Timer than a Thread, this is no longer an issue to me, but I would still be interested in why it is occuring.
See the new code below. I've created two classes - WorkerThread and WorkerTimer, one of which uses Threads and the other Timers (I've tried two Timers, the System.Threading.Timer and the System.Timers.Timer. with the Console output switched on, you can see the difference that this makes with regards to which thread the tick event is raised on). Just comment/uncomment the appropriate lines of MainThread.Start in order to use the required class. For the reason above, it is recommended that the Console.WriteLine lines are commented out, except when you want to check that everything is working as expected.
```
class Program
{
static void Main(string[] args)
{
MainThread.Start();
}
}
public class MainThread
{
private static int _eventsRaised = 0;
private static int _eventsRespondedTo = 0;
private static bool _reload = false;
private static readonly object _reloadLock = new object();
//to do something once in handler, though
//this code would go in onStart in a windows service.
public static void Start()
{
WorkerThread thread1 = null;
WorkerThread thread2 = null;
//WorkerTimer thread1 = null;
//WorkerTimer thread2 = null;
//Console.WriteLine("Start: thread " + Thread.CurrentThread.ManagedThreadId);
//watch config
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "../../";
watcher.Filter = "test.xml";
watcher.EnableRaisingEvents = true;
//subscribe to changed event. note that this event can be raised a number of times for each save of the file.
watcher.Changed += (sender, args) => FileChanged(sender, args);
thread1 = new WorkerThread("foo", 10);
thread2 = new WorkerThread("bar", 15);
//thread1 = new WorkerTimer("foo", 10);
//thread2 = new WorkerTimer("bar", 15);
while (true)
{
if (_reload)
{
//create our two threads.
//Console.WriteLine("Start - reload: thread " + Thread.CurrentThread.ManagedThreadId);
//wait, to enable other file changed events to pass
//Console.WriteLine("Start - waiting: thread " + Thread.CurrentThread.ManagedThreadId);
thread1.Dispose();
thread2.Dispose();
Thread.Sleep(3000); //each thread lasts 0.5 seconds, so 3 seconds should be plenty to wait for the
//LoadData function to complete.
Monitor.Enter(_reloadLock);
//GC.Collect();
thread1 = new WorkerThread("foo", 5);
thread2 = new WorkerThread("bar", 7);
//thread1 = new WorkerTimer("foo", 5);
//thread2 = new WorkerTimer("bar", 7);
_reload = false;
Monitor.Exit(_reloadLock);
}
}
}
//this event handler is called in a separate thread to Start()
static void FileChanged(object source, FileSystemEventArgs e)
{
Monitor.Enter(_reloadLock);
_eventsRaised += 1;
//if it was more than a second since the last event (ie, it's a new save), then wait for 3 seconds (to avoid
//multiple events for the same file save) before processing
if (!_reload)
{
//Console.WriteLine("FileChanged: thread " + Thread.CurrentThread.ManagedThreadId);
_eventsRespondedTo += 1;
//Console.WriteLine("FileChanged. Handled event {0} of {1}.", _eventsRespondedTo, _eventsRaised);
//tell main thread to restart threads
_reload = true;
}
Monitor.Exit(_reloadLock);
}
}
public class WorkerTimer : IDisposable
{
private System.Threading.Timer _timer; //the timer exists in its own separate thread pool thread.
//private System.Timers.Timer _timer;
private string _name = string.Empty;
/// <summary>
/// Initializes a new instance of the <see cref="WorkerThread"/> class.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="interval">The interval, in seconds.</param>
public WorkerTimer(string name, int interval)
{
_name = name;
//Console.WriteLine("WorkerThread constructor: Called from thread " + Thread.CurrentThread.ManagedThreadId);
//_timer = new System.Timers.Timer(interval * 1000);
//_timer.Elapsed += (sender, args) => LoadData();
//_timer.Start();
_timer = new Timer(Tick, null, 1000, interval * 1000);
}
//this delegate instance does NOT run in the same thread as the thread that created the timer. It runs in its own
//thread, taken from the ThreadPool. Hence, no need to create a new thread for the LoadData method.
private void Tick(object state)
{
LoadData();
}
//Loads the data. Called from separate thread. Lasts 0.5 seconds.
//
private void LoadData()
{
for (int i = 0; i < 10; i++)
{
//Console.WriteLine(string.Format("Worker thread {0} ({2}): {1}", _name, i, Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(50);
}
}
public void Stop()
{
//Console.WriteLine("Stop: called from thread " + Thread.CurrentThread.ManagedThreadId);
//_timer.Stop();
_timer.Change(Timeout.Infinite, Timeout.Infinite);
//_timer = null;
//_timer.Dispose();
}
#region IDisposable Members
public void Dispose()
{
//Console.WriteLine("Dispose: called from thread " + Thread.CurrentThread.ManagedThreadId);
//_timer.Stop();
_timer.Change(Timeout.Infinite, Timeout.Infinite);
//_timer = null;
//_timer.Dispose();
}
#endregion
}
public class WorkerThread : IDisposable
{
private string _name = string.Empty;
private int _interval = 0; //thread wait interval in ms.
private Thread _thread = null;
private ThreadStart _job = null;
private object _syncObject = new object();
private bool _killThread = false;
public WorkerThread(string name, int interval)
{
_name = name;
_interval = interval * 1000;
_job = new ThreadStart(LoadData);
_thread = new Thread(_job);
//Console.WriteLine("WorkerThread constructor: thread " + _thread.ManagedThreadId + " created. Called from thread " + Thread.CurrentThread.ManagedThreadId);
_thread.Start();
}
//Loads the data. Called from separate thread. Lasts 0.5 seconds.
//
//private void LoadData(object state)
private void LoadData()
{
while (true)
{
//check to see if thread it to be stopped.
bool isKilled = false;
lock (_syncObject)
{
isKilled = _killThread;
}
if (isKilled)
return;
for (int i = 0; i < 10; i++)
{
//Console.WriteLine(string.Format("Worker thread {0} ({2}): {1}", _name, i, Thread.CurrentThread.ManagedThreadId));
Thread.Sleep(50);
}
Thread.Sleep(_interval);
}
}
public void Stop()
{
//Console.WriteLine("Stop: thread " + _thread.ManagedThreadId + " called from thread " + Thread.CurrentThread.ManagedThreadId);
//_thread.Abort();
lock (_syncObject)
{
_killThread = true;
}
_thread.Join();
}
#region IDisposable Members
public void Dispose()
{
//Console.WriteLine("Dispose: thread " + _thread.ManagedThreadId + " called from thread " + Thread.CurrentThread.ManagedThreadId);
//_thread.Abort();
lock (_syncObject)
{
_killThread = true;
}
_thread.Join();
}
#endregion
}
``` | You have two issues, both separate:
In Watcher.Changed's handler you call Thread.Sleep(3000);
This is poor behaviour in a callback of a thread you do not own (since it is being supplied by the pool owned/used by the watcher. This is not the source of your problem though. This it in direct violation of the [guidelines for use](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher.aspx)
You use statics all over the place which is horrible, and has likely led you into this problem:
```
static void test()
{
_eventsRaised += 1;
//if it was more than a second since the last event (ie, it's a new save), then wait for 3 seconds (to avoid
//multiple events for the same file save) before processing
if (DateTime.Now.Ticks - _lastEventTicks > 1000)
{
Thread.Sleep(3000);
_lastEventTicks = DateTime.Now.Ticks;
_eventsRespondedTo += 1;
Console.WriteLine("File changed. Handled event {0} of {1}.", _eventsRespondedTo, _eventsRaised);
//stop threads and then restart them
thread1.Stop();
thread2.Stop();
thread1 = new WorkerThread("foo", 20);
thread2 = new WorkerThread("bar", 30);
}
}
```
This callback can fire repeatedly on multiple different threads (it uses the system thread pool for this) You code assumes that only one thread will ever execute this method at a time since threads can be created but not not stopped.
Imagine: thread A and B
1. A thread1.Stop()
2. A thread2.Stop()
3. B thread1.Stop()
4. B thread2.Stop()
5. A thread1 = new WorkerThread()
6. A thread2 = new WorkerThread()
7. B thread1 = new WorkerThread()
8. B thread2 = new WorkerThread()
You now have 4 WorkerThread instances on the heap but only two variables referencing them, the two created by A have leaked. The event handling and callback registration with the timer means that theses leaked WorkerThreads are kept alive (in the GC sense) despite you having no reference to them in your code. they stay leaked for ever.
There are other flaws in the design but this is a critical one. | Memory leak while using Threads | [
"",
"c#",
".net",
"multithreading",
"memory",
"timer",
""
] |
I am creating a test program to test the functionality of program which calcultes CPU Utilization.
Now I want to test that program at different times when CPU utilization is 100%, 50% 0% etc.
My question how to make CPU to utilize to 100% or may be > 80%.
I think creating a while loop like will suffice
```
while(i++< 2000)
{
cout<<" in while "<< endl;
Sleep(10); // sleep for 10 ms.
}
```
After running this I dont get high CPU utilization.
What would be the possible solutions to make high cpu intensive?? | You're right to use a loop, but:
* You've got IO
* You've got a sleep
Basically nothing in that loop is going to take very much CPU time compared with the time it's sleeping or waiting for IO.
To kill a CPU you need to give it *just* CPU stuff. The only tricky bit really is making sure the C++ compiler doesn't optimise away the loop. Something like this should probably be okay:
```
// A bit like generating a hashcode. Pretty arbitrary choice,
// but simple code which would be hard for the compiler to
// optimise away.
int running_total = 23;
for (int i=0; i < some_large_number; i++)
{
running_total = 37 * running_total + i;
}
return running_total;
```
Note the fact that I'm returning the value out of the loop. That should stop the C++ compiler from noticing that the loop is useless (if you never used the value anywhere, the loop would have no purpose). You may want to disable inlining too, as otherwise I guess there's a possibility that a smart compiler would notice you calling the function without using the return value, and inline it to nothing. (As Suma points out in the answer, using `volatile` when calling the function should disable inlining.) | Your loop mostly sleeps, which means it has very light CPU load. Besides of Sleep, be sure to include some loop performing any computations, like this (Factorial implementation is left as an exercise to reader, you may replace it with any other non-trivial function).
```
while(i++< 2000)
{
int sleepBalance = 10; // increase this to reduce the CPU load
int computeBalance = 1000; // increase this to increase the CPU load
for (int i=0; i<computeBalance; i++)
{
/* both volatiles are important to prevent compiler */
/* optimizing out the function */
volatile int n = 30;
volatile int pretendWeNeedTheResult = Factorial(n);
}
Sleep(sleepBalance);
}
```
By adjusting sleepBalance / computeBalance you may adjust how much CPU this program takes. If you want to this as a CPU load simulation, you might want to take a few addtional steps:
* on a multicore system be sure to either spawn the loop like this in multiple threads (one for each CPU), or execute the process multiple times, and to make the scheduling predictable assign thread/process affinity explicitly
* sometimes you may also want to increase the thread/process priority to simulate the environment where CPU is heavily loaded with high priority applications. | Create thread with >70% CPU utilization | [
"",
"c++",
"windows",
""
] |
In the current C++ standard (C++03), there are too few specifications about text localization and that makes the C++ developer's life harder than usual when working with localized texts (certainly the C++0x standard will help here later).
### Assuming the following scenario (which is from real PC-Mac game development cases):
1. **responsive (real time) application**: the application has to minimize non-responsive times to "not noticeable", so speed of execution is important.
2. **localized texts**: displayed texts are localized in more than two languages, potentially more - don't expect a fixed number of languages, should be easily extensible.
3. **language defined at runtime**: the texts should not be compiled in the application (nor having one application per language), you get the chosen language information at application launch - which implies some kind of text loading.
4. **cross-platform**: the application is be coded with cross-platform in mind (Windows - Linux/Ubuntu - Mac/OSX) so the localized text system have to be cross platform too.
5. **stand-alone application**: the application provides all that is necessary to run it; it won't use any environment library or require the user to install anything other than the OS (like most games for example).
## What are the best practices to manage localized texts in C++ in this kind of application?
I looked into this last year that and the only things I'm sure of are that you should use `std::wstring` or `std::basic_string<ABigEnoughType>` to manipulate the texts in the application. I stopped my research because I was working more on the "text display" problem (in the case of real-time 3D), but I guess there are some best practices to manage localized texts in raw C++ beyond just that and "use Unicode".
So, all best-practices, suggestions and information (cross-platform makes it hard I think) are welcome! | At a small Video Game Company, Black Lantern Studios, I was the Lead developer for a game called Lionel Trains DS. We localized into English, Spanish, French, and German. We knew all the languages up front, so including them at compile time was the only option. (They are burned to a ROM, you see)
I can give you information on some of the things we did. Our strings were loaded into an array at startup based on the language selection of the player. Each individual language went into a separate file with all the strings in the same order. String 1 was always the title of the game, string 2 always the first menu option, and so on. We keyed the arrays off of an `enum`, as `integer` indexing is very fast, and in games, speed is everything. ( The solution linked in one of the other answers uses `string` lookups, which I would tend to avoid.) When displaying the strings, we used a `printf()` type function to replace markers with values. "*Train 3 is departing city 1.*"
Now for some of the pitfalls.
1) Between languages, phrase order is completely different. "*Train 3 is departing city 1.*" translated to German and back ends up being "*From City 1, Train 3 is departing*". If you are using something like `printf()` and your string is "*Train %d is departing city %d.*" the German will end up saying "*From City 3, Train 1 is departing.*" which is completely wrong. We solved this by forcing the translation to retain the same word order, but we ended up with some pretty broken German. Were I to do it again, I would write a function that takes the string and a zero-based array of the values to put in it. Then I would use markers like `%0` and `%1`, basically embedding the array index into the string. ***Update: @Jonathan Leffler pointed out that a POSIX-compliant `printf()` supports using `%2$s` type markers where the `2$` portion instructs the `printf()` to fill that marker with the second additional parameter. That would be quite handy, so long as it is fast enough. A custom solution may still be faster, so you'll want to make sure and test both.***
2) Languages vary greatly in length. What was 30 characters in English came out sometimes to as much as 110 characters in German. This meant it often would not fit the screens we were putting it on. This is probably less of a concern for PC/Mac games, but if you are doing any work where the text must fit in a defined box, you will want to consider this. To solve this issue, we stripped as many adjectives from our text as possible for other languages. This shortened the sentence, but preserved the meaning, if loosing a bit of the flavor. I later designed an application that we could use which would contain the font and the box size and allow the translators to make their own modifications to get the text fit into the box. Not sure if they ever implemented it. You might also consider having scrolling areas of text, if you have this problem.
3) As far as cross platform goes, we wrote pretty much pure C++ for our Localization system. We wrote custom encoded binary files to load, and a custom program to convert from a CSV of language text into a `.h` with the enum and file to language map, and a `.lang` for each language. The most platform specific thing we used was the fonts and the `printf()` function, but you will have something suitable for wherever you are developing, or could write your own if needed. | I strongly disagree with the accepted answer. First, the part about using static array lookups to speed up the text lookups [is counterproductive premature optimization](https://stackoverflow.com/questions/385506/when-is-optimisation-premature/385529) - Calculating the layout for said text and rendering said text uses 2-4 orders of magnitude more time than a hash lookup. If anyone wanted to implement their own language library it should never be based on static arrays, because doing so trades real benefits (translators don't need access to the code) for imaginary benefits (speed increase of ~0.01%).
Next, [writing your own language library to use in your own game is even worse](https://en.wikipedia.org/wiki/Not_invented_here) than premature optimization.
There are some extremely good reasons to [never write your own localization library](https://stackoverflow.com/questions/1236256/how-do-you-decide-whether-to-use-a-library-or-write-your-own-implementation):
1. Planning the time to use an existing localization library is much easier than planning the time to write a localization library. Localization libraries exist, they work, and many people have used them.
2. Localization is tricky, so you will get things wrong. Every language adds a new quirk, which means whenever you add a new language to your own homegrown localization library you will need to change code again to account for the quirks. Did you know that some languages have more than 2 plural forms, depending on the number of items in question? More than 2 genders (more than 10, even)? Also, the number and date formats vary a lot between different in many languages.
3. When your application becomes successful you will want add support for more languages. Languages nobody on your team speaks fluently. Hiring someone to write a translation will be **considerably cheaper** if they already know the tools they are working with.
A very well known and complete localization library is [GNU Gettext](http://www.gnu.org/software/gettext/manual/gettext.html), which uses the GPL, and should therefore be avoided for commercial work. You can instead use the boost library [boost.locale](http://www.boost.org/doc/libs/1_58_0/libs/locale/doc/html/messages_formatting.html) which works with Gettext files, and is free to use and modify for commercial and non-commercial projects of any kind. | Bests practices for localized texts in C++ cross-platform applications? | [
"",
"c++",
"localization",
""
] |
Currently i am working on a desktop application which consists mathematical analysiss.I am using qt for GUI and project written in c++.
When user starts an analysis, i open a worker thread and start a progress bar.Everything is ok up to now, problem starts when user cancels operation.Operation is complex, i am using several functions and objects, i allocate/deallocate memory at several times.I want to learn what should i do for recovering in cancel operation.Because there can be memory leaks.Which pattern or method i should use to be robust and safe for cancelling operation?
My idea is throwing an exception, but operation is really complex so should i put try-catch to all of my functions or is there a more generic way, pattern..
Edit: Problem is my objects are transfered between scopes, so shared\_ptr or auto\_ptr doesnt solve my problem,
Flag idea can be, but i think it requires so much code and there should be an easy way. | A pretty common way to close down worker threads, is to mark it with a flag, and let the worker thread inspect this flag at regular intervals. If marked, it should discontinue its workflow, clean up and exit.
Is that a possibility in your situation? | The worker thread should check for a message to stop. the message can be through a flag or an event. when stop message received the thread should exit.
USE BOOST safe pointers for all memory allocated. on exit you would have no memory leaks. ever. | How to prevent memory leaks while cancelling an operation in a worker thread? | [
"",
"c++",
"design-patterns",
"qt",
"memory-leaks",
"worker-thread",
""
] |
In my quest in trying to learn more about OOP in PHP. I have come across the constructor function a good few times and simply can't ignore it anymore. In my understanding, the constructor is called upon the moment I create an object, is this correct?
But why would I need to create this constructor if I can use "normal" functions or methods as their called?
cheers,
Keith | Yes the constructor is called when the object is created.
A small example of the usefulness of a constructor is this
```
class Bar
{
// The variable we will be using within our class
var $val;
// This function is called when someone does $foo = new Bar();
// But this constructor has also an $var within its definition,
// So you have to do $foo = new Bar("some data")
function __construct($var)
{
// Assign's the $var from the constructor to the $val variable
// we defined above
$this->val = $var
}
}
$foo = new Bar("baz");
echo $foo->val // baz
// You can also do this to see everything defined within the class
print_r($foo);
```
UPDATE:
A question also asked why this should be used, a real life example is a database class, where you call the object with the username and password and table to connect to, which the constructor would connect to. Then you have the functions to do all the work within that database. | The constructor allows you to ensure that the object is put in a particular state before you attempt to use it. For example, if your object has certain properties that are required for it to be used, you could initialize them in the constructor. Also, constructors allow a efficient way to initialize objects. | Benefits of using a constructor? | [
"",
"php",
"oop",
"constructor",
""
] |
I am interested in getting an install of Django running on IronPython, has anyone had any success getting this running with some level of success?
If so can you please tell of your experiences, performance, suggest some tips, resources and gotchas? | Besides the Jeff Hardy blog post on [Django + IronPython](http://jdhardy.blogspot.com/2008/12/django-ironpython.html) mentioned by Tony Meyer, it might be useful to also read Jeff's two other posts in the same series on his struggles with IronPython, easy\_install and zlib. The first is [Solving the zlib problem](http://jdhardy.blogspot.com/2008/12/solving-zlib-problem-ironpythonzlib.html) which discusses the absence of zlib for IronPython; hence, no easyinstall. Jeff reimplemented zlib based on ComponentAce's zlib.net. And finally, in [easy\_install on IronPython, Part Deux](http://jdhardy.blogspot.com/2008/12/easyinstall-on-ironpython-part-deux.html) Jeff discusses some final tweaks that are needed before easy\_install can be used with IronPython. | [Here's a database provider that runs on .NET & that works with Django](http://blogs.msdn.com/dinoviehland/archive/2008/03/17/ironpython-ms-sql-and-pep-249.aspx) | Django on IronPython | [
"",
"python",
"django",
"ironpython",
""
] |
I'm trying to create system users with a php script securely, In that, I'd like to be able to hash the password with the php script, so that their password shows up nowhere in the bash history.
How to I take a string, and hash it so it is a unix password hash?
```
$UX_PW = some_function('my_password');
exec("useradd -p $UX_PW newusername");
``` | It's `crypt()` that implements the UNIX password hashing.
<http://us.php.net/manual/en/function.crypt.php> | Depending on your system, you're either looking for `crypt()` or `md5()`.
Traditionally, unix uses DES-encrypted passwords (thats the 'crypt' function), with a 2-character salt (two random characters from the set [a-zA-Z0-9./]) which is prepended to the hash to perturb the algorithm.
Newer systems often use MD5 though. | How do I create a unix password hash with php | [
"",
"php",
"security",
"unix",
"hash",
"passwords",
""
] |
Part of a programme builds this list,
```
[u'1 x Affinity for war', u'1 x Intellect', u'2 x Charisma', u'2 x Perception', u'3 x Population growth', u'4 x Affinity for the land', u'5 x Morale']
```
I'm currently trying to sort it alphabetically by the name of the evolution rather than by the number. Is there any way I can do this without just changing the order the two things appear in the list (as in 'intellect x 1)? | You have to get the "key" from the string.
```
def myKeyFunc( aString ):
stuff, x, label = aString.partition(' x ')
return label
aList.sort( key= myKeyFunc )
``` | How about:
```
lst.sort(key=lamdba s: s.split(' x ')[1])
``` | python, sorting a list by a key that's a substring of each element | [
"",
"python",
"list",
"sorting",
""
] |
I'm using google app engine, and am having trouble writing querys to filter ReferenceProperties.
eg.
```
class Group(db.Model):
name = db.StringProperty(required=True)
creator = db.ReferenceProperty(User)
class GroupMember(db.Model):
group = db.ReferenceProperty(Group)
user = db.ReferenceProperty(User)
```
And I have tried writing something like this:
```
members = models.GroupMember.all().filter('group.name =', group_name)
```
and various other things that don't work. Hopefully someone can give me a prod in the right direction... | If what you want is to get the members of a group, ReferenceProperties have that built-in.
```
class GroupMember(db.Model):
group = db.ReferenceProperty(Group, collection_name="groupMembers")
user = db.ReferenceProperty(User, collection_name="groupMembers")
```
Then you can write:
```
# get the group entity somehow
group = Group.get(group_key)
# do something with the members, such as list the nicknames
nicknames = [x.user.nickname for x in group.groupMembers]
``` | If your groups are uniquely named, then your "group.name" is a unique identifier of a Group entity.
That means you can write:
```
members = models.GroupMember.all().filter(
"group =",model.Group.gql("WHERE name=:1", group_name).get()
)
```
though you only need to do that if you don't already have the group entity lying around in the stack somewhere.
Google's essay on many-to-many with appengine is [here](http://code.google.com/appengine/articles/modeling.html "Modeling with App Engine"). | Filtering models with ReferenceProperties | [
"",
"python",
"google-app-engine",
""
] |
I am trying to compile the following code:
```
private String dataToString(){
Map data = (HashMap<MyClass.Key, String>) getData();
String toString = "";
for( MyClass.Key key: data.keySet() ){
toString += key.toString() + ": " + data.get( key );
return toString;
}
```
I get an error in the for line that says:
```
incompatible types
found : java.lang.Object
required: MyClass.Key
```
The `getData()` method returns an `Object` (but in this case the `Object` returned has the `HashMap` structure). `MyClass.Key` is an enum that I have created for the purposes of my application (in another class file - `MyClass`).
When I created a foreach loop with the same structure in `MyClass.java`, I did not encounter this problem.
What am I doing wrong? | A slightly more efficient way to do this:
```
Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData();
StringBuffer sb = new StringBuffer();
for (Map.Entry<MyClass.Key,String> entry : data.entrySet()) {
sb.append(entry.getKey());
sb.append(": ");
sb.append(entry.getValue());
}
return sb.toString();
```
If at all possible, define "getData" so you don't need the cast. | Change:
```
Map data = (HashMap<MyClass.Key, String>) getData();
```
to
```
Map<MyClass.Key, String> data = (HashMap<MyClass.Key, String>) getData();
```
The problem is that `data.keySet()` returns a `Collection<Object>` if data is just a `Map`. Once you make it generic, `keySet()` will return a `Collection<MyClass.Key>`. Even better... iterate over the `entrySet()`, which will be a `Collection<MyClass.Key, String>`. It avoids the extra hash lookups. | How do I use a foreach loop in Java to loop through the values in a HashMap? | [
"",
"java",
"foreach",
"hashmap",
""
] |
> **Possible Duplicate:**
> [Escape string for use in Javascript regex](https://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex)
I have a msg like this:
> **Max {0} chars allowed in {1}**
And I have a function to create a message using the arguments passed as
```
for(var i = 0; i < agrs.length; i++){
reg = new RegExp('\{'+i+'\}', 'gi');
key = key.replace(reg,agrs[i])
}
```
The problem is that it's not able to take the param `i` to create the reg exp.
What's the way to achieve this? | Your regexp is `/{0}/gi` since you create it from a string. And it is not a valid expression.
You need to escape { in the regexp because it has a special meaning in the regexp syntax, so it should be:
```
new RegExp('\\{'+i+'\\}', 'gi');
```
which is `/\\{0\\}/gi`. You need to *escape* the escaping `\\` in the string. | I would strongly encourage you to use the functional form of [String.replace()](https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Global_Objects/String/Replace) to solve your problem, rather than trying to parametrize the regexp in a for-loop that iterates over {0},{1},etc.
In other words, rather than look for '{0}' or '{1}', just look for '{([0-9]+)}' (i.e. {}'s surrounding an arbitrary number, and pass a function to the replace() function to intelligently replace these expressions based on the number between the {}'s. This lets you use a RegExp literal which you can write as /{([0-9]+)}/ rather than mess around with escape characters in strings.
Something like this:
```
s='the song says {0} little {1} little {2} little-endians';
args=['zero','one','two'];
new_string = s.replace(/{([0-9]+)}/g, function(wholematch,firstmatch)
{return args[(+firstmatch)]; }
);
```
which yields
```
the song says zero little one little two little-endians
```
See this [similar question](https://stackoverflow.com/questions/423107).
edit: if you want to leave alone items that are greater than the length of your `args` list, make sure to sanity-check the parameter number:
```
s='the song says {0} little {1} little {2} little-endians,\n'+
' {3} little {4} little {5} little-endians';
args=['zero','one','two'];
new_string = s.replace(/{([0-9]+)}/g, function(wholematch,firstmatch)
{var i = +firstmatch; return i < args.length ? args[i] : wholematch;}
);
```
which yields
```
the song says zero little one little two little-endians,
{3} little {4} little {5} little-endians
``` | passing variable to a regexp in javascript | [
"",
"javascript",
"regex",
""
] |
I have an annoying SQL statement that seem simple but it looks awfull.
I want the sql to return a resultset with userdata ordered so that a certain user is the first row in the resultset if that users emailaddress is in the companies table.
I have this SQL that returns what i want but i think it looks awful:
```
select 1 as o, *
from Users u
where companyid = 1
and email = (select email from companies where id=1)
union
select 2 as o, *
from Users u
where companyid = 1
and email <> (select email from companies where id=1)
order by o
```
And by the way, the emailaddress from the user table can be in many companies so there cant be a join on the emailaddress :-(
Do you have any ideas how to improve that statement?
Im using Microsoft SQL Server 2000.
Edit:
Im using this one:
```
select *, case when u.email=(select email from companies where Id=1) then 1 else 2 end AS SortMeFirst
from Users u
where u.companyId=1
order by SortMeFirst
```
Its way more elegant than mine. Thanks Richard L! | You could do something like this..
```
select CASE
WHEN exists (select email from companies c where c.Id = u.ID and c.Email = u.Email) THEN 1
ELSE 2 END as SortMeFirst, *
From Users u
where companyId = 1
order by SortMeFirst
``` | will this work?:
```
select c.email, *
from Users u
LEFT JOIN companies c on u.email = c.email
where companyid = 1
order by c.email desc
-- order by case when c.email is null then 0 else 1 end
``` | SQL UNION and ORDER BY | [
"",
"sql",
"sorting",
"select",
"union",
""
] |
> **Possible Duplicate:**
> [Which is faster/best? SELECT \* or SELECT column1, colum2, column3, etc](https://stackoverflow.com/questions/65512/which-is-faster-best-select-or-select-column1-colum2-column3-etc)
> [What is the reason not to use select \*?](https://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select)
Is there any performance issue in using SELECT \* rather than SELECT FiledName, FiledName2 ... ? | If you need a subset of the columns, you are giving bad help to the optimizer (cannot choose for index, or cannot go only to index, ...)
Some database can choose to retrieve data from indexes only. That thing is very very helpfull and give an incredible speedup. Running SELECT \* queries does not allow this trick.
Anyway, from the point of view of application is not a good practice.
---
Example on this:
* You have a table T with 20 columns (C1, C2, ..., C19 C20).
* You have an index on T for (C1,C2)
* You make `SELECT C1, C2 FROM T WHERE C1=123`
* The optimizer have all the information on index, does not need to go to the table Data
Instead if you `SELECT * FROM T WHERE C1=123`, the optimizer needs to get all the columns data, then the index on (C1,C2) cannot be used.
In joins for multiple tables is a lot helpful. | Take a look at this post:
[What is the reason not to use select \*?](https://stackoverflow.com/questions/321299/what-is-the-reason-not-to-use-select)
and these:
* [Performance benefit when SQL query is limited vs calling entire row](https://stackoverflow.com/questions/430605/performance-benefit-when-sql-query-is-limited-vs-calling-entire-row)
* [Which is faster or best, select \* or select column1 colum2 column3](https://stackoverflow.com/questions/65512/which-is-faster-best-select-or-select-column1-colum2-column3-etc)
* [SQL query question select \* from view or select col1 col2 col3 from view](https://stackoverflow.com/questions/128412/sql-query-question-select-from-view-or-select-col1-col2-from-view)
* [Which is faster, select \* or select column1 column2 etc](https://stackoverflow.com/questions/65512/which-is-fasterbest-select-or-select-column1-colum2-column3-etc) | Performance issue in using SELECT *? | [
"",
"sql",
"database",
"performance",
""
] |
Our code uses a lot of system properties eg, 'java.io.tmpdir', 'user.home', 'user.name' etc. We do not have any constants defined for these anywhere (and neither does java I think) or any other clever thing for dealing with them so they are in plain text littered throughout the code.
```
String tempFolderPath = System.getProperty("java.io.tmpdir");
```
How is everyone using system properties? | I would treat this just as any other String constant you have scattered throughout your code and define a constant variable for it. Granted, in this case "java.io.tmpdir" is unlikely to change, but you never know. (I don't mean that Sun might change the meaning of "java.io.tmpdir", or what system property it points to, but that you might change your mind about what system property you need to read.)
If you're only using a particular property within one class, then I'd define the constants right in that class.
```
private final String TEMPDIR = "java.io.tmpdir";
```
If you're using the same properties in different classes, you may want to define an static class of your own to hold the constants you use most often.
```
public final Class Prop {
public static final String TEMPDIR = "java.io.tmpdir";
...
}
```
Then, everywhere you need to use that constant just call it using
```
System.getProperty(Prop.TEMPDIR);
``` | [SystemUtils](http://commons.apache.org/proper/commons-lang/javadocs/api-release/index.html?org/apache/commons/lang3/SystemUtils.html) provided by Apache Commons Lang package, solves this problem.
SystemUtils has defined constant for most of the system properties, which can be obtained by a lookup, for example:
```
import org.apache.commons.lang3.SystemUtils;
class Something
{
public static void main(String[] args){
System.out.println(SystemUtils.JAVA_IO_TMPDIR);
}
}
```
Probably, that is a cleaner way to do it. | Best Practice for Using Java System Properties | [
"",
"java",
"properties",
""
] |
I have a few classes which do nothing except in their constructors/destructors. Here's an example
```
class BusyCursor
{
private:
Cursor oldCursor_;
public:
BusyCursor()
{
oldCursor_ = CurrentCursor();
SetCursor(BUSY_CURSOR);
}
~BusyCursor()
{
SetCursor(oldCursor_);
}
}
// example of use
void DoSlowThing
{
BusyCursor busy;
... do something time-consuming ...
}
```
I'm a little concerned about future readability. Am I being too "tricksy" here, with a variable ("busy") which is never actually used in the code? Could some static analysis tool suggest they be removed, or is this idiom sufficiently common not to worry about? | This technique is very common and is known as the design pattern: [Resource Acquisition Is Initialization (RAII)](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization).
I would not hesitate to use this design pattern at all.
It's much better that you are coding using this design pattern because you will avoid bugs by forgetting to reset the cursor, or whatever the resource in question is.
If you are concerned that other programmers might not understand it, then those programmers should be more educated. Always strive to code in the most error free way where you make it impossible for you and others to shoot yourself/themselves in the foot.
---
"Could some static analysis tool suggest they be removed?"
* No static analysis tool will see this as a problem.
* No compiler warning will be given
* No compiler optimization will cause any problems.
The reason is because the object is created and the constructor/destructor are called. So it is not an unreferenced variable. | As others have said, this is good C++ style. To aid readability, I always prefix such RAII-only classes with `Scoped` (for example, `ScopedBusyCursor`) to make it clear from a glance what the class's purpose is. | Good or Bad C++ Idiom - Objects used purely for constructor/destructor? | [
"",
"c++",
"idioms",
"raii",
""
] |
For my exception class i have a constructor that has multi arguments (...) which works fine under windows, how ever, under linux it compiles fine but refuses to link to it.
Why does this not work under linux?
here is an example:
```
class gcException
{
public:
gcException()
{
//code here
}
gcException(uint32 errId, const char* format = NULL, ...)
{
//code here
}
}
enum
{
ERR_BADCURLHANDLE,
};
```
.
Edit
So when i call it like so:
```
if(!m_pCurlHandle)
throw gcException(ERR_BADCURLHANDLE);
```
I get this compile error:
```
error: no matching function for call to ‘gcException::gcException(gcException)’
candidates are: gcException::gcException(const gcException*)
gcException::gcException(gcException*)
gcException::gcException(gcException&)
``` | It compiles and links just fine. I expanded your test code to a full "program":
```
class gcException {
public:
gcException() { }
gcException(int errId, const char* format, ...) { }
};
int main() { new gcException(1, "foo", "bar", "baz"); }
```
And then `g++ -Wall test.cpp` ran without errors. According to `g++ -v`, I have gcc version 4.3.2 (Debian 4.3.2-1.1). Does my quick example compile for you?
(Did you maybe accidentally compile — or link — with gcc instead of g++?) | The problem is that your copy constructor doesn't accept the temporary that you give the throw. It's a temporary and thus an rvalue. A reference-to-nonconst, namely `gcException&` can't bind to it. Read [here](https://stackoverflow.com/questions/445570/when-cant-an-object-be-converted-to-a-reference#445591) on the details.
As a comment on that answer suggests, the microsoft compiler had a bug that made it bind references that point to non-const objects accept rvalues. You should change your copy-constructor to this:
```
gcException(gcException const& other) {
// ...
}
```
To make it work. It says the bug was fixed in Visual C++ 2005. So you would get the same problem with that version onwards. So better fix that problem right away. | Why doesnt Multi Args in constructor work under linux? | [
"",
"c++",
"linux",
"variadic-functions",
""
] |
What does the word "literal" mean when used in context such as literal strings and literal values?
What is the difference between a literal value and a value? | A literal is "any notation for **representing** a value within source code" ([wikipedia](http://en.wikipedia.org/wiki/Literal))
(Contrast this with *identifiers*, which *refer* to a value in memory.)
Examples:
* `"hey"` (a string)
* `false` (a boolean)
* `3.14` (a real number)
* `[1,2,3]` (a list of numbers)
* `(x) => x*x` (a function)
* `/^1?$|^(11+?)\1+$/` (a regexp)
Some things that are not literals:
* `std::cout` (an identifier)
* `foo = 0;` (a statement)
* `1+2` (an expression) | A literal is a value that has been hard-coded directly into your source.
For example:
```
string x = "This is a literal";
int y = 2; // so is 2, but not y
int z = y + 4; // y and z are not literals, but 4 is
int a = 1 + 2; // 1 + 2 is not a literal (it is an expression), but 1 and 2 considered separately are literals
SomeMethod("this is another string literal");
bool b = false; // false is a literal, but b is not.
```
Some literals can have a special syntax, so you know what type the literal is:
```
// In C#, the 'M' in 10000000M means this is a decimal value,
// rather than int or double.
var accountBalance = 10000000M;
```
What sets literals apart from variables or resources is the compiler can treat them as constants or perform certain optimizations with code where they are used, because it's certain they won't change. As one example, the in the `int a = 1 + 2;` snippet above, the compiler probably computes the result is `3` ahead of time and only uses that result in the final compiled code; no addition operation ever takes place at run time.
As another example where the compiler can optimize performance around literals, consider this:
```
// set a 2 hour timeout
int timeOutInSeconds = 60 * 60 * 2;
```
This is better than using the `7200` magic number, because it's easy to confirm at a glance the timeout is actually correct — 60 seconds per minute times 60 minutes per hour times 2 hours — and it will perform *identically* to hardcoding the number 7200 because the compiler will optimize out the multiplication operations. | What does the word "literal" mean? | [
"",
"c#",
"language-agnostic",
"terminology",
"glossary",
""
] |
Does someone know an open source project or code snippets, which demonstrate how to create a google-chrome like interface with similar tabs and toolbar in Swing?
I know, that I can use [JTabbedPane](http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html), but I'm thinking of an interface which looks and feels very similar to the google chrome "tabbed browsing". | I have just created my own open-source library for this, called Jhrome. Check it out!
It's available on github: <https://github.com/jedwards1211/Jhrome>
Documentation is sparse right now, but it's pretty solid, except for AWT/Swing memory leaks I haven't figured out yet. If enough people are interested in it I'll polish it up. | You can probably pull it off with an undecorated JFrame (setUndecorated(true)) to get rid of the title bar.
You'd then create a layout with a tabbed pane filling the window and then overlay the min/max/close buttons on the top right.
If tabbed pane is too inflexible, you will need to put a button bar across the top, with toggle buttons controlling multiple content panels, and do the tab look yourself; as each button becomes active it hides the current panel and unhides the panel that belongs to it. | How to build a Google-chrome tabs and menubar interface in Java Swing? | [
"",
"java",
"user-interface",
"swing",
"open-source",
"google-chrome",
""
] |
I have a horizontal css menu with 5 items.
e.g
1) Home
2) Users
3) Category
4) Products
5) Contact
When "home" is selected the background color (via css) of the entire menu div (id="topmenu") is blue.
I want the background color of the div to change to say green when "users" is selected and say purple when "category" is selected.
How can I do this? | ```
<div id="topmenu">
<ul>
<li><a href="home" onclick="changeBackground('green');">Home</a></li>
<li><a href="users" onclick="changeBackground('blue');">Users</a></li>
<li><a href="home" onclick="changeBackground('purple');">Category</a></li>
<li><a href="home" onclick="changeBackground('brown');">Products</a></li>
<li><a href="users" onclick="changeBackground('orange');">Contact</a></li>
</ul>
</div>
<script type="text/javascript">
function changeBackground(color){
document.getElementById("topmenu").style.backgroundColor = color;
return false;
}
</script>
```
Something like that should do the trick I think. | You can set up multiple classes like so:
```
<ul>
<li class="Menu1 Selected"><a href="#">Home</a></li>
<li class="Menu2"><a href="#">Users</a></li>
</ul>
```
Then in your CSS you have a class set for each menu item for it's selected state:
```
.Menu1 .Selected
{
background-color: #000000;
}
.Menu2 .Selected
{
background-color: #ffffff;
}
``` | Change background color of menu based on menu selection | [
"",
"asp.net",
"javascript",
"css",
""
] |
Actually I am trying to move some box alternatively with in another box. I made it work, but both the blocks do not interrupt each other. What should I do? How can I make the blocks cross each other? I try using style:position, but it is not working.
Here is the code I have been using:
```
<marquee direction="down" behavior="alternate" scrollAmount=10 style="border:2px solid blue;">
<marquee behavior="alternate" scrollAmount=50 >
<img src="img1.JPG">
</marquee>
<marquee behavior="alternate" scrollAmount=10 >
<img src="img1.JPG">
</marquee>
</marquee>
```
What am I doing wrong? | Oh, dear Lord!
Well. They don't cross because they're positioned statically one above the other. The second marquee cannot go above the first.
You can solve\* this problem by ungluing the marquees from each other using absolute positioning. Then doubly-nest each one with different horizontal and vertical motion:
```
<div style="border:2px solid blue; position: relative;">
<marquee direction="down" behavior="alternate" scrollAmount="10">
<marquee behavior="alternate" scrollAmount="50"><img src="img1.jpeg" alt="oh no" /></marquee>
</marquee>
<marquee direction="down" behavior="alternate" scrollAmount="20" style="position: absolute; top: 0;">
<marquee behavior="alternate" scrollAmount="10"><img src="img1.jpeg" alt="help meee" /></marquee>
</marquee>
</div>
```
\*: for values 'x' of 'solve' where x='make a hideous mess of'.
This is for illustration purposes only. Please don't use this. | Please don't use the marquee tag, it's non-standard and deprecated. Use some JavaScript library like [jQuery UI](http://ui.jquery.com) for any kind of animation. | Nested and multiple <marquee> troubles | [
"",
"javascript",
"html",
"marquee",
""
] |
We currently have an inventory management system that was built in-house. It works great, and we are constantly innovating it.
This past Fall, we began selling products directly on one of our websites via a Shopping Cart checkout.
Our inventory management system runs off a server in the office, while the three websites we currently have (only one actually sells things) runs off an outside source, obviously.
See my problem here? Basically, I am trying to think of ways I can create a central inventory control system that allows both the internal software and external websites to communicate so that inventory is always up to date and we are not selling something we don't have.
Our internal inventory tracking works great and flows well, but I have no idea on how I would implement a solid tracking system that can communicate between the two.
The software is all written in Python, but it does not matter as I am mostly looking for ideas and methods on how would this be implemented.
Thanks in advance for any answers, and I hope that made sense .. I can elaborate. | One possibility would be to expose a web service interface on your inventory management system that allows the transactions used by the web shopfront to be accessed remotely. With a reasonably secure VPN link or ssh tunnel type arrangement, the web shopfront could get stock levels, place orders or execute searches against the inventory system.
Notes:
1. You would still have to add a reasonable security layer to the inventory service in case the web shopfront was compromised.
2. You would have to make sure your inventory management application and server was big enough to handle the load, or could be reasonably easily scaled so it could do so.
Your SLA for the inventory application would need to be good enough to support the web shopfront. This probably means some sort of hot failover arrangement. | I don't see the problem... You have an application running on one server that manages your database locally. There's no reason a remote server can't also talk to that database.
Of course, if you don't have a database and are instead using a homegrown app to act as some sort of faux-database, I recommend that you refactor to use something sort of actual DB sooner rather than later. | Inventory Control Across Multiple Servers .. Ideas? | [
"",
"python",
"tracking",
"inventory",
""
] |
### The Question
What is the correct way to install Python 3.0 alongside Python 2.x using Cygwin?
### Notes
I already have a working copy of Cygwin, and Python 2.x is installed within Cygwin (`/lib/python2.x`, not `c:\python2.x`).
Also, I would like to be able to call python 3 separately (and only intentionally) by leaving `python` pointing to Python 2.x to preserve existing dependencies. I would like to use `python30` or some alternative.
Any pointers to guides on the subject would be much appreciated. I cannot seem to find one either at the cygwin site or python.org. | The standard `make install` target of the Python 3.0 sources doesn't install a python binary. Instead, make install prints at the end
```
* Note: not installed as 'python'.
* Use 'make fullinstall' to install as 'python'.
* However, 'make fullinstall' is discouraged,
* as it will clobber your Python 2.x installation.
```
So don't worry.
If you easily want to remove the entire installation, do something like `configure --prefix=/usr/local/py3` | As of yesterday (Wed 25 July 2012), [Python 3.2.3 is included in the standard Cygwin installer](http://cygwin.com/ml/cygwin/2012-07/msg00553.html). Just run Cygwin's `setup.exe` again (download it from [cygwin.com](http://www.cygwin.com) again if you need to), and you should be able to select and install it like any other package.
This will install as `python3`, leaving any existing 2.x install in place:
```
$ python -V
Python 2.6.8
$ python3 -V
Python 3.2.3
$ ls -l $(which python) $(which python3)
lrwxrwxrwx 1 me Domain Users 13 Jun 21 15:12 /usr/bin/python -> python2.6.exe
lrwxrwxrwx 1 me root 14 Jul 26 10:56 /usr/bin/python3 -> python3.2m.exe
``` | Installing Python 3.0 on Cygwin | [
"",
"python",
"windows",
"cygwin",
""
] |
I've never been sure that I understand the difference between str/unicode decode and encode.
I know that `str().decode()` is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.
I know that `unicode().encode()` converts unicode chars into a string of bytes according to a given encoding name.
But I don't understand what `str().encode()` and `unicode().decode()` are for. Can anyone explain, and possibly also correct anything else I've gotten wrong above?
EDIT:
Several answers give info on what `.encode` does on a string, but no-one seems to know what `.decode` does for unicode. | The `decode` method of unicode strings really doesn't have any applications at all (unless you have some non-text data in a unicode string for some reason -- see below). It is mainly there for historical reasons, i think. In Python 3 it is completely gone.
`unicode().decode()` will perform an implicit *encoding* of `s` using the default (ascii) codec. Verify this like so:
```
>>> s = u'ö'
>>> s.decode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
>>> s.encode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 0:
ordinal not in range(128)
```
The error messages are exactly the same.
For `str().encode()` it's the other way around -- it attempts an implicit *decoding* of `s` with the default encoding:
```
>>> s = 'ö'
>>> s.decode('utf-8')
u'\xf6'
>>> s.encode()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0:
ordinal not in range(128)
```
Used like this, `str().encode()` is also superfluous.
**But** there is another application of the latter method that is useful: there are [encodings](http://docs.python.org/library/codecs.html#standard-encodings) that have nothing to do with character sets, and thus can be applied to 8-bit strings in a meaningful way:
```
>>> s.encode('zip')
'x\x9c;\xbc\r\x00\x02>\x01z'
```
You are right, though: the ambiguous usage of "encoding" for both these applications is... awkard. Again, with separate `byte` and `string` types in Python 3, this is no longer an issue. | To represent a unicode string as a string of bytes is known as **encoding**. Use `u'...'.encode(encoding)`.
Example:
```
>>> u'æøå'.encode('utf8')
'\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
>>> u'æøå'.encode('latin1')
'\xc3\xa6\xc3\xb8\xc3\xa5'
>>> u'æøå'.encode('ascii')
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5:
ordinal not in range(128)
```
You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.
To convert a string of bytes to a unicode string is known as **decoding**. Use `unicode('...', encoding)` or '...'.decode(encoding).
Example:
```
>>> u'æøå'
u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
>>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
u'\xc3\xa6\xc3\xb8\xc3\xa5'
>>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
u'\xc3\xa6\xc3\xb8\xc3\xa5'
```
You typically decode a string of bytes whenever you receive string data from the network or from a disk file.
I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.
Some good links:
* [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)](http://www.joelonsoftware.com/articles/Unicode.html)
* [Unicode HOWTO](http://docs.python.org/howto/unicode.html) | What is the difference between encode/decode? | [
"",
"python",
"string",
"unicode",
"character-encoding",
"python-2.x",
""
] |
I have a control which I have to make large modifications to. I'd like to completely prevent it from redrawing while I do that - SuspendLayout and ResumeLayout aren't enough. How do I suspend painting for a control and its children? | At my previous job, we struggled with getting our rich UI app to paint instantly and smoothly. We were using standard .Net controls, custom controls and devexpress controls.
After a lot of googling and reflector usage, I came across the WM\_SETREDRAW win32 message. This really stops controls drawing whilst you update them and can be applied, IIRC to the parent/containing panel.
This is a very very simple class demonstrating how to use this message:
```
class DrawingControl
{
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing( Control parent )
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing( Control parent )
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
parent.Refresh();
}
}
```
There are fuller discussions on this - google for C# and WM\_SETREDRAW, e.g.
[C# Jitter](https://web.archive.org/web/20160324214157/http://blog.bee-eee.com/2008/04/18/c-getting-rid-of-the-jitter/)
[Suspending Layouts](http://www.c-sharpcorner.com/Forums/ShowMessages.aspx?ThreadID=52)
And to whom it may concern, this is a similar example in VB:
```
Public Module Extensions
<DllImport("user32.dll")>
Private Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Boolean, ByVal lParam As IntPtr) As Integer
End Function
Private Const WM_SETREDRAW As Integer = 11
' Extension methods for Control
<Extension()>
Public Sub ResumeDrawing(ByVal Target As Control, ByVal Redraw As Boolean)
SendMessage(Target.Handle, WM_SETREDRAW, True, IntPtr.Zero)
If Redraw Then
Target.Refresh()
End If
End Sub
<Extension()>
Public Sub SuspendDrawing(ByVal Target As Control)
SendMessage(Target.Handle, WM_SETREDRAW, False, IntPtr.Zero)
End Sub
<Extension()>
Public Sub ResumeDrawing(ByVal Target As Control)
ResumeDrawing(Target, True)
End Sub
End Module
``` | The following is the same solution of ng5000 but doesn't use P/Invoke.
```
public static class SuspendUpdate
{
private const int WM_SETREDRAW = 0x000B;
public static void Suspend(Control control)
{
Message msgSuspendUpdate = Message.Create(control.Handle, WM_SETREDRAW, IntPtr.Zero,
IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(control.Handle);
window.DefWndProc(ref msgSuspendUpdate);
}
public static void Resume(Control control)
{
// Create a C "true" boolean as an IntPtr
IntPtr wparam = new IntPtr(1);
Message msgResumeUpdate = Message.Create(control.Handle, WM_SETREDRAW, wparam,
IntPtr.Zero);
NativeWindow window = NativeWindow.FromHandle(control.Handle);
window.DefWndProc(ref msgResumeUpdate);
control.Invalidate();
}
}
``` | How do I suspend painting for a control and its children? | [
"",
"c#",
".net",
"winforms",
"paint",
""
] |
code snippet:
```
//byte[] myByteArray = byte array from database (database BLOB)
myByteArray = (byte[]) ((dbCommand.Parameters["parameter"].Value));
string myString =System.Text.Encoding.UTF8.GetString(myByteArray);
Xmldocument doc = new Xmldocument();
doc.Load(myString);
```
============
I am getting `System.OutOfMemoryException` sometimes.
```
string myString = System.Text.Encoding.UTF8.GetString(myByteArray);
```
when converting bytearray to string i am getting this error.
is there a way i can make this code robust.
All i am trying to do is loading the BLOB in byte array and then converting them to string
and loading them in xmldocument to work with. | If you've got a string containing XML text, you actually want [XmlDocument.LoadXML](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx). XmlDocument.Load treats the string as a URL.
That said, [XmlDocument.Load](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.load.aspx) has overloads taking an XmlReader, a TextReader or a Stream. You can create a MemoryStream on the underlying byte array, and pass that; this avoids the string conversion. | XmlDocument.Load(String) tries to load the XML document from the URL given as parameter, i.e. it tries to interpret your possibly HUGE string as an URL. No wonder that something goes wrong.
Use LoadXml() instead. | getting 'System.OutOfMemoryException' when converting byte array to string | [
"",
"c#",
".net",
"optimization",
""
] |
I'm working with Quickbook's IIF file format and I need to write a parser to read and write IIF files and I'm running into some issues reading the files.
The files are simple, they're tab deliminated. Every line is either a table definition or a row. Definitions begin with'!' and the table name, and rows begin with just the table name. Here's the problem I'm running into: some of the fields allow line breaks.
When I first encountered this, I thought, okay just parse it tab by tab instead of line by line, but to do that I had to replace the line breaks with tabs, and wound up with more values than there were columns, but I wound up with the values with line breaks spread out across too many columns.
How would you parse such a file?
Edit: An example
```
!CUST NAME REFNUM TIMESTAMP BADDR1 BADDR2 BADDR3 BADDR4 BADDR5 SADDR1 SADDR2 SADDR3 SADDR4 SADDR5 PHONE1 PHONE2 FAXNUM CONT1 CONT2 CTYPE TERMS TAXABLE LIMIT RESALENUM REP TAXITEM NOTEPAD SALUTATION COMPANYNAME FIRSTNAME MIDINIT LASTNAME CUSTFLD1 CUSTFLD2 CUSTFLD3 CUSTFLD4 CUSTFLD5 CUSTFLD6 CUSTFLD7 CUSTFLD8 CUSTFLD9 CUSTFLD10 CUSTFLD11 CUSTFLD12 CUSTFLD13 CUSTFLD14 CUSTFLD15 JOBDESC JOBTYPE JOBSTATUS JOBSTART JOBPROJEND JOBEND HIDDEN DELCOUNT
CUST St. Mark 359 1176670332 Saint Mark Catholic Church 609 W Main St City, State Zip
!CLASS NAME REFNUM TIMESTAMP HIDDEN DELCOUNT
!INVITEM NAME REFNUM TIMESTAMP INVITEMTYPE DESC PURCHASEDESC ACCNT ASSETACCNT COGSACCNT QNTY QNTY PRICE COST TAXABLE PAYMETH TAXVEND TAXDIST PREFVEND REORDERPOINT EXTRA CUSTFLD1 CUSTFLD2 CUSTFLD3 CUSTFLD4 CUSTFLD5 DEP_TYPE ISPASSEDTHRU HIDDEN DELCOUNT USEID
INVITEM Labor 1 1119915308 SERV Labor 0
!TIMEACT DATE JOB EMP ITEM PITEM DURATION PROJ NOTE XFERTOPAYROLL BILLINGSTATUS
TIMEACT 3/8/08 876 Development Jane Doe {Consultant} Labor 00:15 Renewing all domain name for 876 Development.
REIMBURSEMENT: 44.72 for one year renewal on all domain names. N 1
TIMEACT 3/17/08 Greg:Bridge Jane Doe {Consultant} Labor 01:00 Preparing Studio N 1
TIMEACT 3/17/08 John Doe and Associates Jane Doe {Consultant} Labor 00:06 REIMBURSEMENT: Toner cartridge on ebay & Fuser from FastPrinters- ask wendell before invoicing to see if this fixed the problem
49.99 (include tax) toner
$175.18 (include tax) fuser
N 1
TIMEACT 3/17/08 John Doe II Jane Doe {Consultant} Labor 01:00 Fixing Kandis's computer - replaced entire computer with similar system N 1
``` | I did it:
```
public DataSet parseIIF(Stream file) {
iifSet = new DataSet();
String fileText;
using (StreamReader sr = new StreamReader(file)) {
fileText = sr.ReadToEnd();
}
//replace line breaks with tabs
//fileText.Replace('\n', '\t');
fileText = fileText.Replace("\r\n", "\n");
fileText = fileText.Replace('\r', '\n');
//split along tabs
string[] lines = fileText.Split('\n');
this.createTables(lines, iifSet);
this.fillSet(lines, iifSet);
return iifSet;
}
/// <summary>
/// Reads an array of lines and parses them into tables for the dataset
/// </summary>
/// <param name="lines">String Array of lines from the iif file</param>
/// <param name="iifSet">DataSet to be manipulated</param>
private void fillSet(string[] lines, DataSet set) {
//CODING HORROR
//WARNING: I will monkey with the for loop index, be prepared!
for (int i = 0; i < lines.Length; i++) {
if (this.isTableHeader(lines[i])) {
//ignore this line, tables are alread defined
continue;
}
if (lines[i] == "" || lines[i] == "\r" || lines[i] == "\n\r" || lines[i] == "\n") {
//ignore lines that are empty if not inside a record
//probably the end of the file, it always ends with a blank line break
continue;
}
if (lines[i].IndexOf(";__IMPORTED__") != -1) {
continue;
//just signifying that it's been imported by quickbook's timer before, don't need it
}
string line = lines[i];
while (!isFullLine(line, set)){
i++; //<--------------------------- MONKEYING done here!
line += lines[i];
}
//now, the line should be complete, we can parse it by tabs now
this.parseRecord(line, set);
}
}
private void parseRecord(string line, DataSet set) {
if (isTableHeader(line)) {
//we don't want to deal with headers here
return;
}
String tablename = line.Split('\t')[0];
//this just removes the first value and the line break from the last value
String[] parameters = this.createDataRowParams(line);
//add it to the dataset
set.Tables[tablename].Rows.Add(parameters);
}
private bool isFullLine(string line, DataSet set) {
if (isTableHeader(line)) {
return true; //assumes table headers won't have line breaks
}
int values = line.Split('\t').Length;
string tableName = line.Split('\t')[0];
int columns = set.Tables[tableName].Columns.Count;
if (values < columns) {
return false;
} else {
return true;
}
}
private void createTables(string[] lines, DataSet set) {
for (int index = 0; index < lines.Length; index++) {
if (this.isTableHeader(lines[index])) {
set.Tables.Add(createTable(lines[index]));
}
}
}
private bool isTableHeader(string tab) {
if (tab.StartsWith("!"))
return true;
else
return false;
}
private bool isNewLine(string p) {
if (p.StartsWith("!"))
return true;
if (iifSet.Tables[p.Split('\t')[0]] != null) //that little mess there grabs the first record in the line, sorry about the mess
return true;
return false;
}
private DataTable createTable(string line) {
String[] values = line.Split('\t');
//first value is always the title
//remove the ! from it
values[0] = values[0].Substring(1); //remove the first character
DataTable dt = new DataTable(values[0]);
values[0] = null; //hide first title so it doesn't get used, cheaper than resetting array
foreach (String name in values) {
if (name == null || name == "")
continue;
DataColumn dc = new DataColumn(name, typeof(String));
try {
dt.Columns.Add(dc);
} catch (DuplicateNameException) {
//odd
dc = new DataColumn(name + "_duplicateCol" + dt.Columns.Count.ToString());
dt.Columns.Add(dc);
//if there is a triple, just throw it
}
}
return dt;
}
private string getTableName(string line) {
String[] values = line.Split('\t');
//first value is always the title
if(values[0].StartsWith("!")){
//remove the ! from it
values[0] = values[0].Substring(1); //remove the first character
}
return values[0];
}
private string[] createDataRowParams(string line) {
string[] raw = line.Split('\t');
string[] values = new string[raw.Length - 1];
//copy all values except the first one
for (int i = 0; i < values.Length; i++) {
values[i] = raw[i + 1];
}
//remove last line break from the record
if (values[values.Length - 1].EndsWith("\n")) {
values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\n'));
} else if (values[values.Length - 1].EndsWith("\n\r")) {
values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf("\n\r"));
} else if (values[values.Length - 1].EndsWith("\r")) {
values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\r'));
}
return values;
}
private string[] createDataRowParams(string line, int max) {
string[] raw = line.Split('\t');
int length = raw.Length - 1;
if (length > max) {
length = max;
}
string[] values = new string[length];
for (int i = 0; i < length; i++) {
values[i] = raw[i + 1];
}
if (values[values.Length - 1].EndsWith("\n")) {
values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\n'));
} else if (values[values.Length - 1].EndsWith("\n\r")) {
values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf("\n\r"));
} else if (values[values.Length - 1].EndsWith("\r")) {
values[values.Length - 1] = values[values.Length - 1].Substring(0, values[values.Length - 1].LastIndexOf('\r'));
}
return values;
}
``` | It has been a while since I have done IIF but unless they have fixed it QuickBooks will barf on those line breaks anyway. It seems [these folks](http://getmytime.com/faq.asp#atq7) have the same issue and they handled it with spaces.
Personally I would lean toward pipes or something that will clearly delineate the line break when it comes into QuickBooks. If you absolutely positively must have the line breaks, join the [Intuit Developer Network](http://developer.intuit.com/) and use the SDK to send these values to QB once your program imports them. | Parsing a Quickbook IIF format file | [
"",
"c#",
"parsing",
"io",
"text-parsing",
"fileparsing",
""
] |
I am an ActiveMQ / Camel noob with a specific scenario in mind, I wonder firstly if it is possible and secondly whether someone might provide a little direction.
Basically I need to perform dynamic throttling off the queue. I.E the ability to set **at runtime** the rate a particular group of messages will be consumed from the queue.
So I might, for example, add a group of messages that are to be consumed at 10 per second, another group which should be consumed at 1 per second and so forth.
I know the basics of setting up routes in camel and message grouping onto the queue etc, but just can't figure this out from the docs. | Yeah looks like you are looking for broker side throtteling to avoid consumers to block.
Have you raised your request at the ActiveMQ user/dev forum? | You could just use Camel's existing [throttler](http://activemq.apache.org/camel/throttler.html) then using a different queue for each type of messages where you need to configure a different throttle rate?
e.g.
```
from("activemq:Queue1.Input").
throttle(20).
to("activemq:Queue1.Output");
from("activemq:Queue2.Input").
throttle(5).
to("activemq:Queue2.Output");
``` | Dynamic throttling of an ActiveMQ message queue with Camel | [
"",
"java",
"jms",
"activemq-classic",
"apache-camel",
""
] |
Do any of the IDEs (or any other tool for that matter) have the ability to generate a POM based on an existing project?
---
I ended up generating the POM with a Maven archetype as [Peter](https://stackoverflow.com/users/57695/peter-lawrey) and [Sal](https://stackoverflow.com/users/13753/sal) suggested and then moving the existing source in. Thanks for the help guys. | You can do this in IntelliJ, but the POM it generates may be more complex than if you write by hand. If your project is currently in JBuilder or Eclipse you can import this first.
Instead I would suggest you describe your project in a POM and use it to generate your project information. You can do this for eclipse and idea (and I assume other IDEs) | One way to do this it to create a template project via maven archetype then move your existing code to the template. I would recommend this only for really simple projects. It would work something like this.
```
mvn archetype:generate
mv src/* src/main/java
mv test/* src/test/java
mvn package
```
You'll get errors. To add the missing dependencies, go here: <http://www.mvnrepository.com/> and start looking them up. If you pick an archetype close to what you need, you'll be half way there.
Once it all works.
```
svn commit -m "hacky maven port"
``` | Generating a Maven POM from an existing project? | [
"",
"java",
"maven-2",
"ide",
""
] |
Well I was reading this [post](http://handyfloss.wordpress.com/2008/02/17/summary-of-my-python-optimization-adventures/) and then I came across a code which was:
```
jokes=range(1000000)
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
```
I thought wouldn't it be better to calculate the value of len(jokes) once outside the list comprehension?
Well I tried it and timed three codes
```
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]'
10000000 loops, best of 3: 0.0352 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0,l*2)]'
10000000 loops, best of 3: 0.0343 usec per loop
jv@Pioneer:~$ python -m timeit -s 'jokes=range(1000000);l=len(jokes)*2;domain=[(0,l-i-1) for i in range(0,l)]'
10000000 loops, best of 3: 0.0333 usec per loop
```
Observing the marginal difference 2.55% between the first and the second made me think - is the first list comprehension
```
domain=[(0,(len(jokes)*2)-i-1) for i in range(0,len(jokes)*2)]
```
optimized internally by python? or is 2.55% a big enough optimization (given that the len(jokes)=1000000)?
If this is - What are the other implicit/internal optimizations in Python ?
What are the `developer's rules of thumb for optimization in Python`?
**Edit1**: Since most of the answers are "don't optimize, do it later if its slow" and I got some tips and links from `Triptych` and `Ali A` for the **do's**.
I will change the question a bit and request for **don'ts**.
Can we have some experiences from people who faced the '**slowness**', what was the problem and how it was corrected?
**Edit2**: For those who haven't here is an [interesting read](http://www.python.org/doc/essays/list2str/)
**Edit3:** Incorrect usage of `timeit` in question please see **dF's** answer for correct usage and hence timings for the three codes. | You're not using [`timeit`](http://docs.python.org/library/timeit.html) correctly: the argument to `-s` (setup) is a statement to be executed once initially, so you're really just testing an empty statement. You want to do
```
$ python -m timeit -s "jokes=range(1000000)" "domain=[(0,(len(jokes)*2)-i-1) for i in range(0, len(jokes)*2)]"
10 loops, best of 3: 1.08 sec per loop
$ python -m timeit -s "jokes=range(1000000)" "l=len(jokes);domain=[(0,(l*2)-i-1) for i in range(0, l*2)]"
10 loops, best of 3: 908 msec per loop
$ python -m timeit -s "jokes=range(1000000)" "l=len(jokes*2);domain=[(0,l-i-1) for i in range(0, l)]"
10 loops, best of 3: 813 msec per loop
```
While the speedup is still not dramatic, it's more significant (16% and 25% respectively). So since it doesn't make the code any more complicated, this simple optimization is probably worth it.
To address the actual question... the usual rule of thumb in Python is to
1. Favor straightforward and readable code over optimization when coding.
2. Profile your code ([`profile / cProfile` and `pstats`](http://docs.python.org/library/profile.html) are your friends) to figure out what you need to optimize (usually things like tight loops).
3. As a last resort, re-implement these as C extensions, which is made much easier with tools like [pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/) and [cython](http://www.cython.org/).
One thing to watch out for: compared to many other languages, function calls are relatively expensive in Python which is why the optimization in your example made a difference even though `len` is O(1) for lists. | Read this: [Python Speed / Performance Tips](http://wiki.python.org/moin/PythonSpeed/PerformanceTips)
Also, in your example, the total time is so short that the margin of error will outweigh any actual difference in speed. | Optimization in Python - do's, don'ts and rules of thumb | [
"",
"python",
"optimization",
""
] |
The SQL Server (2000/2005) function gets the table name and the field name as parameters and returns results from a dynamic query within the function. The results should be assigned to a `Table` variable which will be used further in a stored procedure. How to achieve this?
I am getting error: "Only functions and extended stored procedures can be executed from within a function."
```
Declare @Data as table (FieldValue varchar(100))
insert into @Data select * from MyFunction ('Person.Address','AddressID')
-- Function
Alter function MyFunction (
@TableName varchar(100), @FieldName varchar(100)
) returns @GetData table (
FieldValue varchar(100)
) as
begin
Declare @SQL varchar(250)
Set @SQL = 'Select '+@FieldName+ ' from '+ @TableName
Exec sp_executesql @SQL
return
end
``` | I'm not sure how this works with functions, but if you have a Stored Procedure that returns a resultset, you can insert that into a table variable using INSERT EXEC statements.
```
INSERT @TableVariable
EXEC spYourProcedure
```
As long as the fields match that will work. Otherwise you can use:
```
INSERT @TableVariable (FieldInSp1, FieldInSp2)
EXEC spYourProcedure
```
This way you can pass data between stored procedures. See this page on [INSERT EXEC Statements](http://www.sommarskog.se/share_data.html#INSERTEXEC) for some extra information. | just to close the loop...
here is the syntax for calling the function and putting those results in a table variable
small build on @simons solution
this ran on sql2012 and sql2014.
[ dont forget to close off the table statement. Easy enough to do if you have the table all on a single line. ]
```
declare @t table(field1 nvarchar(100) )
insert @t select * from dbo.Cool_1Field_Function( 'parm1' ,'parm2')
select * from @t
``` | Assign function result to a table variable | [
"",
"sql",
"stored-procedures",
"dynamic-queries",
""
] |
I'm using Visual Studio 2008 to write an installation, and I'm a completely new to installations. I've created an installation and successfully written some custom actions using a C# assembly. One action sets a RunOnce registry value, and now I need to prompt the user to reboot when the installation finishes, but I have no idea how. I've read the Installer class documentation, but I can't find any mention of rebooting.
I'm assuming I need to somehow get down to being able to call MsiSetProperty and set a REBOOT property, but I don't know how to do that from my [.NET](http://en.wikipedia.org/wiki/.NET_Framework) installer project. | Thanks. I ended up using a post-build event to run a batch file with the following command. The hard part was tracking down WiRunSQL.vbs, which was in the ["Windows SDK Components for Windows Installer Developers"](http://msdn.microsoft.com/en-us/library/aa370834(VS.85).aspx) download.
```
cscript "C:\Program Files\Microsoft SDKs\Windows\v6.0\Samples\SysMgmt\MSI\scripts\WiRunSQl.vbs" my.msi "INSERT INTO `Property`(`Property`, `Value`) VALUES ('REBOOT', 'F')"
``` | If you are implementing your installer using [WiX](http://en.wikipedia.org/wiki/WiX), you need to add this:
```
<ScheduleReboot After="InstallFinalize"/>
```
If you're using the cut-down "Installer" project in [Visual Studio](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio), I'm not sure... But this link [here](http://www.omgili.com/newsgroups/microsoft/public/windows/msi/3CCCF4FC-564D-43D7-ACFD-26444AA72126microsoftcom.html) suggests a [CScript](http://en.wikipedia.org/wiki/Windows_Script_Host#Available_scripting_engines) command that seems to show how to inject an MSI property into the installer project, much as you want to do. | How can I prompt the user to reboot in a .NET installation? | [
"",
"c#",
".net",
"installation",
"windows-installer",
""
] |
I have a C++/MFC app on windows - dynamically linked it's only 60kb static it's > 3Mb.
It is a being distributed to customers by email and so needs to be as small as possible.
It statically links the MFC and MSCVRT libraries - because it is a fix to some problems and I don't want more support calls about missing libs - especially the very helpful 'application configuration is incorrect' one!
Is there anyway to strip a Windows exe of all the extra MFC stuff that is the dll but that I'm not using?
Or tell it to dynamically link MSVCRT (which must be present) but statically link the MFC dll which might not be?
Edit - thanks that got it down to 1.6Mb that will have to do! | You can't mix the CRT/MFC dlls. Going from memory...
As the other answer suggested, you can #define WIN32\_LEAN\_AND\_MEAN and VC\_EXTRALEAN. These probably won't help though. They tend to be about minimizing build time - not the final exe size.
Short of rebuilding MFC (Which is an option - you could rebuild it /Os, or if you are feeling really cheeky, /GL - but this will probably lead to more downstream fun - hopefully it's already built /Gy).
OK. Simple things to try. Build your app with /GL /Os /GF /Gy /GA. In the linker you more or less want /OPT:REF and /OPT:ICF and /LTCG.
I have to say - a release build from 30k to megabytes is a bit much. You could also pass /map: to the linker and see what's taking all that space - but that's very very tedius.
It almost sounds like MFC wasn't built with /Gy - but that would be surprising. | For programs using the CRT, you can use the technique in [this video by Per Vognsen](https://www.youtube.com/watch?v=5tg_TbURMy0) on achieving 3.5KB executables. `Windows\System32\msvcrt.dll` ships with every Windows since 95, so by linking to that, you needn't package the Visual C++ Redistributable with your app.
The basic process is:
1. Run Visual Studio's `dumpbin` on `System32\msvcrt.dll` and pipe it to a file
2. Run a simple filter (`awk '{print $4}'`) to create a `msvcrt.def` file
3. Run VS's `lib` on `msvcrt.def` to generate `msvcrt.lib`
4. Disable default libraries in your project (`/NODEFAULTLIB` on the `link` command line)
5. Disable some Visual C++ checks (`/GS-` and remove any `/RTC<x>` flags)
Link against `kernel32.lib` and `msvcrt.lib` and voilà, your tiny executable has zero dependencies besides the OS.
(n.b.: To optimize for size (`/O1`), specify `memset` as an intrinsic as detailed [here](https://stackoverflow.com/a/2945619/3185819).) | Reduce windows executable size | [
"",
"c++",
"windows",
"dll",
"mfc",
"linker",
""
] |
I need to generate many internal client-side (within the company only) graphs from streams of data, and since the data itself is "secret", I can't use a service like Google-Graphs for generating the graphs. So I was wondering if anyone has some recomendations for a javascript graph library that doesn't require a server.
Thanks | Have a look at [flot](http://code.google.com/p/flot/) a javascript plotting library.
**EDIT**
The official flot repo [lives on github](https://github.com/flot/flot) | Have a look at [Raphael](http://raphaeljs.com/) ([github](https://github.com/DmitryBaranovskiy/raphael/tree)). | is there a client side (javascript) graph library that doesn't require a server? | [
"",
"javascript",
"graph",
"client-side",
""
] |
I have seen code around with these two styles , I am not not sure if one is better than another (is it just a matter of style)? Do you have any recommendations of why you would choose one over another.
```
// Example1
class Test {
private:
static const char* const str;
};
const char* const Test::str = "mystr";
```
```
// Example2
class Test {
private:
static const std::string str;
};
const std::string Test::str ="mystr";
``` | Usually you should prefer `std::string` over plain char pointers. Here, however, the char pointer initialized with the string literal has a significant benefit.
There are two initializations for static data. The one is called static initialization, and the other is called dynamic initialization. For those objects that are initialized with constant expressions and that are PODs (like pointers), C++ requires that their initialization happens at the very start, before dynamic initialization happens. Initializing such an std::string will be done dynamically.
If you have an object of a class being a static object in some file, and that one needs to access the string during its initialization, you can rely on it being set-up already when you use the `const char* const` version, while using the `std::string` version, which isn't initialized statically, you don't know whether the string is already initialized - because the order of initialization of objects across translation unit boundaries is not defined. | Hmmm, a std::string is not the same as a const char \*. I usually err on the side of using std::string because it is a class that has many additional capabilities that make it much easier to use.
If performance is paramount and you are using const char \* for efficiency, go that way. | Should I use std::string or const char* for string constants? | [
"",
"c++",
"constants",
"static-members",
"stdstring",
""
] |
I have this Javascript data:
```
[{id:123,type:"test"},{id:154,type:"another"}]
```
How would you transform that into something so that I can pass it as a HTTP post request?
```
menu[0][id] = 123
menu[0][type] = test
menu[1][id] = 154
menu[1][type] = another
```
I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.
**EDIT**
Was able to parse the object on the client side using something like this, maybe you guys would suggest something better before I sign this as "answered"?
```
this.serialize = function(elem) {
var childs = elem.childElements();
var str = "";
for(var i=0, item; i<childs.length; i++) {
item = childs[i];
str += ((i)?"&":"")+"menu[" + i +"][id]=" + item.id.replace(/item_/,"");
str += "&menu[" + i +"][type]=" + item.className;
str += "&menu[" + i +"][section]=" + elem.id;
str += "&menu[" + i +"][position]=" + i;
}
return str;
}
``` | ```
var data = [{id:123,type:"test"},{id:154,type:"another"}];
var params = new Array();
for(var x = 0; x < data.length; x++) {
params.push("id=[" + x + "]=" + escape(data[x].id));
params.push("type=[" + x + "]=" + escape(data[x].type));
}
alert(params.join("&")); // output: id=[0]=123&type=[0]=test&id=[1]=154&type=[1]=another
```
Is that what you want? | ```
"?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]")
``` | Represent a query string in JSON | [
"",
"javascript",
"json",
"query-string",
""
] |
When comparing two strings in c# for equality, what is the difference between InvariantCulture and Ordinal comparison? | ## InvariantCulture
Uses a "standard" set of character orderings (a,b,c, ... etc.). This is in contrast to some specific locales, which may sort characters in different orders ('a-with-acute' may be before ***or*** after 'a', depending on the locale, and so on).
## Ordinal
On the other hand, looks purely at the values of the raw byte(s) that represent the character.
---
There's a great sample at [https://learn.microsoft.com/en-us/dotnet/api/system.string.compare](http://msdn.microsoft.com/en-us/library/e6883c06.aspx) that shows the results of the various StringComparison values. All the way at the end, it shows (excerpted):
```
StringComparison.InvariantCulture:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is less than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
StringComparison.Ordinal:
LATIN SMALL LETTER I (U+0069) is less than LATIN SMALL LETTER DOTLESS I (U+0131)
LATIN SMALL LETTER I (U+0069) is greater than LATIN CAPITAL LETTER I (U+0049)
LATIN SMALL LETTER DOTLESS I (U+0131) is greater than LATIN CAPITAL LETTER I (U+0049)
```
You can see that where InvariantCulture yields (U+0069, U+0049, U+00131), Ordinal yields (U+0049, U+0069, U+00131). | It does matter, for example - there is a thing called character expansion
```
var s1 = "Strasse";
var s2 = "Straße";
s1.Equals(s2, StringComparison.Ordinal); //false
s1.Equals(s2, StringComparison.InvariantCulture); //true
```
With `InvariantCulture` the ß character gets expanded to ss. | Difference between InvariantCulture and Ordinal string comparison | [
"",
"c#",
".net",
"string-comparison",
"ordinal",
""
] |
A static function `retUnique()` returns a unique value. My question is that if there are
many users who are using the same function at a given point of time, what happens? Is there a best practice to make sure that each users accessing this static function simultaneously get a unique value and also do not face threading issues.
Can one give me an example? | Assuming you want to simply return a unique incrementing integer value, the simplest safe approach is probably to use a private static counter and a private static lock object. Something like:
```
private static int s_UniqueCounter; // starts at 0 by default
private static readonly object s_UniqueCounterLock = new object();
public static int GetUnique()
{
lock (s_UniqueCounterLock)
{
s_UniqueCounter++;
return s_UniqueCounter;
}
}
```
It's up to you to make sure the particular lock object is used to protect any other access to the static counter member (which is why they are declared private, of course, so the class which owns them controls any access). It probably shouldn't be accessed anywhere else, for this use, but you might have something look at the current value to see how many times it has been called. That should probably be protected by the lock as well (to make sure the result is current):
```
internal static int QueryUniqueCount() // or this could be private, or public
{
lock (s_UniqueCounterLock)
{
return s_UniqueCounter;
}
}
``` | There is nothing special about static functions that make them more or less safe to use on multiple threads. Instead, you need to examine the data which the function accesses and modifies, and make sure that it still respects the integrity of that data when called concurrently.
Here's an example that might be relevant to your question:
```
private static int myUniqueID = 1;
public static int GetFreshUniqueID()
{
lock(someObject)
{
return myUniqueID++;
}
}
```
The key in this case to keeping it thread-safe is locking the function in some synchronization context so that we don't run into a situation where two threads get the same ID before either of them get around to incrementing it. Your situation may vary. | Is there a best practice to implement static function that gives unique value on simultaneous access | [
"",
"c#",
"multithreading",
""
] |
I'm going through some old stored procedures at work and constantly come across
```
CASE MyColumn WHEN 'Y' THEN 'Yes' WHEN 'N' THEN 'No' ELSE 'Unknown' END
```
It gets even worse when this is tied not to a word, but instead a colour.
```
CASE MyColumn WHEN 'Y' THEN 'style="background-color:pink"' ELSE '' END
```
The reason this was done was for older ASP 1 pages where everything had to be done inline, but as it's such a large system it's impossible to keep up with updating all the pages.
Can anyone give any valid evidence that using a SQL query for conditional statements surpasses that in other languages such as C# or Java? Is this good practice for speed? Should the plain value be returned and the presentation layer decide what should be done? | When speed is of the essence, the SQL case statements might even be the fastest (I'll run a test) but for maintainability, returning the plain values to the presentation layer (or some business layer thingy) is the best option.
[update] ran some quick and dirty tests (code below) and found the C# code variant slightly faster than the SQL case variant. Conclusion: returning the 'raw' data and manipulating it in the presentation layer is both quicker and more maintainable.
-Edoode
I retrieved 196288 rows with queries below.
```
StringBuilder result = new StringBuilder();
using (SqlConnection conn = new SqlConnection(Settings.Default.Conn))
{
conn.Open();
string cmd = "select [state], case [state] when 'ca' then 'california' else [state] end from member";
SqlCommand command = new SqlCommand(cmd, conn);
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
result.AppendLine(reader.GetString(1));
}
}
}
```
C# variant:
```
StringBuilder result = new StringBuilder();
using (SqlConnection conn = new SqlConnection(Settings.Default.Conn))
{
conn.Open();
string cmd = "select [state] from member";
SqlCommand command = new SqlCommand(cmd, conn);
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while (reader.Read())
{
result.AppendLine(reader.GetString(0) == "ca" ? "california" : reader.GetString(0));
}
}
```
} | I would be concerned putting this kind of logic in SQL statements. What happens if your database engine changes? Will you have to update every SQL statement to Oracle SQL? What if the repository itself changes, when you move to a message bus, XML files, or web service call...
It looks like you're storing display information. In which case, it's part of the data model. Let the controller (in a typical [MVC pattern](http://www.asp.net/mvc/)) perform the conditional logic. The presentation layer doesn't need to know what happened and the repository can be happy just holding data. | SQL CASE Statement Versus Conditional Statements In Programming Language | [
"",
"sql",
"language-agnostic",
""
] |
jQuery and JavaScript in general are new ground for me.
What are some good resources to get me up and running.
I am particularly interested in page manipulation - eg moving elements about programmatically. | Well, [docs.jquery.com](http://docs.jquery.com/) would be a good start (especially the [Manipulation](http://docs.jquery.com/Manipulation) section). Usually lots of good examples as well as the documentation.
I picked up [jQuery in Action](http://www.manning.com/bibeault/) which was well-worth a read. | [Visual jQuery](http://visualjquery.com/) is a more pleasant way of browsing the jQuery documentation... | What are good resources for getting started with jQuery? | [
"",
"javascript",
"jquery",
"resources",
""
] |
Does Java and/or Spring have the concept of properties? I have bunch of domain models, each of which has several properties. Example:
```
public class Person {
private String name;
private Date dateOfBirth;
private float height;
private float weight;
// getters and setters not shown
}
```
When displaying a person, the property names are hardcoded in the JSP.
```
Name: ${person.name}<br>
Date of birth: ${person.dateOfBirth}<br>
Height: ${person.height}<br>
Weight: ${person.weight}<br>
```
Furthermore, there may be several different pages that display a person. Note that date of birth is a `java.util.Date`, so the JSP or controller will use `java.text.SimpleDateFormat` to format it. Height and weight are numbers, and they may have their own `java.util.Format` used for formatting.
What I'm looking for a property lookup mechanism. Each property (name, date of birth, height, etc) would have the display name, format, and description (used for help or tooltips). The properties' attributes would be defined in a configuration file somewhere. When displaying a property, the display name and format would be looked-up via the property mechanism. This would also solve localization.
My question is if there's already something like this implemented for Java. | If I understand you correctly, you want to be able to put the format and description of some of these properties in an external file. You might want to take a look at Spring's [`MessageSource`](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#context-functionality-messagesource) (link to [javadoc here](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/MessageSource.html)), which somewhat wraps around and is analagous to the [`ResourceBundle`](http://java.sun.com/j2se/1.5.0/docs/api/java/util/ResourceBundle.html) class in the JDK.
Using `MessageSource`'s will allow you to place the format and any text in an external file (and have different properties files for different languages), but I believe you will still need to include in your JSP which properties to pass as arguments, for example:
```
<spring:message code="user.dob" arguments="${user.dateOfBirth}"/>
```
where your `messages.properties` file contains:
```
user.dob = Your date of birth is {0}
```
I'm not entirely sure how to specify the format within `messages.properties`, but I know that it is possible. | To do this using JSP and JSTL, you can use the "fmt" tag library which supports localization and formatting for numbers, dates, etc.
In the example you posted, the code would be something like this:
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%-- ..assuming bundle and locale are already set... --%>
<fmt:message key="NAME" bundle="${myBundle}"/>: ${person.name}<br>
<fmt:message key="DOB" bundle="${myBundle}"/>: <fmt:formatDate type="date" value="${person.dateOfBirth}"/><br>
<fmt:message key="HEIGHT" bundle="${myBundle}"/>: <fmt:formatNumber pattern="##.##" value="${person.height}"/><br>
<fmt:message key="WEIGHT" bundle="${myBundle}"/>: <fmt:formatNumber pattern="##.##" value="${person.weight}"/><br>
``` | Java web application properties | [
"",
"java",
"spring",
"jakarta-ee",
"properties",
"jstl",
""
] |
My current application has a JFrame with about 15 actions stored as fields within the JFrame. Each of the actions is an anonymous class and some of them are pretty long.
Is it common to break actions into their own classes possibly within a sub-package called actions?
If not, how's this complexity usually tamed?
Thanks | If it is possible that your actions could be reusable (e.g., from keyboard shortcuts, other menus, other dialogs, etc.) and especially if they can work directly on the underlying model (rather than on the UI), then it is generally better not to have them as anonymous classes.
Rather, create a separate package, and create classes for each.
Often, it also makes sense to not instantiate these directly but rather have some sort of a manager that defines constants and initializes and returns sets of actions, so that you could, for example, offer different action sets at different versions or set certain actions only for internal releases.
Finally, check whether your actions can be refactored into a class hierarchy. They often can, which saves code replication, and also helps you add robustness (e.g., check for certain conditions before letting the action execute). | That's typically how I do it. Each action gets it's own class which has a reference to the "app" object so it can get to resources it needs. I usually have an action manager that holds all the actions so there's one place to access them as well as one place to update their enablement and stuff.
Eventually this also becomes unmanageable at which point you should start thinking about using an app framework like Eclipse RCP, the NetBeans framework, JIDE, etc. This is especially true if you want to support user-defined keymaps and stuff like that. | Organizing Actions in a Swing Application? | [
"",
"java",
"swing",
"code-organization",
""
] |
This is for an arrivals/departures flight display. The display is difficult to read because of blurry fonts. The current state is an asp.net page displayed using internet explorer on a HDTV.
From the software side, what can I do to produce good looking fonts? I've noticed that powerpoint presentations have nicely rendered fonts even on smaller resolutions. Refactoring as a windows application is an option.
Note: I know there is an issue with the hardware that needs to be worked out but I want to make sure I'm displaying the best fonts possible. The current hardware setup is a vga output to hardware to convert to component video and a long cable run to a hdtv. | > The current hardware setup is a vga output to hardware to convert to component video and a long cable run to a hdtv.
One more thing: as a rule, component video comes in several predefined resolutions, namely: 720x576 (576p), 1280x720 (720p) and 1920x1080 (1080p).
It seems that your `VGA -> YPrPb` hardware rescales the picture.
Set your `VGA` resolution to one of mentioned above. | Use [ClearType](http://blogs.msdn.com/ie/archive/2006/02/03/524367.aspx).
If it's an `LCD` connected with `DVI` or `VGA`, set it to the native resolution. | How to get the best font clarity to display on an HDTV with c#? | [
"",
"c#",
"asp.net",
""
] |
We have a user provided string that may contain unicode characters, and we want the robot to type that string.
How do you convert a string into keyCodes that the robot will use?
How do you do it so it is also java version independant (1.3 -> 1.6)?
What we have working for "ascii" chars is
```
//char c = nextChar();
//char c = 'a'; // this works, and so does 'A'
char c = 'á'; // this doesn't, and neither does 'Ă'
Robot robot = new Robot();
KeyStroke key = KeyStroke.getKeyStroke("pressed " + Character.toUpperCase(c) );
if( null != key ) {
// should only have to worry about case with standard characters
if (Character.isUpperCase(c))
{
robot.keyPress(KeyEvent.VK_SHIFT);
}
robot.keyPress(key.getKeyCode());
robot.keyRelease(key.getKeyCode());
if (Character.isUpperCase(c))
{
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
``` | Based on javamonkey79's code I've created the following snippet which should work for all Unicode values...
```
public static void pressUnicode(Robot r, int key_code)
{
r.keyPress(KeyEvent.VK_ALT);
for(int i = 3; i >= 0; --i)
{
// extracts a single decade of the key-code and adds
// an offset to get the required VK_NUMPAD key-code
int numpad_kc = key_code / (int) (Math.pow(10, i)) % 10 + KeyEvent.VK_NUMPAD0;
r.keyPress(numpad_kc);
r.keyRelease(numpad_kc);
}
r.keyRelease(KeyEvent.VK_ALT);
}
```
This automatically goes through each decade of the unicode key-code, maps it to the corresponding VK\_NUMPAD equivalent and presses/releases the keys accordingly. | The [KeyEvent Class](http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyEvent.html) does not have direct mappings for many unicode classes in JRE 1.5. If you are running this on a Windows box what you may have to do is write a custom handler that does something like this:
```
Robot robot = new Robot();
char curChar = 'Ã';
// -- isUnicode( char ) should be pretty easy to figure out
if ( isUnicode( curChar ) ) {
// -- this is an example, exact key combinations will vary
robot.keyPress( KeyEvent.VK_ALT );
robot.keyPress( KeyEvent.VK_NUMBER_SIGN );
robot.keyRelease( KeyEvent.VK_NUMBER_SIGN );
// -- have to apply some logic to know what sequence
robot.keyPress( KeyEvent.VK_0 );
robot.keyRelease( KeyEvent.VK_0 );
robot.keyPress( KeyEvent.VK_1 );
robot.keyRelease( KeyEvent.VK_1 );
robot.keyPress( KeyEvent.VK_9 );
robot.keyRelease( KeyEvent.VK_9 );
robot.keyPress( KeyEvent.VK_5 );
robot.keyRelease( KeyEvent.VK_5 );
robot.keyRelease( KeyEvent.VK_ALT );
}
```
e.g. Figure out what they key combinations are, and then map them to some sort of Object (maybe a HashMap?) for later lookup and execution.
Hope this helps :) | How to make the Java.awt.Robot type unicode characters? (Is it possible?) | [
"",
"java",
"unicode",
"automation",
""
] |
I`m writing client-server app for windows using WinSock and I have class for server.
while initialising server I have such code:
```
class Server {
static const int MaxClients = 10;
std::vector connections;
CRITICAL_SECTION cs;
int port;
SOCKET ServerSocket;
sockaddr_in ServerAddress;
void init();
public:
Server(int Port);
void addConnection(const Client& newClient);
void closeConnection(int index);
void Listen();
int size();
/*virtual void ClientService();
virtual void SendMsg(const std::string& msg);*/
virtual ~Server();
};
void Server::init() {
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2, 2), &wsaData))
throw Exception("WinSock init failed");
ServerSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ServerSocket == INVALID_SOCKET)
throw Exception("Socket failed to create!");
ServerAddress.sin_family = AF_INET;
ServerAddress.sin_addr.s_addr = htonl(INADDR_ANY);
ServerAddress.sin_port = htons(port);
if(bind(ServerSocket,(sockaddr*)&ServerAddress,sizeof(ServerAddress)) == SOCKET_ERROR)
{
throw Exception("Binding failed");
closesocket(ServerSocket);
}
}
```
where do I need to handle exceptions? Here, in init() private method (which is called from constructor) or in main function?
Any rules existing where to place handlers for exceptions and what does it depend on? | It depends on whether you're actually going to *handle* the exception, e.g. retry with a slightly different input, or decide to ignore the problem and proceed anyway (rarely appropriate, but *can* be useful). In this case, you may well want to catch the exception close to its source.
In most cases, the only thing you can really do with an exception is log it and abort the operation (e.g. serve the user an error page in a web app, or pop up a friendly "this program has crashed, sorry" dialog and exit). In this case, your catch block is likely to be quite close to the top of the stack - e.g. in the main method. | The basic rule is that you only catch exceptions in that part of the code, where you can actually *handle* it. By handling it I mean that you can take some action based upon the exception thrown, for instance trying to create the socket another time, or trying to use a different configuration.
Additionally, exceptions which cross library-boundaries need to be reviewed. Depending on the context you may want to catch them and rethrow a different type of exception, for instance to hide implementation details from the library client. | How to decide where to handle an exception - in scope of function it been thrown or in global one? | [
"",
"c++",
"exception",
""
] |
I want to send a URI as the value of a query/matrix parameter. Before I can append it to an existing URI, I need to encode it according to RFC 2396. For example, given the input:
`http://google.com/resource?key=value1 & value2`
I expect the output:
`http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue1%2520%26%2520value2`
Neither `java.net.URLEncoder` nor `java.net.URI` will generate the right output. `URLEncoder` is meant for HTML form encoding which is not the same as RFC 2396. `URI` has no mechanism for encoding a single value at a time so it has no way of knowing that value1 and value2 are part of the same key. | Jersey's [UriBuilder](http://download.oracle.com/javaee/6/api/javax/ws/rs/core/UriBuilder.html) encodes URI components using application/x-www-form-urlencoded and RFC 3986 as needed. According to the Javadoc
> Builder methods perform contextual encoding of characters not permitted in the corresponding URI component following the rules of the application/x-www-form-urlencoded media type for query parameters and RFC 3986 for all other components. Note that only characters not permitted in a particular component are subject to encoding so, e.g., a path supplied to one of the path methods may contain matrix parameters or multiple path segments since the separators are legal characters and will not be encoded. Percent encoded values are also recognized where allowed and will not be double encoded. | You could also use Spring's [UriUtils](http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/util/UriUtils.html) | How do I encode URI parameter values? | [
"",
"java",
"url",
"rest",
"urlencode",
"rfc2396",
""
] |
I'm trying to migrate a MySQL-based app over to Microsoft SQL Server 2005 (not by choice, but that's life).
In the original app, we used *almost* entirely ANSI-SQL compliant statements, with one significant exception -- we used MySQL's `group_concat` function fairly frequently.
`group_concat`, by the way, does this: given a table of, say, employee names and projects...
```
SELECT empName, projID FROM project_members;
```
returns:
```
ANDY | A100
ANDY | B391
ANDY | X010
TOM | A100
TOM | A510
```
... and here's what you get with group\_concat:
```
SELECT
empName, group_concat(projID SEPARATOR ' / ')
FROM
project_members
GROUP BY
empName;
```
returns:
```
ANDY | A100 / B391 / X010
TOM | A100 / A510
```
So what I'd like to know is: Is it possible to write, say, a user-defined function in SQL Server which emulates the functionality of `group_concat`?
I have almost no experience using UDFs, stored procedures, or anything like that, just straight-up SQL, so please err on the side of too much explanation :) | No REAL easy way to do this. Lots of ideas out there, though.
[Best one I've found](http://blog.shlomoid.com/2008/11/emulating-mysqls-groupconcat-function.html):
```
SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
SELECT column_name + ','
FROM information_schema.columns AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;
```
Or a version that works correctly if the data might contain characters such as `<`
```
WITH extern
AS (SELECT DISTINCT table_name
FROM INFORMATION_SCHEMA.COLUMNS)
SELECT table_name,
LEFT(y.column_names, LEN(y.column_names) - 1) AS column_names
FROM extern
CROSS APPLY (SELECT column_name + ','
FROM INFORMATION_SCHEMA.COLUMNS AS intern
WHERE extern.table_name = intern.table_name
FOR XML PATH(''), TYPE) x (column_names)
CROSS APPLY (SELECT x.column_names.value('.', 'NVARCHAR(MAX)')) y(column_names)
``` | I may be a bit late to the party but this [STUFF()](https://learn.microsoft.com/en-us/sql/t-sql/functions/stuff-transact-sql?view=sql-server-ver16) + [FOR XML](https://learn.microsoft.com/en-us/sql/relational-databases/xml/for-xml-sql-server?view=sql-server-ver16) method works for me and is easier than the COALESCE method.
```
SELECT STUFF(
(SELECT ',' + Column_Name
FROM Table_Name
FOR XML PATH (''))
, 1, 1, '')
``` | Simulating group_concat MySQL function in Microsoft SQL Server 2005? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"string-aggregation",
""
] |
I'm trying to read the target file/directory of a shortcut (`.lnk`) file from Python. Is there a headache-free way to do it? The spec is way over my head.
I don't mind using Windows-only APIs.
My ultimate goal is to find the `"(My) Videos"` folder on Windows XP and Vista. On XP, by default, it's at `%HOMEPATH%\My Documents\My Videos`, and on Vista it's `%HOMEPATH%\Videos`. However, the user can relocate this folder. In the case, the `%HOMEPATH%\Videos` folder ceases to exists and is replaced by `%HOMEPATH%\Videos.lnk` which points to the new `"My Videos"` folder. And I want its absolute location. | **Create a shortcut using Python (via WSH)**
```
import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
shortcut.Targetpath = "t:\\ftemp"
shortcut.save()
```
**Read the Target of a Shortcut using Python (via WSH)**
```
import sys
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)
``` | I know this is an older thread but I feel that there isn't much information on the method that uses the link specification as noted in the original question.
My shortcut target implementation could not use the win32com module and after a lot of searching, decided to come up with my own. Nothing else seemed to accomplish what I needed under my restrictions. Hopefully this will help other folks in this same situation.
It uses the binary structure Microsoft has provided for [MS-SHLLINK](http://msdn.microsoft.com/en-us/library/dd871305.aspx).
```
import struct
path = 'myfile.txt.lnk'
target = ''
with open(path, 'rb') as stream:
content = stream.read()
# skip first 20 bytes (HeaderSize and LinkCLSID)
# read the LinkFlags structure (4 bytes)
lflags = struct.unpack('I', content[0x14:0x18])[0]
position = 0x18
# if the HasLinkTargetIDList bit is set then skip the stored IDList
# structure and header
if (lflags & 0x01) == 1:
position = struct.unpack('H', content[0x4C:0x4E])[0] + 0x4E
last_pos = position
position += 0x04
# get how long the file information is (LinkInfoSize)
length = struct.unpack('I', content[last_pos:position])[0]
# skip 12 bytes (LinkInfoHeaderSize, LinkInfoFlags, and VolumeIDOffset)
position += 0x0C
# go to the LocalBasePath position
lbpos = struct.unpack('I', content[position:position+0x04])[0]
position = last_pos + lbpos
# read the string at the given position of the determined length
size= (length + last_pos) - position - 0x02
temp = struct.unpack('c' * size, content[position:position+size])
target = ''.join([chr(ord(a)) for a in temp])
``` | Reading the target of a .lnk file in Python? | [
"",
"python",
"directory",
"shortcut",
"target",
"lnk",
""
] |
> **Possible Duplicate:**
> [How do I find out which DOM element has the focus?](https://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus)
Is there a way in javascript to determine which html page element has focus? | **Use the [`document.activeElement`](https://developer.mozilla.org/en-US/docs/DOM/document.activeElement#Browser_compatibility) property.**
The `document.activeElement` property is supported on Chrome 2+, Firefox 3+, IE4+, Opera 9.6+ and Safari 4+.
Note that this property will only contain elements that accept keystrokes (such as form elements). | Check out [this blog post](http://ajaxandxml.blogspot.com/2007/11/emulating-activeelement-property-with.html). It gives a workaround so that `document.activeElement` works in all browsers.
```
function _dom_trackActiveElement(evt) {
if (evt && evt.target) {
document.activeElement = evt.target == document ? null : evt.target;
}
}
function _dom_trackActiveElementLost(evt) {
document.activeElement = null;
}
if (!document.activeElement) {
document.addEventListener("focus",_dom_trackActiveElement,true);
document.addEventListener("blur",_dom_trackActiveElementLost,true);
}
```
Something to note:
> This implementation is slightly over-pessimistic; if the browser window loses focus, the activeElement is set to null (as the input control loses focus as well). If your application needs the activeElement value even when the browser window doesn't have the focus, you could remove the blur event listener. | How to determine which html page element has focus? | [
"",
"javascript",
"html",
""
] |
Could anyone point me to an example implementation of a HOT Queue or give some pointers on how to approach implementing one? | [Here is a page](http://www.lonesock.net/misc.html) I found that provides at least a clue toward what data structures you might use to implement this. Scroll down to the section called "Making A\* Scalable." It's unfortunate that the academic papers on the subject mention having written C++ code but don't provide any. | Here is the link to the paper describing HOT queues. It's very abstract, that's why i wanted
to see a coded example (I'm still trying to fin my way around it).
<http://www.star-lab.com/goldberg/pub/neci-tr-97-104.ps>
The "cheapest", sort to speak variant of this is a two-level heap queue (maybe this sounds more familiar). What i wanted to do is to improve the running time of the Dijkstra's shortest path algorithm. | HOT(Heap On Top) Queues | [
"",
"c++",
""
] |
This is a bit of an open question but I would really like to hear people opinions.
I rarely make use of explicitly declared temporary tables (either table variables or regular #tmp tables) as I believe not doing so leads to more concise, readable and debuggable T-SQL. I also think that SQL can do a better job than I of making use of temporary storage when it's required (such as when you use a derived table in a query).
The only exception is when the database is not a typical relational database but a star or snowflake schema. I understand that it's best to apply filters to the fact table first and then use the resultant temp table to get the values from your dimensions.
Is this the common opinion or does anyone have an opposing view? | Temporary tables are most useful for a complex batch process like a report or ETL job. Generally you would expect to use them fairly rarely in a transactional application.
If you're doing complex query with a join involving multiple large tables (perhaps for a report) the query optimiser may not actually be able to optimise this in one hit, so temporary tables become a win here - they decompose the query into a series of simpler ones that give the query optimiser less opportunity to screw up the plan. Sometimes you have an operation that cannot be done in a single SQL statement at all, so multiple steps for processing are necessary to do the job at all. Again, we're talking about more complex manipulations here.
You can also create a tempory table for an intermediate result and then index the table, possibly even putting a clustered index on it to optimise a subsequent query. This might also be a quick and dirty way to optimise a report query on a system where you are not allowed to add indexes to the database schema. SELECT INTO is useful for this type of operation as it is minimally logged (and therefore fast) and doesn't require to align the columns of a select and insert.
Other reasons might include extracting data from XML fields using CROSS APPLY and xpath queries. Generally it's much more efficient to extract this into a temp table and then work on the temp table. They're also much faster than CTE's for some tasks as they materialise the query results rather than re-evaluating the query.
One thing to note is that temporary tables are exactly the same structure that the query engine uses to store intermediate join results, so there is no performance penalty to using them. Temporary tables also allow multi-phase tasks using set operations and make cursors almost (not quite but almost) unnecessary in T-SQL code.
'Code Smell' is an overstatement but if I saw a lot of simple operations involving temporary tables I would be wondering what was going on. | It really depends on what you are doing. I generally try to avoid them, but sometimes you need to do something complicated that takes multiple steps. Generally this is way beyond the simple select from table stuff. Like anything else it's a tool that you have to know when to use.
I would agree with you that I normally let the db handle stuff behind the scenes, but there are times when it's optimization is off and you have to go in and do it by hand. | Temporary Table Usage in SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
"star-schema",
""
] |
I have the following code in my index view.
```
latest_entry_list = Entry.objects.filter(is_published=True).order_by('-date_published')[:10]
for entry in latest_entry_list:
entry.views = entry.views + 1
entry.save()
```
If there are ten (the limit) rows returned from the initial query, will the save issue 10 seperate updated calls to the database, or is Django "smart" enough to issue just one update call?
Is there a more efficient method to achieve this result? | You can use `F()` objects for this.
Here is how you import `F`: `from django.db.models import F`
**[New in Django 1.1](http://docs.djangoproject.com/en/dev/topics/db/queries/#updating-multiple-objects-at-once).**
Calls to update can also use F() objects to update one field based on the value of another field in the model. This is especially useful for incrementing counters based upon their current value.
```
Entry.objects.filter(is_published=True).update(views=F('views')+1)
```
Although you can't do an update on a sliced query set... **edit: actually you can...**
This can be done completely in django ORM. You need two SQL queries:
1. Do your filter and collect a list of primary keys
2. Do an update on a non-sliced query set of items matching any of those primary keys.
Getting the non-sliced query set is the hard bit. I wondered about using [`in_bulk`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#in-bulk-id-list) but that returns a dictionary, not a query set. One would usually use [`Q objects`](http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects) to do complex OR type queries and that will work, but [`pk__in`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#in) does the job much more simply.
```
latest_entry_ids = Entry.objects.filter(is_published=True)\
.order_by('-date_published')
.values_list('id', flat=True)[:10]
non_sliced_query_set = Entry.objects.filter(pk__in=latest_entry_ids)
n = non_sliced_query_set.update(views=F('views')+1)
print n or 0, 'items updated'
```
Due to the way that django executes queries lazily, this results in just 2 database hits, no matter how many items are updated. | You could handle the updates in a single transaction, which could improve performance significantly. Use a separate function, decorated with @transaction.commit\_manually.
```
@transaction.commit_manually
def update_latest_entries(latest_entry_list):
for entry in latest_entry_list:
entry.views += 1
entry.save()
transaction.commit()
``` | Django: Increment blog entry view count by one. Is this efficient? | [
"",
"python",
"database",
"django",
"performance",
""
] |
For my work I need to create a Autorun application for a CD for our client. The problem is all I'm a C# programmer by trade and .NET does not make for the best autoruns since not all computers will have .NET installed on them.
What is a good solution that will work on Win98-Vista computers? | The answer to this question is really one of preference. Technically, anything can be instructed to open as an autorun. The autorun.inf file is simply an instruction file that Windows knows how to read in order to determine what it should do when a CD is inserted. That could be an application (written in any language you choose), a powerpoint presentation, opening a link to a website, etc. As long as you follow the rules of the autorun.inf file:
<http://autorun.moonvalley.com/autoruninf.htm> | There are many small autorun-utils (some free) that are configurable. I would go for one of those.
<http://www.ezau.com/latest/articles/083.shtml> | Best solution for making an Autorun application? | [
"",
"c#",
".net",
"windows",
"windows-vista",
"autorun",
""
] |
[This article](http://www.sitepoint.com/article/php-security-blunders/) states that
> If your site is run on a shared Web
> server, be aware that any session
> variables can easily be viewed by any
> other users on the same server.
On a larger host like GoDaddy, **are there really no protections in place against this?** Could it really be that easy? If it is that easy, **where are the session vars of the other users on my host so I can check them out?** | It is ridiculously easy because by default [`php.ini#session.save_path`](https://www.php.net/manual/en/session.configuration.php#ini.session.save-path) points to `/tmp` on Linux installs and similar for Windows. This is bad because most users have read and write privileges to `/tmp` because they need them. You can protect against this by storing your sesion state in the database or by changing were your PHP application stores it's session files, using [`session_save_path`](https://www.php.net/session_save_path) | The session files by default are stored in the location given by the [session.save\_path](http://php.net/manual/en/session.configuration.php#ini.session.save-path) in php.ini. While this can be defined separately for each vhost, the files have to be readable by the httpd process, and so if you know the location, your script could read the session files from another vhost.
You could store your sessions in a database (for example, [using ADODb](http://phplens.com/lens/adodb/docs-session.htm)), assuming other users of the server can't read your PHP sources to learn your db credentials! | How Easy Is It to Hijack Session Vars on GoDaddy (PHP) | [
"",
"php",
"security",
"session-hijacking",
""
] |
In JavaScript, I know that a closure is can be defined as a nested function that has access to its containing function's variables. For example:
```
function outerFunction(x, y) {
function innerFunction() {
return x + y + 10;
}
return innerFunction;
}
```
Now, the following code is wiring up a callback for the `onreadystatechange` property of the request object; however, **I was wondering if, by definition, this is also considered to be a closure**:
```
/* This is a contrived example, I know.
* Bear with me - it demonstrates the point I'm trying to convey. */
function submitHandler() {
var oRequest = createRequest(); // assume I'm getting an instance of the xhr
var sUsername = 'Tom'; // assume this is needed for work in the handler
var This = this;
oRequest.onreadystatechange = function() {
This.handleResponse(oRequest, sUsername)
}
}
function handleResponse(oResponse, sUsername) {
if(oResponse.readyState === 4 && oResponse.status === 200) {
// do work with the username
} else {
// we're not done yet...
}
}
```
I realize that the `handleResponse` function could also just be written as an anonymous function in the context of `submitHandler`, but I find that more complex Ajax code can be more readable and easily maintained if callbacks are defined outside the scope of the function calling back to them. Again, this is a contrived example that I'm using in hopes of simply demonstrating the point of my question. | Yes, you are correct in assuming that it is a closure by definition.
It sounds like you know your stuff but [here is a good, extensive article on javascript closures](http://www.jibbering.com/faq/faq_notes/closures.html). | I wholeheartedly agree that too many inline closure functions don't enhance readability. On the other hand I strongly dislike the `var self = this` style of writing closures, to which `this` is just a variant, as it's still too verbose in its declaration, and you introduce your own new 'keyword' whether that is `this` or `self`.
What you want is to curry/bind the method.
```
function $A(o)
{
var a = [];
for (var i = 0; i < o.length; ++i)
a.push(o[i]);
return a;
}
Function.prototype.bind = function()
{
var _method = this;
var a = $A(arguments)
var o = a.shift();
return function()
{
return _method.apply(o, a.concat($A(arguments)));
}
}
Function.prototype.curry = function()
{
var _method = this;
var a = $A(arguments);
return function()
{
return _method.apply(null, a.concat($A(arguments)));
}
}
```
The methods are taken from the [Prototype](http://en.wikipedia.org/wiki/Prototype_JavaScript_Framework) library. I use these even in projects that don't use the Prototype library as they are very useful!
In your case this means instead of writing:
```
var This = this;
oRequest.onreadystatechange = function() {
This.handleResponse(oRequest, sUsername)
}
```
you can now write:
```
oRequest.onreadystatechange = this.handleResponse.curry(oRequest,sUsername);
```
However if you want to transfer the meaning of the this keyword you could do this
```
oRequest.onreadystatechange = this.handleResponse.bind(this,oRequest,sUsername);
```
`handleResponse`, when called, will have the same `this` context as the `submitHandler`. | Based on how they are constructed, can callbacks also be defined as closures? | [
"",
"javascript",
"closures",
"callback",
""
] |
I have a few remote SQL servers that I need to pull a large amount of data from regularly (say 5,000,000 rows per server). This data also needs to be formatted and FTPed to another server. The dial-up portion is fine, I can connect and communicate with the server, but sometimes the connection is slow, maybe only 19Kbps.
Once connected I tried to use System.Data.SqlClient.SqlBulkCopy, but it just throws a timeout error. I've set the timeout on the bulk copy to 7200 seconds, and the timeout on the connection strings to each database at 900 seconds, but it still times out at around 30 seconds.
I tried using a DataReader and running SqlCommand.ExecuteNonQuery() to insert each row, which works OK, but it's slow and sometimes the connection is lost.
I also tried setting up a DTS package on the remote servers, scheduling them to dump the data I need to text, and then tried downloading the files. But, they can be a few hundred MB (possibly even GB on some servers) and the dial-up connection is usually dropped at some point. | What I ended up doing was creating a small app in C (a few of these are WINNT and that was the easiest way, it also allows other to retrieve the data manually if necessary without the ability to alter the source) that takes a few arguments to build the query I need. It then runs the query and dumps the results in the required CSV format. Then it calls 7zip with the highest compression level to compact the data as small as possible (this reduces a 500MB file to about 20MB).
Because I have to bring the data back to me before I can FTP it to the necessary place, and the remote servers don't have any internet access, I'm still just copying the file to a windows share, then decompressing it locally and FTP the uncompressed data (as requested) to it's destination.
This may not be the best approach, but it's working. Thanks | If it is an option, zip it up, ftp and do the bulk insert on your side. | What is the best way to bulk copying SQL data over a dial-up connection? | [
"",
"c#",
"sql-server",
"ras",
""
] |
I am wondering what type the 'value' keyword in a property takes.
so:
```
public class Test
{
string _numberAsString;
int _number = -1;
public Test() {}
public string NumberAsString
{
get { return _numberAsString; }
set { _numberAsString= value; }
}
public int Number
{
get { return int.Parse(_numberAsString); }
set { _number = value; }
}
}
//elsewhere
Test t = new Test();
t.Number = 5;
```
Now, this doesn't compile, as I'd expect. The type of 'value' is determined by the return type of the property, is that correct? I couldn't find anything to that effect, perhaps it's too obvious (I haven't read the language specs, presumably there's something in there).
I ask, because I would like to set the property with a type that is then converted into the type of the getter. I suppose this doesn't really make sense.
It seems I will have to achieve this by creating a couple of methods. | Yes, the type of 'value' is determined by the return type of the property. What exactly are you trying to accomplish? Do you want to be able to set either Number or NumberAsString to a valid value and get a result back out from either property?
If that's the case you need to do something like this:
```
public class Test
{
string _numberAsString;
int _number = -1;
public Test() {}
public string NumberAsString
{
get { return _numberAsString; }
set { _numberAsString= value; }
}
public int Number
{
get { return int.Parse(_numberAsString); }
set { _numberAsString = value.ToString(); }
}
}
```
This would allow you to do this:
```
Test t = new Test();
t.Number = 5;
Console.WriteLine(t.NumberAsString); // should print out "5"
t.NumberAsString = "5";
Console.WriteLine(t.Number); // should print out "5"
```
You can't have a get and a set for a property that take different types. The only option you have is to store it internally as one type and then in either the get or the set (or both) perform the conversion from one type to another. | The type of the value in the setter is the type of the property - you cannot pass a string to a property that is an int, this must first be parsed to an int.
Strings in .net cannot be coerced into any other type (in the way perl, awk and many other dynamic languages allow) they can only be treated as string, or as their parent class object.
you could do the follwoing:
```
private int _number;
private string _numberAsString;
public string NumberAsString
{
get { return _numberAsString; }
set { LinkedSet(value); }
}
public int Number
{
get { return _number; }
set { LinkedSet(value); }
}
private void LinkedSet(string s)
{
this._number = int.Parse(s);
this._numberAsString = s;
}
private void LinkedSet(int i)
{
this._numberAsString = i.ToString();
this._number = i;
}
```
obviously the NumberAsString setter can throw a FormatException the Number setter cannot.
I do not recommend this in general though unless you **really** need to avoid converting the number to a string and the string to a number on a regular basis (at which point you can make the setters lazy in their evalition of the linked value - albeit changing the semantics of the exception from on set of the string to on get of the int - likely to be at best annoying or at worst a nasty bug. | What is the type of the 'value' reserved word in C# properties | [
"",
"c#",
"properties",
"types",
"keyword",
""
] |
Basically the app writes the contents of a Collection to XML. I'm using XMLStreamWriter (`XMLOutputFactory.newInstance().createXMLStreamWriter(...)`) for this purpose.
Works great except for the fact that I can't get how to append data to an existing file. Don't really like the idea of reading all of it first, appending the data in memory and then overwriting. Or is it the only way? | If you're appending a top-level element, you can probably get away with doing what you want. e.g., If you have this file:
```
<some_element>
<nested_element>
...
</nested_element>
</some_element>
```
you can most likely get away with appending another `some_element` element.
However, you're obviously screwed if there's an outer-level element, and you have to append an *inner*-level one. For instance, suppose you want to add a `some_element` element to this file:
```
<data>
<some_element>
<nested_element>
...
</nested_element>
</some_element>
</data>
```
In general, you're far better off reparsing the document, then rewriting it. If it's small, use a DOM-based parser; it's easier. If the file is big, then use a SAX-based one. | Simply appending to an XML file will result in malformed XML. You should build the DOM and attach what new elements you need. | Appending to XML with XMLStreamWriter | [
"",
"java",
"xml",
""
] |
Is it possible to have something like the following:
```
class C
{
public Foo Foos[int i]
{
...
}
public Bar Bars[int i]
{
...
}
}
```
If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties. | Not in C#, no.
However, you can always return collections from properties, as follows:
```
public IList<Foo> Foos
{
get { return ...; }
}
public IList<Bar> Bars
{
get { return ...; }
}
```
IList<T> has an indexer, so you can write the following:
```
C whatever = new C();
Foo myFoo = whatever.Foos[13];
```
On the lines "return ...;" you can return whatever implements IList<T>, but you might what to return a read-only wrapper around your collection, see AsReadOnly() method. | This from C# 3.0 spec
"Overloading of indexers permits a class, struct, or interface to declare multiple indexers, provided their signatures are unique within that class, struct, or interface."
```
public class MultiIndexer : List<string>
{
public string this[int i]
{
get{
return this[i];
}
}
public string this[string pValue]
{
get
{
//Just to demonstrate
return this.Find(x => x == pValue);
}
}
}
``` | C# Multiple Indexers | [
"",
"c#",
"properties",
"indexer",
""
] |
I'm writing an application that gets data from URLs, but I want to make it an option whether or not the user uses "clean" urls (ex: <http://example.com/hello/world>) or "dirty" urls (ex: <http://example.com/?action=hello&sub=world>).
What would be the best way to get variables form both URL schemes? | If your mod\_rewrite has a rule like the following:
```
RewriteRule ^hello/world /?action=hello&sub=world [NC,L]
```
or, the more generalised:
```
// Assuming only lowercase letters in action & sub..
RewriteRule ^([a-z]+)/([a-z]+) /?action=$1&sub=$2 [NC,L]
```
then the same PHP script is being called, with the `$_REQUEST` variables available whichever way the user accesses the page (dirty or clean url).
We recently moved a large part of our site to clean urls (still supporting the older, "dirty" urls) and rules like the above meant we didn't have to rewrite any code that relied on `$_REQUEST` params, only the mod\_rewrite rules.
**Update**
Mod\_rewrite is an Apache module, but there are a number of options [available for IIS](http://en.wikipedia.org/wiki/Rewrite_engine#IIS) also.
Whichever web server you decide to support, the mod\_rewrite approach will likely result in the least amount of work for you. Without it, you'd likely have to create a load of files to mimic the structure of your clean urls, e.g. in your webserver root you'd create a directory `hello`, placing a file `world` into it, containing something like the following:
```
// Set the $_REQUEST params to mimic dirty url
$_REQUEST['action'] = 'hello';
$_REQUEST['sub'] = 'world';
// Include existing file so we don't need to re-do our logic
// (assuming index.php at web root)
include('../index.php');
```
As the number of parameters you wish to handle 'cleanly' increases, so will the number of directories and stub files you require, which will greatly increase your maintenance burden.
mod\_rewrite is designed for exactly this sort of problem, and is now supported on IIS as well as Apache, so I'd strongly recommend going in that direction! | If you're application is running in Apache server, I would recommend the use of mod\_rewrite.
Basically, you code your application to use "dirty" URLs inside. What I mean by this is that you can still use the "clean" URLs in the templates and such, but you use the "dirty" version when parsing the URL. Like, you're real and "diry" URL is www.domain.com/index.php?a=1&b=2, inside of your code you are still going to use $\_GET['a'] and $\_GET['b']. Then, with the power of mod\_rewrite just make the URLs like www.domain.com/1/2/ point to the "dirty" URL. (this is just an example of how things can be done) | Best way to get data from "clean" and "dirty" URLs | [
"",
"php",
""
] |
How do you get the proper index of a selected input from a set of input elements with irregularly numbered indexes using JQuery? JQuery's "index" function always returns a value starting from 0 instead of the indexes I used. My code is below:
JQuery:
```
$("input[name^=myboxes]").click(function() {
var element_id = $("input[name^=myboxes]").index(this);
alert(element_id); //will alert 0, 1, or 2 instead of 3, 8, or 10
});
```
HTML:
```
<input type="checkbox" id="myboxes[3]" name="myboxes[3]" value="CHECKED" >
<input type="checkbox" id="myboxes[8]" name="myboxes[8]" value="CHECKED" >
<input type="checkbox" id="myboxes[10]" name="myboxes[10]" value="CHECKED" CHECKED >
```
Thank you! | The value of your ID does not have an "index" property. It's just a string.
One suggestion: parse the id string to get your value:
```
$("input[name^=myboxes]").click(function() {
var element_id = $(this).attr('id');
//the initial starting point of the substring is based on "myboxes["
var ix = element_id.substring(8,element_id.length - 1)
alert(ix);
});
```
Hope this helps | The following is what has always worked for me.
JQuery:
```
$("input[name^=myboxes]").click(function() {
var element_id = $(this).attr("meta:index");
alert(element_id);
});
```
HTML:
```
<input type="checkbox" id="myboxes[3]" name="myboxes[3]" meta:index="3" value="CHECKED" >
<input type="checkbox" id="myboxes[8]" name="myboxes[8]" meta:index="8" value="CHECKED" >
<input type="checkbox" id="myboxes[10]" name="myboxes[10]" meta:index="10" value="CHECKED" CHECKED >
```
Hope this helps. | Getting correct index from input array in JQuery | [
"",
"javascript",
"jquery",
"html",
""
] |
I've created a custom thread pool utility, but there seems to be a problem that I cannot find.
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
namespace iWallpaper.S3Uploader
{
public class QueueManager<T>
{
private readonly Queue queue = Queue.Synchronized(new Queue());
private readonly AutoResetEvent res = new AutoResetEvent(true);
private readonly AutoResetEvent res_thr = new AutoResetEvent(true);
private readonly Semaphore sem = new Semaphore(1, 4);
private readonly Thread thread;
private Action<T> DoWork;
private int Num_Of_Threads;
private QueueManager()
{
Num_Of_Threads = 0;
maxThread = 5;
thread = new Thread(Worker) {Name = "S3Uploader EventRegisterer"};
thread.Start();
// log.Info(String.Format("{0} [QUEUE] FileUploadQueueManager created", DateTime.Now.ToLongTimeString()));
}
public int maxThread { get; set; }
public static FileUploadQueueManager<T> Instance
{
get { return Nested.instance; }
}
/// <summary>
/// Executes multythreaded operation under items
/// </summary>
/// <param name="list">List of items to proceed</param>
/// <param name="action">Action under item</param>
/// <param name="MaxThreads">Maximum threads</param>
public void Execute(IEnumerable<T> list, Action<T> action, int MaxThreads)
{
maxThread = MaxThreads;
DoWork = action;
foreach (T item in list)
{
Add(item);
}
}
public void ExecuteNoThread(IEnumerable<T> list, Action<T> action)
{
ExecuteNoThread(list, action, 0);
}
public void ExecuteNoThread(IEnumerable<T> list, Action<T> action, int MaxThreads)
{
foreach (T wallpaper in list)
{
action(wallpaper);
}
}
/// <summary>
/// Default 10 threads
/// </summary>
/// <param name="list"></param>
/// <param name="action"></param>
public void Execute(IEnumerable<T> list, Action<T> action)
{
Execute(list, action, 10);
}
private void Add(T item)
{
lock (queue)
{
queue.Enqueue(item);
}
res.Set();
}
private void Worker()
{
while (true)
{
if (queue.Count == 0)
{
res.WaitOne();
}
if (Num_Of_Threads < maxThread)
{
var t = new Thread(Proceed);
t.Start();
}
else
{
res_thr.WaitOne();
}
}
}
private void Proceed()
{
Interlocked.Increment(ref Num_Of_Threads);
if (queue.Count > 0)
{
var item = (T) queue.Dequeue();
sem.WaitOne();
ProceedItem(item);
sem.Release();
}
res_thr.Set();
Interlocked.Decrement(ref Num_Of_Threads);
}
private void ProceedItem(T activity)
{
if (DoWork != null)
DoWork(activity);
lock (Instance)
{
Console.Title = string.Format("ThrId:{0}/{4}, {1}, Activity({2} left):{3}",
thread.ManagedThreadId, DateTime.Now, queue.Count, activity,
Num_Of_Threads);
}
}
#region Nested type: Nested
protected class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
internal static readonly QueueManager<T> instance = new FileUploadQueueManager<T>();
}
#endregion
}
```
}
Problem is here:
```
Console.Title = string.Format("ThrId:{0}/{4}, {1}, Activity({2} left):{3}",
thread.ManagedThreadId, DateTime.Now, queue.Count, activity,
Num_Of_Threads);
```
There is always ONE thread id in title. And program seems to be working in one thread.
Sample usage:
```
var i_list = new int[] {1, 2, 4, 5, 6, 7, 8, 6};
QueueManager<int>.Instance.Execute(i_list,
i =>
{
Console.WriteLine("Some action under element number {0}", i);
}, 5);
```
P.S.: it's pretty messy, but I'm still working on it. | Writing robust threaded code is not trivial. There are numerous thread-pools around that you might look at for reference, but also note that Parallel Extensions (available as [CTP](http://www.microsoft.com/downloads/details.aspx?FamilyId=348F73FD-593D-4B3C-B055-694C50D2B0F3&displaylang=en), or later in .NET 4.0) includes a lot of additional threading constructs out-of-the-box (in the TPL/CCR). For example, `Parallel.For` / `Parallel.ForEach`, which deal with work-stealing, and handling the available cores effectively.
For an example of a pre-rolled thread-pool, see Jon Skeet's `CustomThreadPool` [here](http://www.yoda.arachsys.com/csharp/miscutil/). | I looked through your code and here are a couple of issues I saw.
1. You lock the queue object even though it is synchronized queue. This is unnecessary
2. You inconsistently lock the queue object. It should either be locked for every access or not locked and depending on the Synchronized behavior.
3. The Proceed method is not thread safe. These two lines are the issue
```
if (queue.Count > 0) {
var item = (T)queue.Dequeue();
...
}
```
Using a synchronized queue only guarantees that individual accesses are safe. So both the .Count and the .Dequeue method won't mess with te internal structure of the queue. However imagine the scenario where two threads run these lines of code at the same time with a queue of count 1
* Thread1: if (...) -> true
* Thread2: if (...) -> true
* Thread1: dequeue -> sucess
* Thread2: dequeue -> fails because the queue is empty
4. There is a race condition between Worker and Proceed that can lead to deadlock. The following two lines of code should be switched.
Code:
```
res_thr.Set()
Interlocked.Decrement(ref Num_Of_Threads);
```
The first line will unblock the Worker method. If it runs quickly enough it will go back through the look, notice that Num\_Of\_Threads < maxThreads and go right back into res\_thr.WaitOne(). If no other threads are currently running then this will lead to a deadlock in your code. This is very easy to hit with a low number of maximum threads (say 1). Inverting these two lines of code should fix the issue.
5. The maxThread count property does not seem to be useful beyond 4. The sem object is initialized to accept only 4 maximum concurrent entries. All code that actually executes an item must go through this semaphore. So you've effectively limited the maximum number of concurrent items to 4 regardless of how high maxThread is set. | What is wrong with my custom thread pool? | [
"",
"c#",
".net",
"multithreading",
"lambda",
""
] |
Example
```
int *ptr;
*ptr = 1000;
```
can I catch memory access violation exception using standard C++ without using any microsoft specific. | Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch. | Read it and weep!
I figured it out. If you don't throw from the handler, the handler will just continue and so will the exception.
The magic happens when you throw you own exception and handle that.
```
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <tchar.h>
void SignalHandler(int signal)
{
printf("Signal %d",signal);
throw "!Access Violation!";
}
int main()
{
typedef void (*SignalHandlerPointer)(int);
SignalHandlerPointer previousHandler;
previousHandler = signal(SIGSEGV , SignalHandler);
try{
*(int *) 0 = 0;// Baaaaaaad thing that should never be caught. You should write good code in the first place.
}
catch(char *e)
{
printf("Exception Caught: %s\n",e);
}
printf("Now we continue, unhindered, like the abomination never happened. (I am an EVIL genius)\n");
printf("But please kids, DONT TRY THIS AT HOME ;)\n");
}
``` | Catching access violation exceptions? | [
"",
"c++",
"exception",
""
] |
I found this statement is some old code and it took me a second to figure out...
```
IsTestActive = (TestStateID == 1 ? true : false);
```
Please correct me if I'm wrong but isn't this the same as this one?:
```
IsTestActive = (TestStateID == 1);
```
If it is, why would you ever want to use the first? Which one is more readable? (I think the latter, but I'd like to see what others think.) | Yes, it is exactly the same.
Yes, the latter is more readable. | ```
IsTestActive = (TestStateID == 1);
```
is definitely more readable.
You *could* make a case for defining a constant
```
ACTIVE = 1
```
then replacing the boolean variable `IsTestActive` with
```
(TestStateID == ACTIVE)
```
The way the code is now, the state of the boolean `IsTestActive` will be erroneous if the state of `TestStateID` changes without updating the boolean. Bypassing the boolean and testing the real source of the information you're after will remove the possibility of this error. | Setting a boolean value based on an integer | [
"",
"c#",
"coding-style",
"readability",
""
] |
I have an application written in VB.NET that interacts with Excel via interop.
I eventually ran into the known issue of Cell-edit mode (see [MSDN](http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=4087801&SiteID=1) and [stackoverflow](https://stackoverflow.com/questions/221984/how-to-tell-if-excel-application-is-in-cell-edit-mode) for some background).
I have been trying to convert the suggested code to VB.NET but keep getting the following error:
```
Reference required to assembly 'office, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' containing the type 'Microsoft.Office.Core.CommandBars'. Add one to your project. (BC30652) - E:\ ... .vb:3471
```
The original C# code (from previosuly mentioned articles) is as follows
```
private bool IsEditMode()
{
object m = Type.Missing;
const int MENU_ITEM_TYPE = 1;
const int NEW_MENU = 18;
// Get the "New" menu item.
CommandBarControl oNewMenu = Application.CommandBars["Worksheet Menu Bar"].FindControl(MENU_ITEM_TYPE, NEW_MENU, m, m, true );
if ( oNewMenu != null )
{
// Check if "New" menu item is enabled or not.
if ( !oNewMenu.Enabled )
{
return true;
}
}
return false;
}
```
My converted VB.NET code is as follows
```
Private Function isEditMode() As Boolean
isEditMode = False
Dim m As Object = Type.Missing
Const MENU_ITEM_TYPE As Integer = 1
Const NEW_MENU As Integer = 18
Dim oNewMenu As Office.CommandBarControl
' oExcel is the Excel Application object
' the error is related to the below line
oNewMenu = oExcel.CommandBars("Worksheet Menu Bar").FindControl(MENU_ITEM_TYPE, NEW_MENU, m, m, True)
If oNewMenu IsNot Nothing Then
If Not oNewMenu.Enabled Then
isEditMode = True
End If
End If
End Function
```
I have added a (COM) reference to the Microsoft Office Object Library
```
Imports Office = Microsoft.Office.Core
Imports Microsoft.Office.Interop
```
I am kind of stuck. I already have tried indirectly referencing the CommandBar object, and re-adding refrences but can not figure out what is the problem. any ideas? | As a quick-and-dirty fix i used the following code as an alternative
```
Private Function isEditMode() As Boolean
isEditMode = False
Try
oExcel.GoTo("###")
Catch Ex As Exception
' Either returns "Reference is not valid."
' or "Exception from HRESULT: 0x800A03EC"
If ex.Message.StartsWith("Exception") then isEditMode = True
End Try
End Function
```
The .GoTo function (and corresponding menu item) is not available when Excel is in Cell-edit mode.
Giving the .GoTo function a dummy destination will do nothing and won't affect anything if the user is working in the cell when the code runs.
An added extra is that no reference to the Microsoft Office Object (Microsoft.Office.Core) library is needed. | An older post but not an old problem. The solution above for detect and exit is fine but I found another solution for getting Excel out of edit mode which doesn't need to use an API to find the window or use Sendkeys to click a cell, my solution uses events. Excel can even be in edit mode and minimised and this solution will still work. If you are reading this you probably won't need the exact code but if you do please let me know.
First detect Excel edit mode with a try catch similar to the previous solutions and set a Global flag True if Excel is in edit mode.
Then tell Excel to close. This action will be available even when in edit mode.
In the Excel OnClosing event check if your Global flag is set and if so set the On Closing event 'e.Cancel' to True which will stop Excel closing.
Set your Global flag back to False and when Excel comes back it will be out of edit mode and whatever was written into the edited cell will still be there. | Workaround to see if Excel is in cell-edit mode in .NET | [
"",
"c#",
"vb.net",
"excel",
"interop",
"excel-interop",
""
] |
A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object.
He brought up "Why not just add a method to your own class?" We've been going round and round (in a good way). My general response is that it is another tool in the toolbelt, and his response is it is a useless waste of a tool... but I thought I'd get a more "enlightened" answer.
What are some scenarios that you've used extension methods that you couldn't have (or shouldn't have) used a method added on to your own class? | I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense.
I have a format provider to [format a file size](https://stackoverflow.com/questions/128618/c-file-size-format-provider). To use it I need to write:
```
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize));
```
Creating an extension method I can write:
```
Console.WriteLine(fileSize.ToFileSize());
```
Cleaner and simpler. | The **only** advantage of extension methods is code readability. That's it.
Extension methods allow you to do this:
```
foo.bar();
```
instead of this:
```
Util.bar(foo);
```
Now there are a lot of things in C# that are like this. In other words there are many features in C# that seem trivial and don't have great benefit in and of themselves. However once you begin combining these features together you begin to see something just a bit bigger than the sum of its parts. LINQ benefits greatly from extension methods as LINQ queries would be almost unreadable without them. LINQ would be *possible* without extension methods, but not practical.
Extension methods are a lot like C#'s partial classes. By themselves they are not very helpful and seem trivial. But when you start working with a class that needs generated code, partial classes start to make a lot more sense. | What Advantages of Extension Methods have you found? | [
"",
"c#",
"extension-methods",
""
] |
I have a database with millions of phone numbers with free-for-all formatting. Ie, the UI does not enforce any constraints and the users are typing in whatever they want.
What I'm looking for is a Java API that can make a best-effort to convert these into a consistent format. Ideally, the API would take the free text value and a country code and produce a valid international phone number or throw an exception.
For example, a phone number in the system might look like any of the following:
```
(555) 478-1123
555-478-1123
555.478.1123
5554781123
```
Given the country of US, the API would produce the value "+1 (555) 478-1123" for all these. The exact format does not matter, as long as it's consistent.
There are also numbers in the system without area codes, such as "478-1123". In that case, I would expect a NoAreaCodeException, or something similar.
There could also be data such as "abc", which should also throw exceptions.
Of course, there are countless variations of the examples I have posted, as well as the enormous complication of international phone numbers, which have quite complicated validation rules. This is why I would not consider rolling my own.
Has anyone seen such an API? | You could write your own (for US phone # format):
* Strip any non-numeric characters from the string
* Check that the remaining string is ten characters long
* Put parentheses around the first three characters and a dash between the sixth and seventh character.
* Prepend "+1 " to the string
---
### Update:
Google recently released [libphonenumber](http://code.google.com/p/libphonenumber/) for parsing, formatting, storing and validating international phone numbers. | You could try this Java phone number formatting library <https://github.com/googlei18n/libphonenumber>
It has data for hundreds of countries and formats. | Java phone number format API | [
"",
"java",
""
] |
I was playing around with Boost.Regex to parse strings for words and numbers. This is what I have so far:
```
#include <iostream>
#include <string>
#include <boost/foreach.hpp>
#include <boost/regex.hpp>
#include <boost/range.hpp>
using namespace std;
using namespace boost;
int main()
{
regex re
(
"("
"([a-z]+)|"
"(-?[0-9]+(\\.[0-9]+)?)"
")"
);
string s = "here is a\t list of Words. and some 1239.32 numbers to 3323 parse.";
sregex_iterator m1(s.begin(), s.end(), re), m2;
BOOST_FOREACH (const match_results<string::const_iterator>& what, make_iterator_range(m1, m2)) {
cout << ":" << what[1].str() << ":" << what.position(1) << ":" << what.length(1) << endl;
}
return 0;
}
```
Is there a way to tell regex to parse from a stream rather than a string? It seems like it should be possible to use any iterator. | Boost.IOStreams has a [regex\_filter](http://www.boost.org/doc/libs/1_55_0/libs/iostreams/doc/classes/regex_filter.html) allowing one to perform the equivalent of a regex\_replace on a stream. However, looking at the implementation, it seems to "cheat" in that it simply loads the whole stream into a buffer and then calls Boost.Regex on that buffer.
Making a regex search on a stream's contents without having to entirely load it in memory can be done with the "[partial match](http://www.boost.org/doc/libs/1_55_0/libs/regex/doc/html/boost_regex/partial_matches.html)" support of Boost.Regex. Look at the example at the end of the page. | The regex\_iterator constructor requires BidirectionalIterators, but std::istream\_iterator is only an InputIterator, so it appears that you'd not be able to do this with any of the standard stream classes and/or objects (cin, ifstream, etc.). If you had a custom stream that exposed a bidirectional iterator, it should work. | Can you use Boost.Regex to parse a stream? | [
"",
"c++",
"regex",
"boost",
"stream",
""
] |
Ok, this is bugging me, and I just can't figure out what is wrong...
I have made two forms. First form just has a simple button on it, which opens the other as a dialog like so:
```
using (Form2 f = new Form2())
{
if (f.ShowDialog() != DialogResult.OK)
MessageBox.Show("Not OK");
else
MessageBox.Show("OK");
}
```
The second, which is that `Form2`, has two buttons on it. All I have done is to set the forms AcceptButton to one, and CancelButton to the other. In my head this is all that should be needed to make this work. But when I run it, I click on the button which opens up Form2. I can now click on the one set as CancelButton, and I get the "Not OK" message box. But when I click on the one set as AcceptButton, nothing happens?
The InitializeComponent code of Form2 looks like this:
```
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(211, 13);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(75, 23);
this.button1.TabIndex = 0;
this.button1.Text = "button1";
this.button1.UseVisualStyleBackColor = true;
//
// button2
//
this.button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.button2.Location = new System.Drawing.Point(130, 13);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(75, 23);
this.button2.TabIndex = 1;
this.button2.Text = "button2";
this.button2.UseVisualStyleBackColor = true;
//
// Form2
//
this.AcceptButton = this.button1;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.button2;
this.ClientSize = new System.Drawing.Size(298, 59);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Name = "Form2";
this.Text = "Form2";
this.Load += new System.EventHandler(this.Form2_Load);
this.ResumeLayout(false);
}
```
I have done nothing else than add those two buttons, and set the AcceptButton and CancelButton. Why doesn't it work? | Just setting the `AcceptButton`/`CancelButton` is not enough. This just tells which button should be invoked on `Enter`/`Esc`. You have to set the button's `DialogResult` property. | Try setting `DialogResult` on `button1`
```
this.button1.DialogResult = System.Windows.Forms.DialogResult.OK;
``` | WinForms AcceptButton not working? | [
"",
"c#",
"winforms",
"modal-dialog",
""
] |
Currently I'm working on a simple Mail-Merge module.
I need to load plain \*.RTF template, then replace all words enclosed in [[field]] tags and at the end and print them out.
I found the iText library which is free and capable of loading/saving pdfs and rtf.
I managed to load rtf, merge a few copies to one huge doc but I have no idea how to replace [[field]] by custom data like customer name/address.
Is that feature present, and if yes - how to do it?
The solution platform is c#/.NET | Finally I decided to use \*.docx and "Open XML SDK 2.0 for Microsoft Office" .NET strongly typed wrapper. | I don't think that pdf is the way you want to go.
According to [this article](http://itext.ugent.be/library/question.php?id=48) it is extremely difficult at best and not possible at worst.
Would something like [RTFLib](http://xmlgraphics.apache.org/fop/dev/rtflib.html) work better for you?
G-Man | iText - how to do search/replace on existing RTF document | [
"",
"c#",
"itext",
"mailmerge",
""
] |
We have an old legacy PHP application. Now I want to write a new application module using Ruby on Rails.
Deployment is a one problem. I guess that it should be possible to run PHP app (via mod\_php) and RoR app (via mod\_proxy / mongrel) on a one Apache server. I don't want to use mod\_rails because it requires to run php via fcgi. So is a risk of breaking something. Both PHP and RoR will use the same DB.
The tricky part is how to pass login info from PHP application to RoR app. Users login into PHP and their info is stored in PHP session data. The RoR app will be placed in a subdirectory of main PHP app (eg www.example.com/railsapp). So RoR should receive all HTTP cookies. And the question is how to extract PHP session data from RoR app.
Above this is just my first idea which is rather bad because of possible race conditions between PHP mod and RoR. I can modify the PHP app to store some info in DB when a user logs in. But I don't know how to handle a case when PHP session data expired and some data in DB should be updated (logout a user).
Does anyone solved similar problem? Or at least can point a most promising direction?
Update: It should be possible to configure mod\_php to store session data in sql DB. In this way there will be no race conditions. DB engine should prevent race conditions.
Update2: Actually it is possible to use mod\_rails with Apache in prefork mode. Which is required by the mod\_php. It is just recommended for mod\_rails to run Apache in worker mpm mode. So the whole deployment of PHP / RoR apps is greatly simplified. | First, if you are placing the rails app in a sub directory it is possible to use mod\_rails. In your configuration for the PHP site you can have a location that has a root for rails.
```
<Location /railsapp>
DocumentRoot /.../app/public
</Location>
```
To get a session over to the rails side, you could either create a connect page on the rails and call it from the PHP side and pass in some data to login. You just need to protect this page from any request not from the localhost (easy to do).
You could also switch rails to use a database to store its sessions, you should then be able to generate a session id, store it in a cookie with the correct name and secret, and create a session in the database manually with that id.
You can also (which I recommend) have proxy page on the rails side which logs the user in and redirects them to their desired page. You could do it like this (*not actual working code, but you get the idea)*:
PHP
```
$key = md5hash($user_id . $user_password_hash . $timestamp)
$url = "/railsapp/proxy?userid=" . $user_id . "&key=" . $key . "&page=home%2Fwelcome"
<a href="<$ $url $>">Rails App</a>
```
Rails
```
map.proxy 'proxy', :controller => 'proxy', :action => 'connect'
class ProxyController < ActionController::Base
def connect
key = ...
if params[:key] == key
login_user params[:userid]
redirect_to params[:page]
else
render :nothing, :status => 403
end
end
end
``` | I've done a mixed PHP/RoR app before (old PHP code, new hawt RoR features, as stuff needed fixing it got re-implemented). It's not really all that hard -- you just serve up the PHP as normal files, and use a 404 handler to redirect everything else to the Rails app.
As far as the session data goes, you *could* stuff it into a DB, but if you're willing to write/find routines to read and write PHP's marshalled data formats, PHP uses `flock()` to ensure that there are no race conditions in reading/writing the session data file. Do the same thing in your Rails app for minimal pain. | Tricky integration of a legacy PHP app and a new Ruby on Rails app | [
"",
"php",
"ruby-on-rails",
"interop",
""
] |
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)
```
class Foo {
private:
struct Pos { int x, y, z };
public:
Pos Position;
};
```
Versus:
```
struct Foo {
struct Pos { int x, y, z } Pos;
};
```
---
Similar questions:
* [When should you use a class vs a struct in C++?](https://stackoverflow.com/questions/54585/when-should-you-use-a-class-vs-a-struct-in-c)
* [What are the differences between struct and class in C++?](https://stackoverflow.com/questions/92859/what-are-the-differences-between-struct-and-class-in-c)
* [When should I use a struct instead of a class?](https://stackoverflow.com/questions/85553/when-should-i-use-a-struct-instead-of-a-class) | There is no real advantage of using one over the other, in c++, the only difference between a struct and a class is the default visibility of it's members (structs default to public, classes default to private).
Personally, I tend to prefer structs for POD types and use classes for everything else.
EDIT: [litb](https://stackoverflow.com/users/34509/litb) made a good point in the comment so I'm going to quote him here:
> one important other difference is that
> structs derive from other
> classes/struct public by default,
> while classes derive privately by
> default. | One side point is that structs are often used for aggregate initialized data structures, since all non-static data members must be public anyway (C++03, 8.5.1/1).
```
struct A { // (valid)
{
int a;
int b;
} x = { 1, 2 };
struct A { // (invalid)
private:
int a;
int b;
} x = { 1, 2 };
class A { // (invalid)
int a;
int b;
} x = { 1, 2 };
class A { // (valid)
public:
int a;
int b;
} x = { 1, 2 };
class A { // (invalid)
public:
int a;
private:
int b;
} x = { 1, 2 };
``` | Class vs Struct for data only? | [
"",
"c++",
"class",
"struct",
""
] |
I have a python interpreter embedded inside an application. The application takes a long time to start up and I have no ability to restart the interpreter without restarting the whole application. What I would like to do is to essentially save the state of the interpreter and return to that state easily.
I started by storing the names of all modules in sys.modules that the python interpreter started with and then deleting all new modules from sys.modules when requested. This appears to make the interpreter prepared to re-import the same modules even though it has already imported them before. However, this doesn't seem to work in all situations, such as using singleton classes and static methods, etc.
I'd rather not embed another interpreter inside this interpreter if it can be avoided, as the ease of being able to use the applications API will be lost (as well as including a slight speed hit I imagine).
So, does anyone know of a way I could store the interpreter's state and then return to this so that it can cope with all situations?
Thanks,
Dan | Try this code from ActiveState recipes: <http://code.activestate.com/recipes/572213/>
It extends pickle so it supports pickling anything defined in the shell console. Theoretically you should just be able to pickle the **main** module, according to their documentation:
```
import savestate, pickle, __main__
pickle.dump(__main__, open('savestate.pickle', 'wb'), 2)
``` | I'd suggest tackling the root cause problem.
> "The application takes a long time to
> start up and I have no ability to
> restart the interpreter without
> restarting the whole application"
I doubt this is actually 100% true. If the overall application is the result of an act of Congress, okay, it can't be changed. But if the overall application was written by real people, then finding and moving the code to restart the Python interpreter should be possible. It's cheaper, simpler and more reliable than *anything* else you might do to hack around the problem. | Restarting a Python Interpreter Quietly | [
"",
"python",
"interpreter",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.