Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
The executeTime below is 30 seconds the first time, and 25 seconds the next time I execute the same set of code. When watching in SQL Profiler, I immediately see a login, then it just sits there for about 30 seconds. Then as soon as the select statement is run, the app finishes the ToList command. When I run the generated query from Management Studio, the database query only takes about 400ms. It returns 14 rows and 350 columns. It looks like time it takes transforming the database results to the entities is so small it is not noticable.
So what is happening in the 30 seconds before the database call is made?
If entity framework is this slow, it is not possible for us to use it. Is there something I am doing wrong or something I can change to speed this up dramatically?
**UPDATE:**
All right, if I use a Compiled query, the first time it take 30 seconds, and the second time it takes 1/4th of a second. Is there anything I can do to speed up the first call?
```
using (EntitiesContext context = new EntitiesContext())
{
Stopwatch sw = new Stopwatch();
sw.Start();
var groupQuery = (from g in context.Groups.Include("DealContract")
.Include("DealContract.Contracts")
.Include("DealContract.Contracts.AdvertiserAccountType1")
.Include("DealContract.Contracts.ContractItemDetails")
.Include("DealContract.Contracts.Brands")
.Include("DealContract.Contracts.Agencies")
.Include("DealContract.Contracts.AdvertiserAccountType2")
.Include("DealContract.Contracts.ContractProductLinks.Products")
.Include("DealContract.Contracts.ContractPersonnelLinks")
.Include("DealContract.Contracts.ContractSpotOrderTypes")
.Include("DealContract.Contracts.Advertisers")
where g.GroupKey == 6
select g).OfType<Deal>();
sw.Stop();
var queryTime = sw.Elapsed;
sw.Reset();
sw.Start();
var groups = groupQuery.ToList();
sw.Stop();
var executeTime = sw.Elapsed;
}
``` | I had this exact same problem, my query was taking 40 seconds.
I found the problem was with the `.Include("table_name")` functions. The more of these I had, the worse it was. Instead I changed my code to Lazy Load all the data I needed right after the query, this knocked the total time down to about 1.5 seconds from 40 seconds. As far as I know, this accomplishes the exact same thing.
So for your code it would be something like this:
```
var groupQuery = (from g in context.Groups
where g.GroupKey == 6
select g).OfType<Deal>();
var groups = groupQuery.ToList();
foreach (var g in groups)
{
// Assuming Dealcontract is an Object, not a Collection of Objects
g.DealContractReference.Load();
if (g.DealContract != null)
{
foreach (var d in g.DealContract)
{
// If the Reference is to a collection, you can just to a Straight ".Load"
// if it is an object, you call ".Load" on the refence instead like with "g.DealContractReference" above
d.Contracts.Load();
foreach (var c in d.Contracts)
{
c.AdvertiserAccountType1Reference.Load();
// etc....
}
}
}
}
```
Incidentally, if you were to add this line of code above the query in your current code, it would knock the time down to about 4-5 seconds (still too ling in my option) From what I understand, the `MergeOption.NoTracking` option disables a lot of the tracking overhead for updating and inserting stuff back into the database:
```
context.groups.MergeOption = MergeOption.NoTracking;
``` | It is because of the Include. My guess is that you are eager loading a lot of objects into the memory. It takes much time to build the c# objects that corresponds to your db entities.
My recommendation for you is to try to lazy load only the data you need. | Why is Entity Framework taking 30 seconds to load records when the generated query only takes 1/2 of a second? | [
"",
"c#",
".net",
"entity-framework",
"linq-to-entities",
""
] |
I have been approached to create a website using Sabre Web Services to power the reservations system. All documentation I have seen refers to .NET or Java solutions, and I was in doubt as to whether PHP can be used, as access is performed using SOAP.
I have found no further information about this, and I assume the answer is yes, but I wonder why there is not a single reference to this being possible. All solutions seem to be .NET! | Yes, PHP can be be used to connect to SOAP web services - take a look at [NuSOAP](http://sourceforge.net/projects/nusoap/). It allows a nice & easy object oriented way to consume web services. | SOAP is language independent, which means that any language can communicate with the web service if it can generate SOAP requests and handle responses.
PHP's SOAP documentation can be found in the [php manual](http://uk.php.net/soap) | Accessing Sabre Web Services using PHP | [
"",
"php",
"web-services",
"sabre",
""
] |
So here is a bit of syntax that I have never seen before, can someone tell me what this means? Not sure if this is supposed to be some shorthand for an abstract property declaration or something or what.
```
public Class1 myVar { get; set; }
```
For what its worth, Class1 is an abstract class. | In C# 3.0 and later, [auto-implemented properties](http://msdn.microsoft.com/en-us/library/bb384054.aspx) make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.
```
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
``` | This is the syntax to let the compiler create a (hidden) field for you.
Also very useful is:
```
public Class1 myVar{ get; private set; }
``` | C# Shorthand Property Question | [
"",
"c#",
"properties",
""
] |
I have a list of character range restrictions that I need to check a string against, but the `char` type in .NET is UTF-16 and therefore some characters become wacky (surrogate) pairs instead. Thus when enumerating all the `char`'s in a `string`, I don't get the 32-bit Unicode code points and some comparisons with high values fail.
I understand Unicode well enough that I could parse the bytes myself if necessary, but I'm looking for a C#/.NET Framework BCL solution. So ...
How would you convert a `string` to an array (`int[]`) of 32-bit Unicode code points? | **This answer is not correct. See @Virtlink's answer for the correct one.**
```
static int[] ExtractScalars(string s)
{
if (!s.IsNormalized())
{
s = s.Normalize();
}
List<int> chars = new List<int>((s.Length * 3) / 2);
var ee = StringInfo.GetTextElementEnumerator(s);
while (ee.MoveNext())
{
string e = ee.GetTextElement();
chars.Add(char.ConvertToUtf32(e, 0));
}
return chars.ToArray();
}
```
**Notes**: Normalization is required to deal with composite characters. | You are asking about *code points*. In UTF-16 (C#'s `char`) there are only two possibilities:
1. The character is from the *Basic Multilingual Plane*, and is encoded by a single code unit.
2. The character is outside the *BMP*, and encoded using a surrogare high-low pair of code units
Therefore, assuming the string is valid, this returns an array of code *points* for a given string:
```
public static int[] ToCodePoints(string str)
{
if (str == null)
throw new ArgumentNullException("str");
var codePoints = new List<int>(str.Length);
for (int i = 0; i < str.Length; i++)
{
codePoints.Add(Char.ConvertToUtf32(str, i));
if (Char.IsHighSurrogate(str[i]))
i += 1;
}
return codePoints.ToArray();
}
```
An example with a surrogate pair and a composed character `ñ`:
```
ToCodePoints("\U0001F300 El Ni\u006E\u0303o"); // El Niño
// { 0x1f300, 0x20, 0x45, 0x6c, 0x20, 0x4e, 0x69, 0x6e, 0x303, 0x6f } // E l N i n ̃◌ o
```
Here's another example. These two code points represents a 32th musical note with a staccato accent, both surrogate pairs:
```
ToCodePoints("\U0001D162\U0001D181"); //
// { 0x1d162, 0x1d181 } // ◌
```
When [C-normalized](https://en.wikipedia.org/wiki/Unicode_equivalence#Normalization), they are decomposed into a notehead, combining stem, combining flag and combining accent-staccato, all surrogate pairs:
```
ToCodePoints("\U0001D162\U0001D181".Normalize()); //
// { 0x1d158, 0x1d165, 0x1d170, 0x1d181 } // ◌
```
---
Note that [leppie's solution](https://stackoverflow.com/a/687451/146622) is not correct. The question is about *code points*, not *text elements*. A text element is a combination of code points that together form a single grapheme. For example, in the example above, the `ñ` in the string is represented by a Latin lowercase `n` followed by a combining tilde `̃◌`. Leppie's solution discards any combining characters that cannot be normalized into a single code point. | How would you get an array of Unicode code points from a .NET String? | [
"",
"c#",
"string",
"unicode",
"char",
"astral-plane",
""
] |
I have a Generic class like that :
```
public class Repository<T> {...}
```
And I need to instance that with a string ...
Example :
```
string _sample = "TypeRepository";
var _rep = new Repository<sample>();
```
How can I do that? Is that even possible?
Thanks! | Here is my 2 cents:
```
Type genericType = typeof(Repository<>);
Type[] typeArgs = { Type.GetType("TypeRepository") };
Type repositoryType = genericType.MakeGenericType(typeArgs);
object repository = Activator.CreateInstance(repositoryType);
```
Answering the question in comment.
```
MethodInfo genericMethod = repositoryType.GetMethod("GetMeSomething");
MethidInfo closedMethod = genericMethod.MakeGenericMethod(typeof(Something));
closedMethod.Invoke(repository, new[] { "Query String" });
``` | First get the Type object using `Type.GetType(stringContainingTheGenericTypeArgument)`
Then use `typeof(Repository<>).MakeGenericType(theTypeObject)` to get a generic type.
And finally use `Activator.CreateInstance` | How do I create a generic class from a string in C#? | [
"",
"c#",
".net",
"reflection",
"generics",
""
] |
I was trying this piece of code to check whether the divide by zero exception is being caught:
```
int main(int argc, char* argv[])
{
try
{
//Divide by zero
int k = 0;
int j = 8/k;
}
catch (...)
{
std::cout<<"Caught exception\n";
}
return 0;
}
```
When I complied this using VC6, the catch handler was executed and the output was "Caught exception". However, when I compiled this using VS2008, the program crashed without executing the catch block. What could be the reason for the difference? | Enable structured exception handling under project -> properties -> configuration properties -> c/c++ -> code generation -> enable c++ exceptions.
Use a try except. Ideally with a filter that checks the exception code then returns the constant signalling if it would like to catch. I have skipped that out here but I recommend you see [here](http://msdn.microsoft.com/en-us/library/s58ftw19(VS.80).aspx) for examples of the filter.
```
#include <iostream>
#include <windows.h>
int main(int argc, char* argv[])
{
__try
{
//Divide by zero
int k = 0;
int j = 8/k;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
if(GetExceptionCode()==EXCEPTION_INT_DIVIDE_BY_ZERO)
std::cout << "Caught int divison exception\n";
else
std::cout << "Caught exception\n";
system("pause");
}
return 0;
}
``` | You are catching exceptions generated by Microsoft's structured exception handling (SEH) layer, which is an operating system thing specific to Microsoft. As Mykola suggested, you may need to fiddle with your compiler options, but be aware that this code will then not be portable to other operating systems or even to other compilers running on Windows. | Catching exception in code | [
"",
"c++",
"visual-studio-2008",
"exception",
"visual-c++",
"visual-c++-6",
""
] |
Is there a way in PHP to get a list of all sessions (and the variables within each) on the server?
Basically, we have a maintenance function which needs to know which users are currently logged into the site. We already store data for each user in a session variable, but I am hoping that I can loop through each of these sessions and pluck out the data I need.
MY PHP is very limited (I am a .Net developer ussually) but if anyone knows if this is even possible (and how to do it) I'd be very grateful. I googled this, and the results I found tended to inidcate that it WASN'T possible, but I find this very hard to accept.
Still, If you can't you can't but I thought my buddies on StackOverflow could give me a definitive answer! | PHP stores session data for each user in a temporary folder on the server. This folder is defined in the php.ini configuration file under the variable session.save\_path. Locate this value from within your php.ini file, or alternatively, create a php file with:
```
<?php echo "Session Save Path: " . ini_get( 'session.save_path');?>
```
as it's contents, and open the file in your browser.
Once you find the save path for the session data, open up that folder and you'll notice a fairly simple structure. All sessions are stored in the format: sess\_$SESSIONID .
Session data is serialized before being stored on disk. As such, objects stored in the session file would have to be deserialized before being usable. However, if you're using plain text, which is stored as-is, to store your session data (ex. `$_SESSION['userid'] = 1234`) to store information about your users, it should be easy enough to parse out the data you're looking for from within the files.
One more thing ... I haven't looked into it, but it appears as though the session ID that appears in the filename corresponds directly to, for instance, the name of the PHPSESSID cookie stored on the user's computer. So, with this in mind, it may be possible to loop through the files within the temporary session directory, acquire all the $SESSIONID values, set the current session ID using `session_id($SESSIONID)`, start a session with `session_start()` and access the data you need through PHP without having to parse the contents files themselves. Can anyone confirm whether or not this would be possible?
**Edit:** Adjusted post to match Itay's comment. | This will get you the data for all sessions, stored in an array and indexed by session id:
```
<?php
$allSessions = [];
$sessionNames = scandir(session_save_path());
foreach($sessionNames as $sessionName) {
$sessionName = str_replace("sess_","",$sessionName);
if(strpos($sessionName,".") === false) { //This skips temp files that aren't sessions
session_id($sessionName);
session_start();
$allSessions[$sessionName] = $_SESSION;
session_abort();
}
}
print_r($allSessions);
``` | Looping Through All a Server's Sessions in PHP | [
"",
"php",
"session",
""
] |
stupid question but this statement is worthless
```
int a;
if (a != null)
```
since an integer var is automatically set to null by the compiler when defined
to check integers always check if a >= 0 correct? | The compiler sets the value of a primitive variable to its "default" value if you don't assign it. The default value of int is 0. So yeah, the comparison you mention doesn't really do anything.
If you need a nullable int in your code you should use the "nullable" type "int?".
If your int is nullable, then the comparison you mention might be useful. | int is a class, not equal to null | Integer validation | [
"",
"c#",
"int",
""
] |
I'm aware of the "Enable just my code" debug option, but that only works for managed code.
I'm looking for a way to step into a function call without having to step through, for example, an STL string cast operator because there is an implicit conversion from a char\* to a string in one of the function's parameters. | I found this [blog entry](http://blogs.msdn.com/andypennell/archive/2004/02/06/69004.aspx) which has a solution. Although I'd prefer to be able to say "don't step into anything that isn't part of this project", this looks workable.
EDIT: After looking at a few blogs and newsgroups, the method is to add an entry for each function that you don't want to step into under this registry key (assuming VS 2005):
```
32 bit Windows
\\HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\8.0\NativeDE\StepOver
64 bit Windows
\\HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\8.0\NativeDE\StepOver
```
Version numbers for the path:
```
Visual Studio 2005: 8.0
Visual Studio 2008: 9.0
Visual Studio 2010: 10.0
Visual Studio 2012: 11.0
Visual Studio 2013: 12.0
```
This key contains a set of rules which affect how stepping is performed. Each rule is specified as a separate entry whose name is a decimal number and whose value is a function name pattern that specifies which functions we want to affect. e.g.
```
"10" = "boost\:\:scoped_ptr.*\:\:.*=NoStepInto"
```
prevents stepping into boost::scoped\_ptr functions.
The rules are evaluated from high to low values until a matching pattern is found, or there are no rules left. In that case the function is stepped into.
Function names are regular expressions.
Colons need to be quoted with a backslash.
You can specify StepInto as well as NoStepInto. This gives you a way to avoid stepping into all but a few functions in the same scope/namespace.
Restart Visual Studio to pick up the changes to the registry. | <https://learn.microsoft.com/en-us/visualstudio/debugger/just-my-code?view=vs-2019#BKMK_CPP_Customize_stepping_behavior>
In C++ projects, you can specify functions to step over by listing them as non-user code in \*.natstepfilter files. Functions listed in \*.natstepfilter files are not dependent on Just My Code settings.
* To specify non-user code for all local Visual Studio users, add the .natstepfilter file to the `%VsInstallDirectory%\Common7\Packages\Debugger\Visualizers` folder.
* To specify non-user code for an individual user, add the .natstepfilter file to the `%USERPROFILE%\My Documents\<Visual Studio version>\Visualizers` folder.
A .natstepfilter file is an XML file with this syntax:
```
<?xml version="1.0" encoding="utf-8"?>
<StepFilter xmlns="http://schemas.microsoft.com/vstudio/debugger/natstepfilter/2010">
<Function>
<Name>FunctionSpec</Name>
<Action>StepAction</Action>
</Function>
<Function>
<Name>FunctionSpec</Name>
<Module>ModuleSpec</Module>
<Action>StepAction</Action>
</Function>
</StepFilter>
```
| Element | Description |
| --- | --- |
| Function | Required. Specifies one or more functions as non-user functions. |
| Name | Required. An ECMA-262 formatted regular expression specifying the full function name to match. For example: `<Name>MyNS::MyClass.*</Name>` tells the debugger that all methods in MyNS::MyClass are to be considered non-user code. The match is case-sensitive. |
| Module | Optional. An ECMA-262 formatted regular expression specifying the full path to the module containing the function. The match is case-insensitive. |
| Action | Required. One of these case-sensitive values: `NoStepInto` - tells the debugger to step over the function. `StepInto` - tells the debugger to step into the function, overriding any other NoStepInto for the matched function. | | Is there a way to automatically avoiding stepping into certain functions in Visual Studio? | [
"",
"c++",
"visual-studio",
"debugging",
""
] |
Greetings,
I'm trying to validate whether my integer is null. If it is, I need to prompt the user to enter a value. My background is Perl, so my first attempt looks like this:
```
int startIn = Integer.parseInt (startField.getText());
if (startIn) {
JOptionPane.showMessageDialog(null,
"You must enter a number between 0-16.","Input Error",
JOptionPane.ERROR_MESSAGE);
}
```
This does not work, since Java is expecting boolean logic.
In Perl, I can use "exists" to check whether hash/array elements contain data with:
```
@items = ("one", "two", "three");
#@items = ();
if (exists($items[0])) {
print "Something in \@items.\n";
}
else {
print "Nothing in \@items!\n";
}
```
Is there a way to this in Java? Thank you for your help!
Jeremiah
P.S. Perl [exists](http://perldoc.perl.org/functions/exists.html) info. | `parseInt()` is just going to throw an exception if the parsing can't complete successfully. You can instead use `Integers`, the corresponding object type, which makes things a little bit cleaner. So you probably want something closer to:
```
Integer s = null;
try {
s = Integer.valueOf(startField.getText());
}
catch (NumberFormatException e) {
// ...
}
if (s != null) { ... }
```
*Beware* if you do decide to use `parseInt()`! `parseInt()` doesn't support good internationalization, so you have to jump through even more hoops:
```
try {
NumberFormat nf = NumberFormat.getIntegerInstance(locale);
nf.setParseIntegerOnly(true);
nf.setMaximumIntegerDigits(9); // Or whatever you'd like to max out at.
// Start parsing from the beginning.
ParsePosition p = new ParsePosition(0);
int val = format.parse(str, p).intValue();
if (p.getIndex() != str.length()) {
// There's some stuff after all the digits are done being processed.
}
// Work with the processed value here.
} catch (java.text.ParseFormatException exc) {
// Something blew up in the parsing.
}
``` | Try this:
```
Integer startIn = null;
try {
startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
.
.
.
}
if (startIn == null) {
// Prompt for value...
}
``` | How can I tell if a Java integer is null? | [
"",
"java",
"integer",
""
] |
Is there any site/analysis about what Java version most people are using on WWW ? It seems this data is not available on webserver logs (vs. Flash versions)
Can we safely set e.g. Java 1.4.2 as minimum requirement for our applet, or are there still many users using Java 1.1 (MS one) or Java 1.2-1.3 ?
It's still a bit of a complicated process to update Java if it's too old, e.g. admin rights are needed on Windows machine and it's bit difficult in some Linux distros too. | [This chart](http://www.riastats.com/#) might help.
From 1,471,010 browsers across 47 sites in the past 30 days...
* 6% had 1.4,
* 16% had 1.5
* 50% had 1.6
<http://weblogs.java.net/blog/editors/archives/2009/03/bedbugs_and_bal.html> is an article that talks about the chart. | You can modify Google analytics code to detect Java version, see [this script](http://cowwoc.blogspot.com/2008/12/tracking-java-versions-using-google.html).
Regarding Java versions prior to 1.4 there is little available data, I ran my own test in mid February, sampling almost 20,000 visitors who had Java:
```
Java Number
1.6 15516 79.5%
1.5 2161 11.1%
1.4 685 3.5%
1.3 36 0.2%
1.2 0 0.0%
1.1 1115 5.7%
Total 19513 100.0%
```
Following from this data I finally upped the requirements from 1.1 to 1.4, allowing Swing only a decade after it was released! | What Java versions are commonly installed on browsers, is it safe to assume 1.4? | [
"",
"java",
"applet",
"jvm",
"version",
""
] |
I find this excellent code, posted by [aemkei](https://stackoverflow.com/users/28150/aemkei) as answers to this questions:
1. [How do you dynamically load a javascript file? (Think C’s #include)](https://stackoverflow.com/questions/21294/how-do-you-dynamically-load-a-javascript-file-think-cs-include)
2. [Use javascript to inject script references as needed?](https://stackoverflow.com/questions/203113/use-javascript-to-inject-script-references-as-needed)
> You may write dynamic script tags
> (using Prototype):
>
> ```
> new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
> ```
>
> The problem here is that we do not
> know when the external script file is
> fully loaded.
>
> We often want our dependant code on
> the very next line and like to write
> something like:
>
> ```
> if (iNeedSomeMore){
> Script.load("myBigCodeLibrary.js"); // includes code for myFancyMethod();
> myFancyMethod(); // cool, no need for callbacks!
> }
> ```
>
> There is a smart way to inject script
> dependencies without the need of
> callbacks. You simply have to pull the
> script via a synchronous AJAX request
> and eval the script on global level.
>
> If you use Prototype the Script.load
> method looks like this:
>
> ```
> var Script = {
> _loadedScripts: [],
> include: function(script){
> // include script only once
> if (this._loadedScripts.include(script)){
> return false;
> }
> // request file synchronous
> var code = new Ajax.Request(script, {
> asynchronous: false, method: "GET",
> evalJS: false, evalJSON: false
> }).transport.responseText;
> // eval code on global level
> if (Prototype.Browser.IE) {
> window.execScript(code);
> } else if (Prototype.Browser.WebKit){
> $$("head").first().insert(Object.extend(
> new Element("script", {type: "text/javascript"}), {text: code}
> ));
> } else {
> window.eval(code);
> }
> // remember included script
> this._loadedScripts.push(script);
> }
> };
> ```
I found that, the code does not work on IE if the all of them is executed in 'file://' protocol, however, it is not the problem since its use case involved real web application.
I tried it once to include **<http://www.google-analytics.com/urchin.js>** by google, but from one of web page, but it looks like it cannot request javascript file from different domain.
How we could dynamically add javascript, just like what above scripts does, but from another domain? | The security model in modern browsers prevents JavaScript from making cross-domain requests. That has holes (see every website exploit since the beginning of the internet), but using them is more than a little shady and it's only a matter of time before they're patched. | You can use the `onload` and `onreadystatechange` event to understand when the `<script>` tag is loaded.
```
var script = new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});
script.onload = script.onreadystatechange = function(){
if (!this.readyState ||
this.readyState == "loaded" || this.readyState == "complete") {
//script is loaded
}
};
``` | How do you dynamically load a javascript file from different domain? | [
"",
"javascript",
""
] |
Here is what I'm suppose to accomplish:
> Write a program that stimulates a
> [bean machine](http://en.wikipedia.org/wiki/Bean_machine) Your program should
> prompt the user to enter the number of
> balls and the number of slots in the
> machine. Simulate the falling of each
> ball by printing its path.
>
> EX.
>
> Enter the number of balls: 5
>
> Enter the number of slots: 7
>
> LRLRLRL
> RRLRLLL
> LLRRLLR
>
> LRLLRLR
> RRRLRRL
> \_ \_ 0
>
> \_ \_ 0
> 0 0 0
Here is my code so far:
```
import javax.swing.JOptionPane;
public static void main(String[] args) {
int balls=0;
int slots=0;
char [] direction= new char [slots];
int slot=0;
int i=0;
int path=0;
balls= Integer.parseInt(JOptionPane.showInputDialog("Enter" +
" the number of balls to be dropped:"));
slots= Integer.parseInt (JOptionPane.showInputDialog("Enter " +
"the number of slots:"));
for (int j=1;j<=balls;j++){
while(i<slots){
path= (int)(Math.random()*100);
if (path <50){
direction [slots]='L';
}
else{
direction [slots]='R';
}
i++;
slot++;
}
System.out.println("The pathway is" +direction[0]+direction[1]+direction[2]+direction[3]+direction[4]);
}
}
```
There are a few things that I'm having problems with:
1. In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?
2. How can I print the number 'balls' that the user entered in the pattern as shown above?
3. Are there any other problems with my code? | Well, for starters, I'm getting a consistent `ArrayIndexOutOfBoundsException` on the line `direction[slots] = 'L';` (or `'R'`). That's because `direction` is always of length 0, since you initialized it to `slots` when `slots` was 0. Move the line
```
char [] direction= new char [slots];
```
to after `slots` is input.
Next, you always assign the 'L' or 'R' to the position immediately after the end of the array. That's another reason for the `ArrayIndexOutOfBoundsException` I was getting. Change the assignment to
```
direction[i] = 'L'; // or 'R'
```
Next, you don't reset `i` after the `while` loop. So the path is calculated only for the first ball and then reused for all the others. I would make it a `for` loop instead, like this:
```
for (i = 0; i < slots; i++) {
// your code here (make sure you don't change i inside the loop)
}
```
Finally, as others have said, you should be using a loop to print out the path. You know how long the `direction` array is (it's `direction.length`, if you didn't know), so you can just loop through it and print out each letter.
Once you've made these changes, your program should work (**edit:** except that it doesn't keep track of which slot each ball ends up in). It will still have some room for improvement, but finding those things is part of the fun--isn't it? | > In the last line of my code where I try to print the pathway I have to basically guess the number of slots the user selected. Is there a better way to print this?
Use a for loop, and `System.out.print()` so you don't get a new line after each step.
> How can I print the number 'balls' that the user entered in the pattern as shown above?
For each slot, you need to record the number of balls which ended up in that slot, and the maximum for any slot. Given these two values, you can loop over each slot, and print '\_' or '0' the appropriate number of times with a nested loop.
> Are there any other problems with my code?
You only appear to be printing the path of the last ball dropped, rather than each ball, but that might just be your indentation being squiffy. Post properly formatted, complete code.
The example output you have seems to be reading input from the console, not using swing.
You're declaring variables too early. It's better to declared variables on first use, and if they don't change mark them `final`. If you had:
```
final int slots= Integer.parseInt (...
```
instead of
```
int slots = 0;
...
slots= Integer.parseInt (...
```
then at least one of your bugs would be caught by the compiler. | Java bean machine | [
"",
"java",
"arrays",
""
] |
What's the difference between tuples/lists and what are their advantages/disadvantages? | Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. **Tuples have structure, lists have order.**
Using this distinction makes code more explicit and understandable.
One example would be pairs of page and line number to reference locations in a book, e.g.:
```
my_location = (42, 11) # page number, line number
```
You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.
There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.
There are some interesting articles on this issue, e.g. ["Python Tuples are Not Just Constant Lists"](http://jtauber.com/blog/2006/04/15/python_tuples_are_not_just_constant_lists/) or ["Understanding tuples vs. lists in Python"](http://news.e-scribe.com/397). The official Python documentation [also mentions this](http://docs.python.org/2/tutorial/datastructures.html#tuples-and-sequences)
> "Tuples are immutable, and usually contain an heterogeneous sequence ...".
In a statically typed language like *Haskell* the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.
Finally there is the [namedtuple](http://docs.python.org/dev/library/collections.html#collections.namedtuple) in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances. | Difference between list and tuple
1. **Literal**
```
someTuple = (1,2)
someList = [1,2]
```
2. **Size**
```
a = tuple(range(1000))
b = list(range(1000))
a.__sizeof__() # 8024
b.__sizeof__() # 9088
```
Due to the smaller size of a tuple operation, it becomes a bit faster, but not that much to mention about until you have a huge number of elements.
3. **Permitted operations**
```
b = [1,2]
b[0] = 3 # [3, 2]
a = (1,2)
a[0] = 3 # Error
```
That also means that you can't delete an element or sort a tuple.
However, you could add a new element to both list and tuple with the only difference that since the tuple is immutable, you are not *really* adding an element but you are creating a new tuple, so the id of will change
```
a = (1,2)
b = [1,2]
id(a) # 140230916716520
id(b) # 748527696
a += (3,) # (1, 2, 3)
b += [3] # [1, 2, 3]
id(a) # 140230916878160
id(b) # 748527696
```
4. **Usage**
As a list is mutable, it can't be used as a key in a dictionary, whereas a tuple can be used.
```
a = (1,2)
b = [1,2]
c = {a: 1} # OK
c = {b: 1} # Error
``` | What's the difference between lists and tuples? | [
"",
"python",
"list",
"tuples",
""
] |
Asp.net has turned out to be alot easier to use than PHP (so far). However, I have been searching for a while and simply cannot figure this out. How do I get the variables that are contained in the url of my page (that originate from a form that had the method "GET") and utilize them?
For example, my page would be www.example.com/index.asp?somevariable=something
How would I get the value of somevariable? | You can use what ybo stated, but it isn't complete (for VB at least). That alone could leave to a null reference exception being thrown. You want to cast (i.e. TryParse) the values, and handle any empty parameters that your expected to contain a value:
```
Dim itemId As Integer
Dim itemType as String
If Not Integer.TryParse(Request.QueryString("i").ToString, itemId) Then
itemId = -1 ' Or whatever your default value is
Else
' Else not required. Variable itemId contains the value when Integer.TryParse returns True.
End If
itemType = Request.QueryString("t").ToString ' <-- ToString important here!
``` | It's as easy as :
```
Request.QueryString["somevariable"]; // C#
Request.QueryString("somevariable") ' VB
``` | How do I access the variables from urls that come from the GET method in ASP.net? | [
"",
"c#",
"asp.net",
"vb.net",
"query-string",
""
] |
We have 2 objects A & B: A is system.string and B is some .net primitive type (string,int etc). we want to write generic code to assign the converted (parsed) value of B into A. Any suggestions? Thanks, Adi Barda | The most pragmatic and versatile way to do string conversions is with `TypeConverter`:
```
public static T Parse<T>(string value)
{
// or ConvertFromInvariantString if you are doing serialization
return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
```
More types have type-converters than implement `IConvertible` etc, and you can also add converters to new types - both at compile-time;
```
[TypeConverter(typeof(MyCustomConverter))]
class Foo {...}
class MyCustomConverter : TypeConverter {
// override ConvertFrom/ConvertTo
}
```
and also at runtime if you need (for types you don't own):
```
TypeDescriptor.AddAttributes(typeof(Bar),
new TypeConverterAttribute(typeof(MyCustomConverter)));
``` | As already mentioned, System.Convert and IConvertible would be the first bet. If for some reason you cannot use those (for instance, if the default system conversions for the built in types is not adequate for you), one approach is to create a dictionary that holds delegates to each conversion, and make a lookup in that to find the correct conversion when needed.
For instance; when you want to convert from String to type X you could have the following:
```
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(SimpleConvert.To<double>("5.6"));
Console.WriteLine(SimpleConvert.To<decimal>("42"));
}
}
public static class SimpleConvert
{
public static T To<T>(string value)
{
Type target = typeof (T);
if (dicConversions.ContainsKey(target))
return (T) dicConversions[target](value);
throw new NotSupportedException("The specified type is not supported");
}
private static readonly Dictionary<Type, Func<string, object>> dicConversions = new Dictionary <Type, Func<string, object>> {
{ typeof (Decimal), v => Convert.ToDecimal(v) },
{ typeof (double), v => Convert.ToDouble( v) } };
}
```
Obviously, you would probably want to do something more interesting in your custom conversion routines, but it demonstrates the point. | C# dynamic type conversions | [
"",
"c#",
""
] |
What is the best (and fastest) way to retrieve a random row using Linq to SQL when I have a condition, e.g. some field must be true? | You can do this at the database, by using a fake UDF; in a partial class, add a method to the data context:
```
partial class MyDataContext {
[Function(Name="NEWID", IsComposable=true)]
public Guid Random()
{ // to prove not used by our C# code...
throw new NotImplementedException();
}
}
```
Then just `order by ctx.Random()`; this will do a random ordering at the SQL-Server courtesy of `NEWID()`. i.e.
```
var cust = (from row in ctx.Customers
where row.IsActive // your filter
orderby ctx.Random()
select row).FirstOrDefault();
```
Note that this is only suitable for small-to-mid-size tables; for huge tables, it will have a performance impact at the server, and it will be more efficient to find the number of rows (`Count`), then pick one at random (`Skip/First`).
---
for count approach:
```
var qry = from row in ctx.Customers
where row.IsActive
select row;
int count = qry.Count(); // 1st round-trip
int index = new Random().Next(count);
Customer cust = qry.Skip(index).FirstOrDefault(); // 2nd round-trip
``` | Another sample for Entity Framework:
```
var customers = db.Customers
.Where(c => c.IsActive)
.OrderBy(c => Guid.NewGuid())
.FirstOrDefault();
```
This does not work with LINQ to SQL. The `OrderBy` is simply being dropped. | Random row from Linq to Sql | [
"",
"c#",
".net",
"linq-to-sql",
""
] |
I have a parent table with entries for documents and I have a history table which logs an audit entry every time a user accesses one of the documents.
I'm writing a search query to return a list of documents (filtered by various criteria) with the latest user id to access each document returned in the result set.
Thus for
```
DOCUMENTS
ID | NAME
1 | Document 1
2 | Document 2
3 | Document 3
4 | Document 4
5 | Document 5
HISTORY
DOC_ID | USER_ID | TIMESTAMP
1 | 12345 | TODAY
1 | 11111 | IN THE PAST
1 | 11111 | IN THE PAST
1 | 12345 | IN THE PAST
2 | 11111 | TODAY
2 | 12345 | IN THE PAST
3 | 12345 | IN THE PAST
```
I'd be looking to get a return from my search like
```
ID | NAME | LAST_USER_ID
1 | Document 1 | 12345
2 | Document 2 | 11111
3 | Document 3 | 12345
4 | Document 4 |
5 | Document 5 |
```
Can I easily do this with one SQL query and a join between the two tables? | Revising what Andy White produced, and replacing square brackets (MS SQL Server notation) with DB2 (and ISO standard SQL) "delimited identifiers":
```
SELECT d.id, d.name, h.last_user_id
FROM Documents d LEFT JOIN
(SELECT r.doc_id AS id, user_id AS last_user_id
FROM History r JOIN
(SELECT doc_id, MAX("timestamp") AS "timestamp"
FROM History
GROUP BY doc_id
) AS l
ON r."timestamp" = l."timestamp"
AND r.doc_id = l.doc_id
) AS h
ON d.id = h.id
```
I'm not absolutely sure whether "timestamp" or "TIMESTAMP" is correct - probably the latter.
The advantage of this is that it replaces the inner correlated sub-query in Andy's version with a simpler non-correlated sub-query, which has the potential to be (radically?) more efficient. | I couldn't get the "HAVING MAX(TIMESTAMP)" to run in SQL Server - I guess having requires a boolean expression like "having max(TIMESTAMP) > 2009-03-05" or something, which doesn't apply in this case. (I might be doing something wrong...)
Here is something that seems to work - note the join has 2 conditions (not sure if this is good or not):
```
select
d.ID,
d.NAME,
h."USER_ID" as "LAST_USER_ID"
from Documents d
left join History h
on d.ID = h.DOC_ID
and h."TIMESTAMP" =
(
select max("TIMESTAMP")
from "HISTORY"
where "DOC_ID" = d.ID
)
``` | Subquery to return the latest entry for each parent ID | [
"",
"sql",
"db2",
""
] |
I searched if JavaScript offers a mean to define symbolic constants, but didn't find anything. Did I miss something ?
Is it a common practices to use const var instead ?
```
var const MAXIMUM_VALUE = 100;
```
Thanx. | `const` is not supported by IE, so if you want to support IE that is out of the question.
As far as I know, and the best way of doing this to keep it simple is to just have a naming convention for your constants like the ever-popular ALL UPPERCASE. There are some examples out there to force constants but they are not worth it for the most part. Alternatively, you could use a function:
```
function myConst() { return 'myValue'; }
```
This can of course still be overridden but I've seen it used.
Also see:
> * [Are there constants in Javascript?](https://stackoverflow.com/questions/130396/are-there-constants-in-javascript)
> * [Is it possible to simulate constants in Javascript using closures?](https://stackoverflow.com/questions/622906/is-it-possible-to-simulate-constants-in-javascript-using-closures)
> * [Javascript: final / immutable global variables?](https://stackoverflow.com/questions/664829/javascript-final-immutable-global-variables) | Yes. But you remove the var. const replaces var.
```
const MAXIMUM_VALUE = 100;
``` | Is there a way to define symbolic constants in Javascript? | [
"",
"javascript",
"constants",
""
] |
I added a system property in my run.conf of my JBOSS like this:
```
JAVA_OPTS="$JAVA_OPTS -Dfoo=bar"
```
Now my question is, if there is a way to resolve this property in a web.xml file in a way something like this:
```
...
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext-common.xml
classpath:conf/${foo}/applicationContext-local.xml
</param-value>
</context-param>
...
``` | I don't know any possibility. But in my opinion this should be implemented in the application. Why you wanna increase the indirection? Normaly you access the contents of the web.xml from within you application ( app > web.xml). Why do this: app > web.xml > environment variable? | You have to set *spec-descriptor-property-replacement* in standalone.xml to **true**
```
<subsystem xmlns="urn:jboss:domain:ee:1.2">
<spec-descriptor-property-replacement>true</spec-descriptor-property-replacement>
<jboss-descriptor-property-replacement>true</jboss-descriptor-property-replacement>
</subsystem>
``` | Is there a way to resolve system properties in a web.xml file? | [
"",
"java",
"servlets",
"jboss",
"web.xml",
""
] |
We're planning on setting up a website for student group - most of the content is fairly static but certain portions such as events and members would turn up from the database. I've never worked with PHP much, and was wondering would a CMS system like Drupal or PHP Nuke be appropriate for this kinda work?
Is there anything else that would allow me to go about creating a template and then reusing it across the website? | [Drupal](http://drupal.org/) would be a very good choice for this. It has its learning curve, - anything you choose will. But eventually the light bulb will go off and you'll see how logically its organized and how flexible it is to extend.
And there are vast resources available to help you get up to speed quick. Tutorials and videos touching all angles of how Drupal works. And then there are uncountable quantity of themes, hundreds of add-on modules of every kind.
With a handful of additional modules added to the core distribution (cck certainly, maybe views and taxonomy too) you can configure basically everything and not ever touch a line of PHP code.
It is *extremely* simple to install and get started with. I have both Drupal 5 and 6 running under xampplite on a lil MSI netbook! .. Downoad and be up and running in under 15 mins. | You can try out all of the CMS available @ <http://php.opensourcecms.com>.
I've never used PHP Nuke before, but Drupal can easily do the job.
Check out the [Calendar module](http://drupal.org/project/calendar) in Drupal for the event function. | PHP Newbie question - CMS / Templating | [
"",
"php",
"templates",
"content-management-system",
""
] |
I'm sending xml to another program, which expects boolean flags as "yes" or "no", rather than "true" or "false".
I have a class defined like:
```
[XmlRoot()]
public class Foo {
public bool Bar { get; set; }
}
```
When I serialize it, my output looks like this:
```
<Foo><Bar>true</Bar></Foo>
```
But I would like it to be this:
```
<Foo><Bar>yes</Bar></Foo>
```
Can I do this at the time of serialization? I would prefer not to have to resort to this:
```
[XmlRoot()]
public class Foo {
[XmlIgnore()]
public bool Bar { get; set; }
[XmlElement("Bar")]
public string BarXml { get { return (Bar) ? "yes" : "no"; } }
}
```
Note that I also want to be able to *deserialize* this data back again. | Ok, I've been looking into this some more. Here's what I've come up with:
```
// use this instead of a bool, and it will serialize to "yes" or "no"
// minimal example, not very robust
public struct YesNo : IXmlSerializable {
// we're just wrapping a bool
private bool Value;
// allow implicit casts to/from bool
public static implicit operator bool(YesNo yn) {
return yn.Value;
}
public static implicit operator YesNo(bool b) {
return new YesNo() {Value = b};
}
// implement IXmlSerializable
public XmlSchema GetSchema() { return null; }
public void ReadXml(XmlReader reader) {
Value = (reader.ReadElementContentAsString() == "yes");
}
public void WriteXml(XmlWriter writer) {
writer.WriteString((Value) ? "yes" : "no");
}
}
```
Then I change my Foo class to this:
```
[XmlRoot()]
public class Foo {
public YesNo Bar { get; set; }
}
```
Note that because `YesNo` is implicitly castable to `bool` (and vice versa), you can still do this:
```
Foo foo = new Foo() { Bar = true; };
if ( foo.Bar ) {
// ... etc
```
In other words, you can treat it like a bool.
And w00t! It serializes to this:
```
<Foo><Bar>yes</Bar></Foo>
```
It also deserializes correctly.
There is probably some way to get my XmlSerializer to automatically cast any `bool`s it encounters to `YesNo`s as it goes - but I haven't found it yet. Anyone? | Very simple. Use a surrogate property. Apply XmlIgnore on the actual property. The surrogate is a string, and must use the XmlElement attribute that takes a element-name override. Specify the name of the *actual property* in the override. The surrogate property serializes differently based on the value of the actual property. You must also provide a setter for the Surrogate, and the setter should set the actual property appropriately, for whatever value it serialized. In other words it needs to go both ways.
Snip:
```
public class SomeType
{
[XmlElement]
public int IntValue;
[XmlIgnore]
public bool Value;
[XmlElement("Value")]
public string Value_Surrogate {
get { return (Value)? "Yes, definitely!":"Absolutely NOT!"; }
set { Value= (value=="Yes, definitely!"); }
}
}
```
click here for [full compilable source example](http://cheeso.members.winisp.net/srcview.aspx?dir=xml-serialization&file=Surrogate.cs). | How can I get XmlSerializer to encode bools as yes/no? | [
"",
"c#",
"xml-serialization",
"boolean",
""
] |
Is there any Open Source Code availbale for makeing A SIP Dialer in C# or any other language | Yes, take a look at [PJSIP](http://www.pjsip.org/). It is implemented in very portable C. But it also has a number of wrappers in other languages, like this [.NET wrapper](http://sipekphone.googlepages.com/pjsipwrapper).
PJSIP, or rather its UA (SIP Dialer) interface PJSUA is very easy to handle, and takes care of both signalling and media for you. Oh, and it's under GPL license. | PjSIP and Sofiasip are two top SIP communication libraries to develop dialers of your choice, however there are already many dialers already developed.
Please check following [list](http://trac.pjsip.org/repos/wiki/Projects_Using_PJSIP) of dialers developed over PJSIP sip stack, may someone from list fulfill all of your requirements. | Open Source SIP Dialer in C# | [
"",
"c#",
"sip",
""
] |
If I have a button that sets off a jquery script is there a way to make sure the button is inactive until the script completes? | Somewhere at the beginning of your script (probably on the button's click event), set the button's disabled attribute to true:
```
$("#mybutton").attr("disabled", true);
```
Then, when complete, remove that attribute:
```
$("#mybutton").removeAttr("disabled");
```
EDIT:
If you want to get (slightly) fancy, change the text of the button while you're doing the work. If it's an image button, you can change the src to a friendly "please wait" message. Here's an example of the button text version:
```
$("#mybutton").click(function() {
var origVal = $(this).attr("value");
$(this).attr("value", "Please wait...");
$(this).attr("disabled", true);
//Do your processing.
$(this).removeAttr("disabled");
$(this).attr("value", origVal);
});
``` | This is one area where I like to extend jQuery:
```
$.fn.disable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = true;
});
}
$.fn.enable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") this.disabled = false;
});
}
```
and then you can do:
```
$("#button").disable();
$("#button").enable();
```
I find myself disabling/enabling controls a lot. | JQuery Script Load Timing | [
"",
"javascript",
"jquery",
""
] |
Why is the following seen as better than the old way of casting?
`MyObj obj = someService.find(MyObj.class, "someId");`
vs.
`MyObj obj = (MyObj) someService.find("someId");` | Another advantage to using an explicit type parameter would be to allow the service method to be implemented using a `Proxy` (in this case `MyObj` would need to be `MyInterface`). Without explicit type parameters, this would not be possible.
You might use a `Proxy` under the covers for many reasons (testing for one) | There's no guarantee that the non-generics version will return an object of type 'MyObj', so you might get a ClassCastException. | Java generics | [
"",
"java",
"generics",
""
] |
I am writing a little library with some prime number related methods. As I've done the groundwork (aka working methods) and now I'm looking for some optimization.
Ofcourse the internet is an excellent place to do so. I've, however, stumbled upon a rounding problem and I was wondering how to solve this.
In the loop I use to test a number for it's primality it's more efficient to search until sqrt(n) instead of n/2 or even n - 1. But due to rounding problems some number get skipped and thus some primes are skipped! For example, the 10000th prime should be: 104729, but the 'optimized' version ends up with: 103811.
Some code (it's open for more optimization, I know, but I can handle only one thing at a time):
```
/// <summary>
/// Method for testing the primality of a number e.g.: return IsPrime(29);
/// History:
/// 1. Initial version, most basic form of testing: m smaller then n -1
/// 2. Implemented m smaller then sqrt(n), optimization due to prime factoring
/// </summary>
/// <param name="test">Number to be tested on primality</param>
/// <returns>True if the number is prime, false otherwise</returns>
public static bool IsPrime(int test)
{
// 0 and 1 are not prime numbers
if (test == 0 || test == 1) return false;
// 2 and 3 are prime numbers
if (test == 2) return true;
// all even numbers, save 2, are not prime
if (test % 2 == 0) return false;
double squared = Math.Sqrt(test);
int flooredAndSquared = Convert.ToInt32(Math.Floor(squared));
// start with 5, make increments of 2, even numbers do not need to be tested
for (int idx = 3; idx < flooredAndSquared; idx++)
{
if (test % idx == 0)
{
return false;
}
}
return true;
}
```
I know the squared part fails me (or I fail), tried Math.Ceiling as well, with about the same results. | Sadly, I haven't tried the algorithmic approaches before. But if you want to implement your approach efficiently, I'd suggest doing some caching. Create an array to store all prime numbers less than a defined threshold, fill this array, and search within/using it.
In the following example, finding whether a number is prime is O(1) in the best case (namely, when the number is less than or equal to `maxPrime`, which is 821,461 for a 64K buffer), and is somewhat optimized for other cases (by checking mod over only 64K numbers out of the first 820,000 -- about 8%).
(Note: Don't take this answer as the "optimal" approach. It's more of an example on how to optimize your implementation.)
```
public static class PrimeChecker
{
private const int BufferSize = 64 * 1024; // 64K * sizeof(int) == 256 KB
private static int[] primes;
public static int MaxPrime { get; private set; }
public static bool IsPrime(int value)
{
if (value <= MaxPrime)
{
return Array.BinarySearch(primes, value) >= 0;
}
else
{
return IsPrime(value, primes.Length) && IsLargerPrime(value);
}
}
static PrimeChecker()
{
primes = new int[BufferSize];
primes[0] = 2;
for (int i = 1, x = 3; i < primes.Length; x += 2)
{
if (IsPrime(x, i))
primes[i++] = x;
}
MaxPrime = primes[primes.Length - 1];
}
private static bool IsPrime(int value, int primesLength)
{
for (int i = 0; i < primesLength; ++i)
{
if (value % primes[i] == 0)
return false;
}
return true;
}
private static bool IsLargerPrime(int value)
{
int max = (int)Math.Sqrt(value);
for (int i = MaxPrime + 2; i <= max; i += 2)
{
if (value % i == 0)
return false;
}
return true;
}
}
``` | I guess this is your problem:
```
for (int idx = 3; idx < flooredAndSquared; idx++)
```
This should be
```
for (int idx = 3; idx <= flooredAndSquared; idx++)
```
so you don't get square numbers as primes. Also, you can use "idx += 2" instead of "idx++" because you only have to test odd numbers (as you wrote in the comment directly above...). | How can I test for primality? | [
"",
"c#",
"math",
"primes",
""
] |
Lets say I have a table describing cars with make, model, year and some other columns.
From that, I would like to get one full row of each make and model for latest year.
Or to put it in another way. Each row would have unique combination of make and model with other data from corresponding row with largest value of year.
Standard SQL solution would be great. | ```
select t1.make, t1.model, t1.year, t1.other_cols
from table t1
where year = (select max(year) from table t2
where t2.make = t1.make
and t2.model = t1.model
);
``` | MySQL solution:
```
SELECT * FROM cars GROUP NY CONCAT(make, "-", model) ORDER BY year DESC;
``` | Group by like row filtering | [
"",
"sql",
"group-by",
""
] |
As discussed in [Does the order of fields in C# matter?](https://stackoverflow.com/questions/431203/does-the-order-of-fields-in-c-matter), the order of serializable properties affects, among other things, XmlSerializer output.
But if fields are in 2 files (using partial classes), does anyone know what in fact controls the resulting order? That is, which file's properties comes first?
(Background: I ask this because I've run into a scenario where one of the 2 files is auto-generated from xsd, and the other is manually edited. The test output is different on developer boxes vs. our scripted build box. Presumably this is a side effect of the several differences in the timing and history of the xsd->C# step in the 2 environments. Various ways to fix, but I'd like to understand the compilation process a little better if possible.) | Nothing is guaranteed per C# spec. | I've found that using the 'easy' approach to making an object by marking it [Serializable] is usually only good enough for very simple implementations.
I would recommend that you implement the IXmlSerializable interface which is pretty easy to do and gives you all the control you need. | What controls XML serialization order of C# partial classes? | [
"",
"c#",
"sorting",
"xsd",
"xml-serialization",
"partial-classes",
""
] |
Is there a way to test compile-time errors, but without actually generating the error? For example, if I create a class which is non-copyable, I'd like to test the fact that trying to copy it will generate a compiler error, but I'd still like to execute the other runtime tests.
```
struct Foo {
int value_;
Foo(int value) : value_(value) {}
private:
Foo(const Foo&);
const Foo& operator=(const Foo&);
};
int main()
{
Foo f(12);
assert(f.value_ == 12);
assert(IS_COMPILER_ERROR(Foo copy(f);));
} // Would like this to compile and run fine.
```
I guess this can't be done as simply as that, but is there an idiomatic way to do this, or should I roll my own solution (maybe using scripts compiling separate tests files and testing the results?)?
N.B.: I took non-copyable only to illustrate my point, so I'm not interested in answers about using boost::noncopyable and such. | You can do it using make. Each test will be a code snippet. Here's a working example with 2 tests for VC++. (I've used 2 batch files for pass test and fail test). I'm using GNU make here.
Makefile:
```
FAILTEST = .\failtest.bat
PASSTEST = .\passtest.bat
tests: must_fail_but_passes \
must_pass_but_fails
must_fail_but_passes:
@$(FAILTEST) $@.cpp
must_pass_but_fails:
@$(PASSTEST) $@.cpp
```
must\_pass\_but\_fails.cpp
```
struct Foo {
int value_;
Foo(void) : value_(0) {}
private:
Foo(const Foo&);
const Foo& operator=(const Foo&);
};
```
int main()
{
Foo f(12);
return 0;
}
must\_fail\_but\_passes.cpp
```
struct Foo {
int value_;
Foo(int value) : value_(value) {}
private:
Foo(const Foo&);
const Foo& operator=(const Foo&);
};
```
int main()
{
Foo f(12);
return 0;
}
passtest.bat
```
@echo off
cl /nologo %1 >NUL
if %errorlevel% == 0 goto pass
@echo %1 FAILED
:pass
```
failtest.bat
```
@echo off
cl /nologo %1 >NUL
if not %errorlevel% == 0 goto pass
@echo %1 FAILED
:pass
```
Note that cl.exe (i.e. Visual Studio compiler) need to be in your path for this to "just work"
Have fun!
P.S. I doubt that this would make me famous though :-) | BTW the only build system I know that allows such test out-of-the-box is Boost.Build:
Check here" <http://beta.boost.org/boost-build2/doc/html/bbv2/builtins/testing.html>
For example,
```
# in your Jamfile
compile-fail crappy.cpp ;
```
.
```
int main()
{
my crappy cpp file
}
```
For more examples just `grep -R compile-fail` in your `BOOST_TOP_DIR\libs` directory. | Unit test that a class is non copyable, and other compile-time properties | [
"",
"c++",
"unit-testing",
"compiler-errors",
""
] |
Why can't I set the BackColor of a Label to Transparent? I have done it before, but now it just don't want to...
I created a new UserControl, added a progressbar and a label to it. When I set the BackColor of the label to transparent it is still gray =/ Why is this?
What I wanted was to have the label on top of the progressbar so that its text was "in" the progressbar... | WinForms doesn't really support transparent controls, but you can make a transparent control yourself. [See my answer here](https://stackoverflow.com/questions/373913/setting-the-parent-of-a-usercontrol-prevents-it-from-being-transparent/373961#373961).
In your case you should probably subclass the progress bar and override the OnPaint method to draw a text on the progress bar. | Add a new class to your project and post the code shown below. Build. Drop the new control from the top of the toolbox onto your form.
```
using System;
using System.Windows.Forms;
public class TransparentLabel : Label {
public TransparentLabel() {
this.SetStyle(ControlStyles.Opaque, true);
this.SetStyle(ControlStyles.OptimizedDoubleBuffer, false);
}
protected override CreateParams CreateParams {
get {
CreateParams parms = base.CreateParams;
parms.ExStyle |= 0x20; // Turn on WS_EX_TRANSPARENT
return parms;
}
}
}
``` | Reasons for why a WinForms label does not want to be transparent? | [
"",
"c#",
"winforms",
"transparency",
""
] |
So I have a .NET app which goes thru and generates a series of files, outputs them to a local directory and then determines if it needs to update an existing file or add a new file into a TFS (Team Foundation Server) project.
I have a single workspace on my local machine and there are 10 different working folders that are other coding projects I have worked on from this particular machine. My problem happens when I go to check if the file already exists in the TFS project and an update is required or if needs to be added to the project as a new file.
snipet:
```
static string TFSProject = @"$/SQLScripts/";
static WorkspaceInfo wsInfo;
static VersionControlServer versionControl;
static string argPath = "E:\\SQLScripts\\";
wsInfo = Workstation.Current.GetLocalWorkspaceInfo(argPath);
TeamFoundationServer tfs = new TeamFoundationServer(wsInfo.ServerUri.AbsoluteUri);
versionControl = (VersionControlServer)tfs.GetService(typeof(VersionControlServer));
Workspace workspace = versionControl.GetWorkspace(wsInfo);
workspace.GetLocalItemForServerItem(TFSProject);
```
At this point I check if the file exists and I do one of two things. if the file exists, then I mark the file for EDIT and then I writeout the file to the local directory, otherwise I will script the file first and then ADD the file to the workspace. I dont care if the physical file is identical to the one I am generating as I am doing this as a SAS70 requirement to 'track changes'
If it exists I do:
workspace.PendEdit(filename,RecurisionType.Full);
scriptoutthefile(filename);
or if it doesn't exist
scriptoutthefilename(filename);
workspace.PendAdd(filename,true);
Ok, all of that to get to the problem. When I go to check on pending changes against the PROJECT I get all the pending changes for all of the projects I have on my local machine in the workspace.
```
// Show our pending changes.
PendingChange[] pendingChanges = workspace.GetPendingChanges();
foreach (PendingChange pendingChange in pendingChanges)
{
dosomething...
}
```
I thought that by setting the workspace to workspace.GetLocalItemForServerItem(TFSProject) that it would give me ONLY the objects for that particular working folder.
If there any way to force the workspace object to only deal with a particular working folder?
Did that make any sense? Thanks in advance... | Ok, so it turned out that I had a corrupted TFS workspace cache on my machine.
Here was the solution (from a command prompt):
```
SET AppDataTF=%USERPROFILE%\Local Settings\Application Data\Microsoft\Team Foundation
SET AppDataVS=%APPDATA%\Microsoft\VisualStudio
IF EXIST "%AppDataTF%\1.0\Cache" rd /s /q "%AppDataTF%\1.0\Cache" > NUL
IF EXIST "%AppDataTF%\2.0\Cache" rd /s /q "%AppDataTF%\2.0\Cache" > NUL
IF EXIST "%AppDataVS%\8.0\Team Explorer" rd /s /q "%AppDataVS%\8.0\Team Explorer" > NUL
IF EXIST "%AppDataVS%\9.0\Team Explorer" rd /s /q "%AppDataVS%\9.0\Team Explorer" > NUL
```
The other part of the issue is that by having the project folder in the same workspace, it WILL pull in all pending changes from other projects. I created a secondary workspace with only the SQLScripts project and local folder and everything works like a charm.
Maybe someone else will find this useful... | using LINQ you can get the pending changes of particular folder
```
PendingChange[] pendingChanges = workspace
.GetPendingChanges()
.Where(x => x.LocalOrServerFolder.Contains(argPath))
.ToArray();
``` | Programatically checking files into TFS getting more than expected | [
"",
"c#",
"api",
"tfs",
"checkin",
"working-directory",
""
] |
I need to download emails from the gmail inbox only using poplib.Unfortunately I do not see any option to select Inbox alone, and poplib gives me emails from sent items too.
How do I select emails only from inbox?
I dont want to use any gmail specific libraries. | POP3 has no concept of 'folders'. If gmail is showing you both 'sent' as well as 'received' mail, then you really don't have any option but to receive all that email.
Perhaps you would be better off using IMAP4 instead of POP3. Python has libraries that will work with gmail's IMAP4 server. | I assume you have enabled POP3/IMAP access to your GMail account.
This is sample code:
```
import imaplib
conn= imaplib.IMAP4_SSL('imap.googlemail.com')
conn.login('yourusername', 'yourpassword')
code, dummy= conn.select('INBOX')
if code != 'OK':
raise RuntimeError, "Failed to select inbox"
code, data= self.conn.search(None, ALL)
if code == 'OK':
msgid_list= data[0].split()
else:
raise RuntimeError, "Failed to get message IDs"
for msgid in msgid_list:
code, data= conn.fetch(msgid, '(RFC822)')
# you can also use '(RFC822.HEADER)' only for headers
if code == 'OK':
pass # your code here
else:
raise RuntimeError, "could not retrieve msgid %r" % msgid
conn.close()
conn.logout()
```
or something like this. | Select mails from inbox alone via poplib | [
"",
"python",
"gmail",
"pop3",
"poplib",
""
] |
**Please note the question is about using an asynchronous callback mode only on sockets**!
I want to build a TCP client that will notify me when a packet is received and when i the socket is being closed,because the feautures that NET offers with beginRecv,endRecv doesn't inform if the connection is still available.
My question:
Isn't there a way to create a TCP client much like using WinAPI?
I mean calling WSAAsyncSelect with a message,when the message is received it calls the function you've called in WSAAsyncSelect and then you can see whether the connection is closed or there's a new packet through the WParams FD\_CLOSE FD\_READ FD\_WRITE.
If there isn't.Can't I control my connection and my incoming packets at the same time? I don't want to call BeginRecv EndRecv all the time. -.-
Thanks in advance! | If you pass a state object which includes a reference to your socket, You'll have access to the socket itself.
```
public class SocketState
{
public SocketState(Socket s)
{
this._socket = s;
}
private Socket _socket;
public Socket Socket
{
get{return _socket;}
}
}
void SomeFunction()
{
//do some stuff in your code
SocketState stateObject = new SocketState(mySocket);
mySocket.BeginReceive(buffer, offset, size, flags, CallBack, stateObject);
//do some other stuff
}
public void CallBack(IAsyncResult result)
{
SocketState state = (SocketState)result.AsyncState;
state.Socket.EndReceive(result);
//do stuff with your socket.
if(state.Socket.Available)
mySocket.BeginReceive(buffer, offset, size, flags, CallBack, state);
}
``` | Your question is not really clear. By the tone of your question, it seems like you don't want to do any extra work. You can't do async without some extra work.
The best approach is to use the Asynchronous API from Microsoft, using BeginReceive/EndReceive. These will call your callbacks when the socket is closed. However, you cannot easily use the IO Stream support in .NET by doing this, so there is some extra work involved.
If you want more control, you have to do more work. That's all there is to it. | TCP client Asynchronous socket callback | [
"",
"c#",
"asynchronous",
"sockets",
"client",
""
] |
I have a the following static div:
```
<body>
<div id="div1"></div>
....
```
I want to add a div with id "div1\_1" within div1 dynamically by using dojo. How can I do it? | You can do it using just Dojo Base — no need to include anything, if you use the trunk or Dojo 1.3:
```
dojo.create("div", {id: "div1_1"}, "div1");
```
This line creates a div with id "div1\_1" and appends it to the element with id "div1". Obviously you can add more attributes and styles in one go — read all about it in [the documentation for dojo.create()](http://docs.dojocampus.org/dojo/create). | Another option using flexible [dojo.place](http://dojotoolkit.org/reference-guide/1.7/dojo/place.html):
```
dojo.place("<div id='div1_1'></div>", "div1", /*optional*/ "only");
``` | How to add a div dynamically by using Dojo? | [
"",
"javascript",
"dojo",
""
] |
How do I count the number of files in a directory using Java ? For simplicity, lets assume that the directory doesn't have any sub-directories.
I know the standard method of :
```
new File(<directory path>).listFiles().length
```
But this will effectively go through all the files in the directory, which might take long if the number of files is large. Also, I don't care about the actual files in the directory unless their number is greater than some fixed large number (say 5000).
I am guessing, but doesn't the directory (or its i-node in case of Unix) store the number of files contained in it? If I could get that number straight away from the file system, it would be much faster. I need to do this check for every HTTP request on a Tomcat server before the back-end starts doing the real processing. Therefore, speed is of paramount importance.
I could run a daemon every once in a while to clear the directory. I know that, so please don't give me that solution. | This might not be appropriate for your application, but you could always try a native call (using jni or [jna](http://jna.dev.java.net)), or exec a platform-specific command and read the output before falling back to list().length. On \*nix, you could exec `ls -1a | wc -l` (note - that's dash-one-a for the first command, and dash-lowercase-L for the second). Not sure what would be right on windows - perhaps just a `dir` and look for the summary.
Before bothering with something like this I'd strongly recommend you create a directory with a very large number of files and just see if list().length really does take too long. As [this blogger](http://asserttrue.blogspot.com/2009/03/twice-as-fast-isnt-good-enough.html) suggests, you may not want to sweat this.
I'd probably go with Varkhan's answer myself. | Ah... the rationale for not having a straightforward method in Java to do that is file storage abstraction: some filesystems may not have the number of files in a directory readily available... that count may not even have any meaning at all (see for example distributed, P2P filesystems, fs that store file lists as a linked list, or database-backed filesystems...).
So yes,
```
new File(<directory path>).list().length
```
is probably your best bet. | Counting the number of files in a directory using Java | [
"",
"java",
"performance",
"file",
"directory",
""
] |
A static field in a generic class will have a separate value for each combination of generic parameters. It can therefore be used as a Dictionary<Type, *whatever*>
Is this better or worse than a static Dictionary<Type, *whatever*>?
In other words, which of these implementations is more efficient?
```
public static class MethodGen<TParam> {
public static readonly Action<TParam> Method = CreateMethod();
static Action<TParam> CreateMethod() { /*...*/ }
}
```
Or,
```
public static class MethodGen {
static readonly Dictionary<Type, Delegate> methods
= new Dictionary<Type, Delegate>();
public static Action<T> GetMethod<T>() {
//In production code, this would ReaderWriterLock
Delegate method;
if(!methods.TryGetValue(typeof(T), out method)
methods.Add(typeof(t), method = CreateMethod<T>());
return method;
}
static Action<T> CreateMethod<T>() { /*...*/ }
}
```
In particular, how does the CLR lookup the static fields by generic type parameter? | I like using generic types this way. In particular, I often have private nested generic classes for precisely this purpose.
The main thing I like about it is that it's hard *not* to get the initialization right this way (in terms of thread safety), given the way type initialization works. The only problem is what to do if initialization fails - occasionally I've resorted to remembering an exception to throw on first necessary access, but that's pretty rare.
I wouldn't like to guess at *exactly* how the CLR looks up the type via the type arguments, but I'm pretty sure it'll be optimised to heck and back :) | I believe that the generic (first) version would do the dictionary lookup at compile time, and therefore perform better at runtime.
However, it might use more memory. | Static Generic Class as Dictionary | [
"",
"c#",
".net",
"generics",
"dictionary",
"clr",
""
] |
I have the following query
```
Select field1 as 'node1/field1',
field2 as 'node1/field2',
(Select field3 as 'child1/field3',
field4 as 'child1/field4'
From table2
FOR XML PATH(''),TYPE,Elements)
From Table1 FOR XML PATH('Root'),Elements
```
This produces:
```
<Root>
<node1>
<field1>data1</field1>
<field2>data2</field2>
</node1>
<child1>
<field3>data3</field3>
<field4>data4</field4>
</child1>
<child1>
...
</Root>
```
I would like the child1 nodes to be part of node1, not a separate node below.
```
<Root>
<node1>
<field1>data1</field1>
<field2>data2</field2>
<child1>
<field3>data3</field3>
<field4>data4</field4>
</child1>
<child1>
...
</node1>
<node1>
...
</Root>
```
I've tried putting node1 in the subquery PATH
```
FOR XML PATH('node1'),TYPE,Elements)
```
or prefixing the subquery field names with node1
```
Select field3 as 'node1/child1/field3',
```
but both create a new node1 element for the subquery.
Does anyone know how I can accomplish this?
Thanks | You've gotta tell SQL Server how table1 and table2 are related. Based on your answer below, I think something like this might do the trick:
```
select
table1.field1 as 'Node1/Field1'
, table2.field1 as 'Node1/Child1/Field1'
, table1.field2 as 'Node2/Field2'
from table1
left join table2 on table1.id = table2.table1id
for xml PATH(''), ROOT('Root')
```
This should produce XML like:
```
<Root>
<Node1>
<Field1>Value</Field1>
<Child1>
<Field1>Value</Field1>
</Child1>
</Node1>
<Node2>
<Field2>Value</Field2>
</Node2>
</Root>
``` | I've not done a lot of work with T-SQL and FOR XML, but i got round a similar problem by calling the FOR XML part of the query after each sub-query, as below, and using the PATH identifier to set the nodes:
```
SELECT field1 as "Field1",
field2 as "Field2",
(select
field3 as "Field3",
field4 as "Field4"
from table2 t2 inner join
tlink tl on tl.id = t2.id inner join
table2 on t2.id = tl.id
group by field3, field4
FOR XML PATH ('Child'), type
)
from table2 t2
group by field1, field2
FOR XML PATH('Node'), ROOT('Root')
```
this returns:
```
<Root>
<Node1>
<Field1>data1</Field1>
<Field2>data2</Field2>
<Child1>
<Field3>data3</Field3>
<Field4>data4</Field4>
</Child1>
</Node1>
<Node2>
<Field1>data1.2</Field1>
<Field2>data2.2</Field2>
<Child2>
<Field3>data3.2</Field3>
<Field4>data4.2</Field4>
</Child2>
...
</Node2>
...
</Root>
```
As Andomar mentioned, you need to make sure your data is joined correctly.
I've also got the Group By clause in to make sure data doesn't 'go astray'. I was having a problem with the sub-query data replicating as a child for each entry in the outer query (there were multiple children under each node related to how many nodes there were.) I'm sure there's a simple explanation but I was working to a tight schedule when I did this and never went back to check...
If this is incorrect usage or anyone can shed light on the repeating groups, please point it out and I'll edit... | MS SQL 2005 "For XML Path" Node Layout Question | [
"",
"sql",
"sql-server",
"xml",
"t-sql",
"sqlxml",
""
] |
I need to load a specific `applicationContext.xml` file according to a given system property. This itself loads a file with the actual configuration. Therefore I need two `PropertyPlaceHolderConfigurer`, one which resolves the system param, and the other one within the actual configuration.
Any ideas how to do this? | Yes you can do more than one. Be sure to set [ignoreUnresolvablePlaceholders](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html#setIgnoreUnresolvablePlaceholders(boolean)) so that the first will ignore any placeholders that it can't resolve.
```
<bean id="ppConfig1" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true"/>
<property name="locations">
<list>
<value>classpath*:/my.properties</value>
</list>
</property>
</bean>
<bean id="ppConfig2" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="false"/>
<property name="locations">
<list>
<value>classpath*:/myOther.properties</value>
</list>
</property>
</bean>
```
Depending on your application, you should investigate systemPropertiesMode, it allows you to load properties from a file, but allow the system properties to override values in the property file if set. | Beware -- there might be a bug related to multiple configurers. See <http://jira.spring.io/browse/SPR-5719> for more details.
I'm unable to get multiple to work locally... but I'm not yet blaming anyone but myself. | Is it possible to have multiple PropertyPlaceHolderConfigurer in my applicationContext? | [
"",
"java",
"spring",
""
] |
I have the following hierarchy:
```
class Base
{
public Base(string sMessage)
{
//Do stuff
}
}
class Derived : Base
{
public Derived(string someParams)
{
string sMessage = "Blah " + someParams;
//Here I want to call the base constructor
//base(sMessage);
}
}
``` | You have to call the base class constructor prior to the derived class constructor's body.
```
class Derived : Base
{
public Derived(string someParams)
: base("Blah " + someParams)
{
}
}
``` | I originally missed OregonGhost's comment about using a static method to modify the parameter, which turned out to be the most useful for me, so I thought I'd add a code sample for others who read this thread:
```
class Base
{
public Base( string sMessage )
{
// Do stuff
}
}
class Derived : Base
{
public Derived( string sMessage ) : base( AdjustParams( sMessage ) )
{
}
static string AdjustParams( string sMessage )
{
return "Blah " + sMessage;
}
}
``` | Calling base constructor in C# | [
"",
"c#",
"asp.net",
""
] |
I am currently using the binary formatter (Remoting) to serialize and deserialize objects for sending around my LAN.
I have recently upgraded from 2.0 to .NET 3.5. Has 3.5 introduced any new types to improve serialization performance?
I’ve looked at the `DataContractSerializer`, but this serializes anything to underlying XML right … which must increase the memory footprint.
What’s the fastest serializer for sending objects across my LAN? I don’t care a about interop or versioning …. I need speed!
I am open to third-party open source alternatives. | It sounds like [Protocol Buffers](http://code.google.com/apis/protocolbuffers/) might be what you're looking for.
There are three .NET implementations that I'm aware of: [protobuf-net](http://code.google.com/p/protobuf-net/), [protobuf-csharp-port](http://code.google.com/p/protobuf-csharp-port/) and [Proto#](http://code.google.com/p/protosharp/).
The [performance comparisons](http://code.google.com/p/protobuf-net/wiki/Performance) show that Protocol Buffers outperform the built-in serializers in terms of both size and serialization/deserialization speed. | I have some [benchmarks for the leading .NET serializers](http://mono.servicestack.net/benchmarks/NorthwindDatabaseRowsSerialization.1000000-times.2010-02-06.html) available based on the Northwind dataset.
@marcgravell binary protobuf-net is the fastest implementations benchmarked that is about **7x** faster than Microsoft fastest serializer available (the XML DataContractSerializer) in the BCL.
Microsoft's JsonDataContractSerializer is pretty slow - over **9x** slower that protobuf-net and over **3.6x** slower than my own [JsonSerializer](http://www.servicestack.net/mythz_blog/?p=344). | Fastest serializer and deserializer with lowest memory footprint in C#? | [
"",
"c#",
".net",
"wcf",
"sockets",
"remoting",
""
] |
I would like my application to store some data for access by all users. Using Python, how can I find where the data should go? | If you don't want to add a dependency for a third-party module like winpaths, I would recommend using the environment variables already available in Windows:
* [**What environment variables are available in Windows?**](https://learn.microsoft.com/en-us/windows/deployment/usmt/usmt-recognized-environment-variables)
Specifically you probably want `ALLUSERSPROFILE` to get the location of the common user profile folder, which is where the Application Data directory resides.
e.g.:
```
C:\> python -c "import os; print os.environ['ALLUSERSPROFILE']"
C:\Documents and Settings\All Users
```
**EDIT**: Looking at the winpaths module, it's using ctypes so if you wanted to just use the relevant part of the code without installing winpath, you can use this (obviously some error checking omitted for brevity).
```
import ctypes
from ctypes import wintypes, windll
CSIDL_COMMON_APPDATA = 35
_SHGetFolderPath = windll.shell32.SHGetFolderPathW
_SHGetFolderPath.argtypes = [wintypes.HWND,
ctypes.c_int,
wintypes.HANDLE,
wintypes.DWORD, wintypes.LPCWSTR]
path_buf = wintypes.create_unicode_buffer(wintypes.MAX_PATH)
result = _SHGetFolderPath(0, CSIDL_COMMON_APPDATA, 0, 0, path_buf)
print path_buf.value
```
Example run:
```
C:\> python get_common_appdata.py
C:\Documents and Settings\All Users\Application Data
``` | From <http://snipplr.com/view.php?codeview&id=7354>
```
homedir = os.path.expanduser('~')
# ...works on at least windows and linux.
# In windows it points to the user's folder
# (the one directly under Documents and Settings, not My Documents)
# In windows, you can choose to care about local versus roaming profiles.
# You can fetch the current user's through PyWin32.
#
# For example, to ask for the roaming 'Application Data' directory:
# (CSIDL_APPDATA asks for the roaming, CSIDL_LOCAL_APPDATA for the local one)
# (See microsoft references for further CSIDL constants)
try:
from win32com.shell import shellcon, shell
homedir = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0)
except ImportError: # quick semi-nasty fallback for non-windows/win32com case
homedir = os.path.expanduser("~")
```
To get the app-data directory for all users, rather than the current user, just use `shellcon.CSIDL_COMMON_APPDATA` instead of `shellcon.CSIDL_APPDATA`. | How do I find the Windows common application data folder using Python? | [
"",
"python",
"windows",
"application-data",
"common-files",
""
] |
I'm trying to bind separate ComboBox cells within a DataGridView to a custom class, and keep getting an error
> DataGridViewComboBoxCell value is not valid
I'm currently assigning the data source for the cell to an `IList<ICustomInterface>` from a Dictionary I've got. Upon setting the data source however, the index for the `ComboBoxCell` isn't set, so it has an invalid value selected.
I'm trying to figure out how to get it to select a real value, e.g. the 0th item within the list it has been given to remove this error, or find another way to solve the problem. Anyone have any suggestions? | I managed to find the solution not long after posting the question. For anyone else:
The problem was that I was trying to assign the `DataGridViewComboBoxCell.Value` to an object, expecting that because the Cell was bound to a data source that it would automatically find the object in the source and update.
This wasn't actually the case, you actually need to set the value equal to that of the `ValueMember` property for it to correctly update the value and binding. I believe I was using a property 'Name' for both `ValueMember` and `DisplayMember` (controls how the renders in the cell) so setting the Value to `interface.ToString()` (rather than the interface instance) works for the majority of cases. Then I catch and ignore any DataError exceptions that occur while I'm changing the source around. | Here's my simple solution when using enums
```
ColumnType.ValueType = typeof (MyEnum);
ColumnType.DataSource = Enum.GetValues(typeof (MyEnum));
```
you can do that just after "InitializeComponent();" | DataGridViewComboBoxCell Binding - "value is not valid" | [
"",
"c#",
"datagridview",
"datagridviewcombobox",
""
] |
**The preamble:**
I have designed a strongly interfaced and fully mockable data layer class that expects the business layer to create a [`TransactionScope`](http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx?ppud=4) when multiple calls should be included in a single transaction.
**The problem:** I would like to unit test that my business layer makes use of a `TransactionScope` object when I expect it to.
Unfortunately, the standard pattern for using `TransactionScope` is a follows:
```
using(var scope = new TransactionScope())
{
// transactional methods
datalayer.InsertFoo();
datalayer.InsertBar();
scope.Complete();
}
```
While this is a really great pattern in terms of usability for the programmer, testing that it's done seems... unpossible to me. I cannot detect that a transient object has been instantiated, let alone mock it to determine that a method was called on it. Yet my goal for coverage implies that I must.
**The Question:** How can I go about building unit tests that ensure `TransactionScope` is used appropriately according to the standard pattern?
**Final Thoughts:** I've considered a solution that would certainly provide the coverage I need, but have rejected it as overly complex and not conforming to the standard `TransactionScope` pattern. It involves adding a `CreateTransactionScope` method on my data layer object that returns an instance of `TransactionScope`. But because TransactionScope contains constructor logic and non-virtual methods and is therefore difficult if not impossible to mock, `CreateTransactionScope` would return an instance of `DataLayerTransactionScope` which would be a mockable facade into `TransactionScope`.
While this might do the job it's complex and I would prefer to use the standard pattern. Is there a better way? | I'm just now sitting with the same problem and to me there seems to be two solutions:
1. Don't solve the problem.
2. Create abstractions for the existing classes that follows the same pattern but are mockable/stubable.
**Edit:**
I've created a CodePlex-project for this now: <http://legendtransactions.codeplex.com/>
I'm leaning towards creating a set of interfaces for working with transactions and a default implementation that delegates to the System.Transaction-implementations, something like:
```
public interface ITransactionManager
{
ITransaction CurrentTransaction { get; }
ITransactionScope CreateScope(TransactionScopeOption options);
}
public interface ITransactionScope : IDisposable
{
void Complete();
}
public interface ITransaction
{
void EnlistVolatile(IEnlistmentNotification enlistmentNotification);
}
public interface IEnlistment
{
void Done();
}
public interface IPreparingEnlistment
{
void Prepared();
}
public interface IEnlistable // The same as IEnlistmentNotification but it has
// to be redefined since the Enlistment-class
// has no public constructor so it's not mockable.
{
void Commit(IEnlistment enlistment);
void Rollback(IEnlistment enlistment);
void Prepare(IPreparingEnlistment enlistment);
void InDoubt(IEnlistment enlistment);
}
```
This seems like a lot of work but on the other hand it's reusable and it makes it all very easily testable.
Note that this is not the complete definition of the interfaces just enough to give you the big picture.
**Edit:**
I just did some quick and dirty implementation as a proof of concept, I think this is the direction I will take, here's what I've come up with so far. I'm thinking that maybe I should create a CodePlex project for this so the problem can be solved once and for all. This is not the first time I've run into this.
```
public interface ITransactionManager
{
ITransaction CurrentTransaction { get; }
ITransactionScope CreateScope(TransactionScopeOption options);
}
public class TransactionManager : ITransactionManager
{
public ITransaction CurrentTransaction
{
get { return new DefaultTransaction(Transaction.Current); }
}
public ITransactionScope CreateScope(TransactionScopeOption options)
{
return new DefaultTransactionScope(new TransactionScope());
}
}
public interface ITransactionScope : IDisposable
{
void Complete();
}
public class DefaultTransactionScope : ITransactionScope
{
private TransactionScope scope;
public DefaultTransactionScope(TransactionScope scope)
{
this.scope = scope;
}
public void Complete()
{
this.scope.Complete();
}
public void Dispose()
{
this.scope.Dispose();
}
}
public interface ITransaction
{
void EnlistVolatile(Enlistable enlistmentNotification, EnlistmentOptions enlistmentOptions);
}
public class DefaultTransaction : ITransaction
{
private Transaction transaction;
public DefaultTransaction(Transaction transaction)
{
this.transaction = transaction;
}
public void EnlistVolatile(Enlistable enlistmentNotification, EnlistmentOptions enlistmentOptions)
{
this.transaction.EnlistVolatile(enlistmentNotification, enlistmentOptions);
}
}
public interface IEnlistment
{
void Done();
}
public interface IPreparingEnlistment
{
void Prepared();
}
public abstract class Enlistable : IEnlistmentNotification
{
public abstract void Commit(IEnlistment enlistment);
public abstract void Rollback(IEnlistment enlistment);
public abstract void Prepare(IPreparingEnlistment enlistment);
public abstract void InDoubt(IEnlistment enlistment);
void IEnlistmentNotification.Commit(Enlistment enlistment)
{
this.Commit(new DefaultEnlistment(enlistment));
}
void IEnlistmentNotification.InDoubt(Enlistment enlistment)
{
this.InDoubt(new DefaultEnlistment(enlistment));
}
void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment)
{
this.Prepare(new DefaultPreparingEnlistment(preparingEnlistment));
}
void IEnlistmentNotification.Rollback(Enlistment enlistment)
{
this.Rollback(new DefaultEnlistment(enlistment));
}
private class DefaultEnlistment : IEnlistment
{
private Enlistment enlistment;
public DefaultEnlistment(Enlistment enlistment)
{
this.enlistment = enlistment;
}
public void Done()
{
this.enlistment.Done();
}
}
private class DefaultPreparingEnlistment : DefaultEnlistment, IPreparingEnlistment
{
private PreparingEnlistment enlistment;
public DefaultPreparingEnlistment(PreparingEnlistment enlistment) : base(enlistment)
{
this.enlistment = enlistment;
}
public void Prepared()
{
this.enlistment.Prepared();
}
}
}
```
Here's an example of a class that depends on the ITransactionManager to handle it's transactional work:
```
public class Foo
{
private ITransactionManager transactionManager;
public Foo(ITransactionManager transactionManager)
{
this.transactionManager = transactionManager;
}
public void DoSomethingTransactional()
{
var command = new TransactionalCommand();
using (var scope = this.transactionManager.CreateScope(TransactionScopeOption.Required))
{
this.transactionManager.CurrentTransaction.EnlistVolatile(command, EnlistmentOptions.None);
command.Execute();
scope.Complete();
}
}
private class TransactionalCommand : Enlistable
{
public void Execute()
{
// Do some work here...
}
public override void Commit(IEnlistment enlistment)
{
enlistment.Done();
}
public override void Rollback(IEnlistment enlistment)
{
// Do rollback work...
enlistment.Done();
}
public override void Prepare(IPreparingEnlistment enlistment)
{
enlistment.Prepared();
}
public override void InDoubt(IEnlistment enlistment)
{
enlistment.Done();
}
}
}
``` | I found a great way to test this using Moq and FluentAssertions. Suppose your unit under test looks like this:
```
public class Foo
{
private readonly IDataLayer dataLayer;
public Foo(IDataLayer dataLayer)
{
this.dataLayer = dataLayer;
}
public void MethodToTest()
{
using (var transaction = new TransactionScope())
{
this.dataLayer.Foo();
this.dataLayer.Bar();
transaction.Complete();
}
}
}
```
Your test would look like this (assuming MS Test):
```
[TestClass]
public class WhenMethodToTestIsCalled()
{
[TestMethod]
public void ThenEverythingIsExecutedInATransaction()
{
var transactionCommitted = false;
var fooTransaction = (Transaction)null;
var barTransaction = (Transaction)null;
var dataLayerMock = new Mock<IDataLayer>();
dataLayerMock.Setup(dataLayer => dataLayer.Foo())
.Callback(() =>
{
fooTransaction = Transaction.Current;
fooTransaction.TransactionCompleted +=
(sender, args) =>
transactionCommitted = args.Transaction.TransactionInformation.Status == TransactionStatus.Committed;
});
dataLayerMock.Setup(dataLayer => dataLayer.Bar())
.Callback(() => barTransaction = Transaction.Current);
var unitUnderTest = new Foo(dataLayerMock.Object);
unitUnderTest.MethodToTest();
// A transaction was used for Foo()
fooTransaction.Should().NotBeNull();
// The same transaction was used for Bar()
barTransaction.Should().BeSameAs(fooTransaction);
// The transaction was committed
transactionCommitted.Should().BeTrue();
}
}
```
This works great for my purposes. | Unit Testing the Use of TransactionScope | [
"",
"c#",
".net",
"unit-testing",
"transactions",
""
] |
I have a Rectangle2D and a Line2D. I want to "clip" the line so that only the part of the line which is within the rectangle remains. If none of the line is within the rectangle I want the line to be set to (0,0,0,0). Basically something along the lines of a
```
Rectangle2D.intersect(Line2D src, Line2D dest)
```
or something similar.
Is there a way to do this with the java.awt.geom API? Or an elegant way to code it "by hand"? | Well, I ended up doing it myself.
For those intereseted, I ended up solving it by turning the line into a rectangle (with getBounds), then using `Rectangle.intersect(clipRect,lineRect,intersectLineRect)` to create the intersection, then turning the intersection back into a line. | The source code for [`Rectangle2D.intersectLine()`](http://docs.oracle.com/javase/8/docs/api/java/awt/geom/Rectangle2D.html#intersects-double-double-double-double-) might be helpful:
```
public boolean intersectsLine(double x1, double y1, double x2, double y2) {
int out1, out2;
if ((out2 = outcode(x2, y2)) == 0) {
return true;
}
while ((out1 = outcode(x1, y1)) != 0) {
if ((out1 & out2) != 0) {
return false;
}
if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {
double x = getX();
if ((out1 & OUT_RIGHT) != 0) {
x += getWidth();
}
y1 = y1 + (x - x1) * (y2 - y1) / (x2 - x1);
x1 = x;
} else {
double y = getY();
if ((out1 & OUT_BOTTOM) != 0) {
y += getHeight();
}
x1 = x1 + (y - y1) * (x2 - x1) / (y2 - y1);
y1 = y;
}
}
return true;
}
```
where `outcode()` is defined as:
```
public int outcode(double x, double y) {
int out = 0;
if (this.width <= 0) {
out |= OUT_LEFT | OUT_RIGHT;
} else if (x < this.x) {
out |= OUT_LEFT;
} else if (x > this.x + this.width) {
out |= OUT_RIGHT;
}
if (this.height <= 0) {
out |= OUT_TOP | OUT_BOTTOM;
} else if (y < this.y) {
out |= OUT_TOP;
} else if (y > this.y + this.height) {
out |= OUT_BOTTOM;
}
return out;
}
```
(from [OpenJDK](http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/awt/geom/Rectangle2D.java))
It shouldn't be extremely difficult to change this to clip instead of returning true or false. | Most elegant way to clip a line? | [
"",
"java",
"algorithm",
"geometry",
"clipping",
""
] |
What is the experience of working with [OpenOffice](http://en.wikipedia.org/wiki/OpenOffice.org) in server mode? I know OpenOffice is not multithreaded and now I need to use its services in our server.
What can I do to overcome this problem?
I'm using Java. | Yes, I am using OpenOffice as a document conversion server.
Unfortunately, the solution to your problem is to spawn a pool of OpenOffice processes.
The [commons-pool](http://jodconverter.svn.sourceforge.net/viewvc/jodconverter/branches/3.0.x-200801-commons-pool/) branch of JODConverter (before it moved to `code.google.com`) implemented this out-of-the-box for you. | With the current version of [JODConverter](http://code.google.com/p/jodconverter/) (3.0-SNAPSHOT), it's quite easy to handle multiple threads of OOo in headless-mode, as the library now supports starting up several instances and keeping them in a pool, by just providing several port numbers or named pipes when constructing a OfficeManager instance:
```
final OfficeManager om = new DefaultOfficeManagerConfiguration()
.setOfficeHome("/usr/lib/openoffice")
.setPortNumbers(8100, 8101, 8102, 8103)
.buildOfficeManager();
om.start();
```
You can then us the library e.g. for converting documents without having to deal with the pool of OOo instances in the background:
```
OfficeDocumentConverter converter = new OfficeDocumentConverter(om);
converter.convert(new File("src/test/resources/test.odt"), new File("target/test.pdf"));
``` | How can I use OpenOffice in server mode as a multithreaded service? | [
"",
"java",
"multithreading",
"openoffice.org",
""
] |
So I was feeling bored and decided I wanted to make a hangman game. I did an assignment like this back in high school when I first took C++. But this was before I even too geometry, so unfortunately I didn't do well in any way shape or form in it, and after the semester I trashed everything in a fit of rage.
I'm looking to make a txt document and just throw in a whole bunch of words
(ie:
test
love
hungery
flummuxed
discombobulated
pie
awkward
you
get
the
idea
)
So here's my question:
How do I get C++ to read a random word from the document?
I have a feeling `#include<ctime>` will be needed, as well as `srand(time(0));` to get some kind of pseudorandom choice...but I haven't the foggiest on how to have a random word taken from a file...any suggestions?
Thanks ahead of time! | Here's a rough sketch, assuming that the words are separated by whitespaces (space, tab, newline, etc):
```
vector<string> words;
ifstream in("words.txt");
while(in) {
string word;
in >> word;
words.push_back(word);
}
string r=words[rand()%words.size()];
``` | The operator >> used on a string will read 1 (white) space separated word from a stream.
So the question is do you want to read the file each time you pick a word or do you want to load the file into memory and then pick up the word from a memory structure. Without more information I can only guess.
Pick a Word from a file:
```
// Note a an ifstream is also an istream.
std::string pickWordFromAStream(std::istream& s,std::size_t pos)
{
std::istream_iterator<std::string> iter(s);
for(;pos;--pos)
{ ++iter;
}
// This code assumes that pos is smaller or equal to
// the number of words in the file
return *iter;
}
```
Load a file into memory:
```
void loadStreamIntoVector(std::istream& s,std::vector<std::string> words)
{
std::copy(std::istream_iterator<std::string>(s),
std::istream_iterator<std::string>(),
std::back_inserter(words)
);
}
```
Generating a random number should be easy enough. Assuming you only want psudo-random. | How do you read a word in from a file in C++? | [
"",
"c++",
"file",
"input",
""
] |
Does SQL CE support clustered indexes? | MSDN says about the NONCLUSTERED argument:
```
This is the only supported index type
``` | Judging by [CREATE INDEX](http://technet.microsoft.com/en-us/library/ms345331.aspx "Create Index") syntax for SQL Server Compact Edition, the only supported index type is NONCLUSTERED. | Does SQL Compact Edition Support Clustered Indexes? | [
"",
"sql",
"sql-server-ce",
""
] |
I'm trying to create a simple connection using the jdbc-odbc bridge:
```
public static Connection getConnection() {
Connection con =null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conStr = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" +
"c:\\myfolder\\accesdbfile.accdb";
con = DriverManager.getConnection(conStr);
} catch(Exception e) {
e.printStackTrace();}
return con;
}
```
But then I get this exception:
```
java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver]General error Unable to open registry key Temporary (volatile) Ace DSN for process 0xa4 Thread 0xec0 DBC 0x2f8574c Jet'.
```
Any ideas?
Update 24/Mar/2009: Now it's working. Created a User Data Source, and for some reason the exception went away.
As a general question, What would be the best way to handle database connections in Java? | To answer your general question I would say the best way to handle database connections in Java is to avoid the JDBC-ODBC bridge. Its OK for testing or learning about JDBC but not for real production use. Also, if you have a data source that does not have its own JDBC driver but it has an ODBC driver then you may not have a choice.
The main reason why I suggest that you stay away from it though is that it makes it difficult to deploy your application. You have to set up the Data Source on the machine that you are running your application from. If you have access to the machine no problem, but suppose you are sending the application off to the client? The pure Java JDBC driver works better for this because it is included as part of your application so once your application is installed it is ready to connect to the data source.
Of course depending on your requirements there are two other types of drivers but thats another discussion. | In general, the best way to work with an RDBMS in Java is by using a JDBC driver that is designed to connect directly to the database. Using the JDBC-ODBC bridge tends to be sloww.
If you are trying to do basic read/write manipulations with an Access database, I would also recommend taking a look at the [Jackcess](http://jackcess.sourceforge.net/) library. | What's the right way in Java to connect to a Microsoft Access 2007 database? | [
"",
"java",
"jdbc",
"ms-access-2007",
""
] |
Does it matter which way I declare the `main` function in a C++ (or C) program? | The difference is one is the correct way to define `main`, and the other is not.
And yes, it does matter. Either
```
int main(int argc, char** argv)
```
or
```
int main()
```
are the proper definition of your `main` per the C++ spec.
`void main(int argc, char** argv)`
is not and was, IIRC, a perversity that came with older Microsoft's C++ compilers.
<https://isocpp.org/wiki/faq/newbie#main-returns-int> | [Bjarne Stroustrup](https://en.wikipedia.org/wiki/Bjarne_Stroustrup) made this quite clear:
> The definition `void main()` is not and never has been C++, nor has it even been C.
See [reference](http://www.stroustrup.com/bs_faq2.html#void-main). | Difference between void main and int main in C/C++? | [
"",
"c++",
"c",
"function",
"standards",
"program-entry-point",
""
] |
I'm trying to turn my JoGL project into a `jar` file. What am I doing wrong?
```
Exception in thread "main" java.lang.NoClassDefFoundError: javax/media/opengl/GL
EventListener
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.defineClass(Unknown Source)
at java.net.URLClassLoader.access$000(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
Caused by: java.lang.ClassNotFoundException: javax.media.opengl.GLEventListener
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 12 more
Could not find the main class: chartest. Program will exit.
```
Contents of the JAR file:
```
META-INF\MANIFEST.MF
gluegen-rt.jar
jogl.jar
chartest$1.class
chartest.class
gluegen-rt.dll
jogl.dll
jogl_awt.dll
jogl_cg.dll
test.png
``` | You can check your classpath. It should include atleast
* The jar file with classes you have written
* Supporting jars with classes like javax.media.opengl (jogl.jar?)
Try placing all these jars in your classpath and run it. | is Jogle jar file in your classpath ?
I see you have included the jars themselves in your jar... this unfortunately wil not work out of the box.
Either get the jars out then place in your classpath (that can be part of your manifest also) or write your own classloader...
<http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html>
This is why it worked for William and not for you... he got the jogl from somewhere else and did not use the one within your jar. | What's wrong with this .jar file? | [
"",
"java",
"opengl",
"jar",
"jogl",
""
] |
I need help writing a conditional where clause. here is my situation:
I have a bit value that determines what rows to return in a select statement. If the value is true, I need to return rows where the import\_id column is not null, if false, then I want the rows where the import\_id column is null.
My attempt at such a query (below) does not seem to work, what is the best way to accomplish this?
```
DECLARE @imported BIT
SELECT id, import_id, name FROM Foo WHERE
(@imported = 1 AND import_id IS NOT NULL)
AND (@imported = 0 AND import_is IS NULL)
```
Thanks. | Change the `AND` to `OR`
```
DECLARE @imported BIT
SELECT id, import_id, name FROM Foo WHERE
(@imported = 1 AND import_id IS NOT NULL)
OR (@imported = 0 AND import_is IS NULL)
```
### Decomposing your original statement
you have essentially written
```
@imported = 1
AND import_id IS NOT NULL
AND @imported = 0
AND import_is IS NULL
```
wich is equivalent to
```
@imported = 1 AND @imported = 0
AND import_id IS NOT NULL AND import_is IS NULL
```
what results in two pair of clauses that completely negate each other | I think you meant
```
SELECT id, import_id, name FROM Foo WHERE
(@imported = 1 AND import_id IS NOT NULL)
OR (@imported = 0 AND import_is IS NULL)
^^^
``` | SQL HELP - Conditional where clause based on a BIT variable - SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
In the "Memcache Viewer", is there any way to dump a list of existing keys? Just for debugging, of course, not for use in any scripts!
I ask because it doesn't seem like the GAE SDK is using a "real" memcache server, so I'm guessing it's emulated in Python (for simplicity, as it's just a development server).. This would mean there is a dict somewhere with the keys/values.. | People ask for this on the memcached list a lot, sometimes with the same type of "just in case I want to look around to debug something" sentiment.
The best way to handle this is to know how you generate your keys, and just go look stuff up when you want to know what's stored for a given value.
If you have too many things using memcached to do that within the scope of your debugging session, then start logging access.
But keep in mind -- memcached is fast because it doesn't allow for such things in general. The community server does have limited functionality to get a subset of the keys available within a given slab class, but it's probably not what you really want, and hopefully google doesn't implement it in theirs. :) | No. I did not found such functionality in memcached too.
Thinking about this issue, I found this limitation understandable - it would require keeping a registry of keys with all related problems like key expiration, invalidation and of course locking. Such system would not be as fast as memcaches are intended to be. | Dump memcache keys from GAE SDK Console? | [
"",
"python",
"google-app-engine",
"memcached",
""
] |
I am trying to set the value to the hidden field in parent window from child window and want to set the value to the parent window only when popup window is closed.
This is working fine when i use button to close the window.
The script for the button is:
onclick="javascript:window.close();"
But the same condition fails when i click (X) button in title bar. Can anyone help me out with this issue | best way to do this is to use window.onunload but this event is also fired when you press ctrl+r (i.e. on refresh) so just check this out. | Use onBeforeUnload. | How to check whether (X) button in clicked in popup window | [
"",
"javascript",
"html",
""
] |
Before meeting with Ajax and Jquery, in my projects I had a function like below.
```
Public Sub Raise_Alarm(ByVal p_Page As Page, ByVal p_Message As String, Optional ByVal p_IsError As Boolean = True)
strScript = "<script language= ""javascript""> alert('" & p_Message.Replace("'", "") & "')</script>"
Dim t As Type = p_Page.GetType()
p_Page.ClientScript.RegisterStartupScript(t, "alert", strScript)
Dim mylabel As Label
end sub
```
For now I want to a function instead of function above, which show message as a lightbox (modal box).
How can I do it? | If you want to use jqModal as suggested by cxfx above (+1;), this should work:
```
strScript = "$('<div>" & p_Message.Replace("'", "\'") & "</div>').jqm();";
ClientScriptManager.RegisterStartupScript(p_Page.GetType(), "alert", strScript, true);
``` | If you are using "thickbox" it can just display a noraml aspx page in a modal window. You can then use code behind as normal.
```
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<link href="/themes/ui.all.css" rel="stylesheet" type="text/css" />
<link runat="server" href="/styles/thickbox.css" rel="stylesheet" type="text/css" />
<!-- jQuery -->
<script type="text/javascript" src="/scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="/scripts/ui.core.js"></script>
<script type="text/javascript" src="/scripts/thickbox.js"></script>
</head>
<body>
<a class="thickbox" href="mylink.aspx?KeepThis=true&TB_iframe=true&height=300&width=850">modal thick box link</a>
</body>
</html>
```
Hope this helps. | Control Lightbox (Modal) From Code-Behind Of Asp.Net | [
"",
"asp.net",
"javascript",
"jquery",
"lightbox",
""
] |
I am having a bit of a problem adding a few check boxes and an event handler programatically. The check boxes all appear fine, but they don't do anything when clicked. Does anyone have any idea what I am doing wrong?
### My code:
```
foreach (Statement i in theseStatements)
{
box = new CheckBox();
box.Text = i.StatementText;
box.AutoPostBack = true;
box.CheckedChanged += new EventHandler(this.CheckedChange);
PlaceHolder.Controls.Add(box);
}
protected void CheckedChange(object sender, EventArgs e)
{
CheckBox x = (CheckBox)sender;
Instructions.Text = "change";
WorkPlaceHazardsBox.Text += x.Text;
}
``` | You should do the following:
1. Set the `ID` property for each instance of `CheckBox` you create in your `foreach` loop.
2. For PostBacks, ensure that your CheckBoxes are created and `CheckedChanged` event handler is attached at some point of the page life-cycle *before* control events are raised | Make sure to verify you are doing the following:
* The same list of checkbox is being added on both the initial load and further postbacks
* You set a different ID to each checkbox
* Verify you are getting a postback (set a break point in Page Load)
* The controls are added to the page on Page Load, or even better on Page Init
If you are trying to do something different than that, update us with more info. | Dynamically (programatically) adding check boxes and checkedchanged events | [
"",
"c#",
"asp.net",
"event-handling",
""
] |
The effect of issuing an inner join is the same as stating a cross join with the join condition in the WHERE-clause. I noticed that many people in my company use cross joins, where I would use inner joins. I didn't notice any significant performance gain after changing some of these queries and was wondering if it was just a coincidence or if the DBMS optimizes such issues transparently (MySql in our case). And here a concrete example for discussion:
```
SELECT User.*
FROM User, Address
WHERE User.addressId = Address.id;
SELECT User.*
FROM User
INNER JOIN Address ON (User.addressId = Address.id);
``` | Cross Joins produce results that consist of every combination of rows from two or more tables. That means if table A has 6 rows and table B has 3 rows, a cross join will result in 18 rows. There is no relationship established between the two tables – you literally just produce every possible combination.
With an inner join, column values from one row of a table are combined with column values from another row of another (or the same) table to form a single row of data.
If a WHERE clause is added to a cross join, it behaves as an inner join as the WHERE imposes a limiting factor.
As long as your queries abide by common sense and vendor specific performance guidelines (i), I like to think of the decision on which type of join to use to be a simple matter of taste.
*(i) Vendor Specific Performance Guidelines*
1. [MySQL Performance Tuning and Optimization Resources](https://www.mysql.com/why-mysql/performance/index.html)
2. [PostgreSQL Performance Optimization](https://wiki.postgresql.org/wiki/Performance_Optimization) | There is no difference other than the inner join is a lot clearer because it defines the join, leaving the where clause to be the actual limiting condition. | Performance of Cross join with WHERE clause compared to Inner join | [
"",
"sql",
"performance",
""
] |
The following is an excerpt from Bjarne Stroustrup's book, The C++ Programming Language:
Section 4.6:
> Some of the aspects of C++’s fundamental types, such as the size of an int, are implementation- defined (§C.2). I point out these dependencies and often recommend avoiding them or taking steps to minimize their impact. Why should you bother? People who program on a variety of systems or use a variety of compilers care a lot because if they don’t, they are forced to waste time finding and fixing obscure bugs. People who claim they don’t care about portability usually do so because they use only a single system and feel they can afford the attitude that ‘‘the language is what my compiler implements.’’ This is a narrow and shortsighted view. If your program is a success, it is likely to be ported, so someone will have to find and fix problems related to implementation-dependent features. In addition, programs often need to be compiled with other compilers for the same system, and even a future release of your favorite compiler may do some things differently from the current one. It is far easier to know and limit the impact of implementation dependencies when a program is written than to try to untangle the mess afterwards.
>
> It is relatively easy to limit the impact of implementation-dependent language features.
My question is: How to limit the impact of implementation-dependent language features? Please mention implementation-dependent language features then show how to limit their impact. | Few ideas:
* Unfortunately you will have to use macros to avoid some platform specific or compiler specific issues. You can look at the headers of Boost libraries to see that it can quite easily get cumbersome, for example look at the files:
+ [boost/config/compiler/gcc.hpp](http://www.boost.org/doc/libs/1_38_0/boost/config/compiler/gcc.hpp)
+ [boost/config/compiler/intel.hpp](http://www.boost.org/doc/libs/1_38_0/boost/config/compiler/intel.hpp)
+ [boost/config/platform/linux.hpp](http://www.boost.org/doc/libs/1_38_0/boost/config/platform/linux.hpp)
+ and so on
* The integer types tend to be messy among different platforms, you will have to define your own typedefs or use something like [Boost cstdint.hpp](http://www.boost.org/doc/libs/1_38_0/libs/integer/cstdint.htm)
* If you decide to use any library, then do a check that the library is supported on the given platform
* Use the libraries with good support and clearly documented platform support (for example Boost)
* You can abstract yourself from some C++ implementation specific issues by relying heavily on libraries like Qt, which provide an "alternative" in sense of types and algorithms. They also attempt to make the coding in C++ more portable. Does it work? I'm not sure.
* Not everything can be done with macros. Your build system will have to be able to detect the platform and the presence of certain libraries. Many would suggest `autotools` for project configuration, I on the other hand recommend `CMake` (rather nice language, no more `M4`)
* endianness and alignment might be an issue if you do some low level meddling (i.e. `reinterpret_cast` and friends things alike (friends was a bad word in C++ context)).
* throw in a lot of warning flags for the compiler, for gcc I would recommend at least `-Wall -Wextra`. But there is much more, see the documentation of the compiler or this [question](https://stackoverflow.com/questions/399850/best-compiler-warning-level-for-c-c-compilers).
* you have to watch out for everything that is implementation-defined and implementation-dependend. If you want the truth, only the truth, nothing but the truth, then go to ISO standard. | Well, the variable sizes one mentioned is a fairly well known issue, with the common workaround of providing typedeffed versions of the basic types that have well defined sizes (normally advertised in the typedef name). This is done use preprocessor macros to give different code-visibility on different platforms. E.g.:
```
#ifdef __WIN32__
typedef int int32;
typedef char char8;
//etc
#endif
#ifdef __MACOSX__
//different typedefs to produce same results
#endif
```
Other issues are normally solved in the same way too (i.e. using preprocessor tokens to perform conditional compilation) | How to limit the impact of implementation-dependent language features in C++? | [
"",
"c++",
""
] |
I have a web.py server that responds to various user requests. One of these requests involves downloading and analyzing a series of web pages.
Is there a simple way to setup an async / callback based url download mechanism in web.py? Low resource usage is particularly important as each user initiated request could result in download of multiple pages.
The flow would look like:
User request -> web.py -> Download 10 pages in parallel or asynchronously -> Analyze contents, return results
I recognize that Twisted would be a nice way to do this, but I'm already in web.py so I'm particularly interested in something that can fit within web.py . | Use the async http client which uses asynchat and asyncore.
<http://sourceforge.net/projects/asynchttp/files/asynchttp-production/asynchttp.py-1.0/asynchttp.py/download> | Here is an interesting piece of code. I didn't use it myself, but it looks nice ;)
<https://github.com/facebook/tornado/blob/master/tornado/httpclient.py>
Low level AsyncHTTPClient:
"An non-blocking HTTP client backed with pycurl. Example usage:"
```
import ioloop
def handle_request(response):
if response.error:
print "Error:", response.error
else:
print response.body
ioloop.IOLoop.instance().stop()
http_client = httpclient.AsyncHTTPClient()
http_client.fetch("http://www.google.com/", handle_request)
ioloop.IOLoop.instance().start()
```
"
fetch() can take a string URL or an HTTPRequest instance, which offers more options, like executing POST/PUT/DELETE requests.
The keyword argument max\_clients to the AsyncHTTPClient constructor determines the maximum number of simultaneous fetch() operations that can execute in parallel on each IOLoop.
"
There is also new implementation in progress:
<https://github.com/facebook/tornado/blob/master/tornado/simple_httpclient.py>
"Non-blocking HTTP client with no external dependencies. ... This class is still in development and not yet recommended for production use." | Python: simple async download of url content? | [
"",
"python",
"asynchronous",
""
] |
We'd like to write this query:
```
select * from table
where col1 != 'blah' and col2 = 'something'
```
We want the query to include rows where col1 is null (and col2 = 'something'). Currently the query won't do this for the rows where col1 is null. Is the below query the best and fastest way?
```
select * from table
where (col1 != 'blah' or col1 is null) and col2 = 'something'
```
Alternatively, we could if needed update all the col1 null values to empty strings. Would this be a better approach? Then our first query would work.
---
**Update**: Re: using NVL: I've read on another [post](https://stackoverflow.com/questions/191640/get-null-null-in-sql) that this is not considered a great option from a performance perspective. | In Oracle, there is no difference between an empty string and NULL.
That is blatant disregard for the SQL standard, but there you go ...
In addition to that, you cannot compare against NULL (or not NULL) with the "normal" operators: "col1 = null" will not work, "col1 = '' " will not work, "col1 != null" will not work, you have to use "is null".
So, no, you cannot make this work any other way then "col 1 is null" or some variation on that (such as using nvl). | I think that the solution that you posted is one of best options.
Regarding to performance, in my opinion it is not a big difference in this case, if the clause already have a != comparison usually the optimizer won't use an index in that column, because the selectivity is not enough, so the more discriminating filter will be the other side of the "and" condition.
If you ask me, I won't use an empty string as a null, but may be is just a personal preference. | SQL not equals & null | [
"",
"sql",
"performance",
"oracle",
""
] |
I have a long document in LaTex, which contains paragraphs. The paragraphs contain sentences such that no subsequent sentence start at a new line.
**How can you make each subsequent sentence to start at a new line in my .tex file?**
*My attempt to the problem*
We need to put \n to the end of Sentence B where Sentence B has Sentence A before it.
We must not put \n to the situations where there are the mark `\`.
I see that the problem can be solved by AWK and Python. | What's wrong with putting a newline after each period? Eg:
```
awk '{ gsub(/\. +/, ".\n"); print }'
$ echo "abc. 123. xyz." | awk '{ gsub(/\. +/, ".\n"); print }'
abc.
123.
xyz.
``` | So you want every sentence in your .tex file to start on a new line, but without introducing extra paragraphs? Is that correct?
Possibly you could go through your file and, every time you see a '.' followed by whitespace and a capital letter, insert a newline.
e.g. in python:
```
import re
sentence_end = r'\.\s+([A-Z])'
source = open('myfile.tex')
dest = open('myfile-out.tex', 'w')
for line in source:
dest.write(re.sub(sentence_end, '.\n\g<1>', line))
``` | Unable to make each sentence to start at a new line in LaTex by AWK/Python | [
"",
"python",
"latex",
"awk",
""
] |
I have a form that inherits from 2 other forms. In my form, I want to change the label of a field that was defined in one of the parent forms. Does anyone know how this can be done?
I'm trying to do it in my `__init__`, but it throws an error saying that "'RegistrationFormTOS' object has no attribute 'email'". Does anyone know how I can do this?
Thanks.
Here is my form code:
```
from django import forms
from django.utils.translation import ugettext_lazy as _
from registration.forms import RegistrationFormUniqueEmail
from registration.forms import RegistrationFormTermsOfService
attrs_dict = { 'class': 'required' }
class RegistrationFormTOS(RegistrationFormUniqueEmail, RegistrationFormTermsOfService):
"""
Subclass of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
email2 = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict, maxlength=75)), label=_(u'verify email address'))
def __init__(self, *args, **kwargs):
self.email.label = "New Email Label"
super(RegistrationFormTOS, self).__init__(*args, **kwargs)
def clean_email2(self):
"""
Verifiy that the values entered into the two email fields
match.
"""
if 'email' in self.cleaned_data and 'email2' in self.cleaned_data:
if self.cleaned_data['email'] != self.cleaned_data['email2']:
raise forms.ValidationError(_(u'You must type the same email each time'))
return self.cleaned_data
``` | You should use:
```
def __init__(self, *args, **kwargs):
super(RegistrationFormTOS, self).__init__(*args, **kwargs)
self.fields['email'].label = "New Email Label"
```
Note first you should use the super call. | Here's an example taken from [Overriding the default fields](https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#overriding-the-default-fields):
> ```
> from django.utils.translation import ugettext_lazy as _
>
> class AuthorForm(ModelForm):
> class Meta:
> model = Author
> fields = ('name', 'title', 'birth_date')
> labels = {
> 'name': _('Writer'),
> }
> help_texts = {
> 'name': _('Some useful help text.'),
> }
> error_messages = {
> 'name': {
> 'max_length': _("This writer's name is too long."),
> },
> }
> ``` | Django form - set label | [
"",
"python",
"django",
"inheritance",
"django-forms",
""
] |
What do you guys recommend for a UI library to use with jQuery. [jQuery UI](http://jqueryui.com/) seems to have less widgets compared to other frameworks. I've been playing around lately with the [Dojo Toolkit](http://www.dojotoolkit.org/) which seems pretty nice so far, and I know that there is always the [Yahoo! User Interface](http://developer.yahoo.com/yui/), but is there anything else?
I also need to consider licensing, something that can be distributed with Open Source software licensed under the BSD license as well as internal-use software. | Those other "ui libraries" depend on entire other frameworks. If you're using Prototype, choose Scriptaculous. If you're using Dojo, use Dijit.
If you're using jQuery, really, use jQuery UI. You can style the jQuery UI "widgets" a number of different ways; take a look at the Theme Roller Gallery: <http://themeroller.com/>
What do you mean by lack of maturity and polish? | I've found the jQuery UI widget's in various stages. Some are mature. Some are less so.
The beauty of jQuery is that it's great at not interfering with anything else, **so I like to use jQuery with YUI** for my UI widgets. YUI is mature, professional looking "out of the box", and thoroughly tested against all A grade browsers. I can't say the same for all the jQuery UI widgets. | Best UI Library to use with jQuery | [
"",
"javascript",
"jquery",
"user-interface",
"yui",
""
] |
Maybe I am being a bit paranoid, but as I am re-writing a contact module, the following question came to mind:
Can I use unfiltered input in php's native functions?
It is easy to sanitize stuff to put in a database, output to the screen, etc. but I was wondering if for example the following statement could be dangerous:
```
if (file_exists($_POST['brochure'])) {
// do some stuff
}
```
If someone somehow managed to post to that page, could the above code be exploited?
The above code is just an example, I can think of other functions I use when processing a form.
**Edit:** Thanks everybody, the file\_exists in the example is actually part of a sanitation function but when cleaning up, php functions are being used so it is rapidly becoming a chicken and egg story: To use functions, I have to clean up, but to clean up I have to use functions.
Anyway, I have got some fresh ideas now. | Yep. All I'd have to do is post "/etc/passwd", or "includes/dbconnection.php" (or anything) to your page, and depending on what `//do some stuff` actually is, I could possibly delete, modify or read sensitive information. The `file_exists` function itself won't do anything you wouldn't expect, but you can expect malicious users exploiting your logic.
**Always** sanitise your user input. ***Always.*** If you're expecting to only grab files from one particular folder, don't allow .. or / in the input | By itself, that looks reasonably safe, but it could be used to reveal information. It could allow an attack to check for the presence (or absence) of particular files (e.g. `/etc/passwd`, `/proc/*`, etc).
So in this example, you should ensure that `$_POST['brochure']` is sanitised first to only accept inputs that match potentially valid file names. Drop any input that contains `..`, or that starts with a `/`.
Other functions could have potentially much worse side effects... | How safe are php's native functions to use with unfiltered input? | [
"",
"php",
"security",
""
] |
I'm getting some html data from remote server and before displaying it in the UI of application i need to make some changes, i.e. delete counters, replace links, etc. Removing some tag with contents and changing specific link is not a big deal, but when it comes to some advanced processing, i have some problems.There is a need to replace (delete) few html tag attributes (not a tag itself - there are plenty of examples over internet about this). For example : delete all onmouseover handlers from buttons. I know that XPath would be a perfect fit for such problem, but i don't know it at all and although my information is XHTML-complaint, it's stored in a string variable and not queryable :(. So i'm trying to use Regular Expressions to solve this problem, with no success for now. I guess it's a mistake in pattern...
```
public string Processing (string Source, string Tag, string Attribute)
{
return System.Text.RegularExpressions.Regex.Replace(Source, string.Format(@"<{0}(\s+({1}=""([^""]*)""|\w+=(""[^""]*""|\S+)))+>", Tag, Attribute), string.Empty);
}
...
string before = @"<input type=""text"" name=""Input"" id=""Input"" onMouseOver=""some js to be eliminated"">";
string after = Processing(before,"input","onMouseOver");
// expected : <input type="text" name="Input" id="Input">"
``` | That's an interesting approach, but like bobince said, you can only process one attribute per match. This regex will match everything up to the attribute you're interested in:
```
@"(<{0}\b[^>]*?\b){1}=""(?:[^""]*)"""
```
Then you use "$1" as your replacement string to plug back in everything but the attribute.
This approach requires you to make a separate pass over the string for each of your target tag/attribute pairs, and at the beginning of each pass you have to create and compile the regex. Not very efficient, but if the string isn't too large it should be okay. A much bigger problem is that it won't catch duplicate attributes; if there are two "onmouseover" attributes on a button, you'll only catch the first one.
If I were doing this in C# I would probably use the regex to match the target tag, then use a MatchEvaluator to remove all of the target attributes at once. But seriously, if the string really is well-formed XML, there's no excuse for not using XML-specific tools to process it--this is what XML was *invented* for. | > I know that XPath would be a perfect fit for such problem
Quite so. Or any other XML parser-based technique, such as DOM methods.
It's really not a hard thing to learn: stuff your string into the [XmlDocument.LoadXml()](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.loadxml.aspx) method then call [selectNodes()](http://msdn.microsoft.com/en-us/library/hcebdtae.aspx) on it with something like '//tagname[@attrname]' to get a list of elements with the unwanted attribute. Peasy.
> i'm trying to use Regular Expressions to solve this problem, with no success
What is it with regexes? People keep using them even when they know it's the wrong thing, even though they're frequently unreadable and difficult to get right (as the endless “why doesn't my regex work?” questions demonstrate).
So what's so attractive about the damned things? There are several questions on SO every day about parsing [X][HT]ML with regex, all answered “don't use regex, regex is not powerful enough to parse HTML”. But somehow it never gets through.
> I guess it's a mistake in pattern...
Well the pattern appears to be trying to match entire tags to replace with an empty string, which isn't what you want. Instead you'd want to be targeting just the attribute, then to ensure only attributes inside a “<tag ...>” counted, you'd have to use a negative lookbehind assertion — “(?!<tag )”. But you usually can't have a variable-length lookbehind assertion, which you would need to allow other attributes to come between the tag name and the targeted attribute.
Also your ‘\S+’ clause has the potential to gobble up large amounts of unintended content. As you've got well-formed XHTML, you're guaranteed properly quoted attributes, so you don't need that anyway.
But the mistake is not the pattern. It is regex. | C# - Processing html tag attributes | [
"",
"c#",
".net",
"html",
"regex",
""
] |
I can't seem to connect to mysql with a php script, even though I can connect fine with phpmyadmin. I created a user with a password, and gave it the proper priveleges for the db, but everytime it connects it dies saying access denied. I am using xampp on a windows xp box. Firewalls are all disabled, and I've checked the username nad password are correct. Here's the code:
```
$conn=mysql_connect('localhost','westbrookc16','megadots') || die (mysql_error());
```
Do usernames have to be in a specific format or something? | I have a hunch that the problem here is the host you granted it to, though it's really not more than an educated guess. If you grant access myuser@'127.0.0.1' or the servers actual ip address, you won't be allowed to connect using localhost as host. This is due to the fact that when "localhost" is specified as host, php will assume that you want to use a unix socket instead of network sockets, and in that context 127.0.0.1 isn't the same as localhost.
From the manual entry for [mysql\_connect()](https://www.php.net/mysql_connect):
> Note: Whenever you specify "localhost"
> or "localhost:port" as server, the
> MySQL client library will override
> this and try to connect to a local
> socket (named pipe on Windows). If you
> want to use TCP/IP, use "127.0.0.1"
> instead of "localhost". If the MySQL
> client library tries to connect to the
> wrong local socket, you should set the
> correct path as Runtime Configuration
> in your PHP configuration and leave
> the server field blank.
Hope this isn't totally redundant. :) | I've seen this before, where one mysql user logs in via php and another does not. Sometimes the user even works from the commandline but not from php.
It's always been what Emil is reffering two. A mysql user is really user/host pair. so the user megadots@localhost and the user megadots@mycoolhost are listed in the mysql.user table as two seperate records.
If you can login from the command line run this query.
```
SELECT user, host FROM mysql.user
```
you should see the full list of users and thier hosts.
if you recognize the phpMyAdmin user that is working, look at the host column that's probably the host you want to use.
to reset the host run these queries (!be careful doing this your working with the privilages table for the entire mysql installation)
```
update mysql.user set host = 'hostname'
where user = 'username' and host = 'oldhostname';
flush privileges;
```
If you see a record with the username and % as the host that will have priority over everything else, if there are multiple records for the user and % as the host for one of them, it's possible that the username with % as the host has the wrong password and no matter how manytimes you reset username@localhost's password it's invalid because it'll be compared to username@% on login. | can't connect to mysql with php | [
"",
"php",
"mysql",
"xampp",
"wamp",
""
] |
Is it possible on a CLR trigger in SQL Server 2005 to send a message to a queue via MSMQ?
I am using the SQL Server Project type, but System.Messaging does not appear as a reference I can add.
---
Basically I need some type of action to take place (printing) when a row is written to the table. The device generating the row is a hand held scanner that can only do basic operations -- one of which is writing to SQL server over odbc. The initial idea was to just poll the table, grab records, print records, delete records. This will probably work fine, but it seemed like a good case and excuse to learn about message queues. | This might work for you: <http://support.microsoft.com/kb/555070> | Yes, it's possible.
I wouldn't do it in a trigger though: the TXN will stay open longer, it's resource intensive, what if it hangs etc.
Can you update via a stored proc?
Or push a row into a polling table monitored by a SQL agent job that writes to the queue? | SQL Server Trigger - Send Message to Queue | [
"",
"c#",
"sql-server",
"sql-server-2005",
"msmq",
""
] |
I am aware of javascript techniques to detect whether a popup is blocked in other browsers (as described in [the answer to this question](https://stackoverflow.com/questions/2914/how-can-i-detect-if-a-browser-is-blocking-an-popup)). Here's the basic test:
```
var newWin = window.open(url);
if(!newWin || newWin.closed || typeof newWin.closed=='undefined')
{
//POPUP BLOCKED
}
```
But this does not work in Chrome. The "POPUP BLOCKED" section is never reached when the popup is blocked.
Of course, the test is working to an extent since Chrome doesn't actually block the popup, but opens it in a tiny minimized window at the lower right corner which lists "blocked" popups.
What I would like to do is be able to tell if the popup was blocked by Chrome's popup blocker. I try to avoid browser sniffing in favor of feature detection. Is there a way to do this without browser sniffing?
**Edit**: I have now tried making use of `newWin.outerHeight`, `newWin.left`, and other similar properties to accomplish this. Google Chrome returns all position and height values as 0 when the popup is blocked.
Unfortunately, it also returns the same values even if the popup is actually opened for an unknown amount of time. After some magical period (a couple of seconds in my testing), the location and size information is returned as the correct values. In other words, I'm still no closer to figuring this out. Any help would be appreciated. | Well the "magical time" you speak of is probably when the popup's DOM has been loaded. Or else it might be when everything (images, outboard CSS, etc.) has been loaded. You could test this easily by adding a very large graphic to the popup (clear your cache first!). If you were using a Javascript Framework like jQuery (or something similar), you could use the ready() event (or something similar) to wait for the DOM to load before checking the window offset. The danger in this is that Safari detection works in a conflicting way: the popup's DOM will never be ready() in Safari because it'll give you a valid handle for the window you're trying to open -- whether it actually opens or not. (in fact, i believe your popup test code above won't work for safari.)
I think the best thing you can do is wrap your test in a setTimeout() and give the popup 3-5 seconds to complete loading before running the test. It's not perfect, but it should work at least 95% of the time.
Here's the code I use for cross-browser detection, without the Chrome part.
```
function _hasPopupBlocker(poppedWindow) {
var result = false;
try {
if (typeof poppedWindow == 'undefined') {
// Safari with popup blocker... leaves the popup window handle undefined
result = true;
}
else if (poppedWindow && poppedWindow.closed) {
// This happens if the user opens and closes the client window...
// Confusing because the handle is still available, but it's in a "closed" state.
// We're not saying that the window is not being blocked, we're just saying
// that the window has been closed before the test could be run.
result = false;
}
else if (poppedWindow && poppedWindow.test) {
// This is the actual test. The client window should be fine.
result = false;
}
else {
// Else we'll assume the window is not OK
result = true;
}
} catch (err) {
//if (console) {
// console.warn("Could not access popup window", err);
//}
}
return result;
}
```
What I do is run this test from the parent and wrap it in a setTimeout(), giving the child window 3-5 seconds to load. In the child window, you need to add a test function:
function test() {}
The popup blocker detector tests to see whether the "test" function exists as a member of the child window.
ADDED JUNE 15 2015:
I think the modern way to handle this would be to use window.postMessage() to have the child notify the parent that the window has been loaded. The approach is similar (child tells parent it's loaded), but the means of communication has improved. I was able to do this cross-domain from the child:
```
$(window).load(function() {
this.opener.postMessage({'loaded': true}, "*");
this.close();
});
```
The parent listens for this message using:
```
$(window).on('message', function(event) {
alert(event.originalEvent.data.loaded)
});
```
Hope this helps. | Just one improvement to InvisibleBacon's snipet (tested in IE9, Safari 5, Chrome 9 and FF 3.6):
```
var myPopup = window.open("popupcheck.htm", "", "directories=no,height=150,width=150,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,top=0,location=no");
if (!myPopup)
alert("failed for most browsers");
else {
myPopup.onload = function() {
setTimeout(function() {
if (myPopup.screenX === 0) {
alert("failed for chrome");
} else {
// close the test window if popups are allowed.
myPopup.close();
}
}, 0);
};
}
``` | Detect blocked popup in Chrome | [
"",
"javascript",
"google-chrome",
"popup",
""
] |
A String is a reference type even though it has most of the characteristics of a value type such as being immutable and having == overloaded to compare the text rather than making sure they reference the same object.
Why isn't string just a value type then? | Strings aren't value types since they can be huge, and need to be stored on the heap. Value types are (in all implementations of the CLR as of yet) stored on the stack. Stack allocating strings would break all sorts of things: the stack is only 1MB for 32-bit and 4MB for 64-bit, you'd have to box each string, incurring a copy penalty, you couldn't intern strings, and memory usage would balloon, etc...
*(Edit: Added clarification about value type storage being an implementation detail, which leads to this situation where we have a type with value sematics not inheriting from System.ValueType. Thanks Ben.)* | It is not a value type because performance (space and time!) would be terrible if it were a value type and its value had to be copied every time it were passed to and returned from methods, etc.
It has value semantics to keep the world sane. Can you imagine how difficult it would be to code if
```
string s = "hello";
string t = "hello";
bool b = (s == t);
```
set `b` to be `false`? Imagine how difficult coding just about any application would be. | In C#, why is String a reference type that behaves like a value type? | [
"",
"c#",
"string",
"clr",
"value-type",
"reference-type",
""
] |
I've been thinking some about "good practice" regarding package structure within osgi bundles. Currently, on average, we have like 8-12 classes per bundle. One of my initiative/proposal has been to have two packages; com.company\_name.osgi.services.api (for api-related classes/interfaces (which is exported externally) and one package com.company\_name.osgi.services.impl for implementation (not exported)). What are the pros cons of this? Any other suggestions? | You might also consider puting the interfaces in `com.company_name.subsystem`, and the implementation in `com.company_name.subsystem.impl`, the OSGI specific code, if there is any, could be in `com.company_name.subsystem.osgi`.
Sometime you might have multiple implementation of the same interfaces. In this case you could consider - `com.company_name.subsystem.impl1` and `com.company_name.subsystem.impl2`, for example:
```
com.company.scm // the scm api
com.company.scm.git // its git implementaton
com.company.scm.svn // its subversion implementation
com.company.scm.osgi // the place to put an OSGI Activator
```
In this sense package structure could be OSGi agnostic, if you later on move to a different container, you just put an additional
```
com.company.scm.sca // or whatever component model you might think of
```
Always having `api` and `impl` in your package name could be annoying. If in doubt use `impl` but not `api`. | It's not the number of classes that is important but the concepts. In my opinion you should have one conceptual entity in a bundle. In some cases this might be just a few classes in other several packages with 100s of classes.
What it important is that you separate the API and the implementation. One bundle contains the API of your concept and the other the implementation. Like this you can provide different implementations for a well defined API. In some cases this might be even necessary if you want to access the services from a bundle remotely (using e.g. R-OGSi)
The API bundles are then used by code sharing and the services from the implementation bundles by service sharing. Best way to explore those possibilities is to look at the ServiceTrackers. | OSGi bundle's package structure | [
"",
"java",
"osgi",
"modularization",
""
] |
I'm having trouble calling rsync from java on windows vista with cygwin installed.
Its strange as pasting the exact same command into a command shell works fine.
My test java call looks like this.
```
String[] envVars = {"PATH=c:/cygwin/bin;%PATH%"};
File workingDir = new File("c:/cygwin/bin/");
Process p = Runtime.getRuntime().exec("c:/cygwin/bin/rsync.exe -verbose -r -t -v --progress -e ssh /cygdrive/c/Users/dokeeffe/workspace/jrsync/ www.servername.net:/home/dokeeffe/rsync/",envVars,workingDir);
```
Then I start 2 stream reader threads to capture and log the inputStream and errorStream of the Process p.
Here is the output....
```
DEBUG: com.mddc.client.rsync.StreamGobbler - opening connection using: ssh www.servername.net rsync --server -vvtre.iLs . /home/dokeeffe/rsync/
DEBUG: com.mddc.client.rsync.StreamGobbler - rsync: pipe: Operation not permitted (1)
DEBUG: com.mddc.client.rsync.StreamGobbler - rsync error: error in IPC code (code 14) at /home/lapo/packaging/rsync-3.0.4-1/src/rsync-3.0.4/pipe.c(57) [sender=3.0.4]
```
The rsync code where the error happens is pipe.c(57) which is this.
```
if (fd_pair(to_child_pipe) < 0 || fd_pair(from_child_pipe) < 0) {
rsyserr(FERROR, errno, "pipe");
exit_cleanup(RERR_IPC);
}
```
So, for some reason fd\_pair(to\_child\_pipe) is < 0 or fd\_pair(from\_child\_pipe) < 0.
If anyone has any suggestions it would be great as I'm stuck now.
Thanks, | Does cygwin's binary distribution of rsync recognize the ssh command? The command you are trying to execute probably works fine when you put into the shell because something like bash knows how to interpret the ssh command to establish a connection, i.e. use the ssh program to create a connection for the rsync program. From your debugging information I think rsync is expecting a connection but instead receives a string "ssh ..." which it fails to pipe.
To get around this you have to let bash do the work for you. Look at [this page](http://mindprod.com/jgloss/exec.html) in the section on threads to tend the child. You would need to fork an instance of a command shell and write your command to the shell subprocess. So something like this:
```
Process p = Runtime.getRuntime().exec("c:/cygwin/bin/bash.exe");
OutputStreamWriter osw = new OutputStreamWriter(p.getOutputStream());
BufferedWriter bw = new BufferedWriter( osw, 100);
try{
bw.write(command);
bw.close();
}catch(IOExeception e){
System.out.println("Problem writing command.");
}
```
You would probably want to read the processes output too because it will stop executing if you do not read it. The link provided covers the topic well. | Do you have ssh private/public keystore somewhere that you have forgotten about? | Problem with calling rsync+ssh from java on windows | [
"",
"java",
"ssh",
"rsync",
""
] |
I am attempting to create a new COM object in my DLL using the **ATL Simple Object Wizard** in Visual Studio 2005.
I enter the short name for the object, and all of the other fields are derived.
However, when I click *Next* in the wizard, the following error message comes up:
```
Object 'IXxxInterfaceName' already exists
```
I have searched my entire solution for all references to IXxxInterfaceName and can't see it defined anywhere.
How is the wizard determining that it exists already? | I never found out why the wizard determined that the object name existed already - I'm guessing something was cached somewhere that I couldn't track down.
In the end, I appended a 2 to the end of the interface name when creating it which allowed it to be added. Then I replaced all the occurrences of IXxxInterfaceName2 with IXxxInterfaceName. Everything worked after this.
If I ever track down the root cause of this problem, I'll update the answer. | Is it defined in a library you are referencing? | ATL simple object wizard - "Object Xxx already exists" error | [
"",
"c++",
"visual-studio",
"com",
"visual-studio-2005",
"atl",
""
] |
What would be the best way of removing any duplicate characters and sets of characters separated by spaces in string?
I think this example explains it better:
```
foo = 'h k k h2 h'
```
should become:
```
foo = 'h k h2' # order not important
```
Other example:
```
foo = 's s k'
```
becomes:
```
foo = 's k'
``` | ```
' '.join(set(foo.split()))
```
Note that split() by default will split on all whitespace characters. (e.g. tabs, newlines, spaces)
So if you want to split ONLY on a space then you have to use:
```
' '.join(set(foo.split(' ')))
``` | Do you mean?
```
' '.join( set( someString.split() ) )
```
That's the unique space-delimited words in no particular order. | Best way to remove duplicate characters (words) in a string? | [
"",
"python",
"string",
"duplicates",
""
] |
I have an OpenGL program that works on all of my computers but one. It's a desktop with Vista 64 and a Radeon HD4850. The problem seems to be in my call to SwapBuffers(hdc).
It compiles fine and then gives me an exception:
Unhandled exception at 0x00000000 in Program.exe: 0xC0000005: Acces violation.
Using VC++ to break before the call to SwapBuffers shows hdc's value to be:
0xfe011734 {unused=???}
CXX0030: Error: expression cannot be evaluated
Anyone have a clue what could be happening? Is there something about SwapBuffers that would change from one PC to the next? I've gotten it to work on XP32, XP64 and a (different) Vista64.
```
while (!quit)
{
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE))
{
if (msg.message == WM_QUIT)
quit = true;
TranslateMessage(&msg);
DispatchMessage(&msg);
}
renderFrame(); //draws the scene
SwapBuffers(hdc);
if (GetAsyncKeyState(VK_ESCAPE))
shutdown();
think(); //calculates object positions, etc.
}
```
The drivers on the problematic system (HD4850) are up-to-date. I've run, and wrote, the program on another Vista64 system with a Radeon HD4870, also with up-to-date drivers. As far as I know, the drivers for these two cards are nearly identical as both are in the HD48xx series. For that reason it seems odd that the GPU is causing the problem.
Anyway, am I wrong or is this a memory issue? (Access violation)
Also, if I remove the call to SwapBuffers(hdc), the program runs seemingly well, although nothing is drawn, of course, because the framebuffers are never swapped. But it is at least stable.
Call stack (-> is stack ptr):
```
ATKOGL32.dll!6aef27bc()
opengl32.dll!665edb2d()
opengl32.dll!665f80d1()
gdi32.dll!75e14104()
-> MyProg.exe!WinMain(HINSTANCE__ * hinstance=0x009a0000, HINSTANCE__ * hprevinstance=0x00000000, char * lpcmdline=0x003b4a51, int nshowcmd=1) Line 259 + 0xe bytes
MyProg.exe!__tmainCRTStartup() Line 578 + 0x35 bytes
MyProg.exe!WinMainCRTStartup() Line 400
kernel32.dll!7641e3f3()
ntdll.dll!777dcfed()
ntdll.dll!777dd1ff()
```
Heres the assembly (-> is the next instruction to be executed):
```
SwapBuffers(hdc);
009B1B5C mov esi,esp
009B1B5E mov eax,dword ptr [hdc (9BF874h)]
009B1B63 push eax
009B1B64 call dword ptr [__imp__SwapBuffers@4 (0E1040Ch)]
-> 009B1B6A cmp esi,esp
009B1B6C call @ILT+780(__RTC_CheckEsp) (9B1311h)
``` | This is almost definitely a bug in the drivers. The reason why you can't see the value of hdc is because the top stackframe for the crash is actually inside ATKOGL32.dll but since there are no symbols for that the debugger shows you your code. As far as I can tell ATKOGL32.dll is actually an ASUS wrapper for the ATI driver and that's where the crash happens. You might want to install stock ATI drivers from amd.com and see if the crash still persists.
While the driver should never crash no matter what series of OpenGL calls you make, in my experience usually the crashes are the result of some kind of invalid call that your program makes. Technically this should just be ignored and the error state set but thats not always what happens. You can check for any invalid OpenGL calls easily by using a program like gDebugger. | It looks like you could be accessing the HDC after the window has been destroyed, does the problem disappear if you break out of the loop as soon as you get WM\_QUIT ? | SwapBuffers crashing my program! | [
"",
"c++",
"winapi",
"opengl",
""
] |
example strings
```
785*()&!~`a
##$%$~2343
455frt&*&*
```
i want to capture the first and the third but not the second since it doesnt contain any alphabet character plz help | In fact, I think `[a-zA-Z]` might suffice to match your strings.
To capture the whole thing, try: `^.*[a-zA-Z].*$` | Here is one possible way:
```
.*[a-zA-Z]+
``` | Regex - Match a string only when it contains any alphabetic characters | [
"",
"c#",
".net",
"regex",
"match",
"alpha",
""
] |
My second day with ASP.NET MVC and my first request for code on SO (yep, taking a short cut).
I am looking for a way to create a filter that intercepts the current output from an Action and instead outputs JSON (I know of [alternate approaches](http://weblogs.asp.net/omarzabir/archive/2008/10/03/create-rest-api-using-asp-net-mvc-that-speaks-both-json-and-plain-xml.aspx) but this is to help me understand filters). I want to ignore any views associated with the action and just grab the ViewData["Output"], convert it to JSON and send it out the client. Blanks to fill:
`TestController.cs:`
```
[JSON]
public ActionResult Index()
{
ViewData["Output"] = "This is my output";
return View();
}
```
`JSONFilter.cs:`
```
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
/*
* 1. How to override the View template and set it to null?
* ViewResult { ViewName = "" } does not skip the view (/Test/Index)
*
* 2. Get existing ViewData, convert to JSON and return with appropriate
* custom headers
*/
}
```
Update: Community answers led to a fuller implementation for a [filter for JSON/POX](http://aleembawany.com/2009/03/27/aspnet-mvc-create-easy-rest-api-with-json-and-xml/). | I would suggest that what you really want to do is use the Model rather than arbitrary `ViewData` elements and override `OnActionExecuted` rather than `OnActionExecuting`. That way you simply replace the result with your `JsonResult` before it gets executed and thus rendered to the browser.
```
public class JSONAttribute : ActionFilterAttribute
{
...
public override void OnActionExecuted( ActionExecutedContext filterContext)
{
var result = new JsonResult();
result.Data = ((ViewResult)filterContext.Result).Model;
filterContext.Result = result;
}
...
}
[JSON]public ActionResult Index()
{
ViewData.Model = "This is my output";
return View();
}
``` | You haven't mentioned only returning the JSON conditionally, so if you want the action to return JSON every time, why not use:
```
public JsonResult Index()
{
var model = new{ foo = "bar" };
return Json(model);
}
``` | ASP.NET MVC: How to create an action filter to output JSON? | [
"",
"c#",
"asp.net-mvc",
"json",
"action-filter",
""
] |
I have a requirement to be able to track how much a user interacts with the different applications running on their machine. What seemed logical to me was to keep a log of window focus events with timestamps which would tell you what applications were in focus over the course of the day.
We have some other things to do in this application that would be straightforward in Java. However I haven't done any GUI programming in Java so I'm not sure if it's possible to get information about OS-level windows through the awt API. Is that even possible? Would there be another way to do this through JNI or would a native application be required to do this?
PS: I know that this requirement sounds a little nefarious but I am only here to determine whether or not this is technically possible. Please don't shoot the messenger, this wasn't my idea. :) | Focus events might work; you might also want to consider Windows [keyboard and mouse hooks](http://msdn.microsoft.com/en-us/library/ms644990(VS.85).aspx). With any of these approaches, you'll want to create a DLL (native code) and use JNI to access it. | With out resorting to native code I don't think this will be possible. | Tracking OS-level window events in Java | [
"",
"java",
"user-interface",
"awtrobot",
""
] |
I have to find the code blocks from the given code using a regex in C#.
e.g. I have to find the For loop block from the following code
```
For A in 1..10
Loop
stmt1;
For C in cur_op
Loop
stmt2;
end loop;
end loop;
For T in 4..8
loop
stmt3;
end loop;
```
I want to retrieve the code blocks as
```
For A in 1..10
Loop
stmt1;
For C in cur_op
Loop
stmt2;
end loop;
end loop;
```
and
```
For T in 4..8
loop
stmt3;
end loop;
```
Can anyone suggest me a regex for this? | I don't think it's possible. You're asking for a regex parsing a context-free language, and while Perl REs actually can parse CFLs, I'm not sure C# regular expressions can do it, and using it is not the biggest pleasure out there.
Natural solution for your problem would be to create a parser for the language, and get the info from that. You could use a parser generator like CoCo/R or ANTLR. | Well, it's possible to do that with .net Regex, and if you really don't need a real parser, you can go for this solution. It is nicely explained in [this article on codeproject.com](http://www.codeproject.com/KB/recipes/Nested_RegEx_explained.aspx) and I can confirm you that it works well (I used that to implement a simple bbcode parser).
You pattern might look like something like that :
```
String pattern = @"
(?# line 01) For ... in ...
(?# line 02) (?>
(?# line 03) For ... in ... (?<DEPTH>)
(?# line 04) |
(?# line 05) end loop; (?<-DEPTH>)
(?# line 06) |
(?# line 07) .?
(?# line 08) )*
(?# line 09) (?(DEPTH)(?!))
(?# line 10) end loop;
";
``` | Regex to find the code blocks in a C# program | [
"",
"c#",
"regex",
""
] |
I'm using TinyMCE to provide users the capability of simple text formatting (bold, italics, lists) on a textarea form field. Everthing is working properly except that in Internet Explorer (8 but I've read it happens on earlier versions), when users type a URL (e.g. www.google.com) it is automatically converted into an HTML link in the TinyMCE editor as they type. This does not happen in Firefox (3). How can I prevent IE from doing this?
I've initialized TinyMCE with the following:
```
tinyMCE.init({
mode : "textareas",
theme : "simple",
convert_urls : false
});
```
But I don't think convert\_urls is intended to affect the behavior I'm describing: <http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/convert_urls>
I tried:
```
function myCustomURLConverter(url, node, on_save) {
return url;
}
tinyMCE.init({
mode : "textareas",
theme : "simple",
urlconverter_callback : "myCustomURLConverter"
});
```
But similarly I think this is just a way to affect how/whether URLs are converted upon load/save, not to prevent them from being converted to links as users type:
<http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/urlconverter_callback>
The issue I'm trying to fix is described in at least a couple of places:
<http://tinymce.moxiecode.com/punbb/viewtopic.php?id=2182&p=1> (third post, by tommya)
<http://drupal.org/node/149511>
Has anyone seen this before or have any suggestions on how to fix it? The TinyMCE code-base is pretty big and difficult to trace so I was hoping someone could help me isolate the issue a bit. | Doesn't seem to be a way to disable that in IE. It seems to be a 'feature' and it occurs on FCKEditor too. A couple alternatives, remove the element out of the valid elements. <http://wiki.moxiecode.com/index.php/TinyMCE:Configuration/valid_elements>
Or do a serverside tag parse to remove it.
I think this may be the 'feature'
<http://msdn.microsoft.com/en-us/library/aa769893(VS.85).aspx>
And here maybe a hint in getting it to work, but it looked like ActiveX and VB so I got lost pretty quick in my experiment
<http://www.mindfrost82.com/showpost.php?p=1114381&postcount=2> | I think I solved it this way:
```
remove_script_host: "false",
relative_urls: "false",
document_base_url : "http//www.mywebsite.nlhttp://www.mywebsite.nl",
``` | Prevent TinyMCE/Internet Explorer from converting URLs to links | [
"",
"javascript",
"internet-explorer",
"drupal",
"tinymce",
""
] |
When I change some interface things in Java, like the contents of a menu item, and save them, the commit option does not enable. NetBeans does not know that changes have been produced so I cannot commit them. How can I commit them? | Can you commit from the console?
try *svn stat* in the root directory of your project, that should show you the files that have been modified with an M near the name of the file. if you can see them, run *svn ci* to commit all changes.
**Maybe** (and just maybe), svn is ignoring those files on purpose, to check if this is true, run from the console svn propedit svn:ignore .(<- this dot is necesary) in your project root to check if that directory/file/file extension is being ignored.
Good luck! | 1. [Are you using Netbeans 6 or higher?](http://wiki.netbeans.org/FaqSubvesionRequirements) If not, you need to tell Netbeans where the svn executable is (see the link and the [associated FAQ](http://wiki.netbeans.org/NetBeansUserFAQ#section-NetBeansUserFAQ-VersionControlSystems)).
2. Are you sure that your subversion repository is running on a machine that is in sync with your workstation's view of the current time (e.g., synch-ed via [ntp](http://www.ntp.org/))? If the time is enough out of sync, it's possible that the subversion module is missing the update and, therefore, not flagging the change.
3. Also, you should check to make sure that you have an active valid connection to the subversion repository. You can easily do this for the file you just edited: right click on the editor tab for that file and choose Subversion -> Diff or Show Changes or Search History. If any of those fail, your IDE has lost its connection to SVN for some reason.
4. Another possibility is that you didn't succeed with a real checkout: if the `.svn` subdirectories aren't properly configured, the menu item will definitely be disabled. I would recommend that you right click on the project (under Projects) and try Show Changes. If that doesn't succeed, you don't have a valid Subversion checkout and the Netbeans options definitely won't work. | Can't commit to Subversion from NetBeans | [
"",
"java",
"svn",
"netbeans",
""
] |
I am considering starting a project which is used to generate code in Java using annotations (I won't get into specifics, as it's not really relevant). I am wondering about the validity and usefulness of the project, and something that has struck me is the dependence on the Annontation Processor Tool (apt).
What I'd like to know, as I can't speak from experience, is what are the drawbacks of using annotation processing in Java?
These could be anything, including the likes of:
* it is hard to do TDD when writing the processor
* it is difficult to include the processing on a build system
* processing takes a long time, and it is very difficult to get it to run fast
* using the annotations in an IDE requires a plugin for each, to get it to behave the same when reporting errors
These are just examples, not my opinion. I am in the process of researching if any of these are true (including asking this question ;-) )
I am sure there must be drawbacks (for instance, [Qi4J](http://www.qi4j.org/) specifically list not using pre-processors as an advantage) but I don't have the experience with it to tell what they are.
The ony reasonable alternative to using annotation processing is probably to create plugins for the relevant IDEs to generate the code (it would be something vaguely similar to override/implement methods feature that would generate all the signatures without method bodies). However, that step would have to be repeated each time relevant parts of the code changes, annotation processing would not, as far as I can tell.
In regards to the example given with the invasive amount of annotations, I don't envision the use needing to be anything like that, maybe a handful for any given class. That wouldn't stop it being abused of course. | I created a set of JavaBean annotations to generate property getters/setters, delegation, and interface extraction (edit: removed link; no longer supported)
**Testing**
Testing them can be quite trying...
I usually approach it by creating a project in eclipse with the test code and building it, then make a copy and turn off annotation processing.
I can then use Eclipse to compare the "active" test project to the "expected" copy of the project.
I don't have too many test cases yet (it's very tedious to generate so many combinations of attributes), but this is helping.
**Build System**
Using annotations in a build system is actually very easy. Gradle makes this incredibly simple, and using it in eclipse is just a matter of making a plugin specifying the annotation processor extension and turning on annotation processing in projects that want to use it.
I've used annotation processing in a continuous build environment, building the annotations & processor, then using it in the rest of the build. It's really pretty painless.
**Processing Time**
I haven't found this to be an issue - be careful of what you do in the processors. I generate a lot of code in mine and it runs fine. It's a little slower in ant.
Note that Java6 processors can run a little faster because they are part of the normal compilation process. However, I've had trouble getting them to work properly in a code generation capacity (I think much of the problem is eclipse's support and running multiple-phase compiles). For now, I stick with Java 5.
**Error Processing**
This is one of the best-thought-through things in the annotation API. The API has a "messenger" object that handles all errors. Each IDE provides an implementation that converts this into appropriate error messages at the right location in the code.
The only eclipse-specific thing I did was to cast the processing environment object so I could check if it was bring run as a build or for editor reconciliation. If editing, I exit. Eventually I'll change this to just do error checking at edit time so it can report errors as you type. Be careful, though -- you need to keep it *really* fast for use during reconciliation or editing gets sluggish.
**Code Generation Gotcha**
[added a little more per comments]
The annotation processor specifications state that you are not allowed to modify the class that contains the annotation. I suspect this is to simplify the processing (further rounds do not need to include the annotated classes, preventing infinite update loops as well)
You *can* generate other classes, however, and they recommend that approach.
I generate a superclass for all of the get/set methods and anything else I need to generate. I also have the processor verify that the annotated class extends the generated class. For example:
```
@Bean(...)
public class Foo extends FooGen
```
I generate a class in the same package with the name of the annotated class plus "Gen" and verify that the annotated class is declared to extend it.
I have seen someone use the compiler tree api to modify the annotated class -- this is against spec and I suspect they'll plug that hole at some point so it won't work.
I would recommend generating a superclass.
**Overall**
I'm *really* happy using annotation processors. Very well designed, especially looking at IDE/command-line build independence.
For now, I would recommend sticking with the Java5 annotation processors if you're doing code generation - you need to run a separate tool called apt to process them, then do the compilation.
Note that the API for Java 5 and Java 6 annotation processors is different! The Java 6 processing API is better IMHO, but I just haven't had luck with java 6 processors doing what I need yet.
When Java 7 comes out I'll give the new processing approach another shot.
Feel free to email me if you have questions. (scott@javadude.com)
Hope this helps! | I think if annotation processor then definitely use the Java 6 version of the API. That is the one which will be supported in the future. The Java 5 API was still in the in the non official com.sun.xyz namespace.
I think we will see a lot more uses of the annotation processor API in the near future. For example Hibernate is developing a processor for the new JPA 2 query related static meta model functionality. They are also developing a processor for validating Bean Validation annotations. So annotation processing is here to stay.
Tool integration is ok. The latest versions of the mainstream IDEs contain options to configure the annotation processors and integrate them into the build process. The main stream build tools also support annotation processing where maven can still cause some grief.
Testing I find a big problem though. All tests are indirect and somehow verify the end result of the annotation processing. I cannot write any simple unit tests which just assert simple methods working on TypeMirrors or other reflection based classes. The problem is that one cannot instantiate these type of classes outside the processors compilation cycle. I don't think that Sun had really testability in mind when designing the API. | The drawbacks of annotation processing in Java? | [
"",
"java",
""
] |
How would one go about implementing the indexing "operator" on a class in C# ?
```
class Foo {
}
Foo f = new Foo();
f["key"] = "some val";
f["other key"] = "some other val";
```
in C# ? Searched MSDN but came up empty. | Here is an example using a dictionary as storage:
```
public class Foo {
private Dictionary<string, string> _items;
public Foo() {
_items = new Dictionary<string, string>();
}
public string this[string key] {
get {
return _items[key];
}
set {
_items[key]=value;
}
}
}
``` | ```
private List<string> MyList = new List<string>();
public string this[int i]
{
get
{
return MyList[i];
}
set
{
MyList[i] = value;
}
}
```
You can define several accessors for different types (ie string instead of int for example) if it's needed. | Implementing indexing "operator" in on a class in C# | [
"",
"c#",
".net",
"asp.net",
""
] |
Quick question: When do you decide to use properties (in C#) and when do you decide to use methods?
We are busy having this debate and have found some areas where it is debatable whether we should use a property or a method. One example is this:
```
public void SetLabel(string text)
{
Label.Text = text;
}
```
In the example, `Label` is a control on a ASPX page. Is there a principle that can govern the decision (in this case) whether to make this a method or a property.
I'll accept the answer that is most general and comprehensive, but that also touches on the example that I have given. | From the [Choosing Between Properties and Methods](https://msdn.microsoft.com/en-us/library/ms229054(v=vs.100).aspx) section of Design Guidelines for Developing Class Libraries:
> In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use. | Yes, if all you're doing is getting and setting, use a property.
If you're doing something complex that may affect several data members, a method is more appropriate. Or if your getter takes parameters or your setter takes more than a value parameter.
In the middle is a grey area where the line can be a little blurred. There is no hard and fast rule and different people will sometimes disagree whether something should be a property or a method. The important thing is just to be (relatively) consistent with how **you** do it (or how your team does it).
They are largely interchangeable but a property signals to the user that the implementation is relatively "simple". Oh and the syntax is a little cleaner.
Generally speaking, my philosophy is that if you start writing a method name that begins with get or set and takes zero or one parameter (respectively) then it's a prime candidate for a property. | Properties vs Methods | [
"",
"c#",
"properties",
"methods",
""
] |
In this simplified example I have a generic class, and a method that returns a Map regardless of the type parameter. Why does the compiler wipe out the types on the map when I don't specify a type on the containing class?
```
import java.util.Map;
public class MyClass<T>
{
public Map<String, String> getMap()
{
return null;
}
public void test()
{
MyClass<Object> success = new MyClass<Object>();
String s = success.getMap().get("");
MyClass unchecked = new MyClass();
Map<String, String> map = unchecked.getMap(); // Unchecked warning, why?
String s2 = map.get("");
MyClass fail = new MyClass();
String s3 = fail.getMap().get(""); // Compiler error, why?
}
}
```
I get this compiler error.
```
MyClass.java:20: incompatible types
found : java.lang.Object
required: java.lang.String
String s3 = fail.getMap().get(""); // Compiler error
``` | Got it. This actually *isn't* a bug, strange as it might seem.
From [section 4.8 (raw types) of the JLS](http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#110257):
> The type of a constructor (§8.8),
> instance method (§8.8, §9.4), or
> non-static field (§8.3) M of a raw
> type C that is not inherited from its
> superclasses or superinterfaces is the
> erasure of its type in the generic
> declaration corresponding to C. The
> type of a static member of a raw type
> C is the same as its type in the
> generic declaration corresponding to
> C.
So even though the method's type signature doesn't use any type parameters of the class itself, type erasure kicks in and the signature becomes effectively
```
public Map getMap()
```
In other words, I think you can imagine a raw type as being the same API as the generic type but with all `<X>` bits removed from *everywhere* (in the API, not the implementation).
EDIT: This code:
```
MyClass unchecked = new MyClass();
Map<String, String> map = unchecked.getMap(); // Unchecked warning, why?
String s2 = map.get("");
```
compiles because there's an implicit but unchecked conversion from the raw `Map` type to `Map<String, String>`. You can get the same effect by making an explicit conversion (which does nothing at execution time) in the last case:
```
// Compiles, but with an unchecked warning
String x = ((Map<String, String>)fail.getMap()).get("");
``` | Hm ... unfortunately I can't tell you why it fails. But I can give you a simple workaround:
Change the type of `fail` to `MyClass<?>`, then it will compile just fine. | Why won't this generic java code compile? | [
"",
"java",
"generics",
""
] |
How can I tell if the substring "template" (for example) exists inside a String object?
It would be great if it was not a case-sensitive check. | Use a regular expression and mark it as case insensitive:
```
if (myStr.matches("(?i).*template.*")) {
// whatever
}
```
The **(?i)** turns on case insensitivity and the **.\*** at each end of the search term match any surrounding characters (since **String.matches** works on the entire string). | [String.indexOf(String)](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#indexOf(java.lang.String))
For a case insensitive search, to toUpperCase or toLowerCase on both the original string and the substring before the indexOf
```
String full = "my template string";
String sub = "Template";
boolean fullContainsSub = full.toUpperCase().indexOf(sub.toUpperCase()) != -1;
``` | How do I see if a substring exists inside another string in Java 1.4? | [
"",
"java",
"string",
"substring",
""
] |
I wondering if a can make a form with silverlight like an HTML form and submit its data to a server to store them on a database.
Can I do that?
Thanks! | You can definately do this. But you cannot talk to a server directly via Silverlight like you can with ASP.Net. You have to use web services to achieve this.
There are a number of ways to do this:
1. Use **Web Services** (Old ASMX; This has security issues)
2. Use **WCF** (For complex systems)
3. Use **ADO.Net Data Services** (This is probably the easiest and fastest way to achieve this) using ADO.Net Entity Framework.
4. Use **RIA Services** (In CTP now for Silverlight 3) | Just take a look at some videos over here:
<http://silverlight.net/learn/videocat.aspx?cat=2#HDI2WebServices>
basically, you build your data model with Linq (or some other orm), expose that data through Select/Update/Delete/... methods with web service (new WCF or old one, ASMX), and consume that in silverlight. Silverlight automatically make proxy classes for communication. In Silverlight, you can use it's rich databinding capabilities, so you do not need to worry about how data are transferred, serialized, read from UI and similar.
Video tutorials on silverlight.net web explains most of stuff regarding programming SL2 really good. | Silverlight and a form application | [
"",
"c#",
"asp.net",
"silverlight",
""
] |
Google provides APIs for a number of their services and bindings for several languages. However, not everything is supported. So this question comes from my incomplete understanding of things like wget, curl, and the various web programming libraries.
1. How can I authenticate programmatically to Google?
2. Is it possible to leverage the existing APIs to gain access to the unsupported parts of Google?
Once I have authenticated, how do I use that to access my restricted pages? It seems like the API could be used do the login and get a token, but I don't understand *what I'm supposed to do next* to fetch a restricted webpage.
Specifically, I am playing around with Android and want to write a script to grab my app usage stats from the Android Market once or twice a day so I can make pretty charts. My most likely target is python, but code in any language illustrating non-API use of Google's services would be helpful. Thanks folks. | You can get the auth tokens by authenticating a particular service against <https://www.google.com/accounts/ClientLogin>
E.g.
```
curl -d "Email=youremail" -d "Passwd=yourpassword" -d "service=blogger" "https://www.google.com/accounts/ClientLogin"
```
Then you can just pass the auth tokens and cookies along when accessing the service. You can use firebug or temper data firefox plugin to find out the parameter names etc. | You can use something like mechanize, or even urllib to achieve this sort of thing. As a tutorial, you can check out my article [here](http://ssscripting.wordpress.com/2009/03/17/how-to-submit-a-form-programmatically/) about programmatically submitting a form .
Once you authenticate, you can use the cookie to access restricted pages. | Programmatic login and use of non-api-supported Google services | [
"",
"python",
"curl",
"gdata-api",
""
] |
I'm writing a Python function to split text into words, ignoring specified punctuation. Here is some working code. I'm not convinced that constructing strings out of lists (buf = [] in the code) is efficient though. Does anyone have a suggestion for a better way to do this?
```
def getwords(text, splitchars=' \t|!?.;:"'):
"""
Generator to get words in text by splitting text along specified splitchars
and stripping out the splitchars::
>>> list(getwords('this is some text.'))
['this', 'is', 'some', 'text']
>>> list(getwords('and/or'))
['and', 'or']
>>> list(getwords('one||two'))
['one', 'two']
>>> list(getwords(u'hola unicode!'))
[u'hola', u'unicode']
"""
splitchars = set(splitchars)
buf = []
for char in text:
if char not in splitchars:
buf.append(char)
else:
if buf:
yield ''.join(buf)
buf = []
# All done. Yield last word.
if buf:
yield ''.join(buf)
``` | You can use re.split
```
re.split('[\s|!\?\.;:"]', text)
```
However if the text is very large the resulting array may be consuming too much memory. Then you may consider re.finditer:
```
import re
def getwords(text, splitchars=' \t|!?.;:"'):
words_iter = re.finditer(
"([%s]+)" % "".join([("^" + c) for c in splitchars]),
text)
for word in words_iter:
yield word.group()
# a quick test
s = "a:b cc? def...a||"
words = [x for x in getwords(s)]
assert ["a", "b", "cc", "def", "a"] == words, words
``` | <http://www.skymind.com/~ocrow/python_string/> talks about several ways of concatenating strings in Python and assesses their performance as well. | Effective way to iteratively append to a string in Python? | [
"",
"python",
"string",
"split",
"append",
"generator",
""
] |
Many times, I find myself having to define a container for multi-dimensional data.
Let's take an example: I have many Chips, each Chip has many Registers, each Register has many Cells, and each Cell has many Transistors.
At some stage of my C++ program I have to read this data, and later I have to use it.
I cannot use any external storage for this data: file, data-base, etc.
So, should I create some multi-dimensional STL container? A map of maps of vectors, or something like that... ?
Or should I create classes (structs) for each of them? Cell class that contains a vector of Transistors, and then a Register class that contains a vector of Cells, etc? But what if later I want to access my data by Transistor, and not by Chip?
Any other way?
Thank you
EDIT: Forgot to mention: I cannot use boost. | **Implement full classes for them. Your code will be cleaner in the end.**
Whenever I ignore this axiom, it comes back to haunt me. I implemented a hierarchical 3-tiered string collection in terms of std::pairs of std::strings and std:pairs. It was quick and simple, and when I had to replace one layer and then another with a class to contain extra attributes, it was surprisingly easy to do. But in the end, the code was a mess and I wasn't happy documenting it. Lesson learned again, and again, and again... | You need to map your domain.
> So, should I create some multi-dimensional STL container? A map of maps of vectors, or something like that... ?
Each vector/map will contain objects of some type. That brings us to your next question :)
> Or should I create classes (structs) for each of them?
Looks like that is what you need at the very least.
> Cell class that contains a vector of Transistors, and then a Register class that contains a vector of Cells, etc?
Look at both `has-a` and `is-implemented-in-terms-of` designs.
> But what if later I want to sort my data by Transistor, and not by Chip?
What data? You can always pass around comparators depending on the context. Also, ask yourself if you really need to expose the `Transistor` level details to someone working with a `Chip`. That'll help get started. | C++ multi-dimensional data handling | [
"",
"c++",
"oop",
"stl",
"containers",
""
] |
Here is the premise:
I have a desktop that I need to be able to start up and stop applications on, but cannot get remote access to. What I had in mind is setting up a service on the machine that will start/stop a list of applications as told. This windows service will periodically pole a web service for new commands and execute them accordingly.
These are my questions.
1) Is this the easiest solution? What else would you recommend?
2) How hard is it to run an exe from a windows service? How about stopping one?
This isn't for a project or anything, just something I am interested in implementing (mostly for fun). Any answers or even thoughts are appreciated. General discussion is also welcome (feel free to leave comments). | As for creating the Windows service itself in C#, see my post [here](https://stackoverflow.com/questions/593454/easiest-language-to-create-a-windows-service/593803#593803).
The polling mechanism would work, but in general, I prefer event-driven processes instead of polling processes. You didn't mention what version of .NET you were using, but if it is .NET 3.0/3.5, I would suggest using WCF. When the command is posted to the web service, the web service could send the command to the Windows service to be executed. Pretty straightforward. Juval Lowy, the author of Programming WCF Services, offers a bunch of WCF examples/libraries that are free to use at his [website](http://www.idesign.net). | So I guess [PsExec](http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx) is out of question?
Other than that, it's not hard to implement running of programs inside a Win service. Simply use the .NET Process class to do it, sample from my code:
```
ProcessStartInfo processStartInfo = new ProcessStartInfo (programExePath, commandLineArgs);
consoleLogger.WriteLine (log, Level.Debug, "Running program {0} ('{1}')", programExePath, commandLineArgs);
processStartInfo.CreateNoWindow = true;
processStartInfo.ErrorDialog = false;
processStartInfo.RedirectStandardError = true;
processStartInfo.RedirectStandardOutput = true;
processStartInfo.UseShellExecute = false;
using (Process process = new Process ())
{
process.StartInfo = processStartInfo;
process.ErrorDataReceived += new DataReceivedEventHandler (process_ErrorDataReceived);
process.OutputDataReceived += new DataReceivedEventHandler (process_OutputDataReceived);
process.Start ();
process.BeginOutputReadLine ();
process.BeginErrorReadLine ();
if (false == process.WaitForExit ((int)TimeSpan.FromHours(1).TotalMilliseconds))
throw new ArgumentException("The program '{0}' did not finish in time, aborting.", programExePath);
if (process.ExitCode != 0)
throw new ArgumentException ("failed.");
}
``` | Windows Service Application Controller | [
"",
"c#",
".net",
"windows-services",
""
] |
Most Java code is also syntactically valid Groovy code. However, there are a few exceptions which leads me to my question:
Which constructs/features in Java are syntactically invalid in Groovy? **Please provide concrete examples of Java code (Java 1.6) that is NOT valid Groovy code (Groovy 1.6).**
**Update:**
So far we've got five examples of syntactically valid Java code that is not valid Groovy code:
1. Array initializations
2. Inner classes
3. `def` is a keyword in Groovy, but not in Java
4. `"$$"`-strings - parsed as an invalid `GString`s in Groovy
5. Non-static initialization blocks `-- class Foo { Integer x; { x = 1; } }`
Is this the complete list? Any further examples?
**Update #1:** I've started a bounty to bump this question. The bounty will be granted to the person who provides the most comprehensive list of examples. So far we've uncovered five examples, but I'm sure there a quite some more out there. So keep them coming! | Here is a list of items that are valid Java 6, but not valid Groovy 1.6. This isn't a complete list, but I think it covers most of the cases. Some of these are permitted by later Groovy versions as noted below.
(By the way, I think you should note that non-static initialization blocks DO work in Groovy.)
**Any inner class declaration in Groovy 1.6 ([1.7 added inner classes](http://groovy-lang.org/releasenotes/groovy-1.7.html)):**
including static,
```
public class Outer{
static class Inner{}
}
```
non-static,
```
public class Outer{
class Inner{}
}
```
local classes,
```
public class Outer{
public static void main(String[] args) {
class Local{}
}
}
```
and anonymous classes
```
java.util.EventListener listener=new java.util.EventListener(){};
```
**Using Groovy keywords as variables won't work in any Groovy version:**
```
int def;
int in;
int threadsafe;
int as;
```
**Java array initialization**
```
String[] stuff=new String[]{"string"};
int[] array={1,2,3};
```
Use the Groovy array-literal format by changing `{...}` to `[...]`.
**Using dollar signs in strings where what follows isn't a valid expression**
```
String s="$$";
String s="$def";
String s="$enum";
String s="$;";
String s="$\\";
//etc.
```
**More than one initializer in a for loop**
```
for (int i=0, j=0; i < 5; i++) {}
```
**More than one increment in a for loop**
```
int j=0;
for (int i=0; i < 5; i++,j++) {}
```
**Breaking up some expressions using newlines**
```
int a= 2
/ 2
;
```
Hint: use a backslash line-continuation in Groovy
```
int a= 2 \
/ 2 \
;
```
**Ending switch with a case that has no body**
```
switch(a){
case 1:
}
```
**Having a default in a switch with no body**
Applies in both cases where default is at the end
```
int a=0;
switch(a){
default:
}
```
or somewhere in the middle
```
switch(a){
default:
case 1:
break;
}
```
**Annotations with lists**
```
@SuppressWarnings({"boxing","cast"})
```
Hint: use Groovy list-literal syntax instead:
```
@SuppressWarnings(["boxing","cast"])
```
**Native method declaration**
```
public native int nativeMethod();
```
\*\*Class per enum in 1.6 (valid in later Groovy versions) \*\*
```
public enum JavaEnum{
ADD{
public String getSymbol(){ return "+"; }
};
abstract String getSymbol();
}
```
**Do loop**
```
do{
System.out.println("stuff");
}while(true);
```
**Equality**
While technically `==` is valid Groovy and Java, it's semantically different. It's one of the reasons you can't rely on just compiling Java as Groovy without changes. Worse, it might seem to work sometimes due to Java string interning.
The example was too long to add to an existing answer, but the point is that **Java code that's *syntatically* valid as Groovy might behave differently at runtime**.
To get the same result as Java's `x == y` for two not-null objects you need `x.is(y)` in Groovy. `x == y` is valid Groovy, it just *does something different*.
[The Groovy documentation has a more detailed and broader list of differences](http://groovy-lang.org/differences.html). | Ok, heres one point:
```
int[] i = { 0, 1, 2 };
```
That is good syntax in java, bad in groovy.
I don't think you want to assume any given java code will be equivalent in groovy. [This site](http://groovy-lang.org/differences.html) describes some of the differences, which includes things as basic as == not meaning the same thing in both languages. Also, static array initialization is different, and there are no anonymous inner classes.
This compiles fine in Java 1.6
```
public class Test2 {
int[] i = { 0, 1, 2 };
private class Class1 {
public void method1() {
if (i[2] == 2) {
System.out.println("this works");
}
}
}
public void method1() {
Class1 class1 = new Class1();
class1.method1();
}
}
```
But is so wrong in Groovy. It gives the following errors in Groovy 1.6:
```
unexpected token: 1 @ line 2, column 14.
Class definition not expected here. Possible attempt to use inner class. Inner classes not supported, perhaps try using a closure instead. at line: 4 column: 2.
```
If you fix those things, it does print what you expect, though.
If you're looking for newer language syntax issues, like generics or annotations, Groovy supports both of those, though not fully. | Valid Java code that is NOT valid Groovy code? | [
"",
"java",
"grails",
"groovy",
""
] |
How to retrieve at runtime the version info stored in a Windows exe/dll? This info is manually set using a resource file. | Here is a C++ way of doing it, using the standard Windows API functions:
```
try
{
TCHAR szFileName[ MAX_PATH ];
if( !::GetModuleFileName( 0, szFileName, MAX_PATH ) )
throw __LINE__;
DWORD nParam;
DWORD nVersionSize = ::GetFileVersionInfoSize( szFileName, &nParam );
if( !nVersionSize )
throw __LINE__;
HANDLE hMem = ::GetProcessHeap();
if( !hMem )
throw __LINE__;
LPVOID lpVersionData = ::HeapAlloc( hMem, 0, nVersionSize );
if( !lpVersionData )
throw __LINE__;
if( !::GetFileVersionInfo( szFileName, 0, nVersionSize, lpVersionData ) )
throw __LINE__;
LPVOID pVersionInfo;
UINT nSize;
if( !::VerQueryValue( lpVersionData, _T("\\"), &pVersionInfo, &nSize ) )
throw __LINE__;
VS_FIXEDFILEINFO *pVSInfo = (VS_FIXEDFILEINFO *)pVersionInfo;
CString strVersion;
strVersion.Format( _T(" version %i.%i.%i.%i"),
pVSInfo->dwProductVersionMS >> 16,
pVSInfo->dwProductVersionMS & 0xFFFF,
pVSInfo->dwProductVersionLS >> 16,
pVSInfo->dwProductVersionLS & 0xFFFF
);
GetDlgItem( IDC_ABOUT_VERSION )->SetWindowText( strAppName + strVersion );
if( !HeapFree( hMem, 0, lpVersionData ) )
throw __LINE__;
}
catch( int err )
{
ASSERT( !err ); // always break on debug builds to inspect error codes and such
DWORD dwErr = ::GetLastError();
// handle memory cleanup...
}
```
Note that the *catch* part is purely educational - in a real situation you would properly cleanup after the memory allocation and actually use the error code! | Here's a Delphi 7 version:
```
uses Windows, SysUtils;
function GetEXEVersion(exename: string; const Fmt : string = '%d.%d.%d.%d'): string;
{
credit to martinstoeckli@gmx.ch
( http://martinstoeckli.ch/delphi/delphi.html#AppVersion )
}
var
iBufferSize, iDummy : dword;
pBuffer, pFileInfo : Pointer;
iVer : array[1..4] of word;
begin
Result := '';
iBufferSize := GetFileVersionInfoSize(PChar(exename), iDummy);
if iBufferSize > 0 then begin
GetMem(pBuffer, iBufferSize);
try
GetFileVersionInfo(PChar(exename), 0, iBufferSize, pBuffer);
VerQueryValue(pBuffer, '\', pFileInfo, iDummy);
iVer[1] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
iVer[2] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionMS);
iVer[3] := HiWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
iVer[4] := LoWord(PVSFixedFileInfo(pFileInfo)^.dwFileVersionLS);
finally FreeMem(pBuffer);
end;
Result := Format(Fmt, [iVer[1],iVer[2],iVer[3],iVer[4]] );
end;
end;
``` | How might I retrieve the version number of a Windows EXE or DLL? | [
"",
"c++",
"windows",
"winapi",
"version",
""
] |
At the moment my code successfully sets the value of fields/properties/arrays of an object using reflection given a path to the field/property from the root object.
e.g.
```
//MyObject.MySubProperty.MyProperty
SetValue('MySubProperty/MyProperty', 'new value', MyObject);
```
The above example would set 'MyProperty' property of the 'MyObject' object to 'new value'
I'm unable to use reflection to set a value of a field in a struct which is part of an array of structs because the struct is a value type (within an array).
Here are some test classes/structs...
```
public class MyClass {
public MyStruct[] myStructArray = new MyStruct[] {
new MyStruct() { myField = "change my value" }
};
public MyStruct[] myOtherStructArray = new MyStruct[] {
new MyStruct() { myOtherField = "change my value" },
new MyStruct() { myOtherField = "change my other value" }
};
}
public struct MyStruct { public string myField; public string myOtherField; }
```
Below is how I successfully set the value of normal properties/fields and props/fields in lists...
```
public void SetValue(string pathToData, object newValue, object rootObject)
{
object foundObject = rootObject;
foreach (string element in pathToData.Split("/"))
{
foundObject = //If element is [Blah] then get the
//object at the specified list position
//OR
foundObject = //Else get the field/property
}
//Once found, set the value (this is the bit that doesn't work for
// fields/properties in structs in arrays)
FieldInf.SetValue(foundObject, newValue);
}
object myObject = new MyClass();
SetValue("/myStructArray/[0]/myField", "my new value", myObject);
SetValue("/myOtherStructArray/[1]/myOtherField", "my new value", myObject);
```
After that I want the myObject.myStructArray[0].myField = ''my new value" and
myObject.myOtherStructArray[1].myOtherField = ''my new value"
All I need is a replacement for the 'FieldInf.SetValue(foundObject, newValue);' line
thanks in advance | Get the FieldInfo for the array object (not the specific element).
If it's an array, cast it to a System.Array and use Array.SetValue to set the object's value. | Due to boxing/unboxing, the following should do exactly what you are looking for, for any kind of struct member:
```
var property = this.GetType().GetProperty(myPropertyName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
ValueType vthis = this;
property.SetValue(vthis, myValue, null); // myValue is the value/object to be assigned to the property.
this = (UnderlyingsList)vthis;
``` | Use reflection to set the value of a field in a struct which is part of an array of structs | [
"",
"c#",
"arrays",
"reflection",
"struct",
"field",
""
] |
I have a php script that checks for updates on many (thousands) of sites.
On occasion (more frequently as the number of sites increases), I get an execution timeout on the update of one of these sites, and the whole script goes down the drain.
The best idea I could come up with is to fork each update, so if it dies, the overall update just continues.
From what I gathered, it seems PHP threading isn't something to rely on, especially on a windows platform (which I unfortunately have to work on).
I thought about using curl as a forking mechanism, but won't it be much more costly for the server (in time and processing power)?
I'd be happy to hear some ideas and experience about PHP forking/threading...
thanks,
Omer. | Well, at the end I went for curl, and it works just fine.
I needed a cross-platform solution, as I develop on a Mac while in this case the production serer is Windows. That meant `pcntl` was out of the question.
I was worried that sending thousands of curl requests to my own server might hog it and bother users on the site at the time, but I was mistaken.
I did, however, have to add a `set_time_limit(0)` to the script that initiates all the curl calls, otherwise it just times out. | If you're going to use cURL look into the multi\* family of methods which allows you to streamline cURL and interacting with a set of sites. That being said, you could also set your max execution time (via ini\_set) to some arbitrarily high number and/or keep your own watchdog counter so that you never let it get too high.
But yeah, ultimately are going to run into issues and the lack of full thread support in PHP. So your best bet is to look at other alternatives, e.g. other languages/platforms that provide native threading support. | What's the best way to fork/thread in PHP on Win? | [
"",
"php",
"windows",
"multithreading",
"fork",
""
] |
I am currently writing a WPF application which does command-line argument handling in App.xaml.cs (which is necessary because the Startup event seems to be the recommended way of getting at those arguments). Based on the arguments I want to exit the program at that point already which, as far as I know, should be done in WPF with `Application.Current.Shutdown()` or in this case (as I am in the current application object) probably also just `this.Shutdown()`.
The only problem is that this doesn't seem to work right. I've stepped through with the debugger and code after the `Shutdown()` line still gets executed which leads to errors afterwards in the method, since I expected the application not to live that long. Also the main window (declared in the StartupUri attribute in XAML) still gets loaded.
I've checked the documentation of that method and found nothing in the remarks that tell me that I shouldn't use it during `Application.Startup` or `Application` at all.
So, what is the right way to exit the program at that point, i. e. the `Startup` event handler in an `Application` object? | First remove the StartupUri property from App.xaml and then use the following:
```
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
bool doShutDown = ...;
if (doShutDown)
{
Shutdown(1);
return;
}
else
{
this.StartupUri = new Uri("Window1.xaml", UriKind.Relative);
}
}
``` | If you remove the StartupUri from app.xaml for an application with a MainWindow you need to make sure you make the following call in your OnStartup method otherwise the application will not terminate when your MainWindow closes.
```
this.ShutdownMode = System.Windows.ShutdownMode.OnMainWindowClose;
```
@Frank Schwieterman, something along these lines may help you with your console window issue. | Shutting down a WPF application from App.xaml.cs | [
"",
"c#",
"wpf",
"application-shutdown",
""
] |
Searched for a while, but I can't figure out why this would raise a bus error.
Any help would be much appreciated.
```
typedef struct {
set<int> pages;
} someStruct;
...
void someFunction() {
...
someStruct *a = createSomeStruct(); // just mallocs and returns
a->pages.insert(5);
...
}
``` | malloc doesn't initialize the memory it allocates. try with new. | It is possible to initialise the set, if you really do have to use malloc for some reason:
```
typedef struct {
set<int> pages;
} someStruct;
...
void someFunction() {
...
someStruct *a = createSomeStruct();
a->pages.insert(5);
...
}
...
someStruct *createSomeStruct(void) {
someStruct *a = (someStruct *) malloc(sizeof(*a));
new(&a->pages) set<int>;
return a;
}
``` | "Bus error" accessing a set<int> from a struct | [
"",
"c++",
"stl",
"struct",
"bus-error",
""
] |
How do I remove an items from a data bound array? My code follows.
```
for(var i = 0; i < listBox.selectedIndices.length; i++) {
var toRemove = listFiles.selectedIndices[i];
dataArray.splice(toRemove, 1);
}
```
Thanks in advance!
**Edit** Here is my swf. The Add Photos works except when you remove items.
<http://www.3rdshooter.com/Content/Flash/PhotoUploader.html>
1. Add 3 photos different.
2. Remove 2nd photo.
3. Add a different photo.
4. SWF adds the 2nd photo to the end.
Any ideas on why it would be doing this?
**Edit 2** Here is my code
```
private function OnSelectFileRefList(e:Event):void
{
Alert.show('addstart:' + arrayQueue.length);
for each (var f:FileReference in fileRefList.fileList)
{
var lid:ListItemData = new ListItemData();
lid.fileRef = f;
arrayQueue[arrayQueue.length]=lid;
}
Alert.show('addcomplete:' + arrayQueue.length);
listFiles.executeBindings();
Alert.show(ListItemData(arrayQueue[arrayQueue.length-1]).fileRef.name);
PushStatus('Added ' + fileRefList.fileList.length.toString() + ' photo(s) to queue!');
fileRefList.fileList.length = 0;
buttonUpload.enabled = (arrayQueue.length > 0);
}
private function OnButtonRemoveClicked(e:Event):void
{
for(var i:Number = 0; i < listFiles.selectedIndices.length; i++) {
var toRemove:Number = listFiles.selectedIndices[i];
//Alert.show(toRemove.toString());
arrayQueue.splice(toRemove, 1);
}
listFiles.executeBindings();
Alert.show('removecomplete:' + arrayQueue.length);
PushStatus('Removed photos from queue.');
buttonRemove.enabled = (listFiles.selectedItems.length > 0);
buttonUpload.enabled = (arrayQueue.length > 0);
}
``` | It would definitely be helpful to know two things:
1. Which version of ActionScript are you targeting?
2. Judging from the behavior of your application, the error isn't occurring when the user removes an item from the list of files to upload. Looks more like an issue with your logic when a user adds a new item to the list. Any chance you could post that code as well?
**UPDATE**:
Instead of: `arrayQueue[arrayQueue.length]=lid`
Try: `arrayQueue.push(lid)`
That will add a new item to the end of the array and push the item in to that spot.
**UPDATE 2**:
Ok, did a little more digging. Turns out that the fileList doesn't get cleared every time the dialog is opened (if you're not creating a new instance of the FileReferenceList each time the user selects new files). You need to call splice() on the fileList after you add each file to your Array.
Try something like this in your AddFile() method...
```
for(var j:int=0; j < fileRefList.fileList.length; j++)
{
arrayQueue.push(fileRefList.fileList[j]);
fileRefList.fileList.splice(j, 1);
}
```
That will keep the fileList up to date rather than holding on to previous selections. | I'd really need to see the whole class to provide a difinitive answer, but I would write a method to handle removing multiple objects from the dataProvider and perhaps assigning a new array as the dataProvider for the list instead of toying with binding and using the same list for the duration. Like I said, this is probably inefficient, and would require a look at the context of the question, but that is what I would do 9unless you have a big need for binding in this circumstance)
```
/**
* Returns a new Array with the selected objects removed
*/
private function removeSelected(selectedItems:Array):Array
{
var returnArray:Array = []
for each(var object:Object in this.arrayQueue)
{
if( selectedItems.indexOf(object)==-1 )
returnArray.push( object )
}
return returnArray;
}
``` | Removing items from data bound array | [
"",
"javascript",
"arrays",
"actionscript",
""
] |
I have a records of events with starttime and endtime for a calendar control.
I want to get the events done on a particular date say 2/28/2009
But the db table has date data in form 2/28/2009 10:00:00, 2/28/2009 12:00:00.
I tried this query in a sproc created in VS 2005 IDE but it didn't work
```
ALTER PROCEDURE dbo.spSelectBenchEvent
(
@EVENT_DATE DATE // BTW, THIS RETURNS ERROR :CANNOT FIND DATE DATATYPE.
//@EVENT_DATE HAS INVALID DATATYPE
)
AS
BEGIN TRAN
SET NOCOUNT ON;
SELECT ID, EID, BENCHID, PACCODE, START_TIME, END_TIME
FROM tbl_benchbook
WHERE START_TIME=EVENT_DATE
ORDER BY START_TIME
```
Thanks in advance. | There were many questions related to this one, check out:
* [Floor a date in SQL server](https://stackoverflow.com/questions/85373/floor-a-date-in-sql-server/85379#85379)
and for best performance-wise solution check: [MS SQL Date Only Without Time](https://stackoverflow.com/questions/467103/ms-sql-date-only-without-time/467130#467130)
Basically your code could look like:
```
select
id, eid, benchid, paccode, start_time, end_time
from
tbl_benchbook
where start_time >= dateadd(dd, datediff(dd, 0, @event_date), 0)
and start_time < dateadd(dd, datediff(dd, 0, @event_date)+1, 0)
``` | If you wish to evaluate all events on the date 3/29/2009 use the following where cluase.
```
SELECT *
FROM tableName
WHERE Date >= '2009/03/29' AND Date < '2009/03/30'
```
The key point to take away here is that in order to capture all records that occured on a given date you need to define a date range that includes all time values for that day.
Make sense?
Cheers, John | sqlserver date arithmetic problem | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
"stored-procedures",
""
] |
I need to store a bunch of configuration information in PHP.
I have considered the following....
```
// Doesn't seem right.
$mysqlPass = 'password';
// Seems slightly better.
$config = array(
'mysql_pass' => 'password'
);
// Seems dangerous having this data accessible by anything. but it can't be
// changed via this method.
define('MYSQL_PASSWORD', 'password');
// Don't know if this is such a good idea.
class Config
{
const static MYSQL_PASSWORD = 'password';
}
```
This is all I have thought of so far. I intend to import this configuration information into my application with `require /config.inc.php`.
What works for you with regard to storing configuration data, and what are best practices concerning this? | I've always gone with option #2 and just ensure that no one but the owner has ANY sort of access to it. It's the most popular method among PHP applications like Joomla, vBulletin, Gallery, and numerous others.
First method is too messy to me (readability) and the third is WAY too dangerous to do. I've never thought about the Class method, so someone else can provide their input on that one. But I guess it's fine so long as the right access is used on the class' usage.
---
Example..
```
define('EXAMPLE1', "test1"); // scenario 1
$example2 = "test2"; // scenario 2
function DealWithUserInput($input)
{
return eval($input);
}
```
Now this example of code is really dumb, but just an example. Consider what could be returned by the function depending on which scenario the user could try to use in their input.
Scenario 2 would only cause an issue if you made it a global within the function. Otherwise it's out of scope and unreachable. | I'd say it also depends of userbase a bit. If configurations has to be very user friendly or user has to have ability to change config via web etc.
I use [Zend Config Ini](http://framework.zend.com/manual/en/zend.config.adapters.ini.html) for this and other settings are stored in SQL DB. | What is the best way to store configuration variables in PHP? | [
"",
"php",
"configuration-files",
""
] |
While [raknet](http://www.jenkinssoftware.com/) seems fairly interesting and really appealing from a feature-point of view, its [licensing terms](http://creativecommons.org/licenses/by-nc/2.5/) seem to be possibly troublesome for GPL'ed projects that may be leveraged commercially, something which is explicitly forbidden by the terms of the creative commons license.
While there's also [opentnl](http:///www.opentnl.org), it doesn't seem to be as actively maintained anymore nowadays, in fact downloading the latest stable tarball even fails during compilation because it doesn't seem to support gcc >= 3.0 (?)
Of course, there's still also [enet](http://enet.bespin.org/), but this one cannot be really compared to the abstract features that are supported by raknet/opentnl.
So, apart from any non-trivial dependencies such as ACE, Boost or Poco, are there any viable alternatives for embedding a fairly compact, well-maintained UDP-networking library?
Thanks | The [wiki of Ogre3D](http://www.ogre3d.org/wiki/index.php/Libraries#Networking) provides a list of networking libraries and a short description for them. | Though this answer comes late to the party, I'm using OpenTNL for my game, [Bitfighter](http://bitfighter.org), and I really like it. I use it on OS X, Windows, and Linux without a hitch. True, it's not maintained by its creator, but when I get the time, I'm going to create a new SourceForge project for it so people have a place to post their patches. It's stable and (fairly) well documented, so I would recommend giving it another look. | Open Source & Cross Platform Multiplayer/Networking Libraries? | [
"",
"c++",
"open-source",
"network-programming",
"udp",
""
] |
I am learning how to use [mechanize](http://wwwsearch.sourceforge.net/mechanize/), a Python module to automate interacting with websites.
One feature is the automated handling of cookies. I would to want to dump cookies from a `mechanize.Browser` instance for debugging purposes, but I can't seem to figure this out myself. | ```
>>> from mechanize import Browser
>>> b = Browser()
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[]
>>> b.open('http://google.com')
response_seek_wrapper at 0xb7a922ccL whose wrapped object = closeable_response at 0xb7aa070cL whose fp = socket._fileobject object at 0xb7a94224
>>>
>>> b._ua_handlers['_cookies'].cookiejar
mechanize._clientcookie.CookieJar[Cookie(version=0, name='PREF', value='ID=57d545c229b4cf3f:TM=1236081634:LM=1236081634:S=p001WJMOr-V8Rlvi', port=None, port_specified=False, domain='.google.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153634, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False), Cookie(version=0, name='PREF', value='ID=20534d80a5ccf2ea:TM=1236081635:LM=1236081635:S=jW3UotZ0dg8sv6mf', port=None, port_specified=False, domain='.google.com.ua', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153635, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]
>>>
``` | Just print the CookieJar Instance
```
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Dump
print cj
``` | Python: how to dump cookies of a mechanize.Browser instance? | [
"",
"python",
"cookies",
"mechanize-python",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.