Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm consistently running into an internal compiler error while attempting to switch from MSVC6 to MSVC 2008. After much work commenting out different parts of the program, I've traced the error to two lines of code in two different CPP files. Both of these CPP files compile successfully, yet somehow have an effect on whether or not the error manifests in other files.
Both of those lines involve instantianting several complex, nested templates. They also appear to be the only places in the app that use an abstract class as one of the template parameters. That said, I'm far from certain that the issue involves either abstract classes or templates, it's just the most obvious thing I've noticed. I can't even be sure that these lines are significant at all. Here's what they look like, though:
```
m_phDSAttributes = new SObjDict<RWCString, SIDataSource>(&RWCString::hash);
```
So we've got SObjDict, a templatized dictionary class, SIDataSource, an abstract interface, and the parameter is a pointer to a static member function of RWCString.
I've been playing around with the code some, and I can occasionally get the error to move from one CPP file to another (for instance, I changed a bunch of template declarations from using `class` to `typename`), but I can't find any rhyme or reason to it.
I'm at a loss as to how to debug this issue further. The exact error output by the compiler (with the name of my source file changed) is below. There is no mention of it anywhere on the internet. I'm pretty desperate for any advice on how to proceed. I don't expect someone to say "oh, you just need to do XYZ", but a pointer on how to debug this sort of issue would be greatly appreciated.
```
1>d:\Dev\webapi.cpp : fatal error C1001: An internal error has occurred in the compiler.
1>(compiler file 'f:\dd\vctools\compiler\utc\src\p2\p2symtab.c', line 5905)
``` | The trick seems to be disabling precompiled headers. I have no idea *why* that solves the problem, and it's very unfortunate since my build time for the affected project has gone from less than 30 secs to nearly 5 minutes, but at least I can progress forward. | It's a reasonable bet to assume that `p2symtab.c` is (part of) the symbol table code. This would immediately explain how the upgrade caused it; this code has been rewritten. (Remember the 255 character length warnings of VC6?)
In this case, there is no new entry in the symbol table, so it's likely a lookup in the symbol table failing spectactularly. It would be interesting to see if the context in which th name lookup happens affects the result. For instance, what happens if you change the code to
```
typedef SObjDict<RWCString, SIDataSource> SObjDict_RWCString_SIDataSource;
m_phDSAttributes = new SObjDict_RWCString_SIDataSource(&RWCString::hash);
```
This will force another symbol table entry to be created, for `SObjDict_RWCString_SIDataSource`. This entry is sort of a symbolic link to the template *instantiation*. The new name can (and must) be looked up on its own. | VS2008 internal compiler error | [
"",
"c++",
"visual-studio",
"compiler-construction",
"visual-c++",
"c1001",
""
] |
I have a template class that will bundle some information with a type:
```
template <typename T>
class X
{
int data[10]; // doesn't matter what's here really
T t;
public:
// also not terribly relevant
};
```
Then lets say we have a Base class and Derived class:
```
class Base {};
class Derived : public Base {};
```
I'd like to be able to do something like this (but don't think I can):
```
void f(shared_ptr<X<Base> > b);
shared_ptr<X<Derived> > d(new X<Derived>);
f(d);
```
Is there a way that I can make pointers to `X<T>` convertible to pointers of `X<Y>` if T\* is convertible to Y\*? | Rephrasing the question to a more general: *is it possible to convert pointers from unrelated types if the unrelated types are themselves convertible?*, the answer is not. And different template instantiations define different unrelated types.
You can implicitly convert (see note below) a pointer to a derived object to a pointer of the base object (some restrictions apply due to access or ambiguity) or you can make an explicit conversion from a base pointer to a derived pointer (again with some restrictions). You can also convert back and forth to void\*, but converting to an unrelated type ends up with undefined behavior.
There are clear reasons for pointers not being convertible from unrelated types. The first of which is that converting one pointer type to another pointer type will not convert the pointed memory. That is, you can convert an int to a double, but converting a pointer to an int to a pointer to double would make the compiler believe that there are 8 bytes of memory at the pointed address while in fact only 4 bytes are present (assuming 32 or 64 bit architecture with 32 bit integers and 64 bit doubles). Dereferencing the pointer will surely end bad.
*Notes from the standard:*
Section 4.10 of the standard deals with pointer conversions, first paragraph deals with *null-pointer* conversions, second paragraph with *void* pointer conversions. The third paragraph states that you can convert a pointer to type D to a pointer of type B as long as B is a base class of D. No other pointer conversion is defined there. In Section 5.4 where explicit conversions are specified, paragraph 7 deals with pointer conversions and only adds the possible explicit conversion from B\* to D\* in several situations as long as B is a base of B. | I don't want to point out the obvious but is there any reason you can't make the function a template ? I.e.
```
template <typename T>
void f(shared_ptr<T> b);
shared_ptr<X<Derived> > d(new X<Derived>);
f(d);
``` | Is it possible to make pointers to distinct template types convertible? | [
"",
"c++",
""
] |
Using Perl, Python, or Ruby, can I write a program, probably calling Win32 API, to "click" on the screen at scheduled time, like every 1 hour?
**Details:**
This is for experimentation -- and can the clicking be effective on Flash content as well as any element on screen? It can be nice if the program can record where on screen the click needs to happen, or at least draw a red dot on the screen to show where it is clicking on.
Can the click be targeted towards a window or is it only a general pixel on the screen? What if some virus scanning program pops up covering up the place where the click should happen? (although if the program clicks on the white space of a window first, then it can bring that window to the foreground first).
By the way, can Grease Monkey or any Firefox add-on be used to do this too? | If you are trying to automate some task in a website you might want to look at [`WWW::Selenium`](http://search.cpan.org/dist/Test-WWW-Selenium/lib/WWW/Selenium.pm). It, along with [Selenium Remote Control](http://seleniumhq.org/projects/remote-control/), allows you to remote control a web browser. | In Python there is [ctypes](http://www.python.org/doc/2.5.2/lib/module-ctypes.html) and in Perl there is [Win32::API](http://search.cpan.org/~cosimo/Win32-API-0.58/API.pm)
**ctypes Example**
```
from ctypes import *
windll.user32.MessageBoxA(None, "Hey MessageBox", "ctypes", 0);
```
**Win32::Api Example**
```
use Win32::GUI qw( WM_CLOSE );
my $tray = Win32::GUI::FindWindow("WindowISearchFor","WindowISearchFor");
Win32::GUI::SendMessage($tray,WM_CLOSE,0,0);
``` | Using Perl, Python, or Ruby, how to write a program to "click" on the screen at scheduled time? | [
"",
"python",
"ruby",
"perl",
"winapi",
""
] |
Is it possible to specify a custom classloader for javac (or some alternative java compiler)?
I'd love such a feat because it would allow me to compile classes that use classes that are only found by my special classloader.
For the curious ones: I'd write a classloder that connects to a database and creates classes based on the tables it finds. | When you run javac you can specify the classloader like so:
```
javac -J-Djava.system.class.loader=org.awesome.classloader sourcefile.java
``` | It may be possible to initialize a custom classloader and then use it while calling the new Java 6 Compiler API in [javax.tools](http://java.sun.com/javase/6/docs/api/javax/tools/package-summary.html). | Use a custom classloader at compile time | [
"",
"java",
"classloader",
""
] |
I have a data table 44 columns wide that I need to write to file. I don't want to write:
```
outfile.write("%i,%f,%f,$f ... )\n" % (i, a,b,c ...))
```
In Fortran you can specify multiple format specifiers easily:
```
write (*,"(3f8.3)") a,b,c
```
Is there a similar capability in Python? | ```
>>> "%d " * 3
'%d %d %d '
>>> "%d " * 3 % (1,2,3)
'1 2 3 '
``` | Are you asking about
```
format= "%i" + ",%f"*len(row) + "\n"
outfile.write( format % ([i]+row))
``` | is there a multiple format specifier in Python? | [
"",
"python",
""
] |
My situation is that I need to get a single value that defines the combination of multiple selection options. Here is a small example of what I'm looking to do.
A user is buying a shirt. There are many different options the user can select when buying the shirt. Only one option can (and must) be selected from each selection group. The selection groups could be represented as a Radio Button List or Dropdown List, anythign that only allows one selection for each group. For example:
Shirt Color: Red, Blue, Green, Black, White, or Yellow
Shirt Size: X-Small, Small, Medium, Large, X-Large, XX-Large
Shirt Design: Horizontal Striped, Vertical Stripes, Polka Dots, Diagonal Stripes, No Design
Shirt Type: Button Up Shirt, Polo Shirt, T-Shirt, Long Sleeve T-Shirt, Sweatshirt
So only one option can be selected from each group for the sake of this problem. I get a total of 900 different variations (6x6x5x5) using the possible selections. Given that the following options have the following values:
Red = 1, Blue = 2, Green = 3, Black = 4, White = 5, Yellow = 6
X-Small = 0, Small = 1, Medium = 2, Large = 3, X-Large = 4, XX-Large = 5
Horizontal Striped = 0, Vertical Stripes = 1, Polka Dots = 2, Diagonal Stripes = 3, No Design = 4
Button Up Shirt = 0, Polo Shirt = 1, T-Shirt = 2, Long Sleeve T-Shirt = 3, Sweatshirt = 4
and that a selection of {Red, X-Small, Horizontal Striped, Button Up Shirt} = 1 and {Blue, X-Small, Horizontal Striped, Button Up Shirt} = 2, etc,
What is the correct way to find the value based on the selections made? For example what should the selection value of {Black, Large, Horizontal Striped, T-Shirt} be and how do you come to the solution? I can't quite put my finger on it and everything I've tried seems to have been unsuccessful. It's probably a simple solution and I'm just brain dead right now. | You could concatenate the values of the options like they were strings (by converting each individual value to a string, concatenating them, then converting that to an integer). So, {Black, Large, Horizontal Striped, T-Shirt} would be 4302. This should guarantee that no two possible combinations have the same identifier (though I am no math whiz). | In my mind, your scenario maps to a `Shirt` class with 4 enums - `Color`, `Size`, `Design` and `Type`. The class has public properties which expose private members of the type of all 4 enums.
Therefore, One shirt instance can have all 4 properties set without having to worry about 900 possible combinations. Additionally, one single Shirt instance will only have one possible combination of each of the properties. You can query the types of values set in a intuitive manner without having to remember what integer value maps to what type of property. This is precisely what Enums are for! ;-) | How to get a single value from multiple selectable options? | [
"",
"c#",
""
] |
I'm used to ending the python interactive interpreter using Ctrl-d using Linux and OS X. On windows though, you have to use `CTRL`+`Z` and then enter. Is there any way to use `CTRL`+`D`? | Ctrl-d works to exit from [IPython](http://ipython.scipy.org/moin/)
(installed by [python(x,y)](https://python-xy.github.io/) package).
* OS: WinXP
* Python version: 2.5.4
---
**Edit: I've been informed in the comments by the OP, Jason Baker, that Ctrl-d functionality on Windows OSes is made possible by the [PyReadline](http://pypi.python.org/pypi/pyreadline/1.3.svn) package**: "The pyreadline package is a python implementation of GNU readline functionality it is based on the ctypes based UNC readline package by Gary Bishop. It is not complete. It has been tested for use with windows 2000 and windows xp."
---
Since you're accustomed to \*nix you may like that IPython also offers \*nix-like shell functionality without using something like Cygwin...
* Proper bash-like tab completion.
* Use of / instead of \, everywhere
* Persistent %bookmark's
* %macro
* %store. Especially when used with macros and aliases.
* cd -. (easily jump around directory history). Directory history persists across sessions.
* %env (see cookbook)
* Shadow history - %hist and %rep (see cookbook)
* %mglob
* Expansion of $python\_variables in system commands
* var = !ls -la (capture command output to handy string lists) | You can't use **`CTRL`+`D`** on windows.
**`CTRL`+`Z`** is a [windows-specific control char that prints EOF](http://en.wikipedia.org/wiki/End_of_file). On \*nix, it is typically **`CTRL`+`D`**. That's the reason for the difference.
You *can*, however, train yourself to use `exit()`, which is cross-platform. | Can I make Python 2.5 exit on ctrl-D in Windows instead of ctrl-Z? | [
"",
"python",
"windows",
"python-2.5",
""
] |
Basically I have a two databases on SQL Server 2005.
I want to take the table data from one database and copy it to another database's table.
I tried this:
```
SELECT * INTO dbo.DB1.TempTable FROM dbo.DB2.TempTable
```
This didn't work.
I don't want to use a restore to avoid data loss...
Any ideas? | SELECT ... INTO creates a new table. You'll need to use INSERT. Also, you have the database and owner names reversed.
```
INSERT INTO DB1.dbo.TempTable
SELECT * FROM DB2.dbo.TempTable
``` | SELECT \* INTO requires that the destination table not exist.
Try this.
```
INSERT INTO db1.dbo.TempTable
(List of columns here)
SELECT (Same list of columns here)
FROM db2.dbo.TempTable
``` | Copy Data from a table in one Database to another separate database | [
"",
"sql",
"sql-server",
""
] |
I'm trying to generate a release build for a C++ application that I've written. The application runs fine (debug & release) when you run it from within VS2008; but when you run the executable it crashes nearly every single time.
Now, is there a hack so I can run this application as a standalone application without having to run through all of the code and finding the bug that is causing it?
Thanks in advance. | In short, no.
you will have to find the bug, if it works within VS, then I'd hazard a guess that it is a timing issue, possibly you're overwriting shared thread data, this would be less likely (though still possible to see) inside VS as its being run in a debug environment which slows it down a bit.
If you want help finding your bug, then tell us more. Otherwise, build your release with debug symbols (pdbs), install DrWatson as the system debugger and run it standalone. When it crashes DrWatson will create a minidump file, load this into WinDbg (my favourite) and you'll be able to see exactly where your bug is (it'll even tell you that the dump contains an exception and show you it by default. You need to add your source code path and path to your symbols in WinDbg to get it to do this correctly).
Then you will also know how to diagnose crashes when the app is run on-site too. | Are you loading external resources? If you are check that your relative paths are correct in the C++ program. | Visual studio release build | [
"",
"c++",
"build",
"release",
""
] |
Is it possible to avoid having 'NULL' stings on the client when binding JSON data to HTML UI?
I'm using ASP.NET MVC + jQuery + [jTemplates](http://jtemplates.tpython.com/). Data is coming from linq-to-sql classes and these classes have quite a lot of nullable properties. When such properties get serialized and transferred back to client I end up with such JSON:
```
[{"Id":1,"SuitId":1,"TypeId":null,"Type":null,"CourtId":null,"Court":null}]
```
Whey I bind this data to HTML I have a lot of 'NULL' strings. I've tried both manual binding and JavaScript templating engines (jTemplate). Results are the same.
Currently I'm dealing with this issue by 'coalescing' the null values as follows:
```
$('#Elem').val(someVar||'');
```
But I don't want to do it manually.
Please advice if I:
1. Can automatically translate nullable properties to empty strings by either tweaking the serialization process or maybe choosing the 3rd party JSON serializer over .NET JSON serializer.
2. Can do anything on client side, such as working around this with either jQuery or templating engines.
Thank you. | You could set up custom serialization (see
[How to implement custom JSON serialization from ASP.NET web service?](https://stackoverflow.com/questions/159704/how-to-implement-custom-json-serialization-from-asp-net-web-service) )
You could also make your own version of val that converts null to an empty string. However, I think that the method you are currently using is probably better anyway - the generic methods could add a lot of complexity and possibly hidden bugs. | You can modify jtemplate to return an empty string instead of null by modifying the follow line of code in jquery.jtemplate.js.
First find this function
```
TemplateUtils.cloneData = function(d, filter, f_escapeString) {
```
The very next block of code is an if statement
```
if (d == null) {
return d;
}
```
Modify that to
```
if (d == null) {
return "";
}
```
And that should do it | How to avoid 'null' strings when binding JSON data on client side | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"json",
""
] |
I've been working on a server and I'm starting to implement logging. However, I'm not sure whether I should use the db for logging, or just a plaintext file.
I'm planning on logging some basic information for every request (what type of request, ip address of request, session tracking). For some requests there will be extended information present (details on what type of request was made), and if there are any errors I will log those, too.
On the one hand, putting the logs into the db means I could run queries on the logged data. On the other hand, I'm not sure if this would be putting unnecessary strain on the db. Of course, I could also use both the db and a log file for logging. What are people's thoughts on proper logging?
(If it makes a difference, I'm using mod\_python on an Apache server with a MySQL db. So I'd either be using the [logging](http://docs.python.org/library/logging.html) library or just creating some logging tables in the db.) | First, use a logging library like SLF4J/Logback that allows you to make this decision dynamically. Then you can tweak a configuration file and route some or all of your log messages to each of several different destinations.
Be very careful before logging to your application database, you can easily overwhelm it if you're logging a lot of stuff and volume starts to get high. And if your application is running close to full capacity or in a failure mode, the log messages may be inaccessible and you'll be flying blind. Probably the only messages that should go to your application database are high-level application-oriented events (a type of application data).
It's much better to "log to the file system" (which for a large production environment includes logging to a multicast address read by redundant log aggregation servers).
Log files can be read into special analytics databases where you could use eg, Hadoop to do map/reduce analyses of log data. | Mix file.log + db would be the best.
Log into db information that you eventually might need to analyse, for example average number of users per day etc.
And use file.log to store some debug information. | Server Logging - in Database or Logfile? | [
"",
"python",
"logging",
""
] |
Our product is halted at Java version 1.5.0\_13 and we would like to upgrade. Our software deploys a large number of jars via Java Web Start; all of these jars must be signed. However, a couple of the jars do not contain class files, and starting with Java version 1.5.0\_14, it appears that the jarsign utility chooses not to sign any jar that does not contain class files.
What can I do to force jarsign to sign these jars? Or what can I do to distribute these jars through Java Web Start without signing them? And is there anywhere where this change to jarsign with versions 1.5.0\_14 and above is documented? I can't find it in the [release notes](http://java.sun.com/j2se/1.5.0/ReleaseNotes.html). | I'm not able to verify that there is any problem. Can you look through and see what might be different in your environment? I'm running on Windows 7 RC.
Let's check the version:
```
C:\temp>java -version
java version "1.5.0_14"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_14-b03)
Java HotSpot(TM) Client VM (build 1.5.0_14-b03, mixed mode, sharing)
```
Let's see what'll be in our jar:
```
C:\temp>dir /s /b com
C:\temp\com\rdc
C:\temp\com\rdc\test
C:\temp\com\rdc\test\logging.properties
```
Let's make the jar:
```
C:\temp>jar -cfv test-source.jar com/*
added manifest
adding: com/rdc/(in = 0) (out= 0)(stored 0%)
adding: com/rdc/test/(in = 0) (out= 0)(stored 0%)
adding: com/rdc/test/logging.properties(in = 13) (out= 15)(deflated -15%)
```
Let's sign the jar: I'm using a self-signed certificate.
```
C:\temp>jarsigner -signedjar test-dest.jar test-source.jar vinay
Enter Passphrase for keystore:
Warning: The signer certificate will expire within six months.
```
Let's see what's in our signed jar:
```
C:\temp>jar tvf test-dest.jar
155 Wed Jul 15 23:39:12 BST 2009 META-INF/MANIFEST.MF
276 Wed Jul 15 23:39:12 BST 2009 META-INF/VINAY.SF
1130 Wed Jul 15 23:39:12 BST 2009 META-INF/VINAY.DSA
0 Wed Jul 15 23:37:18 BST 2009 META-INF/
0 Wed Jul 15 19:44:44 BST 2009 com/rdc/
0 Wed Jul 15 19:44:58 BST 2009 com/rdc/test/
13 Wed Jul 15 23:37:10 BST 2009 com/rdc/test/logging.properties
```
OK, it certainly appears to have been signed, and it has no classes. Let's look at the contents of `MANIFEST.MF`:
```
Manifest-Version: 1.0
Created-By: 1.5.0_14 (Sun Microsystems Inc.)
Name: com/rdc/test/logging.properties
SHA1-Digest: Ob/S+a7TLh+akYGEFIDugM12S88=
```
And the contents of `VINAY.SF`:
```
Signature-Version: 1.0
Created-By: 1.5.0_14 (Sun Microsystems Inc.)
SHA1-Digest-Manifest-Main-Attributes: 4bEkze9MHmgfBoY+fnoS1V9bRPs=
SHA1-Digest-Manifest: YB8QKIAQPjEYh8PkuGA5G8pW3tw=
Name: com/rdc/test/logging.properties
SHA1-Digest: qXCyrUvUALII7SBNEq4R7G8lVQQ=
```
Now, let's verify the jar:
```
C:\temp>jarsigner -verify -verbose test-dest.jar
155 Wed Jul 15 23:51:34 BST 2009 META-INF/MANIFEST.MF
276 Wed Jul 15 23:51:34 BST 2009 META-INF/VINAY.SF
1131 Wed Jul 15 23:51:34 BST 2009 META-INF/VINAY.DSA
0 Wed Jul 15 23:37:18 BST 2009 META-INF/
0 Wed Jul 15 19:44:44 BST 2009 com/rdc/
0 Wed Jul 15 19:44:58 BST 2009 com/rdc/test/
smk 13 Wed Jul 15 23:37:10 BST 2009 com/rdc/test/logging.properties
s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope
jar verified.
Warning: This jar contains entries whose signer certificate will expire within
six months. Re-run with the -verbose and -certs options for more details.
```
On the face of it, everything appears to be in order. Can you check if your certificates have expired, or been revoked? Are you using self-signed certs or real certs? Or have I misunderstood what your problem is? | For anyone searching on this issue, we determined it only affects certain later versions of Java 1.5, those from 1.5.0\_14 onward, I believe. It appears to be fixed in the latest versions of 1.5, and is definitely fixed in 1.6. | How do I force jarsign to sign jarfiles? | [
"",
"java",
"jar",
"jarsigner",
""
] |
what's wrong with this post-build event? I want to copy the entire contents of a resources folder over to the target directory while maintaining the but it keeps exiting with code 1:
copy $(SolutionDir)$(ProjectName)\Resources\*.\* $(TargetDir)Resources\
Thanks in advance! | Try
```
xcopy /Y $(ProjectDir)Resources\*.* $(TargetDir)Resources\
```
That is probably the most robust as it will also create the directory for you if it doesn't already exist. | It's probably not running from the directory you think it's running from. | Post-build Event error visual studio 2008 | [
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I am having a hard time getting this to work
```
file: myclass.hpp
Class MyClass {
public:
template <class T>
MyClass &operator<<(const T &val);
};
file: myclass.cpp
template <class T>
MyClass &MyClass::operator<<(const T &val) {
...
}
```
I can compile this in to a object without a problem, But when other functions try to calling it, this error comes up (for every time << was used).
```
myclass.cpp: undefined reference to `MyClass& MyClass::operator<< <int>(int const&)'
```
What am I doing wrong? | If you want to define instances of your template in separate compilation units (which is typically the case) then you can't define template methods in a separate cpp. Every template method must be visible to the compiler when compiling compilation units that use that template class. Therefore when using the template across cpps, the template must be defined in a header. Template's are really ways of generating classes not classes in-and-of-themselves. Therefore when the compiler sees
```
YourClass<int>
```
it needs to see the entire YourClass template *at compile time* to generate a type called
```
YourClass<int>
```
and all its methods, which have completely separate methods from say
```
YourClass<float>
```
Which means it must see all the C++ source code. If these two uses of the template are instantiated in separate cpp's then the only way only way the compiler can generate both is to fully define the template in one header.
See my answer [here](https://stackoverflow.com/questions/966544/i-get-no-member-function-declared-in-class-error-on-my-copy-constructor-when-i/966549#966549) for more info.
**Thanks for the useful comments that greatly improved this answer** | Put the definition of the operator in the `.hpp` instead of the `.cpp`. The compiler needs to be able to see the complete definition of the template when it gets instantiated for some new type, so that it can generate the code for this specialization.
There are also some questions and answers about this kind of template related linker errors and different possible solutions in the [C++ FAQ Lite](http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12). | C++ overloaded operator declaration and definition problems | [
"",
"c++",
"declaration",
"definition",
""
] |
My web app allows users to upload a bunch of photos simultaneously to the server, and then stores them in a database. When the first photo finishes uploading, it should create a default album based on today's date, and add it to that. But what if photo1 completes, looks for the album, and can't find it so it decides to create it, but before it can, photo2 completes and also can't find it, so then they both try to create the same album, causing one to fail? This would probably be very highly unlikely, but could happen I reckon. Or do most web servers process only one PHP script at a time?
Would this be a valid and good solution?: Instead of photo1 checking if the album exists first, it just tries to create it. If it throws back an error 1062 (duplicate entry), THEN it selects it. Then it shouldn't matter which finishes first if you think about it... I just don't know if catching errors will come as a big performance hit. If I'm uploading 200 photos, then 199 of them will fail the insert query, and then try select. If the other solution works correctly, 199 will succeed and one will miss.
Thoughts? | Combine both
Check if it exists and if it does join
if not try to create one
if that doesnt work start the whole thing again | We have something similar albeit not to do with photos but we simply wait for ALL the items to be sent up before processing them. This means keeping them in a staging area first but solves the other issue. | Handling simultaneous uploads on the database | [
"",
"php",
"mysql",
"mysql-error-1062",
""
] |
Lets say I have a File table with the column, "File\_ID".
How can I write a quick LINQ query/statement to set every "File\_ID" in the File table to "1"?
I'm using LINQPad in Statement mode, but that doesn't matter really. | LINQ is for querying, not updating. The LINQ to SQL (and other data sources) models use a traditional object model of Add, Remove, getters and setters, and Update() to commit the changeset to the data backing.
What you are describing is simply iterating over all the record objects in your table collection, setting a property, and calling `Update()`. It would be much faster and more efficient to do this in SQL with a single `UPDATE` command.
```
myDataContext.ExecuteQuery("UPDATE [File] SET File_ID = {0}", 1);
``` | Kinda cheating:
```
dataContext.ExecuteQuery("update File set File_ID = 1");
``` | How can I set the value of a column for every row in a table using LINQ? | [
"",
"sql",
"linq",
"linq-to-sql",
""
] |
I'm trying to figure out how to wrap text like this:
> Morbi nisl tortor, consectetur vitae
> laoreet eu, lobortis id ipsum. Integer
> scelerisque blandit pulvinar. Nam
> tempus mi eget nunc laoreet venenatis.
> Proin viverra, erat at accumsan
> tincidunt, ante mi cursus elit, non
>
> congue mauris dolor ac elit. Maecenas
> mollis nisl a sem semper ornare.
> Integer nunc purus, dapibus nec
> dignissim sed, dictum eget leo. Etiam
> in mi ut erat pretium fringilla sed
Into this:
> <p>Morbi nisl tortor, consectetur vitae
> laoreet eu, lobortis id ipsum. Integer
> scelerisque blandit pulvinar. Nam
> tempus mi eget nunc laoreet venenatis.
> Proin viverra, erat at accumsan
> tincidunt, ante mi cursus elit, non</p>
>
> <p>congue mauris dolor ac elit. Maecenas
> mollis nisl a sem semper ornare.
> Integer nunc purus, dapibus nec
> dignissim sed, dictum eget leo. Etiam
> in mi ut erat pretium fringilla sed</p>
Note the `p` tags around the text. | This should do it
```
$text = <<<TEXT
Morbi nisl tortor, consectetur vitae laoreet eu, lobortis id ipsum. Integer scelerisque blandit pulvinar. Nam tempus mi eget nunc laoreet venenatis. Proin viverra, erat at accumsan tincidunt, ante mi cursus elit, non
congue mauris dolor ac elit. Maecenas mollis nisl a sem semper ornare. Integer nunc purus, dapibus nec dignissim sed, dictum eget leo. Etiam in mi ut erat pretium fringilla sed
TEXT;
$paragraphedText = "<p>" . implode( "</p>\n\n<p>", preg_split( '/\n(?:\s*\n)+/', $text ) ) . "</p>";
``` | ```
$str = '<p>'. str_replace('\n\n', '</p><p>', $str) .'</p>';
```
OR
```
$str = '<p>'. preg_replace('\n{2,}', '</p><p>', $str) .'</p>';
```
To catch 2 or more. | Wrap Text in P tag | [
"",
"php",
"regex",
"tags",
""
] |
How do I shuffle a list of objects? I tried [`random.shuffle`](https://docs.python.org/library/random.html#random.shuffle):
```
import random
b = [object(), object()]
print(random.shuffle(b))
```
But it outputs:
```
None
``` | [`random.shuffle`](https://docs.python.org/library/random.html#random.shuffle) should work. Here's an example, where the objects are lists:
```
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)
print(x)
# print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
```
Note that `shuffle` works **in place**, and returns `None`.
More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return `None` (rather than, say, the mutated object). | As you learned the in-place shuffling was the problem. I also have problem frequently, and often seem to forget how to copy a list, too. Using `sample(a, len(a))` is the solution, using `len(a)` as the sample size. See <https://docs.python.org/3.6/library/random.html#random.sample> for the Python documentation.
Here's a simple version using `random.sample()` that returns the shuffled result as a new list.
```
import random
a = range(5)
b = random.sample(a, len(a))
print a, b, "two list same:", a == b
# print: [0, 1, 2, 3, 4] [2, 1, 3, 4, 0] two list same: False
# The function sample allows no duplicates.
# Result can be smaller but not larger than the input.
a = range(555)
b = random.sample(a, len(a))
print "no duplicates:", a == list(set(b))
try:
random.sample(a, len(a) + 1)
except ValueError as e:
print "Nope!", e
# print: no duplicates: True
# print: Nope! sample larger than population
``` | Shuffling a list of objects | [
"",
"python",
"list",
"random",
"shuffle",
""
] |
I have a stored procedure that accepts a date input that is later set to the current date if no value is passed in:
```
CREATE PROCEDURE MyProc
@MyDate DATETIME = NULL
AS
IF @MyDate IS NULL SET @MyDate = CURRENT_TIMESTAMP
-- Do Something using @MyDate
```
I'm having problems whereby if `@MyDate` is passed in as `NULL` when the stored procedure is first compiled, the performance is always terrible for all input values (`NULL` or otherwise), wheras if a date / the current date is passed in when the stored procedure is compiled performance is fine for all input values (`NULL` or otherwise).
What is also confusing is that the poor execution plan that is generated in is terrible even when the value of @MyDate used is **actually** `NULL` (and not set to `CURRENT_TIMESTAMP` by the IF statement)
I've discovered that disabling parameter sniffing (by spoofing the parameter) fixes my issue:
```
CREATE PROCEDURE MyProc
@MyDate DATETIME = NULL
AS
DECLARE @MyDate_Copy DATETIME
SET @MyDate_Copy = @MyDate
IF @MyDate_Copy IS NULL SET @MyDate_Copy = CURRENT_TIMESTAMP
-- Do Something using @MyDate_Copy
```
I know this is something to do with parameter sniffing, but all of the examples I've seen of "parameter sniffing gone bad" have involved the stored procedure being compiled with a non-representative parameter passed in, however here I'm seeing that the execution plan is terrible for all conceivable values that SQL server might think the parameter might take at the point where the statement is executed - `NULL`, `CURRENT_TIMESTAMP` or otherwise.
Has anyone got any insight into why this is happening? | Basically yes - parameter sniffing (in some patch levels of) SQL Server 2005 is badly broken. I have seen plans that effectively never complete (within hours on a small data set) even for small (few thousand rows) sets of data which complete in seconds once the parameters are masked. And this is in cases where the parameter has always been the same number. I would add that at the same time I was dealing with this, I found a lot of problems with LEFT JOIN/NULLs not completing and I replaced them with NOT IN or NOT EXISTS and this resolved the plan to something which would complete. Again, a (very poor) execution plan issue. At the time I was dealing with this, the DBAs would not give me SHOWPLAN access, and since I started masking every SP parameter, I've not had any further execution plan issues where I would have to dig in to this for non-completion.
In SQL Server 2008 you can use `OPTIMIZE FOR UNKNOWN`. | One way I was able to get around this problem in (SQL Server 2005) instead of just masking the parameters by redeclaring local parameters was to add query optimizer hints.
Here is a good blog post that talks more about it:
[Parameter Sniffing in SqlServer 2005](http://blogs.msdn.com/queryoptteam/archive/2006/03/31/565991.aspx)
I used: OPTION (optimize for (@p = '-1')) | SQL poor stored procedure execution plan performance - parameter sniffing | [
"",
"sql",
"sql-server",
"t-sql",
"sql-execution-plan",
"parameter-sniffing",
""
] |
add and GetContentPane are methods
Does this code access a method in a method? What does this code do?
frame.getContentPane().add(BorderLayout.SOUTH, b); | A method can return an object. And you can call a method on that object.
There are languages that support local functions. But those are not visible from the outside. | In the code that is shown, it is not a "nested method", but a method that is being called on object that was returned from another method. (Just for your information, in the Java programming language, there is no concept of a nested method.)
The following line:
```
f.getContentPane().add(component);
```
is equivalent to:
```
Container c = f.getContentPane();
c.add(component);
```
Rather than separating the two statements into two lines, the first example performs it in one line.
Conceptually, this is what is going on:
1. The `f.getContentPane` method returns a `Container`.
2. The `add` method is called on the `Container` that was returned.
It may help to have some visuals:
```
f.getContentPane().add(component);
|________________|
L returns a Container object.
[Container object].add(component);
|________________________________|
L adds "component" to the Container.
```
This is not too unlike how substitution works in mathematics -- the result of an expression is used to continue evaluating an expression:
```
(8 * 2) + 4
|_____|
L 8 * 2 = 16. Let's substitute that.
16 + 4
|____|
L 16 + 4 = 20. Let's substitute that.
20 -- Result.
``` | nested methods | [
"",
"java",
"methods",
""
] |
I'm wondering how to make a window transparent, not cutout holes or the same transparency overall.
Well, just say I want to slap a PNG image of a rose or something and have it blend nicely with stuff behind and allow stuff behind to redraw and have their changes shine through the transparent parts of the picture/window.
I could (or would like to) use something like wxWidgets or OpenGL. But rather not Qt or GTK. | I found out that it's actually pretty simple to throw up a transparent picture on the screen using wxW:
```
wxScreenDC dc;
wxBitmap bmp(wxT("test.png"), wxBITMAP_TYPE_PNG);
dc.DrawBitmap(bmp, 250, 100, true);
```
Now I has to find out how to handle updates and such, it has to be ( maybe partially redrawn ) when something beneath updates.
As it is right now it just redraws itself ontop of itself, making it become fully opacue in a while.
There was another version of wxScreenDC::DrawBitmap that took a window as an argument, maybe it's that one solves this? | How about using shaped frames?
```
wxBitmap m_bmp = wxBitmap(_T("redroseonwhite.png"), wxBITMAP_TYPE_PNG);
SetSize(wxSize(m_bmp.GetWidth(), m_bmp.GetHeight()));
wxRegion region(m_bmp, *wxWHITE);
bool m_hasShape = SetShape(region);
```
Look \*wxWidgets-2.9.0\samples\shaped\* for the full example. | Cross-platform transparent windows in C++? | [
"",
"c++",
"cross-platform",
"transparency",
""
] |
I'm having a Repeater used as a sort of Paging TagCloud. To do so, I've added simple properties to the Page's ViewState such as a Page, RowCount, etc...
I feel like it doesn't belong there but I had bad experiences with server controls, debugging, dll and deployment.
Could I just inherit the Repeater class, add a few ControlState/ViewState properties and be able to use it exactly as a Repeater dragged straight from the ToolBox?
Here, having the following simple class:
```
public class TagCloud : Repeater
{
public int selectedIndex;
public TagCloud()
{
selectedIndex = -1;
//
// TODO: Add constructor logic here
//
}
public int SelectedIndex
{
get { return selectedIndex; }
set { selectedIndex = value; }
}
}
```
Without creating a new WebControlLibrary project, could this cs file stands in the App\_Code folder and work like expected?
Thanks. | Yes, there is no problem doing this. As long as you use the control's property syntax:
public int RowCount
{
```
get { return (int) (ViewState["RowCount"] ?? 0); }
set { ViewState["RowCount"] = value; }
```
}
Also, to make your properties look the same as the default ones you can add Description or DefaultValue attributes. | This works, and is one suggested way of building server controls. Try it and see. | Inheriting a web server control in a simple fashion? | [
"",
"c#",
"asp.net",
"custom-server-controls",
""
] |
I was looking for a way to stuff some data into a string across a DLL boundary. Because we use different compilers, all our dll interfaces are simple char\*.
Is there a correct way to pass a pointer into the dll function such that it is able to fill the string buffer directly?
```
string stringToFillIn(100, '\0');
FunctionInDLL( stringToFillIn.c_str(), stringToFillIn.size() ); // definitely WRONG!
FunctionInDLL( const_cast<char*>(stringToFillIn.data()), stringToFillIn.size() ); // WRONG?
FunctionInDLL( &stringToFillIn[0], stringToFillIn.size() ); // WRONG?
stringToFillIn.resize( strlen( stringToFillIn.c_str() ) );
```
The one that looks most promising is &stringToFillIn[0] but is that a correct way to do this, given that you'd think that string::data() == &string[0]? It seems inconsistent.
Or is it better to swallow an extra allocation and avoid the question:
```
vector<char> vectorToFillIn(100);
FunctionInDLL( &vectorToFillIn[0], vectorToFillIn.size() );
string dllGaveUs( &vectorToFillIn[0] );
``` | I'm not sure the standard guarantees that the data in a `std::string` is stored as a `char*`. The most portable way I can think of is to use a `std::vector`, which is guaranteed to store its data in a continuous chunk of memory:
```
std::vector<char> buffer(100);
FunctionInDLL(&buffer[0], buffer.size());
std::string stringToFillIn(&buffer[0]);
```
This will of course require the data to be copied twice, which is a bit inefficient. | > **Update (2021):** C++11 cleared this up and the concerns expressed here are no longer relevant.
After a lot more reading and digging around I've discovered that `string::c_str` and `string::data` could legitimately return a pointer to a buffer that has nothing to do with how the string itself is stored. It's possible that the string is stored in segments for example. Writing to these buffers has an undefined effect on the contents of the string.
Additionally, `string::operator[]` should not be used to get a pointer to a sequence of characters - it should only be used for single characters. This is because pointer/array equivalence does not hold with string.
What is very dangerous about this is that it can work on some implementations but then suddenly break for no apparent reason at some future date.
Therefore the only safe way to do this, as others have said, is to avoid any attempt to directly write into the string buffer and use a vector, pass a pointer to the first element and then assign the string from the vector on return from the dll function. | writing directly to std::string internal buffers | [
"",
"c++",
"string",
""
] |
I am struggling to find a way to create the Forms functionality that I want using C#.
Basically, I want to have a modal dialog box that has a specified timeout period. It seems like this should be easy to do, but I can't seem to get it to work.
Once I call `this.ShowDialog(parent)`, the program flow stops, and I have no way of closing the dialog without the user first clicking a button.
I tried creating a new thread using the BackgroundWorker class, but I can't get it to close the dialog on a different thread.
Am I missing something obvious here?
Thanks for any insight you can provide. | Use a [System.Windows.Forms.Timer](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx). Set its [Interval](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.interval.aspx) property to be your timeout and its [Tick](http://msdn.microsoft.com/en-us/library/system.windows.forms.timer.tick.aspx) event handler to close the dialog.
```
partial class TimedModalForm : Form
{
private Timer timer;
public TimedModalForm()
{
InitializeComponent();
timer = new Timer();
timer.Interval = 3000;
timer.Tick += CloseForm;
timer.Start();
}
private void CloseForm(object sender, EventArgs e)
{
timer.Stop();
timer.Dispose();
this.DialogResult = DialogResult.OK;
}
}
```
The timer runs on the UI thread so it is safe to close the form from the tick event handler. | You will need to call the Close method on the thread that created the form:
```
theDialogForm.BeginInvoke(new MethodInvoker(Close));
``` | Close modal dialog from external thread - C# | [
"",
"c#",
"winforms",
"user-interface",
""
] |
Does [urllib2](http://docs.python.org/library/urllib2.html) in Python 2.6.1 support proxy via https?
I've found the following at <http://www.voidspace.org.uk/python/articles/urllib2.shtml>:
> NOTE
>
> Currently urllib2 does not support
> fetching of https locations through a
> proxy. This can be a problem.
I'm trying automate login in to web site and downloading document, I have valid username/password.
```
proxy_info = {
'host':"axxx", # commented out the real data
'port':"1234" # commented out the real data
}
proxy_handler = urllib2.ProxyHandler(
{"http" : "http://%(host)s:%(port)s" % proxy_info})
opener = urllib2.build_opener(proxy_handler,
urllib2.HTTPHandler(debuglevel=1),urllib2.HTTPCookieProcessor())
urllib2.install_opener(opener)
fullurl = 'https://correct.url.to.login.page.com/user=a&pswd=b' # example
req1 = urllib2.Request(url=fullurl, headers=headers)
response = urllib2.urlopen(req1)
```
I've had it working for similar pages but not using HTTPS and I suspect it does not get through proxy - it just gets stuck in the same way as when I did not specify proxy. I need to go out through proxy.
I need to authenticate but not using basic authentication, will urllib2 figure out authentication when going via https site (I supply username/password to site via url)?
EDIT:
Nope, I tested with
```
proxies = {
"http" : "http://%(host)s:%(port)s" % proxy_info,
"https" : "https://%(host)s:%(port)s" % proxy_info
}
proxy_handler = urllib2.ProxyHandler(proxies)
```
And I get error:
> urllib2.URLError: urlopen error
> [Errno 8] \_ssl.c:480: EOF occurred in
> violation of protocol | I'm not sure Michael Foord's article, that you quote, is updated to Python 2.6.1 -- why not give it a try? Instead of telling ProxyHandler that the proxy is only good for http, as you're doing now, register it for https, too (of course you should format it into a variable just once before you call ProxyHandler and just repeatedly use that variable in the dict): that may or may not work, but, you're not even *trying*, and that's **sure** not to work!-) | Fixed in Python 2.6.3 and several other branches:
* \_bugs.python.org/issue1424152 (replace \_ with http...)
* <http://www.python.org/download/releases/2.6.3/NEWS.txt>
Issue #1424152: Fix for httplib, urllib2 to support SSL while working through
proxy. Original patch by Christopher Li, changes made by Senthil Kumaran. | Does urllib2 in Python 2.6.1 support proxy via https | [
"",
"python",
"proxy",
"https",
"urllib2",
""
] |
I want to add a variable number of records in a table (days)
And I've seen a neat solution for this:
```
SET @nRecords=DATEDIFF(d,'2009-01-01',getdate())
SET ROWCOUNT @nRecords
INSERT int(identity,0,1) INTO #temp FROM sysobjects a,sysobjects b
SET ROWCOUNT 0
```
But sadly that doesn't work in a UDF (because the #temp and the SET ROWCOUNT). Any idea how this could be achieved?
At the moment I'm doing it with a WHILE and a table variable, but in terms of performance it's not a good solution. | this is the approach I'm using and works best for my purposes and using SQL 2000. Because in my case is inside an UDF, I can't use ## or # temporary tables so I use a table variable.
I'm doing:
```
DECLARE @tblRows TABLE (pos int identity(0,1), num int)
DECLARE @numRows int,@i int
SET @numRows = DATEDIFF(dd,@start,@end) + 1
SET @i=1
WHILE @i<@numRows
begin
INSERT @tblRows SELECT TOP 1 1 FROM sysobjects a
SET @i=@i+1
end
``` | If you're using SQL 2005 or newer, you can use a recursive CTE to get a list of dates or numbers...
```
with MyCte AS
(select MyCounter = 0
UNION ALL
SELECT MyCounter + 1
FROM MyCte
where MyCounter < DATEDIFF(d,'2009-01-01',getdate()))
select MyCounter, DATEADD(d, MyCounter, '2009-01-01')
from MyCte
option (maxrecursion 0)
/* output...
MyCounter MyDate
----------- -----------------------
0 2009-01-01 00:00:00.000
1 2009-01-02 00:00:00.000
2 2009-01-03 00:00:00.000
3 2009-01-04 00:00:00.000
4 2009-01-05 00:00:00.000
5 2009-01-06 00:00:00.000
....
170 2009-06-20 00:00:00.000
171 2009-06-21 00:00:00.000
172 2009-06-22 00:00:00.000
173 2009-06-23 00:00:00.000
174 2009-06-24 00:00:00.000
(175 row(s) affected)
*/
``` | Inserting n number of records with T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2000",
""
] |
Is there any way to detect if a computer is slow and not run some code (by either turning jQuery animations off or just running a function if it *is* fast)?
I know this question is probably really trivial, but I noticed that on some slower computers even the simplest margin animation to move something is done in flashes that doesn't look very nice.
Update:
The code I'm trying to run is simply a bunch of animations; they all take the same amount of time but on slower browsers the animation is segmented like what you see when you watch a video that is buffering. | When running javascript, you don't have the luxury of knowing the target computer's performance beforehand. The only thing I can think of, would be to run a function doing some calculations and measuring the time taken. The function must do a sufficient number of calculations in order to make sure that the time taken to run, is representative of the performance of the machine.
In general, I would advise against doing such a performance test, because it takes resources on the target machine, something that users generally don't like. But perhaps you could measure the time taken to complete the first animation, and if it is too slow, disable subsequent ones. | The most simple solution would be to leave it up to the user with a check box, but other wise you could try timing the first animation for a computer and then if it exceeds a certain time limit, the remaining animations are turned off... for example...
```
var start = new Date();
//... some jQuery animation
var end = new Date();
var diff = end - start;
```
Then, for example, if the animation should take 1.5 seconds, and the time difference is like 5 seconds, then turn off any remaining animations. | Skip some code if the computer is slow | [
"",
"javascript",
"jquery",
""
] |
What is the limit of rows in a table for SQL Server 2005, when SQL query starts getting slower? Is there any way to find out the limit?
I understand it will depend upon the data length of a row. This will also depend on how many more data in other tables and the hardware available. | I think you are asking the wrong question.
If you have the 'right' indexes to cover your query workload, the number of rows won't make much difference until you reach 10's or 100's millions of rows.
Make sure your server has enough RAM. | There are no limits, the only restriction is hard-drive space.
The performance is based on your machine spec and how your tables are indexed. | limit of rows in SQL Server 2005 when performance degrades | [
"",
"sql",
"sql-server",
"sql-server-2005",
"performance",
""
] |
I have to deal with a table where there is a set of fields each followed by a second field that will hold a suggested new value until this change is confirmed.
It looks a little like this:
```
refID field1 newField1 field2 newField2 ...
```
refID is an ID value that links to a master table. One row in the master table can have n rows in my detail table. The data-types include ints, strings and dateTimes.
Now, i'm looking to have a query that tells me, given a refID, if there are any suggested changes in the detail table.
I was playing around a little with some UNION selects, with COALESCE() and ISNULL() ... but all those attempts looked a little weird at best. The DB is MS-SQL-Server 2005.
For clarification of my problem:
```
--this is a simplification of the details table in question
CREATE TABLE [dbo].[TEST_TABLE](
[ID] [int] IDENTITY(1,1) NOT NULL,
[refID] [int] NOT NULL,
[firstName] [varchar](50) NULL,
[newFirstName] [varchar](50) NULL,
[lastName] [varchar](50) NULL,
[newLastName] [varchar](50) NULL
)
--here we insert a detail row ... one of many that might exist for the master table (e.g. data about the company)
insert into TEST_TABLE(refID, firstName, lastName) values(666, 'Bill', 'Ballmer')
--this is what happens when a user saves a suggested change
update TEST_TABLE SET newLastName = 'Gates' where ID = 1
--and this is what happens when this suggestion is accepted by a second user
update TEST_TABLE set lastName=newLastName, newLastName = NULL where ID = 1
``` | This is the cleanest solution I can think of off the top of my head. You'd need to repeat the logic for each data element (col1, col2, etc):
```
DECLARE @RefID int, @Changes bit
SET @Changes = 0 --No changes by default
SET @RefID = 42 --Your RefID
IF EXISTS(SELECT * FROM MyDetailTable
WHERE RefID = @RefID
AND (
(Col1 IS NULL AND NewCol1 IS NOT NULL)
OR
(Col1 IS NOT NULL AND NewCol1 IS NULL)
OR
(Col1 <> Col2)
))
SET @Changes = 1
``` | I modified randolphos solution.
```
select
refID ,
case when
newField1 is not null or
newField2 is not null or
...
then 1 else 0 end haschanged
from myTable
where refID = @refID
```
Update: basically what Aron Aalton said in another output format. | Is one of my DB-fields NOT NULL? | [
"",
"sql",
"select",
"null",
""
] |
I am cropping an image, and wish to return it using a ashx handler. The crop code is as follows:
```
public static System.Drawing.Image Crop(string img, int width, int height, int x, int y)
{
try
{
System.Drawing.Image image = System.Drawing.Image.FromFile(img);
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);
Graphics gfx = Graphics.FromImage(bmp);
gfx.SmoothingMode = SmoothingMode.AntiAlias;
gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
// Dispose to free up resources
image.Dispose();
bmp.Dispose();
gfx.Dispose();
return bmp;
}
catch (Exception ex)
{
return null;
}
}
```
The bitmap is being returned, and now need to send that back to the browser through the context stream, as I do not want a physical file created. | You really just need to send it over the response with an appropriate MIME type:
```
using System.Drawing;
using System.Drawing.Imaging;
public class MyHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
Image img = Crop(...); // this is your crop function
// set MIME type
context.Response.ContentType = "image/jpeg";
// write to response stream
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
}
}
```
You can change the format to a number of different things; just check the enum. | A better approach will be to use write a Handler to accomplish the function. [Here](http://dotnetperls.com/ashx-handler) is one tutorial that returns image from query string and [here](http://msdn.microsoft.com/en-us/magazine/cc302030.aspx) is a MSDN article on the topic. | Return Bitmap to Browser dynamically | [
"",
"c#",
"asp.net",
"image-manipulation",
"ashx",
""
] |
```
public DerivedClass(string x) : base(x)
{
x="blah";
}
```
will this code call the base constructor with a value of x as "blah"? | The base call is always done first, but you *can* make it call a static method. For example:
```
public Constructor(string x) : base(Foo(x))
{
// stuff
}
private static string Foo(string y)
{
return y + "Foo!";
}
```
Now if you call
```
new Constructor("Hello ");
```
then the base constructor will be called with "Hello Foo!".
Note that you *cannot* call instance methods on the instance being constructed, as it's not "ready" yet. | No, `base` call we be performed before executing the constructor body:
```
//pseudocode (invalid C#):
public Constructor(string x) {
base(x);
x = "blah";
}
``` | calling base constructor passing in a value | [
"",
"c#",
""
] |
this is my first post here.
I'm using an existing Flash widget but would like to add more functionality to.
The Flash widget is a basic audio player with limited functionality. As I don't have any control over how the widget was built, I'm unable to directly communicate with it but I'd like to detect when it's stopped streaming so I can modify other parts of the page.
Any help would be greatly appreciated. | Unless the developer of the flash widget implemented it with JavaScript in mind, you're out of luck.
Since you say you can't directly communicate with it, sounds like they didn't intend for you to do so. | Agreed, you can experiment with loading that SWF into another SWF you make yourself and adding event listeners and see if you can figure out a way to get some sort of events and then link that to you javascript, but this would be a mess to do. | Using JavaScript, is it possible to detect when an embedded Flash object has stopped streaming audio/video? | [
"",
"javascript",
"flash",
""
] |
Every time there is a post from page the entire bunch of css gets reloaded. Is it possible to tell them not to come in again and again. There is a series of GET that get fired. Can we optimize in some way or is it normal behavior?
The environment is google apps in python. | Check out Using [Static Files](http://code.google.com/appengine/docs/python/gettingstarted/staticfiles.html) and [Handlers for Static Files](http://code.google.com/appengine/docs/python/config/appconfig.html#Static_File_Handlers). Since the latter link refer to cache duration of static files, I believe the the caching functionality is possible.
> Unlike a traditional web hosting
> environment, Google App Engine does
> not serve files directly out of your
> application's source directory unless
> configured to do so. We named our
> template file index.html, but this
> does not automatically make the file
> available at the URL /index.html.
>
> But there are many cases where you
> want to serve static files directly to
> the web browser. Images, CSS
> stylesheets, JavaScript code, movies
> and Flash animations are all typically
> stored with a web application and
> served directly to the browser. You
> can tell App Engine to serve specific
> files directly without your having to
> code your own handler. | If your CSS comes from a static file, then as Steve mentioned you want to put it in a static directory and specify it in your app.yaml file. For example, if your CSS files are in a directory called stylesheets:
```
handlers:
- url: /stylesheets
static_dir: stylesheets
expiration: "180d"
```
The critical thing to remember with this is that when you upload a new version of your CSS file, you must change the filename because otherwise, visitors to your site will still be using the old cached version instead of your shiny new one. Simply incrementing a number on the end works well.
If your CSS is dynamically generated, then when the request comes in you want to set the caching in the response object's headers. For example, in your request handler you might have something like this:
```
class GetCSS(webapp.RequestHandler):
def get(self):
# generate the CSS file here, minify it or whatever
# make the CSS cached for 86400s = 1 day
self.response.headers['Cache-Control'] = 'max-age=86400'
self.response.out.write(your_css)
``` | static stylesheets gets reloaded with each post request | [
"",
"python",
"css",
"google-app-engine",
"post",
"get",
""
] |
I'm about to start a fair amount of work extending Trac to fit our business requirements.
So far I've used pythonWin and now Netbeans 6.5 as the development environments - neither of these seem to provide any way of debugging the plugin I am working on.
*I'm totally new to Python* so probably have not set up the development environment how it could be congfigured to get it debugging.
Am I missing something obvious? It seems a bit archaic to have to resort to printing debug messages to the Trac log, which is how I'm debugging at the moment. | You can create a wrapper wsgi script and run it in a debugger. For example:
```
import os
import trac.web.main
os.environ['TRAC_ENV'] = '/path/to/your/trac/env'
application = trac.web.main.dispatch_request
from flup.server.fcgi import WSGIServer
server = WSGIServer(application, bindAddress=("127.0.0.1", 9000), )
server.run()
```
You would run this script in the debugger, and you can use lighttpd as a frontend for the web application with a trivial config like this one:
```
server.document-root = "/path/to/your/trac/env"
server.port = 1234
server.modules = ( "mod_fastcgi" )
server.pid-file = "/path/to/your/trac/env/httpd.pid"
server.errorlog = "/path/to/your/trac/env/error.log"
fastcgi.server = ( "/" =>
(( "host" => "127.0.0.1",
"port" => 9000,
"docroot" => "/",
"check-local" => "disable",
))
)
```
Just run the fcgi wsgi wrapper in the debugger, set the breakpoints in your plugin, and open the web page. | Usually, we unit test first.
Then, we write log messages to diagnose problems.
We generally don't depend heavily on debugging because it's often hard to do in situations where Python scripts are embedded in a larger product. | How should I debug Trac plugins? | [
"",
"python",
"trac",
"netbeans6.5",
""
] |
I know how to set a control's BackColor dynamically in C# to a named color with a statement such as Label1.BackColor = Color.LightSteelBlue; ( using System.Drawing; )
But how do I convert a hex value into a System.Color , ie Label1.BackColor = "#B5C7DE | I would use the color translator as so:
```
var color = ColorTranslator.FromHtml("#FF1133");
```
Hope this helps. | ```
string hexColor = "#B5C7DE";
Color color = ColorTranslator.FromHtml(hexColor);
``` | How do I dynamically change color in C# to a hex value? | [
"",
"c#",
"asp.net",
"user-interface",
""
] |
I have a C# application that has links to certain features on a web application that uses the same login credentials. If the user has logged in using the application and they click a link, a new browser window opens (usually IE but may be just the default browser) and asks the them to authenticate again.
Is there a way to make the account stay logged in whether it is in the C# application or in a separate browser window? The web application uses cookies to store the users session variables for authentication, the C# application has the same session info but not in a cookie.
Essentially I need to create a cookie from the C# application's session information and pass it to the new browser window.
Any ideas? | I believe any new window instance will start a new session and therefore wipe out any session cookies you may have created prior to opening a new browser through either `Process.Start("iexplorer.exe", "www.msn.ca")` or `webBrowser1.Navigate("www.msn.ca", true)`.
However I finally found a work around for this problem. It involves the following:
1. Create your own web browser that looks almost exactly like Internet Explorer. See the folowing link for code for a basic browser and customize it as needed.
<http://msdn.microsoft.com/en-us/library/ms379558(VS.80).aspx>
I fixed the bug by replacing the obsolete RaftingStrip with the ToolStrip, ToolStripContainer. (Email me if you want this debugged code. I'd post it but I think it's too long for this forum.)
For myself, I added
1. constructor to pass the target url, set it to the Address bar, set it as the home page and also pass the security token
2. properties to enable/disable the Address bar and Search bars
3. added Cut, Copy, Paste, SaveAs, and Print buttons
4. changed the progress icon from "C#" to an hourglass
2. On the web browser form's declaration section, add
```
DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName,
string lbszCookieName, string lpszCookieData);
```
3. On the web browser form load and Create\_a\_new\_tab(), before the webpage.Navigate() insert the lines below that save the token to a session cookie. (This may also be required on the button\_go\_click and button\_search\_click events if navigating to a new domain. Personally, I would disable the Address and Search bars if passing a security token.)
```
string url = comboBox_url.Text.Trim(); // write the session cookie
string security_token = "my_session_id=12345" // should have been passed to constructor
InternetSetCookie(url, null, security_token);
```
The user will never know the difference and you have control over what features to turn on/off or implement. | I've only been able to do this for an embedded WebBrowser control (see code below) but NOT for new IE window. Still haven't found an answer.
```
[DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
string url = "http://www.google.com";
// write the session cookie
InternetSetCookie(url, null, "abc=1");
webBrowser1.Navigate(url);
``` | Sending cookies from C# Application to an Internet Explorer pop-up window | [
"",
"c#",
"browser",
"cookies",
"webforms",
""
] |
I just start playing with GWT I'm having a really hard time to make GWT + JAVA + JDO + Google AppEngine working with DataStore.
I was trying to follow different tutorial but had no luck. For example I wend to these tutorials: [TUT1](https://stackoverflow.com/questions/958879/problems-passing-class-objects-through-gwt-rpc) [TUT2](http://fredsa.allen-sauer.com/2009/04/1st-look-at-app-engine-using-jdo.html)
I was not able to figure out how and what i need to do in order to make this work.
Please look at my simple code and tell me what do i need to do so i can persist it to the datastore:
**1. ADDRESS ENTITY**
```
package com.example.rpccalls.client;
import java.io.Serializable;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
public class Address implements Serializable{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private int addressID;
@Persistent private String address1;
@Persistent private String address2;
@Persistent private String city;
@Persistent private String state;
@Persistent private String zip;
public Address(){}
public Address(String a1, String a2, String city, String state, String zip){
this.address1 = a1;
this.address2 = a2;
this.city = city;
this.state = state;
this.zip = zip;
}
/* Setters and Getters */
}
```
**2. PERSON ENTITY**
```
package com.example.rpccalls.client;
import java.io.Serializable;
import java.util.ArrayList;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
@PersistenceCapable
public class Person implements Serializable{
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent private String name;
@Persistent private int age;
@Persistent private char gender;
@Persistent ArrayList<Address> addresses;
public Person(){}
public Person(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
/* Getters and Setters */
}
```
**3. RPCCalls**
```
package com.example.rpccalls.client;
import java.util.ArrayList;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
public class RPCCalls implements EntryPoint {
private static final String SERVER_ERROR = "An error occurred while attempting to contact the server. Please check your network connection and try again.";
private final RPCCallsServiceAsync rpccallService = GWT.create(RPCCallsService.class);
TextBox nameTxt = new TextBox();
Button btnSave = getBtnSave();
public void onModuleLoad() {
RootPanel.get("inputName").add(nameTxt);
RootPanel.get("btnSave").add(btnSave);
}
private Button getBtnSave(){
Button btnSave = new Button("SAVE");
btnSave.addClickHandler(
new ClickHandler(){
public void onClick(ClickEvent event){
saveData2DB(nameTxt.getText());
}
}
);
return btnSave;
}
void saveData2DB(String name){
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
Window.alert("WOOOHOOO, ERROR: " + SERVER_ERROR);
// TODO: Do something with errors.
}
public void onSuccess(String result) {
Window.alert("Server is saying: ' " + result + "'");
}
};
ArrayList<Address> aa = new ArrayList<Address>();
aa.add(new Address("123 sasdf","", "Some City", "AZ", "93923-2321"));
aa.add(new Address("23432 asdf", "Appt 34", "Another City", "AZ", "43434-4432"));
Person p = new Person();
p.setName(name);
p.setAge(23);
p.setGender('m');
p.setAddresses(aa);
// !!!!!!!!!!!!!!!!!! SERVER CALL !!!!!!!!!!!!!!!!!!
rpccallService.saveName(p, callback);
// !!!!!!!!!!!!!!!!!! SERVER CALL !!!!!!!!!!!!!!!!!!
}
}
```
**4. RPCCallsService**
```
package com.example.rpccalls.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("calls")
public interface RPCCallsService extends RemoteService {
String saveName(Person p);
}
```
**5. RPCCallsServiceAsync**
```
package com.example.rpccalls.client;
import com.google.gwt.user.client.rpc.AsyncCallback;
public interface RPCCallsServiceAsync {
void saveName(Person p, AsyncCallback<String> callback);
}
```
**6. \*\*RPCCalls.gwt.xml**
```
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE module PUBLIC "-//Google Inc.//DTD Google Web Toolkit 1.6.4//EN" "http://google-web-toolkit.googlecode.com/svn/tags/1.6.4/distro-source/core/src/gwt-module.dtd">
<module rename-to='rpccalls'>
<inherits name='com.google.gwt.user.User'/>
<inherits name='com.google.gwt.user.theme.standard.Standard'/>
<entry-point class='com.example.rpccalls.client.RPCCalls'/>
</module>
```
I tried to add Key class and everything else in those tutorials but it looks like i'm missing something.
Here is my error:
[alt text http://vasura.s3.amazonaws.com/Picture2.png](http://vasura.s3.amazonaws.com/Picture2.png)
or before i was getting this error:
> Key cannot be resolved to a type
What is the best solution to make this working? | [Sriram Narayan](http://blog.sriramnarayan.com/2009/04/gwt-and-jdo-on-java-appengine.html) says to String-encode the Key to get it to pass through GWT's RPC mechanism:
`@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class SomeDomainClass implements Serializable {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
@Extension(vendorName = "datanucleus", key = "gae.encoded-pk", value = "true")
String id;` | The second tutorial you've referenced has a section on shadowing the `com.google.appengine.api.datastore.Key` class, since it's not available to GWT:
> Since I'm not doing anything with the Key class on the client I'm going to stub it out. This actually requires a few steps and involves the super-src feature of GWT XML module files.
You might want to take a look at [the GWT documentation](http://code.google.com/docreader/#p=google-web-toolkit-doc-1-5&s=google-web-toolkit-doc-1-5&t=DevGuideJavaToJavaScriptCompiler), which states that
> The heart of GWT is a compiler that converts Java source into JavaScript
, therefore you need to have the source code available to use a given class in the client code. | GWT with JDO problem | [
"",
"java",
"google-app-engine",
"gwt",
"rpc",
"google-cloud-datastore",
""
] |
Does anyone know how to parse SQL Text with VB.NET?
Ex: I got a sql file "CREATE TABLE..." i want to get an array of columns and an array of data types. | Expanding on @Tomalak's post: once you have the table built you can use a DataReader to select just 1 line if you only need the schema or your actual data, then do something like this:
```
Dim myReader As DataReader
Dim myTable As DataTable
Dim myColumns As New Collection
myReader = //' get your data
If myReader.HasRows Then
myTable.Load(myReader)
For Each col As DataColumn In myTable.Columns
myColumns.Add(col.DataType.ToString, col.ColumnName)
Next
End If
```
The collection myColumns will now have a `Key` of the column's name and the `Value` is the columns datatype. You can modify this to make 2 separate collections if you need.
Parsing a string on the other hand will involve significantly more debugging and offer lots of room for error. | It may be the easiest approach to feed that statement to an SQL Server and actually *create* that table in a temp database.
After that, finding out about the table structure would be easy.
All you'd have to parse out of the statement string would be the name of the table. Even better, you could simply replace it and have a known table name from the start.
Additionally, you would get the info if the statement is even valid SQL. | Parsing SQL text | [
"",
"sql",
"vb.net",
"parsing",
""
] |
I need some help figuring out what I'm doing wrong here. I am trying
to master one to many relationships and running into a roadblock.
I tried to modify the Employee and ContactInfo example to do one to
many mappings:
Everything works if I create both the parent (employee) and child
(Contact) and then call makePersistent.
But if I try to add a child object to an already persistent parent, I
get a java.lang.ClassCast exception. The full stack trace is at the
bottom of the post.
Here is the code that breaks (If I move the makePersistent() call to
after the add(), everything works fine:
```
public void testOneToMany(){
pm = newPM();
Employee e = new Employee("peter");
pm.makePersistent(e);
Contact c = new Contact("123 main");
List<Contact> contacts = e.getContacts();
contacts.add(c); // here I get java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.String
}
```
Here is the parent class
```
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Employee {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Long id;
@Persistent
private String name;
@Persistent(mappedBy="employee")
private List<Contact> contacts;
public Employee(String e){
contacts = new ArrayList<Contact>();
name = e;
}
List<Contact> getContacts(){
return contacts;
}
Long getId(){
return id;
}
public String getName(){
return name;
}
}
```
Here is the child class
```
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class Contact {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String streetAddress;
@Persistent
private Employee employee;
public Contact(String s){
streetAddress = s;
}
public String getAddress(){
return streetAddress;
}
public Employee getEmployee(){
return employee;
}
}
```
Here's the full stacktrace:
```
java.lang.ClassCastException: java.lang.Long cannot be cast to
java.lang.String
at org.datanucleus.store.appengine.DatastoreRelationFieldManager
$1.setObjectViaMapping(DatastoreRelationFieldManager.java:148)
at org.datanucleus.store.appengine.DatastoreRelationFieldManager
$1.apply(DatastoreRelationFieldManager.java:108)
at
org.datanucleus.store.appengine.DatastoreRelationFieldManager.storeRelations
(DatastoreRelationFieldManager.java:80)
at
org.datanucleus.store.appengine.DatastoreFieldManager.storeRelations
(DatastoreFieldManager.java:770)
at
org.datanucleus.store.appengine.DatastorePersistenceHandler.insertObject
(DatastorePersistenceHandler.java:231)
at org.datanucleus.state.JDOStateManagerImpl.internalMakePersistent
(JDOStateManagerImpl.java:3067)
at org.datanucleus.state.JDOStateManagerImpl.makePersistent
(JDOStateManagerImpl.java:3043)
at org.datanucleus.ObjectManagerImpl.persistObjectInternal
(ObjectManagerImpl.java:1258)
at org.datanucleus.sco.SCOUtils.validateObjectForWriting
(SCOUtils.java:1365)
at
org.datanucleus.store.mapped.scostore.ElementContainerStore.validateElementForWriting
(ElementContainerStore.java:401)
at
org.datanucleus.store.mapped.scostore.FKListStore.validateElementForWriting
(FKListStore.java:764)
at org.datanucleus.store.mapped.scostore.FKListStore.internalAdd
(FKListStore.java:503)
at org.datanucleus.store.mapped.scostore.AbstractListStore.add
(AbstractListStore.java:123)
at org.datanucleus.sco.backed.List.add(List.java:752)
at com.btg.plyus.scratch.JDOTest.testOneToMany(JDOTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at junit.framework.TestCase.runTest(TestCase.java:168)
at com.btg.plyus.test.BaseTest.runTest(BaseTest.java:79)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.OldTestClassRunner.run
(OldTestClassRunner.java:76)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run
(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run
(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests
(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests
(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run
(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main
(RemoteTestRunner.java:196)
``` | i dont think *you* are doing anything wrong. this seems to be a bug with the vendor code. see [this link](http://code.google.com/p/datanucleus-appengine/issues/detail?id=59). there isnt a whole lot of info, but they intimate that the PK on your type `Long` Employee.id is problematic. | Your database's id column isn't compatible with Long. I don't think this has anything to do with the parent/child mapping. If you want to confirm, please share your create statements. | ClassCastException when trying to add child to parent in owned one to many. (using jdo on google appengine) | [
"",
"java",
"google-app-engine",
"jdo",
"google-cloud-datastore",
""
] |
I am using Spring to manage my DAO & Services. And JSF for UI. I want to use dependency injection in my JSF backing-bean. There is an article that explained how I can do that.
But I have two separate projects: one for Service and one for UI. The Spring configuration file is located in Service project.
How can I connect both project with Spring? I want to annotate my JSF pages for DI. | I find some solution one:
[Sample Application using JSF, Spring 2.5, and Java Persistence APIs with Glassfish v2](http://blogs.oracle.com/carolmcdonald/entry/sample_application_using_jsf_spring)
. But I have problem with it.
I can post this problem hear or must create new topic? Sorry for stupid question, i'm newbie her. | You can achieve this by using Spring Web Flow.
Spring have examples which show:
1. A JSF centric approach where your Spring and JSF beans are managed/configured the JSF way (faces-config) and a
2. Spring centric approach where your beans (including ManagedBeans) are managed in the Spring Context.
See [Spring Flow Web Home](http://www.springsource.org/webflow) | JSF 1.2 + Spring 2.5. How to? | [
"",
"java",
"spring",
"jsf",
""
] |
I have a table "users" with a column "date\_of\_birth" (DATE format with day, month, year).
In frontend I need to list 5 upcoming birthdays.
Spent ages trying to work out the logic.. also browsed every possible article in Google with no luck..
Any suggestions how to do this in RoR?
Thanks! | Several answers have suggested calculating/storing *day of year* and sorting on that, but this alone won't do much good when you're close to the end of the year and need to consider people with birthdays in the beginning of the next year.
I'd go for a solution where you calculate the full date (year, month, day) of each person's *next birthday*, then sort on that. You can do this in Ruby code, or using a stored procedure in the database. The latter will be faster, but will make your app harder to migrate to a different db platform later.
It would be reasonable to update this list of upcoming birthdays once per day only, which means you can use some form of caching. Thus the speed of the query/code needed is less of an issue, and something like this should work fine as long as you cache the result:
```
class User
def next_birthday
year = Date.today.year
mmdd = date_of_birth.strftime('%m%d')
year += 1 if mmdd < Date.today.strftime('%m%d')
mmdd = '0301' if mmdd == '0229' && !Date.parse("#{year}0101").leap?
return Date.parse("#{year}#{mmdd}")
end
end
users = User.find(:all, :select => 'id, date_of_birth').sort_by(&:next_birthday).first(5)
```
**Edit**: Fixed to work correctly with leap years. | Thanks to this post in my rails 3 app i use:
```
u = User.where("strftime('%m%d', date_of_birth) = ?", Date.today.strftime('%m%d'))
```
Update:
To use this with Postgresql:
```
u = User.where("extract(month from date_of_birth) = ? AND extract(day from date_of_birth) = ?", Date.today.strftime('%m'), Date.today.strftime('%d'))
``` | How to create "Upcoming birthdays" module in Rails? | [
"",
"sql",
"mysql",
"ruby-on-rails",
"ruby",
""
] |
How i can determine when a web service is available (on-line)? in Delphi or C#? | Just do a valid call to the web service. If it times out, or you get a 404 error, the web service is not available. | You can try this method..
```
public bool IsAddressAvailable(string address)
{
try
{
using(System.Net.WebClient client = new WebClient())
{
client.DownloadData(address);
return true;
}
}
catch
{
return false;
}
}
```
...and call it like this...
```
MessageBox.Show(IsAddressAvailable("http://localhost/my.webservices/mywebservice.asmx").ToString());
``` | Determine when a web service is available | [
"",
"c#",
"web-services",
"delphi",
""
] |
I have 2 APIs from 2 different companies that allow me to communicate with their servers in order to process transactions. I am tasked with creating a generic interface to these APIs. I came up with something like this:
```
IServiceProvider <- ServiceProvider <- CompanyAServiceProvider
IServiceProvider <- ServiceProvider <- CompanyBServiceProvider
```
In `CompanyAServiceProvider` I am using the API that they offer to interface with their remote servers. This API from company A throws exceptions that are completely different from Company B's.
I can handle the exception locally but I don't really think that suites the situation.
```
public String purchase(String amount) {
try {
request = new Request( RequestIF.NEW_ORDER_TRANSACTION );
} catch ( InitializationException e ) {
//do something.
}
}
```
Or I can throw this exception to the caller:
```
public String purchase(String amount) throws Exception {
request = new Request( RequestIF.NEW_ORDER_TRANSACTION );
}
```
And let the caller handle just the `Exception` no matter what that exception is and no matter what API throws it.
How can I write an interface to 2 different APIs and keep it generic when I am dealing with 2 different sets of thrown exceptions. Am I dealing with this correctly? What would be the best choice? | In this case I create my own Exception sublcass and just wrap the actual exception. My API then exposes only my exception. | Think about what level of abstraction you are dealling with at the level of the calling functions. Presumably you don't want to expose details of the individual companies you are dealing with, and would prefer to deal with more generic concepts like Orders, PurchaceTransactions etc.
So the previous poster's advice is good: create a class like PurchaseException, which is a wrapper around the information you got back from the vendor's individual exception classes. | Exception handling pattern for this type of situation? | [
"",
"java",
"exception",
""
] |
I'm working on a standard Java system with critical timing requirements for my producers (1/100s of ms matters).
I have a producer placing stuff in a blocking queue, and a single consumer later picking up that stuff and dumping it to a file. The consumer blocks when data is not available.
Obviously, blocking queue is the appropriate interface, but which actual implementation should I choose if I want to *minimize the cost to the producer*? I wan to play as little as possible on things like locking and allocating when I am putting stuff in the queue, and I don't mind if the consumer has to wait a lot longer or work a lot harder.
Is there an implementation that can be faster because I only have a single consumer and single producer ? | Well, there really aren't too many options. Let me go through the [listed subclasses](http://java.sun.com/javase/6/docs/api/java/util/concurrent/BlockingQueue.html):
[`DelayQueue`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/DelayQueue.html), [`LinkedBlockingDeque`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingDeque.html), [`PriorityBlockingQueue`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/PriorityBlockingQueue.html), and [`SynchronousQueue`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/SynchronousQueue.html) are all made for special cases requiring extra functionality; they don't make sense in this scenario.
That leaves only [`ArrayBlockingQueue`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ArrayBlockingQueue.html) and [`LinkedBlockingQueue`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html). If you know how to tell whether you need an `ArrayList` or a `LinkedList`, you can probably answer this one yourself.
Note that in `LinkedBlockingQueue`, "linked nodes are dynamically created upon each insertion"; this might tend to push you toward `ArrayBlockingQueue`. | You can write a latency sensitive system in Java but you have to be careful of memory allocations, information passing between threads and locking. You should write some simple tests to see how much time these things cost on your server. (They vary bases on the OS and the memory architecture)
If you do this you can get stable timings for operations up to 99.99% of the time. This is not proper real-time, but it may be close enough. On a trading system, using Java instead of C costs might cost £100/d, however the cost of developing in C/C++ rather than Java is likely to be much higher than this. e.g. in terms of the flexibility it gives us and the number of bugs it saves.
You can get fairly close the same amount of jitter you would see in a C program doing the same thing. Some call this "C-like" Java.
Unfortunately it takes about 8 micro-second to pass an object between threads in Java via a ArrayBlockingQueue on the servers I work on and I suggest you test this on your servers. A simple test is to pass the System.nanoTime() between threads and see how long it takes.
ArrayBlockingQueue has a "feature" where it creates an object on each element added (though there is not much of a good reason to do so) So if you find a standard implementation which doesn't do this, let me know. | Which Java blocking queue is most efficient for single-producer single-consumer scenarios | [
"",
"java",
"collections",
"concurrency",
""
] |
I have a messages folder(package) with `__init__.py` file and another module `messages_en.py` inside it. In `__init__.py` if I import `messages_en` it works, but `__import__` fails with "ImportError: No module named messages\_en"
```
import messages_en # it works
messages = __import__('messages_en') # it doesn't ?
```
I used to think 'import x' is just another way of saying `__import__('x')` | Adding the globals argument is sufficient for me:
```
__import__('messages_en', globals=globals())
```
In fact, only `__name__` is needed here:
```
__import__('messages_en', globals={"__name__": __name__})
``` | If it is a path problem, you should use the `level` argument (from [docs](http://docs.python.org/2/library/functions.html?highlight=__import__#__import__)):
```
__import__(name, globals={}, locals={}, fromlist=[], level=-1) -> module
Level is used to determine whether to perform
absolute or relative imports. -1 is the original strategy of attempting
both absolute and relative imports, 0 is absolute, a positive number
is the number of parent directories to search relative to the current module.
``` | How can I import a package using __import__() when the package name is only known at runtime? | [
"",
"python",
"python-import",
""
] |
I'm setting up a registration page, and I'm using PHP primarily to verify the data.
I've realized that using a client-driven language for some of the validation will reduce the workload from the server.
I don't have much knowledge in jquery, but I'm looking for code that will determine the correct syntax of an email (ex, one '@' and no funny characters).
Additionally, is there a function in jquery where every time, after a certain event (on click, on keyup) it preforms a php script and display the results without reloading? I'm looking for something that will allow me to give the user fast feedback on more complicated functions (like looking up an email's DNS to make sure its' real, checking if the username exists ect.)
Can someone point me to a resource on this? | There is a very widely used validation plugin for jquery that you can find here:
<http://plugins.jquery.com/project/validate>
It contains many "common" validation rules built in, and you can add your own. Email is there by default.
But always remember to always validate on the server side. You can add client side validation to increase responsiveness, but remember that a malicious user can easily bypass any javascript validation. | It should be noted that client side validation should never be relied upon, but should exist to enhance the user experience. You MUST perform validation on the server as client side code is easily circumvented. | using jquery vs php to reduce load | [
"",
"php",
"jquery",
"ajax",
""
] |
Say I create *CreateUserWizard* control and use *AspNetSqlMembershipProvider* (defined in *machine.config*) as a default membership provider. Assuming I change default provider's *requiresQuestionAndAnswer* attribute to *false*, then *CreateUserWizard* control template should not be required to provide *Question* and *Answer* fields. But if I request the page via *IIS7* I get the following exception:
> CreateUserWizard1: CreateUserWizardStep.ContentTemplate does not contain an IEditableTextControl with ID Question for the security question, this is required if your membership provider requires a question and answer.
A) The above exception suggests that when requesting a page via *IIS7*, runtime doesn’t use *AspNetSqlMembershipProvider* (defined in *machine.config*)as a default provider?! If true, then why is that?
B) And where can I find the definition for *IIS7’s* default provider?
thanx
EDIT:
Here is `<Membership>` element in machine.config file:
```
<membership>
<providers>
<add name="AspNetSqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider, System.Web,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="LocalSqlServer"
enablePassswordRetrieval="false"
requiresQuestionAndAnswer="false"
applicationName="/" requiresUniqueEmail="false"
passwordFormat="Hashed" maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
passwordStrengthRegularExpression=""/>
</providers>
</membership>
```
> Are you changing the `machine.config` for the correct version of runtime?
I'm not sure what you mean by that. I'm running Asp.Net 3.5, which I think uses Asp.Net engine version 2.0.50727. Thus I manipulated machine.config located inside *C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG* | IIS7 uses its own configuration file located at `%windir%\System32\inetsrv\config\applicationHost.config`. However, this file deals with IIS7 specific configuration (e.g. `<system.webServer>`) and not `<system.web>` stuff. I believe those are still read from `machine.config` and `web.config` files. Indeed, the default value (specified in `machine.config`) for `requiresQuestionAndAnswer` for the `AspNetSqlMembershipProvider` is `true` on my machine.
**UPDATE:**
Under a 64 bit OS, a .NET application can either run on a 32 bit CLR in WOW64 mode or natively run under x64 mode. Each .NET framework instance has its own set of config files and ignores all other configuration files.
IIS7 on a 64 bit OS runs applications in 64 bit mode by default. You can, however, set an application pool to run as a 32 bit WOW64 process (`enable32BitAppOnWin64`, which you can set in Advanced Settings dialog for an application pool in IIS7 manager). If you do that, obviously it'll use settings from 32 bit `machine.config`. The reason VS Web server uses 32 bit `machine.config` is exactly this: it runs as a WOW64 process. | Where exactly did you make the change on "requiresQuestionAndAnswer"? If it is on machine.config, IIS should honor that. | Does IIS7 use different default membership provider? | [
"",
"c#",
"asp.net",
"iis",
"iis-7",
"asp.net-membership",
""
] |
When I have just one <%@Register %> line in my page, it loads fine.
When I add a second one, it gives me this compilation error:
> Compiler Error Message: CS0433: The
> type 'ASP.test1\_ascx' exists in both
> 'c:\Users\me\AppData\Local\Temp\Temporary
> ASP.NET
> Files\root\c2d75602\aae4f906\App\_Web\_dta-e2tq.dll'
> and
> 'c:\Users\me\AppData\Local\Temp\Temporary
> ASP.NET
> Files\root\c2d75602\aae4f906\App\_Web\_layerwindow.ascx.cdcab7d2.zxul1sik.dll'
(slightly anonymized)
Any ideas?
**EDIT:** Additional information I just noticed: the line above the broken line in the YSOD said: [System.Diagnostics.DebuggerNonUserCodeAttribute()] When I searched for information on this, I found a page telling me to check to make sure I didn't have any open brackets I wasn't closing. Haven't found any yet, but this may be part of the issue.
**EDIT:** Argh. Just want to kill the computer at this point. After daughtkom suggested creating a new project to see if the code worked from scratch, I did that and it worked. I then decided to create a new control and copied the Test1 code into there... and then it started working. (No changes to Test1 or Default.aspx, just created Test1-2.ascx.) Then I added the link to Test2 into Default.aspx... and now it's giving me the same error, just with test2. And creating a Test2-2.ascx isn't fixing it this time. | I ended up setting "<compilation batch="false">" in my web.config file, which fixed the issue. I found it from a MSDN article... somewhere. If I find the link again I'll post it. | Delete your temporary files or restart your webserver. | Adding a second <%@Register %> line to my page causes Compilation Error | [
"",
"c#",
"asp.net",
""
] |
I've got this query:
```
SELECT PICTURE FROM LOGO WHERE LOGONO = ?
```
("PICTURE" is an Image column in SQL Server)
And this code to read the data:
```
using (DbDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
if (!reader.IsDBNull(0))
{
byte[] buffer = new byte[8000];
while (reader.GetBytes(0, 0, buffer, 0, 8000) > 0)
picture.AddRange(buffer);
}
}
}
```
The problem is an InvalidOperationException ("No data exists for the row/column") always gets thrown on the reader.IsDBNull(0) statement when the column contains null.
[MSDN](http://msdn.microsoft.com/en-us/library/system.data.datatablereader.isdbnull.aspx) says:
> Call this method to see if there are null column values before calling the typed get methods (for example, GetByte, GetChar, and so on) to avoid raising an error.
How can I check that the column doesn't contain null without triggering the Exception? Am I going about this in the wrong way? | You need to call reader.[Read()](http://msdn.microsoft.com/en-us/library/system.data.datatablereader.read.aspx) before accessing any data. From the MSDN docs for Read:
> The default position of the DataTableReader is before the first record. Therefore, you must call Read to start accessing any data. | You did not call reader.Read(). Since your working with a reader, you either need to check if Read returns true for a single record, or use a while loop to iterate through all the records.
```
if (reader.Read())
{
// handle single record
}
// or
while (reader.Read())
{
// handle each record
}
``` | Reading an image from the database using C#? | [
"",
"c#",
"image",
"blob",
""
] |
How can I convert the `str` representation of a dictionary, such as the following string, into a `dict`?
```
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
```
I prefer not to use `eval`. What else can I use? | You can use the built-in [`ast.literal_eval`](https://docs.python.org/library/ast.html#ast.literal_eval):
```
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
```
This is safer than using `eval`. As its own docs say:
```
>>> help(ast.literal_eval)
Help on function literal_eval in module ast:
literal_eval(node_or_string)
Safely evaluate an expression node or a string containing a Python
expression. The string or node provided may only consist of the following
Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
and None.
```
For example:
```
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
``` | <https://docs.python.org/library/json.html>
JSON can solve this problem, though its decoder wants double quotes around keys and values. If you don't mind a replace hack...
```
import json
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}"
json_acceptable_string = s.replace("'", "\"")
d = json.loads(json_acceptable_string)
# d = {u'muffin': u'lolz', u'foo': u'kitty'}
```
NOTE that if you have single quotes as a part of your keys or values this will fail due to improper character replacement. This solution is only recommended if you have a strong aversion to the eval solution.
More about json single quote: [jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON](https://stackoverflow.com/questions/2275359/jquery-single-quote-in-json-response) | Convert a String representation of a Dictionary to a dictionary | [
"",
"python",
"string",
"dictionary",
""
] |
I have an array of ushort pixel data that I need to save as a jpeg file. From what I've found I can do this by using
```
Image.Save(path, ImageFormat.Jpeg);
```
but I don't know how to get the ushort data into the Image object. I've found ways to do this with byte arrays but not ushort.
I've spent far to much time trying to figure this out so now I ask the mighty StackOverflow, How do I this?
Edit:
Sorry, the ushorts are 16 bit grayscale values. | I think you have to actually create a `Bitmap`, draw the pixels onto it and save it afterwards.
Something like this:
```
var bitmap = new Bitmap(sizeX, sizeY, Imaging.PixelFormat.Format16bppGrayScale)
for (y = 0; ...)
for (x = 0; ...)
{
bitmap.SetPixel(x, y, color information from ushort array);
}
bitmap.Save("filename.jpg", ImageFormat.Jpeg);
```
Note that I don't know how to get a 16 bit greyscale color information into the Color struct. | This is a complete working example based on the accepted answer:
```
public static void SaveJpg(string fileName,int sizeX,int sizeY,ushort [] imData)
{
var bitmap = new Bitmap(sizeX, sizeY, PixelFormat.Format48bppRgb);
int count = 0;
for (int y = 0; y < sizeY; y++)
{
for (int x = 0; x < sizeX; x++)
{
bitmap.SetPixel(x, y, Color.FromArgb(imData[count], imData[count], imData[count]));
count++;
}
}
bitmap.Save(fileName, ImageFormat.Jpeg);
}
``` | ushort array to Image object | [
"",
"c#",
""
] |
In another question I posted someone told me that there is a difference between:
```
@variable
```
and:
```
variable
```
in MySQL. He also mentioned how MSSQL has batch scope and MySQL has session scope. Can someone elaborate on this for me? | MySQL has a concept of *[user-defined variables](http://dev.mysql.com/doc/refman/5.0/en/user-variables.html)*.
They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.
They are prepended with an `@` sign, like this: `@var`
You can initialize this variable with a `SET` statement or inside a query:
```
SET @var = 1
SELECT @var2 := 2
```
When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:
```
DELIMITER //
CREATE PROCEDURE prc_test (var INT)
BEGIN
DECLARE var2 INT;
SET var2 = 1;
SELECT var2;
END;
//
DELIMITER ;
```
These variables are not prepended with any prefixes.
The difference between a procedure variable and a session-specific user-defined variable is that a procedure variable is reinitialized to `NULL` each time the procedure is called, while the session-specific variable is not:
```
CREATE PROCEDURE prc_test ()
BEGIN
DECLARE var2 INT DEFAULT 1;
SET var2 = var2 + 1;
SET @var2 = @var2 + 1;
SELECT var2, @var2;
END;
SET @var2 = 1;
CALL prc_test();
var2 @var2
--- ---
2 2
CALL prc_test();
var2 @var2
--- ---
2 3
CALL prc_test();
var2 @var2
--- ---
2 4
```
As you can see, `var2` (procedure variable) is reinitialized each time the procedure is called, while `@var2` (session-specific variable) is not.
(In addition to user-defined variables, MySQL *also* has some predefined "system variables", which may be "global variables" such as `@@global.port` or "session variables" such as `@@session.sql_mode`; these "session variables" are unrelated to session-specific user-defined variables.) | In MySQL, `@variable` indicates a [user-defined variable](http://dev.mysql.com/doc/refman/5.0/en/user-variables.html). You can define your own.
```
SET @a = 'test';
SELECT @a;
```
Outside of stored programs, a `variable`, without `@`, is a [system variable](http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html), which you cannot define yourself.
The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.
This is in contrast with MSSQL, where the variable will only be available in the current batch of queries (stored procedure, script, or otherwise). It will not be available in a different batch in the same session. | MySQL: @variable vs. variable. What's the difference? | [
"",
"sql",
"mysql",
"database",
"local-variables",
"user-defined-variables",
""
] |
I have been reading Programming Microsoft® Visual C#® 2008: The Language to get a better understanding of C# and what can be done with it. I came across partial classes which I had already encountered from ASP.Net's Page class.
To me it seems that you can do what partial classes do with an abstract class and an overridden one. Obviously one team will be in control of the interface via the abstract methods but you would be relying on each other anyway. And if the goal is collaboration then isn't that what source control and other tools solve.
I am just missing the point to a partial class. Also could someone provide a real world use. | Partial classes have nothing to do with object inheritance. Partial classes are just a way of splitting the source code that defines a class into separate files (this is for example done when you create a new form in your Windows Forms application - one file is "your" code, another file .designer.cs contains the code that VS2008 manages for you). | A good usage example is when one side of the partial class is generated (such as an ORM) | What are the benefits to using a partial class as opposed to an abstract one? | [
"",
"c#",
"class",
"abstract-class",
"partial-classes",
""
] |
I have 1 DLL in the .Net 3.5 framework and another in 2.0. The `ListBoxItem` class exists in 2.0 and I have linked the class in the 3.5 DLL in the same namespace.
When I try to compile I get an "exists in both" error. How can I compile this and maintain the same structure.
I don't want reference the 2.0 DLL to 3.5 to eliminate this problem, I want keep these DLLs separate. | This doesn't seem like a good idea no matter what, but change the namespaces and fully qualify your usages.
Otherwise, why don't you just reference one dll? | This is a relevant solution as well, where you can define which type to use in your usings:
<https://stackoverflow.com/a/9194582/178620>
You can't use fully qualified names when dealing with Extension methods and etc. | The type <type> exists in both DLLs | [
"",
"c#",
".net",
""
] |
Why can't you pass an anonymous method as a parameter to the `BeginInvoke` method? I have the following code:
```
private delegate void CfgMnMnuDlg(DIServer svr);
private void ConfigureMainMenu(DIServer server,)
{
MenuStrip mnMnu = PresenterView.MainMenu;
if (mnMnu.InvokeRequired)
{
mnMnu.BeginInvoke((CfgMnMnuDlg)ConfigureMainMenu,
new object[] { server});
}
else
{
// Do actual work here
}
}
```
I'm trying to avoid declaring the delegate. Why can't I write something like the below instead? Or can I, and I just can't figure out the correct syntax? The below currently generates an:
> Argument type 'Anonymous method' is not assignable to parameter type 'System.Delegate'
Ok, that's right of course, but is there some other syntax I can use to do this (avoid having to declare a separate delegate in order to use `BeginInvoke()`?
(Being able to do this would fit in neatly with the concept of using anon methods/lamdas in place of explicit delegates which works so cleanly everywhere else.)
```
private void ConfigureMainMenu(DIServer server,)
{
MenuStrip mnMnu = PresenterView.MainMenu;
if (mnMnu.InvokeRequired)
{
mnMnu.BeginInvoke( // pass anonymous method instead ?
delegate(DIServer svr) { ConfigureMainMenu(server);},
new object[] { server});
}
else
{
// Do actual work here
}
}
``` | Try this:
```
control.BeginInvoke((MethodInvoker) delegate { /* method details */ });
```
Or:
```
private void ConfigureMainMenu(DIServer server)
{
if (control.InvokeRequired)
{
control.BeginInvoke(new Action<DIServer >(ConfigureMainMenu), server);
}
else
{
/* do work */
}
}
```
Or:
```
private void ConfigureMainMenu(DIServer server)
{
MenuStrip mnMnu = PresenterView.MainMenu;
if (mnMnu.InvokeRequired)
{
// Private variable
_methodInvoker = new MethodInvoker((Action)(() => ConfigureMainMenu(server)));
_methodInvoker.BeginInvoke(new AsyncCallback(ProcessEnded), null); // Call _methodInvoker.EndInvoke in ProcessEnded
}
else
{
/* do work */
}
}
``` | You should be able to write something like this:
```
private void ConfigureMainMenu(DIServer server,)
{
MenuStrip mnMnu = PresenterView.MainMenu;
if (mnMnu.InvokeRequired)
{
mnMnu.BeginInvoke(new Action<DIServer>(ConfigureMainMenu),
new object[] { server});
}
else
{
// Do actual work here
}
}
``` | Anonymous method as parameter to BeginInvoke? | [
"",
"c#",
"delegates",
"anonymous-methods",
"begininvoke",
""
] |
Using jQuery how would I find/extract the "Spartan" string if the outputted HTML page had the following..
```
<a href="/mytlnet/logout.php?t=e22df53bf4b5fc0a087ce48897e65ec0">
<b>Logout</b>
</a> : Spartan<br>
``` | [Regular Expressions](http://www.regular-expressions.info/javascript.html). Or by [splitting the string](http://www.w3schools.com/jsref/jsref_split.asp) in a more tedious fashion.
Since I'm not a big regex-junkie, I would likely get the text-equivalent using .text(), then split the result on ":", and grab the second index (which would be the 'Spartan' text). | if the pattern is going to be consistent you can your RegEx
or if the markup is going to be the same you can try the [jQuery HTML Parser](http://ejohn.org/blog/pure-javascript-html-parser/) | How to extract a string from a larger string? | [
"",
"javascript",
"jquery",
"string",
"extract",
""
] |
I want to extend a large C project with some new functionality, but I really want to write it in Python. Basically, I want to call Python code from C code. However, Python->C wrappers like SWIG allow for the OPPOSITE, that is writing C modules and calling C from Python.
I'm considering an approach involving IPC or RPC (I don't mind having multiple processes); that is, having my pure-Python component run in a separate process (on the same machine) and having my C project communicate with it by writing/reading from a socket (or unix pipe). my python component can read/write to socket to communicate. Is that a reasonable approach? Is there something better? Like some special RPC mechanism?
Thanks for the answer so far - **however, i'd like to focus on IPC-based approaches since I want to have my Python program in a separate process as my C program. I don't want to embed a Python interpreter. Thanks!** | I recommend the [approaches detailed here](http://www.linuxjournal.com/article/8497). It starts by explaining how to execute strings of Python code, then from there details how to set up a Python environment to interact with your C program, call Python functions from your C code, manipulate Python objects from your C code, etc.
**EDIT**: If you really want to go the route of IPC, then you'll want to use [the struct module](http://docs.python.org/library/struct.html) or better yet, [protlib](http://courtwright.org/protlib). Most communication between a Python and C process revolves around passing structs back and forth, either [over a socket](http://docs.python.org/library/socket.html) or through [shared memory](http://docs.python.org/library/mmap.html).
I recommend creating a `Command` struct with fields and codes to represent commands and their arguments. I can't give much more specific advice without knowing more about what you want to accomplish, but in general I recommend the [protlib](https://pythonhosted.org/protlib/) library, since it's what I use to communicate between C and Python programs (disclaimer: I am the author of protlib). | Have you considered just wrapping your python application in a shell script and invoking it from within your C application?
Not the most elegant solution, but it is very simple. | How do you call Python code from C code? | [
"",
"python",
"c",
"interop",
"cross-domain",
""
] |
I just finished designing a simple code program. I called it a "Guessing Game". The program is so far working fine and I would like to open it without opening my Microsoft Visual Studio.
How can I do that? | The easiest way is:
* Find the drop-down box at the top of Visual Studio's window that says *Debug*
* Select *Release*
* Hit `F6` to build it
* Switch back to *Debug* and then close Visual Studio
* Open Windows Explorer and navigate to your project's folder (`My Documents\Visual Studio 200x\Projects\my_project\`)
* Now go to `bin\Release\` and copy the executable from there to wherever you want to store it
* Make shortcuts as appropriate and enjoy your new game! :) | Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder. | How to compile the finished C# project and then run outside Visual Studio? | [
"",
"c#",
"projects",
""
] |
Does anyone know how I can check if a string contains well-formed XML without using something like `XmlDocument.LoadXml()` in a try/catch block? I've got input that may or may not be XML, and I want code that recognises that input may not be XML without relying on a try/catch, for both speed and on the general principle that non-exceptional circumstances shouldn't raise exceptions. I currently have code that does this;
```
private bool IsValidXML(string value)
{
try
{
// Check we actually have a value
if (string.IsNullOrEmpty(value) == false)
{
// Try to load the value into a document
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(value);
// If we managed with no exception then this is valid XML!
return true;
}
else
{
// A blank value is not valid xml
return false;
}
}
catch (System.Xml.XmlException)
{
return false;
}
}
```
But it seems like something that shouldn't require the try/catch. The exception is causing merry hell during debugging because every time I check a string the debugger will break here, 'helping' me with my pesky problem. | I don't know a way of validating without the exception, but you can change the debugger settings to only break for `XmlException` if it's unhandled - that should solve your immediate issues, even if the code is still inelegant.
To do this, go to Debug / Exceptions... / Common Language Runtime Exceptions and find System.Xml.XmlException, then make sure only "User-unhandled" is ticked (not Thrown). | Steve,
We had an 3rd party that accidentally sometimes sent us JSON instead of XML. Here is what I implemented:
```
public static bool IsValidXml(string xmlString)
{
Regex tagsWithData = new Regex("<\\w+>[^<]+</\\w+>");
//Light checking
if (string.IsNullOrEmpty(xmlString) || tagsWithData.IsMatch(xmlString) == false)
{
return false;
}
try
{
XmlDocument xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xmlString);
return true;
}
catch (Exception e1)
{
return false;
}
}
[TestMethod()]
public void TestValidXml()
{
string xml = "<result>true</result>";
Assert.IsTrue(Utility.IsValidXml(xml));
}
[TestMethod()]
public void TestIsNotValidXml()
{
string json = "{ \"result\": \"true\" }";
Assert.IsFalse(Utility.IsValidXml(json));
}
``` | Check well-formed XML without a try/catch? | [
"",
"c#",
"xml",
"well-formed",
""
] |
I'm a PHP virgin (first day), so please type slowly.
I have a number of images, bg\_001.jpg, bg\_002.jpg, etc., which I want to rotate through each time the page is refreshed. I tried this:
```
if (isset($_COOKIE["bg1"])) {
$img_no = $_COOKIE["bg1"] + 1;
} else {
$img_no = 1;
}
$filename = 'bg_' . sprintf("%03d", $img_no) . '.jpg';
if (!file_exists("/img/" . $filename)) {
$img_no = 1;
$filename = 'bg_' . sprintf("%03d", $img_no) . '.jpg';
}
setcookie("bg1", $img_no, time() + 86400);
print '<img src="img/' . $filename . '" alt="" height="175" width="800"> ';
```
Instead of a cookie I get a
```
Warning: Cannot modify header information - headers already sent by (output
started at /home2/.../about.php:7) in /home2/.../about.php on line 31
```
Line 31 being the line with the *setcookie*. I already found pointers about PHP having trouble with Unicode's BOM, but I have no idea how to fix it (if it is the problem here in the first place).
So, to make it official (and avoid a "not a real question" label), how do I fix this? :-)
Constructive criticism on my code is welcome too.
**epilogue:**
Seemed like a common newbie error: several answers toward the same solution within fifteen minutes. Thanks guyz/galz.
So I moved everything except the *print* to the start of the file, and indeed: fixed. | cookies can only be sent, if there are no information sent prior. This means that the first thing in your PHP file has to be `<?php`, and nothing can get before that part (not even the dreaded UTF-8 BOM), because if something is before the first `<?php` (like `<html>`), then php will send those data for the browser and after data is sent you can't use setcookie. Refactor your code to look something like this:
```
<?php
(...)
setcookie(...)
(...)
?>
<HTML>
(...)
</HTML>
```
And double check that editors like notepad didn't put any UTF-8 BOM signatures before the first `<?php` in the file. | With HTTP your header (request/response info) and Content (actual textor binary content) are set separately and Header must precede the Content.
Setting a cookie actually adds a command to the header response, so any modifications to the cookie need to happen before you start outputting any content.
Move all your code that references your cookie before the opening html element on your page and you should be ok. | PHP fails to setcookie | [
"",
"php",
"cookies",
""
] |
I want to make sure that \_content does not end with a NewLine character:
```
_content = sb.ToString().Trim(new char[] { Environment.NewLine });
```
but the **above code doesn't work** since Trim seems to not have an overloaded parameter for a collection of strings, only characters.
**What is the simplest one-liner to remove an Enivronment.Newline from the end of a string?** | The following works for me.
```
sb.ToString().TrimEnd( '\r', '\n' );
```
or
```
sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());
``` | `.Trim()` removes `\r\n` for me (using .NET 4.0). | What is the easiest way in C# to trim a newline off of a string? | [
"",
"c#",
"string",
""
] |
I have a situation where I think using the 'em' metric would be perfect. I have a container with several elements inside. These elements all use em for dimensions, font-size, borders.. everything. I want to be able to grow or shrink all of these elements dynamically by simply changing the em value of the parent container.
At least that's my theory. I tried to implement something like this using jquery but it appears that everything is converted to px and changing the em has no effect on the child elements.
Here is an example:
```
<div id="parent">
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
</div>
<style>
#parent { font-size: 1em; }
.child { width: 10em; height: 10em; font-size: 5em; }
</style>
```
With javascript (jquery for this example), I would like to be able to do something like this:
```
$('#parent').css('font-size', '2em') // This would make everything grow
$('#parent').css('font-size', '.5em') // This would make everything shrink
```
This line does not produce an error. However, after inspecting further it appears that everything has been converted to px value. Thus, parent em values lose their power. Here is what I mean:
After the page renders, I run these commands through the firebug console
```
$('#parent').css('font-size'); // Returns 100px (for example's sake)
$('.child:first').css('font-size'); // Returns 50px
$('#parent').css('font-size', '2em'); // This should affect all children
$('#parent').css('font-size'); // Returns 20px
$('.child:first').css('font-size'); // STILL Returns 50px
```
As you can see, all the children remain at 50px.
Am I going about this the right way? What am I missing? Is this really a lot harder than I think it is? In a sense, I'm trying to duplicate the effect that browser-zoom has.
Thanks for any help. | You try resizing the text using percentage.
```
$('#parent').css('font-size', '200%')// This would make everything grow
$('#parent').css('font-size', '50%') // This would make everything shrink
```
---
edit after comment - using FF2.0
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>test</title>
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<style type="text/css">
body {font-size:10px;}
#parent { font-size: 1em; }
.child { width: 10em; height: 10em; font-size: 5em; }
</style>
<script type="text/javascript">
$(document).ready(function(){
alert($('#parent').css('font-size')); // Returns 10px (for example's sake)
alert($('.child:first').css('font-size')); // Returns 50px
$('#parent').css('font-size', '200%'); // or you can use 2em here
alert($('#parent').css('font-size')); // Returns 20px
alert($('.child:first').css('font-size')); // Returns 100px
});
</script>
</head>
<body>
<div id="parent">
<div class="child">Text</div>
<div class="child">Text</div>
<div class="child">Text</div>
</div>
</body>
</html>
``` | The above works just fine for me in Opera, FF and IE6 (can't test others). Using these two calls do grow and shrink the text.
```
$('#parent').css('font-size', '2em'); // grows
$('#parent').css('font-size', '0.5em'); // shrinks
```
Before I call either of those
```
alert($('#parent').css('fontSize')); // 16px in Opera,FF,IE6
alert($('.child:first').css('fontSize')); // 80px in Opera&FF, 400px in IE6
```
After a call to say
```
$('#parent').css('font-size', '0.5em'); // shrinks
alert($('#parent').css('fontSize')); // 0.5em in Opera,FF,IE6
alert($('.child:first').css('fontSize')); // 45px Opera, 40 px FF, 200px in IE6
```
So what browsers (version) and jQuery version are you using? | Resize all containing elements with javascript utilizing em | [
"",
"javascript",
"jquery",
"css",
""
] |
for short, this could be paraphrased like "inheritance versus function library"
for example, I'd like to add a method to the javax.servlet.http.HttpServletRequest that gives me the whole body, a getBody() method that would read the body thru the getReader method, just to put an example.
In other languages, like ruby or javascript, you could add a method to the base class, or even to a specific instance, but in java I see this two choices...
1. extend HttpServletRequest ( something like MyHttpServletRequest) and add the method
2. or create an HttpServeletHelper static class, with static methods, with the following method
public static String HttpServeletHelper.getBody( HttpServletRequest request )
the first approach is more object oriented, and elegant, but forces you to cast your object every time you need it, and somehow you have to tell jsp to use your class...
the second approach is just a good old function library... which might be a good or bad thing depending on how you look at it...
what pros / cons do you see in each approach, and which one is the more recommended for this kind of situations? | Your particular example suffers from at least one problem: servlet/JSP engines won't know or care about your subclass. They'll only deal with HttpServletRequest. I suppose you can wrap it and cast it, but I'd hardly call that "elegant".
You don't even cite another possibility: composition. You can have a class that's non-static that takes an HttpServletRequest as a ctor argument and defers to it as implementation of the ServletRequest methods. You add in the additional getBody call to perform your specialized behavior.
Maybe reading [this](http://www.artima.com/lejava/articles/designprinciples4.html) will help.
There are other SO questions about preferring composition over inheritance. See what you think of those.
I would go with the helper class for this particular example as well, but god forbid a Singleton. It's not really necessary or desirable.
This example feels especially awkward. Is this really what you want to do? | I would choose #2. HttpServletRequest is part of a framework, so Tomcat (or whatever) is going to instantiate it and hand it to your code. You won't get to choose whether to use your subclass. (Actually, with the rise of frameworks like Servlets, EJBs, etc, I find this problem to be rather common.)
Also, a lot has been written recently about over-reliance on inheritance as an anti-pattern. In Java, inheritance is a "scarce resource": for each class, you only get to do it once. You should reserve inheritance for things that are genuinely "sub-classes," not just to add some functionality here and there. | Best approach to extend a class functionality in java? | [
"",
"java",
"inheritance",
"function",
""
] |
What are some of the technical differences between memory that is allocated with the `new` operator and memory that is allocated via a simple variable declaration, such as `int var`? Does c++ have any form of automatic memory management?
In particular, I have a couple questions. First, since with dynamic memory you have to declare a pointer to store the address of the actual memory you work with, doesn't dynamic memory use *more* memory? I don't see why the pointer is necessary at all unless you're declaring an array.
Secondly, if I were to make a simple function such as this:
> ```
> int myfunc() { int x = 2; int y = 3; return x+y; }
> ```
...And call it, would the memory allocated by the function be freed as soon as it's scope of existence has ended? What about with dynamic memory? | **Note:** This answer is *way* too long. I'll pare it down sometime. Meanwhile, comment if you can think of useful edits.
---
To answer your questions, we first need to define two areas of memory called the **stack** and the **heap**.
# The stack
Imagine the stack as a stack of boxes. Each box represents the execution of a function. At the beginning, when `main` is called, there is one box sitting on the floor. Any local variables you define are in that box.
## A simple example
```
int main(int argc, char * argv[])
{
int a = 3;
int b = 4;
return a + b;
}
```
In this case, you have one box on the floor with the variables `argc` (an integer), `argv` (a pointer to a char array), `a` (an integer), and `b` (an integer).
## More than one box
```
int main(int argc, char * argv[])
{
int a = 3;
int b = 4;
return do_stuff(a, b);
}
int do_stuff(int a, int b)
{
int c = a + b;
c++;
return c;
}
```
Now, you have a box on the floor (for `main`) with `argc`, `argv`, `a`, and `b`. On top of that box, you have another box (for `do_stuff`) with `a`, `b`, and `c`.
This example illustrates two interesting effects.
1. As you probably know, `a` and `b` were passed-by-value. That's why there is a *copy* of those variables in the box for `do_stuff`.
2. Notice that you don't have to `free` or `delete` or anything for these variables. When your function returns, the box for that function is destroyed.
## Box overflow
```
int main(int argc, char * argv[])
{
int a = 3;
int b = 4;
return do_stuff(a, b);
}
int do_stuff(int a, int b)
{
return do_stuff(a, b);
}
```
Here, you have a box on the floor (for `main`, as before). Then, you have a box (for `do_stuff`) with `a` and `b`. Then, you have another box (for `do_stuff` calling itself), again with `a` and `b`. And then another. And soon, you have a stack *overflow*.
## Summary of the stack
Think of the stack as a stack of boxes. Each box represents a function executing, and that box contains the local variables defined in that function. When the function returns, that box is destroyed.
## More technical stuff
* Each "box" is officially called a *stack frame*.
* Ever notice how your variables have "random" default values? When an old stack frame is "destroyed", it just stops being relevant. It doesn't get zeroed out or anything like that. The next time a stack frame uses that section of memory, you see bits of old stack frame in your local variables.
# The heap
This is where dynamic memory allocation comes into play.
Imagine the heap as an endless green meadow of memory. When you call `malloc` or `new`, a block of memory is allocated in the heap. You are given a pointer to access this block of memory.
```
int main(int argc, char * argv[])
{
int * a = new int;
return *a;
}
```
Here, a new integer's worth of memory is allocated on the heap. You get a pointer named `a` that points to that memory.
* `a` is a local variable, and so it is in `main`'s "box"
# Rationale for dynamic memory allocation
Sure, using dynamically allocated memory seems to waste a few bytes here and there for pointers. However, there are things that you just can't (easily) do without dynamic memory allocation.
## Returning an array
```
int main(int argc, char * argv[])
{
int * intarray = create_array();
return intarray[0];
}
int * create_array()
{
int intarray[5];
intarray[0] = 0;
return intarray;
}
```
What happens here? You "return an array" in `create_array`. In actuality, you return a pointer, which just points to the part of the `create_array` "box" that contains the array. What happens when `create_array` returns? Its box is destroyed, and you can expect your array to become corrupt at any moment.
Instead, use dynamically allocated memory.
```
int main(int argc, char * argv[])
{
int * intarray = create_array();
int return_value = intarray[0];
delete[] intarray;
return return_value;
}
int * create_array()
{
int * intarray = new int[5];
intarray[0] = 0;
return intarray;
}
```
Because function returning does not modify the heap, your precious `intarray` escapes unscathed. Remember to `delete[]` it after you're done though. | Dynamic memory lives on the heap as opposed to the stack. The lifetime of dynamic memory is from the time of allocation, to the time of deallocation. With local variables, their lifetime is limited to the function / block they are defined in.
Regarding your question about the memory usage in the function, in your example the memory for your local variables would be freed at the end of the function. However, if the memory was dynamically allocated with `new`, it would not be automatically disposed, and you would be responsible for explicitly using `delete` to free the memory.
Regarding automatic memory management, the C++ Standard Library provides auto\_ptr for this. | Differences between dynamic memory and "ordinary" memory | [
"",
"c++",
"memory",
"memory-management",
""
] |
I am a front-end developer writing a C# application to export data from an oracle stored procedure into a text file for later importing into a different oracle database. The data will be loaded with SQL Loader (sqlldr) and I am trying to understand that tool's abilities so that I can output the file in a format that will be easy to process with SQL Loader.
I am unsure of how to handle line breaks in the column data. Some of the columns are descriptions, and may contain line breaks. I cannot find an option in SQL Loader to handle the possibility of a non-constant number of line breaks in the data.
It does appear that I could use a sentential value to terminate or start a record in the text file, then use CONTINUEIF. Then that presents me with the issue of handling the sentential value within the data.
I am hesitant to just strip out the breaks because, while not critical for this specific application, I do not want to lessen the fidelity of the data.
Any ideas on how I can approach this?
Thanks! | I'd look at EXPDP and IMPDP ahead of a text file. In 10g, you can read/write to external tables using datapump. See [here](http://blogs.oracle.com/datawarehousing/2009/06/unloading_data_using_external.html). Your export becomes as simple as
```
SQL> CREATE TABLE EMP_50
2 ORGANIZATION EXTERNAL
3 ( TYPE oracle_datapump
4 DEFAULT DIRECTORY dmp_dir
5 LOCATION (‘emp_50.dmp'))
6 )
7 AS SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 50
8 ;
```
You don't have to worry about any exotic characters, date or number conversion/formatting, even raw binary data. | Isn't it easier to create a database link between those different databases? When you use a database link you no longer need to write a C# app. You just select the data from the other database with a select-statement. | How to handle line breaks in data for importing with SQL Loader | [
"",
"c#",
"oracle",
"export",
"sql-loader",
""
] |
I would like to intercept string starting with `\*#\*`
followed by a number between 0 and 7
and ending with: `##`
so something like `\*#\*0##`
but I could not find a regex for this | Assuming you want to allow **only** one # before and two after, I'd do it like this:
```
r'^(\#{1}([0-7])\#{2})'
```
It's important to note that [Alex's](https://stackoverflow.com/questions/889143/python-regular-expression/889154#889154) regex will also match things like
```
###7######
########1###
```
which may or may not matter.
My regex above matches a string starting with #[0-7]## and ignores the end of the string. You could tack a **$** onto the end if you wanted it to match only if that's the entire line.
The first backreference gives you the entire #<number>## string and the second backreference gives you the number inside the #. | None of the above examples are taking into account the \*#\*
```
^\*#\*[0-7]##$
```
Pass : \*#\*7##
Fail : \*#\*22324324##
Fail : \*#3232#
The ^ character will match the start of the string, \\* will match a single asterisk, the # characters do not need to be escape in this example, and finally the [0-7] will only match a single character between 0 and 7. | Python regular expression to match # followed by 0-7 followed by ## | [
"",
"python",
"regex",
""
] |
E.g. which way is better
```
class Foo {
private string _Bar ;
Foo ( string bar)
{
_Bar = bar ;
}
public string Bar
{
get { return _Bar ; //more logic here
}
set { _Bar = value ; //more logic could be added
}
}
}
```
OR
```
class Foo {
private string _Bar ;
Foo ( string bar)
{
this.Bar = bar ;
}
public string Bar {
get { return _Bar ; //more logic could be added }
set { _Bar = value ; //more logic could be added }}
}
```
Edit: I know that the latter allows to put some more logic in it , yet is it justifiable to use it because of it ... | Whichever way makes sense for the class; there is no "best practice".
Sometimes you might want to ensure that you only perform the same operations the property could; in which case it makes sense to use the property.
Sometimes you want to do things that can only be done in the constructor which violate the things you can do via the property post-construction, in which case it makes sense to use the field. | It depends.
I prefer using the properties, when there are no side effects. There are times, however, when setting a property has other side effects, such as event notification, potentially unnecessary (at this point) validation, etc. In those cases, setting the backing field directly is a better option. | Should Constructor initialize own parameters directly to the private member or via the public field ( C# centric)? | [
"",
"c#",
"constructor",
"initialization",
""
] |
I wish to have an internal (non window) dialog to ask for member input. I would like the dialog to be placed centrally on an existing JPanel.
I have looked at [layeredpanes](http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html) and these seem unusable due to only having a single layout manager (or no layout manager) across all the panes. I guess I could try to override JLayeredPane and provide a custom layout but this seems extreme.
[Glass panes](http://java.sun.com/docs/books/tutorial/uiswing/components/rootpane.html) don't seem to be appropriate either.
How can this be done? Is there no usable concept of z-indexes in Swing?
[](https://i.stack.imgur.com/YgqbY.png)
**EDIT**
The reason Layered Panes weren't appropriate was due to the lack of a layout manager per layer. The panel is resizeable, Panel A should stay at 100% of area and Panel B should stay centralized. | I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. [Tutorial for positioning without a LayoutManager](http://java.sun.com/docs/books/tutorial/uiswing/layout/none.html).
```
public class Main {
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
private JPanel panelBlue = new JPanel();
private JPanel panelGreen = new JPanel();
public Main()
{
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
frame.add(lpane, BorderLayout.CENTER);
lpane.setBounds(0, 0, 600, 400);
panelBlue.setBackground(Color.BLUE);
panelBlue.setBounds(0, 0, 600, 400);
panelBlue.setOpaque(true);
panelGreen.setBackground(Color.GREEN);
panelGreen.setBounds(200, 100, 100, 100);
panelGreen.setOpaque(true);
lpane.add(panelBlue, new Integer(0), 0);
lpane.add(panelGreen, new Integer(1), 0);
frame.pack();
frame.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main();
}
}
```
You use setBounds to position the panels inside the layered pane and also to set their sizes.
**Edit to reflect changes to original post**
You will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B. | You can add an undecorated JDialog like this:
```
import java.awt.event.*;
import javax.swing.*;
public class TestSwing {
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame("Parent");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
final JDialog dialog = new JDialog(frame, "Child", true);
dialog.setSize(300, 200);
dialog.setLocationRelativeTo(frame);
JButton button = new JButton("Button");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(button);
dialog.setUndecorated(true);
dialog.setVisible(true);
}
}
``` | Java Swing - how to show a panel on top of another panel? | [
"",
"java",
"swing",
"dialog",
"jpanel",
"z-index",
""
] |
Im attempting to write a push server for the iPhone in C#. I have the following code:
```
// Create a TCP/IP client socket.
using (TcpClient client = new TcpClient())
{
client.Connect("gateway.sandbox.push.apple.com", 2195);
using (NetworkStream networkStream = client.GetStream())
{
Console.WriteLine("Client connected.");
X509Certificate clientCertificate = new X509Certificate(@"certfile.p12", passwordHere);
X509CertificateCollection clientCertificateCollection = new X509CertificateCollection(new X509Certificate[1] { clientCertificate });
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
try
{
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com");
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine("Authentication failed - closing the connection.");
client.Close();
return;
}
}
```
ect....
Only I keep receiving a exception:
"A call to SSPI failed, see Inner exception"
Inner Exception -> "The message received was unexpected or badly formatted."
Does anyone have any idea whats going wrong here? | Figured it out. Replaced sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com"); with sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false); And registered the certificates on the PC.
Edit: Here is the code for creating a payload as requested:
```
private static byte[] GeneratePayload(byte [] deviceToken, string message, string sound)
{
MemoryStream memoryStream = new MemoryStream();
// Command
memoryStream.WriteByte(0);
byte[] tokenLength = BitConverter.GetBytes((Int16)32);
Array.Reverse(tokenLength);
// device token length
memoryStream.Write(tokenLength, 0, 2);
// Token
memoryStream.Write(deviceToken, 0, 32);
// String length
string apnMessage = string.Format ( "{{\"aps\":{{\"alert\":{{\"body\":\"{0}\",\"action-loc-key\":null}},\"sound\":\"{1}\"}}}}",
message,
sound);
byte [] apnMessageLength = BitConverter.GetBytes((Int16)apnMessage.Length);
Array.Reverse ( apnMessageLength );
// message length
memoryStream.Write(apnMessageLength, 0, 2);
// Write the message
memoryStream.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(apnMessage), 0, apnMessage.Length);
return memoryStream.ToArray();
} // End of GeneratePayload
``` | From Zenox's comment:
use a different version of AuthenticateAsClient
```
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false);
``` | C# iPhone push server? | [
"",
"c#",
"iphone",
"push-notification",
""
] |
Should I pair every data() call with a later removeData() call?
My assumptions: jQuery's remove() will remove elements from the DOM, and if I don't have any other references to remove, I don't have to do any more clean up.
However, if I have some javascript var or object referring to one of the elements being removed, I'll need to clean that up, and I'm assuming **that applies to jQuery's data function, too,** because it's referencing the elements somehow.
So if I do need to call removeData before remove, is there a shortcut to remove all data associated with an element or do I have to call each explicitly by name?
Edit: I looked through the source code and confirmed what Borgar and roosteronacid said. Remove takes the elements out of the dom and deletes any events and data stored with them - which is convenient, but makes me wonder when you would use removeData(). Probably not often. | jQuery's data does not keep a reference to the element *so that* you don't need to worry about memory leaks. Its intended purpose is to solve this exact problem.
**A slight simplification of how it works:**
An id member is added to each "touched" DOM node. All subsequent actions involving that DOM element use that id.
```
var theNode = document.getElementById('examplenode');
theNode[ 'jQuery' + timestamp ] = someInternalNodeID;
```
You can access the id using the same function jQuery uses:
```
someInternalID = jQuery.data( document.body );
```
When you append data to the node it stores that on the jQuery object, filed under the node's internal id. Your `$(element).data(key,value)` translates internally to something like:
```
jQuery.cache[ someInternalNodeID ][ theKey ] = theValue;
```
Everything goes into the same structure, including event handlers:
```
jQuery.cache[ someInternalNodeID ][ 'events' ][ 'click' ] = theHandler;
```
When an element is removed, jQuery can therefore throw away all the data (and the event handlers) with one simple operation:
```
delete jQuery.cache[ someInternalNodeID ];
```
Theoretically, you may therefore also remove jQuery without leaks occurring from any references. jQuery even supports multiple separate instances of the library, each holding it's own set of data or events.
You can see John Resig explaining this stuff in [the "The DOM Is a Mess" presentation](http://video.yahoo.com/watch/4403981/11812238). | The whole point of jQuery is to abstract away from crappy JavaScript implementations and bugs in browsers.. such as memory leaks :)
.. Yup; all associated data to an element will be removed when that element is removed from the DOM. | What sort of memory leaks should I watch for with jQuery's data()? | [
"",
"javascript",
"jquery",
"dom",
"memory",
"memory-leaks",
""
] |
In dotNet a line throws an exception and is caught, how can I figure out which line in which file threw the exception? Seems relatively straightforward, but I can't figure it out... | You can only do it if you have debug symbols available.
```
catch(Exception ex) {
// check the ex.StackTrace property
}
```
If you want to debug such a situation in VS, you'd better just check `Thrown` checkbox for `Common Language Runtime Exceptions` in `Exceptions` dialog located in `Debug` menu. The debugger will break as soon as the exception is thrown, even if it's in a `try` block. | Personally, I just log the exception's ToString() return value. The whole stack trace is included. It's one line of code ... dead simple. | Determining which code line threw the exception | [
"",
"c#",
"exception",
"stack",
"stack-frame",
""
] |
How could a page display different content based on the [URL hash](https://stackoverflow.com/questions/940905/can-php-read-the-hash-portion-of-the-url)?
I'm not talking about the browser scrolling down to display the anchored section, but something like JavaScript reacting to that hash and loading different content via AJAX.
Is this common or even probable? | Oh yes - it's becoming a common pattern to handle page-state-to-URL persistence when content is AJAX driven.
Javascript can access this value via window.location.hash. Once that's done, you can perform any actions based on the value of that hash
* Show/hide nodes
* Makes other AJAX calls
* Change page titles or colors
* Swap images
* etc
Really, any DHTML effect. | [Sammy](http://sammyjs.org/) is a javascript library that does just this. | Could a page display diferrent content if the URL hash changes? | [
"",
"javascript",
"ajax",
"url",
"hash",
"fragment-identifier",
""
] |
Been trying to solve this for a while now.
I need a regex to strip the newlines, tabs and spaces between the html tags demonstrated in the example below:
Source:
```
<html>
<head>
<title>
Some title
</title>
</head>
</html>
```
Wanted result:
```
<html><head><title>Some title</title></head></html>
```
The trimming of the whitespaces before the "Some title" is optional.
I'd be grateful for any help | `s/\s*(<[^>]+>)\s*/\1/gs`
or, in c#:
`Regex.Replace(html, "\s*(<[^>]+>)\s*", "$1", RegexOptions.SingleLine);` | If the HTML is strict, load it with an XML reader and write it back without formatting. That will preserve the whitespace within tags, but not between them. | Using regular expression to trim html | [
"",
"c#",
"html",
"regex",
""
] |
I'd like to use the same enum across three tiers of my application (presentation -> bal -> dal). I defined the enum in the data layer and I want to use the same enum in the presentation layer (the presentation layer does not have a reference to the data layer). Using someone else's [answer](https://stackoverflow.com/questions/40107/using-attributes-to-cut-down-on-enum-to-enum-mapping-and-enum-const-to-action-swi) to what I think is a similar question, I've built the following enum in the business layer:
```
namespace bal
{
public enum TransactionCode
{
Accepted = dal.TransactionCode.Accepted,
AcceptedWithErrors = dal.TransactionCode.AcceptedWithErrors,
InvalidVendorCredentials = dal.TransactionCode.InvalidVendorCredentials,
BrokerOffline = dal.TransactionCode.BrokerOffline
}
}
```
Is this an appropriate way to construct enums between the tiers? | One approach is to have one "layer" (well, not really a layer as such) which is shared across *all* layers.
I [blogged about this a while ago](http://perfectprojectquest.blogspot.com/2007/03/of-layers-and-designs.html) (in a blog/project which is now dormant, unfortunately). It may seem "impure" but it makes life a lot easier in many ways and reduces duplication. Of course, it does then reduce flexibility too - if you ever want the presentation enum to be *different* from the data layer enum, you'd have to refactor... | Your enum is actually part of an API. When you think about layered software, its often hard to think about shared types, but most of the time, a set of types is always shared accross layers. Instead of just thinking about the standard layering:
```
Presentation -> Business -> Data
```
Try thinking about it like this:
```
Presentation -> API
|-> Business ----^
|-> Data ----^
```
Where API is a shared aspect of your system. The API contains any shared data types, entities, enumerations, service interfaces, etc. The API can be isolated into its own library, and reused in your presentation, while also being the gateway to your domain (which is business and data logic.) | enums across tiers | [
"",
"c#",
"enums",
""
] |
I'd like to add a button column dynamically to a DataGridView after it has been populated.
The button column is visible after adding it, but when I try to loop through the DataGridView rows, I get a null for the button in each cell.
```
var buttonCol = new DataGridViewButtonColumn();
buttonCol.Name = "ButtonColumnName";
buttonCol.HeaderText = "Header";
buttonCol.Text = "Button Text";
dataGridView.Columns.Add(buttonCol);
foreach (DataGridViewRow row in dataGridView.Rows)
{
var button = (Button)row.Cells["ButtonColumnName"].Value;
// button is null here!
}
``` | I tried the exact same thing a while ago and couldn't get it working; my solution (as it was just a test application) was to change the background colour of the button cell and test for that. Pretty awful. However, looking back at the code - have you tried casting the `row.Cells["ButtonColumnName"]` to a `DataGridViewButtonCell` and then checking out the properties on that? | Use this:
```
foreach (DataGridViewRow row in dataGridView.Rows)
{
// DataGridViewButtonCell button = (row.Cells["ButtonColumnName"] as DataGridViewButtonCell);
row.Cells["ButtonColumnName"].Value = "ButtonText";
}
``` | Win form DataGridView dynamically adding button column | [
"",
"c#",
"winforms",
"datagridview",
""
] |
I need help figuring out some regular expressions. I'm running the dig command and I need to use its output. I need to parse it and get it neatly arranged as an array using php.
dig outputs something like this:
```
m0.ttw.mydomain.tel. 60 IN TXT ".tkw" "1" "20090624-183342" "Some text here1"
m0.ttw.mydomain.tel. 60 IN TXT ".tkw" "1" "20090624-183341" "Some text here2"
```
I want to get this:
```
Array
(
[0] => Array
(
[0] => .tkw
[1] => 1
[2] => 20090624-183342
[3] => Some text here1
)
[1] => Array
...
)
```
I just need the contents inside the double quotes. I *can* parse the dig output line by line, but I think it would be faster if I just run the regex pattern matching on all of it...
Thoughts? | This gets close with a single line
```
preg_match_all( '/"([^"]+)"\s*"([^"]+)"\s*"([^"]+)"\s*"([^"]+)"/', $text, $matches, PREG_SET_ORDER );
print_r( $matches );
```
however, becuase of how the preg\_match\* functions work, the full match is included at index 0 of each match group. You could fix this if you really wanted to.
```
array_walk( $matches, create_function( '&$array', 'array_shift( $array );return $array;' ) );
``` | I'm not sure about PHP regular expressions, but in Perl the RE would be simple:
```
my $c = 0;
print <<EOF;
Array
(
EOF
foreach (<STDIN>) {
if (/[^"]*"([^"]*)"\s+"([^"]*)"\s+"([^"]*)"\s+"([^"]*)"/) {
print <<EOF;
[$c] => Array
(
[0] = $1
[1] = $2
[2] = $3
[3] = $4
)
EOF
$c++;
}
}
print <<EOF;
)
EOF
```
This has some limitations, namely:
* It does not work if the text in the quotes can have escaped quotes (e.g. `\"`)
* It is hard coded to support four quoted values only. | Regular expressions / parsing dig output / extracting text from double quotes | [
"",
"php",
"regex",
"quotes",
""
] |
I'm getting started on a small internal web application at work, mostly a proof-of-concept, but we want to treat it like a "real" application. I don't have much experience as a DBA, nor does anyone in my group (it's not particularly important to have one, since it's a PoC).
I was wondering though, if this web app was going public, should we have separate accounts to the DB server for different query types? E.g. have one SQL account for SELECT queries, and another for UPDATE/DELETE? I can't convince myself of any particular advantage to doing so, but I've heard of the technique before so there must be some value. | It's useful to have different accounts for different types of tasks (for example, batch jobs vs. web serving) and have limits on connection count and the like on each. This means that if your batch jobs go crazy that it can't take out your web app.
You'd also want different accounts for different permissions. For instance if your admin and user apps were separate they should have their own accounts. This helps to ensure that if your user app was to be compromised, it wouldn't be able to do as much damage to your data.
In these two regards it is useful to have a "readonly" user, but only if your application doesn't do writes. | You can limit the type of queries the main account that is used when anonymous users access the site has access to. However, I don't think you need a different user per query within that subset.
What you want to focus on is what databases/tables are accessible by each user, rather than the specific type of query. | Should I have separate SQL accounts for different query types? | [
"",
"sql",
""
] |
Is there a utility that will convert POSIX to PCRE for PHP? I'm somewhat confused by the PHP manual on PCRE, and while I'll try to find more info on PCRE, I was wondering if anyone had designed such a utility.
Or, if anyone would explain how to convert the following, that would also be fine:
```
ereg("^#[01-9A-F]{6}$", $sColor)
```
But please explain how it's done, not just tell me the conversion. | ```
preg_match("/^#[01-9A-F]{6}$/", $sColor)
```
In this case you only need to add the two delimiters.
In perl you can write something like
```
if ( s =~ /x.+y/ )
{ print "match"; }
```
As you can see the actual regular expression is encapsulated in //. If you want to set an option on the regular expression you put it after the second /, e.g. switching the expression to ungreedy by default /x.+y/U
pcre now emulates this behaviour. Though you have to call a function you also have to provide the delimiters and set the options after the second delimiter. In perl the delimiter has to be /, with pcre you can chose more freely
```
preg_match("/^#[01-9A-F]{6}$/", $sColor)
preg_match("!^#[01-9A-F]{6}$!", $sColor)
preg_match("#^\#[01-9A-F]{6}$#", $sColor) // need to escape the # within the expression here
preg_match("^#[01-9A-F]{6}$", $sColor)
```
all the same to pcre, best to chose a character that doesn't appear within the expression. | `preg_match("/^#[01-9A-F]{6}$/D", $sColor)`
Note the [`D` modifier](http://php.net/manual/en/reference.pcre.pattern.modifiers.php). People forget about it all the time. Without it `$` will allow a final newline character. A string like "#000000\n" would pass. This is a subtle difference between POSIX and PCRE.
And, of course, `[01-9]` can be rewritten to `[0-9]`. | Is there a utility that will convert POSIX to PCRE for PHP? | [
"",
"php",
"regex",
"posix",
"utilities",
"pcre",
""
] |
I don't know if there is an official name for this, but I have been playing with what I like to call the "self-factory" pattern. Basically, it's when an abstract base class acts as a factory for itself. Let me explain:
I have Foo objects and Bar objects in my system, which are used via interfaces FooInterface and BarInterface. I need to give my clients the right type of Foo and Bar. The decision of which concrete Foo object to create is made at compile time. For example, if you compile on win32, you want to only create Win32Foo objects, and if you compile on OSX you want to only create OSXFoo objects and so on. But, the decision of which concrete Bar object to create is made at runtime, based on a key string.
Now, my question is about the best way to implement this scheme. One way I come up with uses regular factories:
```
shared_ptr<FooInterface> foo = FooFactory::create();
shared_ptr<BarInterface> happyBar = BarFactory::create("Happy");
shared_ptr<BarInterface> sadBar = BarFactory::create("Sad");
```
Another way is to use what I call "self-factories":
```
shared_ptr<FooInterface> foo = FooInterface::create();
shared_ptr<BarInterface> happyBar = BarInterface::create("Happy");
shared_ptr<BarInterface> sadBar = BarInterface::create("Sad");
```
What are the pros and cons of each approach, both from a usability standpoint and from an architectural standpoint? | Factories have two common uses:
1) Decide dynamic polymorphic type at runtime, based on parameters and/or global state (such as configuration). Your pattern does this.
2) Dependency injection: rather than using a static function to create objects, use a factory *object*, so that the type of object returned can be configured by the caller, by passing in whatever factory they want. Neither of these patterns provides this. Furthermore, your second pattern doesn't even allow static dependency injection (by having template functions that take a factory class as a template parameter), because the interface and the factory are the same.
So one con of your pattern (and of your regular factories) is that dependency injection isn't really supported. There is one and only one function to call to get an object that's a FooInterface, and that is FooInterface::create(). I'll not argue why dependency injection is useful, just point out that if you build this way, you can't use it. | I'd make an improvement:
```
shared_ptr<FooInterface> foo = Factory<FooInterface>::create();
shared_ptr<BarInterface> happyBar = Factory<BarInterface>::create("Happy");
shared_ptr<BarInterface> sadBar = Factory<BarInterface>::create("Sad");
```
You'd declare:
```
template <class I>
struct Factory { };
```
And then for each interface that needs a factory, you'd do this:
```
template <>
struct Factory<FooInterface>
{
static FooInterface create();
};
```
This allows you to keep the factory implementation separate from the interface declaration, but still using the type system to bind them at compile time. | The "Self-Factory" Pattern | [
"",
"c++",
"factory",
""
] |
is there any recommendation for a library (c++, Win32, open source) to get the sound from a microphone?
Thanks | Try having a look at OpenAL[1] it might be overkill, but should be able to record from microphone as you wanted. There exists some pretty good articles about it on Gamedev.net[2] although I'm afraid none of them tells you how to record from a microphone. You should however be able to find the answer for that in the documentation. :) good luck,
---
[1] <http://connect.creativelabs.com/openal/default.aspx>
[2] <http://www.gamedev.net/reference/articles/article2008.asp> | [PortAudio - portable cross-platform Audio API](http://www.portaudio.com/)
> PortAudio provides a very simple API
> for recording and/or playing sound
> using a simple callback function. | Free C++ lib (Win32) to record microphone | [
"",
"c++",
"winapi",
"open-source",
"microphone",
""
] |
I use @ symbol with local path only, but when do I use @ exactly? | You use @ before strings to avoid having to escape special characters.
This from the [MSDN](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/#regular-and-verbatim-string-literals):
> Use verbatim strings for convenience and better readability when the
> string text contains backslash characters, for example in file paths.
> Because verbatim strings preserve new line characters as part of the
> string text, they can be used to initialize multiline strings. Use
> double quotation marks to embed a quotation mark inside a verbatim
> string. The following example shows some common uses for verbatim
> strings:
```
string filePath = @"C:\Users\scoleridge\Documents\"; //Output: C:\Users\scoleridge\Documents\
string text = @"My pensive SARA ! thy soft cheek reclined
Thus on mine arm, most soothing sweet it is
To sit beside our Cot,..."; /* Output: My pensive SARA ! thy soft cheek reclined Thus on mine arm, most soothing sweet it is To sit beside our Cot,...
*/
string quote = @"Her name was ""Sara."""; //Output: Her name was "Sara."
``` | AFAIK, You can use @ at any place where you don't want to let the default meaning of the thing persist. For example, @class will make class an identifier. @bool will make bool an identifier instead of a keyword.
You know the usage of @ before strings. It is used to indicate that take all the text of the string literally and don't treat any character in the string specially.
Edit: An yes, another thing to this is that `@Keyword` is compiled into a `Keyword` in IL.
[See this Link](http://msdn.microsoft.com/en-us/library/aa664670(VS.71).aspx) for more details. | when to use @ in c#? | [
"",
"c#",
""
] |
I was just wondering how to get
the link of the webpage which was not found on my website.
With following .htaccess code, when a non-existing page is requested, user is redirected to my\_404.php.
```
Options -Indexes
ErrorDocument 404 http://mysite.com/my_404.php
```
If I have to track down what was the link of the page, which was not found, how do I do that??
Just for example, A.php is a valid web page, while b.php is not. So if I am on A.php and try to view b.php (non-existent page) .. .htaccess redirects me to my\_404.php on which I see `HTTP_REFERER` as A.php .. but what I am looking for is that "somebody tried to view B.php". How do I do that?
Thanks for your help.
**EDIT**
Please see: I dont want to check in log files. I am asking about something on page. Thanks. | When you use a remote ErrorDocument URL like `http://mysite.com/my_404.php`, Apache will send a redirect to that URL to the client, that's why you can't get the URL that causes the 404 from `$_SERVER['REQUEST_URI']` like Matt Bridges suggested.
You might want to try using a local ErrorDocument (no scheme and servername), like this:
```
ErrorDocument 404 /my_404.php
```
I suspect `$_SERVER['REQUEST_URI']` will then return the originally requested URL. | This is likely already being done in your Apache log file. You could just parse the data rather than recording it twice.
Stackoverflow Archives:
* [How can I parse Apache's error log in PHP?](https://stackoverflow.com/questions/159393/how-can-i-parse-apaches-error-log-in-php)
Additional Relevant Content:
* [Apache Log Parser Class](http://www.phpclasses.org/browse/package/2596.html) via PHPClasses.org | how to log which page was "not found"? (Trying custom error page with htaccess, php, http_referer) | [
"",
"php",
".htaccess",
"http-referer",
""
] |
I am working on a ASP.NET MVC web site that has multiple submit buttons. i.e.
```
<input type="submit" name="SubmitButton" value="Reset" />
<input type="submit" name="SubmitButton" value="OK" />
<input type="submit" name="SubmitButton" value="Back" />
```
I need to allow users to quickly submitting the form by pressing the 'Enter' key. HTML standard seems to specify that the first submit button will be assumed if a user press the 'Enter' key. However, I need to make the 2nd button (i.e. the "OK") button the default button and for reasons I don't even want to talk about, changing the button order is not an option.
I googled around and I found [this post](http://marekblotny.blogspot.com/2009/03/defaultbutton-deal-with-users-hitting.html) about using Page.Form.DefaultButton in ASP.NET but this doesn't work with ASP.NET MVC.
I also tried the following javascript solution, while it works in Chrome but doesn't work in IE6
```
$('body').keypress(function(e) {
if (e.which === 13) {
$("input[value='OK']").trigger('click');
}
});
```
I can think of some really extreme solutions such as going through every single controls in the form an attach the above function to them. However, I don't think that's a very neat solution so I am wondering has anyone got a better solution? | First off, this is wrong:
```
<input type="submit" name="SubmitButton" value="Reset" />
<input type="submit" name="SubmitButton" value="OK" />
<input type="submit" name="SubmitButton" value="Back" />
```
All three of them are submit buttons. A reset is an input of type="reset". Get that sorted. Second of all, I've successfully implemented something like that, and it works on IE6. Try this:
```
function keypressHandler(e)
{
if(e.which == 13) {
e.preventDefault(); //stops default action: submitting form
$(this).blur();
$('#SubmitButton').focus().click();//give your submit an ID
}
}
$('#myForm').keypress(keypressHandler);
```
The focus() part makes the button appear to be pressed when the user presses enter. Quite nifty. | Use this.
```
$(function(){
$('input').keydown(function(e){
if (e.keyCode == 13) {
$("input[value='OK']").focus().click();
return false;
}
});
});
``` | Handle user hitting 'Enter' key in a ASP.NET MVC web site | [
"",
"asp.net",
"javascript",
"jquery",
"asp.net-mvc",
""
] |
I've created a simple project with an SQL Server database with dozens of tables and plenty of indices but nothing really complicated. No triggers, no stored procedures, no additional "database magic".
The code is written in C#, using the Entity model and the Dynamic Data Site to just set up the basics real fast, so some typing monkeys could be put to work and do some basic data entries while I will modify the project to become more mature.
Tested it on SQL Server 2005 and all worked fine. So I've made a setup through Visual Studio and sent it over to the typing Monkeys and their administrator. All they had to do was:
1) Create a new database.
2) Execute the Create script for the database.
3) Install the setup I gave them.
4) Modify the connection string, which happens to be placed in a special config file for their convenience.
5) Use the web interface and notify me if something goes wrong.
And something went wrong. This complete error: *Line 1: Incorrect syntax near '('. 'row\_number' is not a recognized function name. Incorrect syntax near the keyword 'AS'.*
I don't use 'row\_number' in my code. I just use Linq for the queries. Besides, because of the entity model I don't even have to worry much about doing any SQL stuff. (even though I'm good at it.)
My first guess is that they're using a faulty connection string. They might be installing this application on SQL Server (which should still work) but they didn't change the connection string completely and now my project thinks it's using SQL Server 2005. (Or whatever.) Am I right or is this caused by some other nasty bug?
Full error:
> [SqlException (0x80131904): Line 1:
> Incorrect syntax near '('.
> 'row\_number' is not a recognized
> function name. Incorrect syntax near
> the keyword 'AS'.]
> System.Data.SqlClient.SqlConnection.OnError(SqlException
> exception, Boolean breakConnection)
> +1950890 System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
> exception, Boolean breakConnection)
> +4846875 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
> stateObj) +194
> System.Data.SqlClient.TdsParser.Run(RunBehavior
> runBehavior, SqlCommand cmdHandler,
> SqlDataReader dataStream,
> BulkCopySimpleResultSet
> bulkCopyHandler, TdsParserStateObject
> stateObj) +2392
> System.Data.SqlClient.SqlDataReader.ConsumeMetaData()
> +33 System.Data.SqlClient.SqlDataReader.get\_MetaData()
> +83 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader
> ds, RunBehavior runBehavior, String
> resetOptionsString) +297
> System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
> cmdBehavior, RunBehavior runBehavior,
> Boolean returnStream, Boolean async)
> +954 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
> cmdBehavior, RunBehavior runBehavior,
> Boolean returnStream, String method,
> DbAsyncResult result) +162
> System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
> cmdBehavior, RunBehavior runBehavior,
> Boolean returnStream, String method)
> +32 System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
> behavior, String method) +141
> System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
> behavior) +12
> System.Data.Common.DbCommand.ExecuteReader(CommandBehavior
> behavior) +10
> System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
> entityCommand, CommandBehavior
> behavior) +387
>
> [EntityCommandExecutionException: An
> error occurred while executing the
> command definition. See the inner
> exception for details.]
> System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
> entityCommand, CommandBehavior
> behavior) +423
> System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext
> context, ObjectParameterCollection
> parameterValues) +743
> System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1
> forMergeOption) +157
> System.Data.Objects.ObjectQuery`1.GetIListSourceListInternal()
> +13 System.Data.Objects.ObjectQuery.System.ComponentModel.IListSource.GetList()
> +7 System.Web.UI.WebControls.EntityDataSourceView.ExecuteSelect(DataSourceSelectArguments
> arguments, Creator qbConstructor)
> +1168 System.Web.UI.WebControls.EntityDataSourceView.ExecuteSelect(DataSourceSelectArguments
> arguments) +102
> System.Web.UI.DataSourceView.Select(DataSourceSelectArguments
> arguments,
> DataSourceViewSelectCallback callback)
> +19 System.Web.UI.WebControls.DataBoundControl.PerformSelect()
> +142 System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
> +73 System.Web.UI.WebControls.GridView.DataBind()
> +4 System.Web.UI.WebControls.BaseDataBoundControl.EnsureDataBound()
> +82 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls()
> +72 System.Web.UI.Control.EnsureChildControls()
> +87 System.Web.UI.Control.PreRenderRecursiveInternal()
> +44 System.Web.UI.Control.PreRenderRecursiveInternal()
> +171 System.Web.UI.Control.PreRenderRecursiveInternal()
> +171 System.Web.UI.Control.PreRenderRecursiveInternal()
> +171 System.Web.UI.Control.PreRenderRecursiveInternal()
> +171 System.Web.UI.Control.PreRenderRecursiveInternal()
> +171 System.Web.UI.Page.ProcessRequestMain(Boolean
> includeStagesBeforeAsyncPoint, Boolean
> includeStagesAfterAsyncPoint) +842
---
This application was previously build on an SQL Server 2000 system and then it also worked just fine. However, the test database was upgraded to 2005 while the production database still uses 2000. I would expect that this should cause no problems, but am I correct in my assumption? | Well, I did a simple test. I've connected my project with an SQL Server 2000 database, installed the database and ran the SQL scripts. Then -without recompiling- I used my site to connect to this database and it failed. It was the same error.
Then the next part of the test: I refreshed the entity models in my project and recompiled the whole project. Still connected with SQL Server 2000, I started the site again and there it was, my beautiful site. :-)
As it turns out, the Entity model (and LINQ-TO-SQL) will detect which database you use when you compile your project. If you use 2005, the final code gets optimized for 2005 and you won't be able to install the whole thing on SQL Server 2000.
So, annoying as it is, I will have to continue to develop on an SQL Server 2000 machine. (And kick someone's arse because he was supposed to test my setup on a system similar to the end user!) | I know this is an old thread, but I think it still has some importance.
I ran into the same problem. I was developing on a sql2008 server and deploying to a sql2000 server. Instead of developing on your 2000 machine, open up your .edmx file in wordpad and change the manifest token to "2000". Then rebuild and publish. Much easier than developing on a different machine. | 'row_number' is not a recognized function name. Incorrect syntax near the keyword 'AS' | [
"",
"c#",
"entity-model",
"dynamic-data-site",
""
] |
I'm having a terrible time convincing myself what I've done here is a good idea. The specific section I find objectionable is:
```
return ((float)($now+$sec).'.'.$mic);
```
In order to preserve the floating point precision, I'm forced to either fall back on the BC or GMP libraries (neither of which is always available). In this case, I've resorted to jamming the numbers together with string concatenation.
```
<?php
// return the current time, with microseconds
function tick() {
list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");
return ((float)($now+$sec).'.'.$mic);
}
// compare the two given times and return the difference
function elapsed($start, $end) {
$diff = $end-$start;
// the difference was negligible
if($diff < 0.0001)
return 0.0;
return $diff;
}
// get our start time
$start = tick();
// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);
// get our end time
$end = tick();
$elapsed = elapsed($start, $end);
// should produce output similar to: float(2.00113797188)
var_dump($elapsed);
?>
```
If I attempt to add two numbers like **123456789** (representing a timestamp) and **0.0987654321** (representing microseconds), using the addition operator (**+**) I invariably end up with 123456789.099. Even when casting the integer to float, the result is the same.
Is there a solution for this issue which is 1) not a hack and 2) doesn't involve string concatenation? I shouldn't have to fall back on this sort of garbled code in order to get an accurate timestamp with microsecond resolution.
**Edit:** As S. Gehrig has explained, floating point numbers in PHP can be, at times, a bit tricky to display. The "precision" indicated in the PHP configuration is regarding display. The actual values are not rounded like I thought. A far simpler solution to the above code would look like so:
```
// return the current time, with microseconds
function tick() {
return microtime(true);
}
// compare the two given times and return the difference
function elapsed($start, $end) {
return $end-$start;
}
// get our start time
$start = tick();
// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);
// get our end time
$end = tick();
$elapsed = elapsed($start, $end);
// should produce output similar to: float(2.00113797188)
var_dump($elapsed);
```
If you were to examine **$start** or **$end** before subtracting one from the other, it might appear they were rounded to the hundredths position. This is not the case. It seems arbitrary precision is maintained for arithmetic while the display is limited. | Why don't you use [`microtime(true)`](http://de.php.net/manual/en/function.microtime.php) which simply returns a microsecond timestamp as `float`? The parameter `[bool] $get_as_float` was added in PHP 5.0.0.
**Regarding the comment about the "loss" of precision:**
```
$start = microtime(true);
$end = microtime(true);
echo $end - $start;
// prints 7.1526861190796
```
`microtime(true)` is not limited to 2 decimal places. What the poster encounters is the effect of the configuration setting `precision` which controls how many decimal places will be printed when outputting float variables. **This has nothing to do with the internal precision `microtime(true)` uses.** You can always use [`number_format()`](http://de.php.net/manual/en/function.number-format.php) or [`(s)printf()`](http://de.php.net/manual/en/function.sprintf.php) to format the output to the precision you like. | First, spligak, I see that your code contains an error.
```
list($sec, $mic, $now) = sscanf(microtime(), "%d.%d %d");
return ((float)($now+$sec).'.'.$mic);
```
If $mic has fewer than six digits, you get garbage results. Do a desk check on
```
the case where microtime() returns "0.000009 1234567890"
```
Second, you can greatly reduce the floating-point error as follows:
(WARNING: untested code!)
// compare the two given times and return the difference
```
// get our start time
$start = microtime();
// sleep for 2 seconds (should be ever slightly more than '2' when measured)
sleep(2);
// get our end time
$end = microtime();
// work around limited precision math
// subtract whole numbers from whole numbers and fractions from fractions
list($start_usec, $start_sec) = explode(" ", $start);
list($end_usec, $end_sec) = explode(" ", $end);
$elapsed = ((float)$end_usec)-((float)$start_usec);
$elapsed += ((float)$end_sec)-((float)$start_sec);
// please check the output
var_dump($elapsed);
``` | Imprecise numbers with microtime and floating point addition in PHP | [
"",
"php",
"time",
"floating-point",
""
] |
Say I have 3 strings in a List (e.g. "1","2","3").
Then I want to reorder them to place "2" in position 1 (e.g. "2","1","3").
I am using this code (setting indexToMoveTo to 1):
```
listInstance.Remove(itemToMove);
listInstance.Insert(indexToMoveTo, itemToMove);
```
This seems to work, but I am occasionally getting strange results; sometimes the order is incorrect or items from the list are getting deleted!
Any ideas? Does `List<T>` guarantee order?
### Related:
> [Does a List<T> guarantee that items will be returned in the order they were added?](https://stackoverflow.com/questions/453006/does-a-listt-guarantee-that-items-will-be-returned-in-the-order-they-were-added) | The [`List<>`](https://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx) class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.
According to MSDN:
> ...List "Represents a strongly typed list of objects that can be
> accessed **by index**."
The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.
You might be getting odd results from your code if you're moving the item later in the list, as your [`Remove()`](https://msdn.microsoft.com/en-US/library/cd666k3e(v=vs.110).aspx) will move all of the other items down one place before the call to [`Insert()`](https://msdn.microsoft.com/en-us/library/sey5k5z4(v=vs.110).aspx).
Can you boil your code down to something small enough to post? | Here are 4 items, with their index
```
0 1 2 3
K C A E
```
You want to move K to between A and E -- you might think position 3. You have be careful about your indexing here, because after the remove, all the indexes get updated.
So you remove item 0 first, leaving
```
0 1 2
C A E
```
Then you insert at 3
```
0 1 2 3
C A E K
```
To get the correct result, you should have used index 2. To make things consistent, you will need to send to (indexToMoveTo-1) `if indexToMoveTo > indexToMove`, e.g.
```
bool moveUp = (listInstance.IndexOf(itemToMoveTo) > indexToMove);
listInstance.Remove(itemToMove);
listInstance.Insert(indexToMoveTo, moveUp ? (itemToMoveTo - 1) : itemToMoveTo);
```
This may be related to your problem. Note my code is untested!
**EDIT**: Alternatively, you could `Sort` with a custom comparer (`IComparer`) if that's applicable to your situation. | Does List<T> guarantee insertion order? | [
"",
"c#",
".net",
"collections",
""
] |
I'm currently writing a little toy assembler in c# (going through [the elements of computing systems book](http://www1.idc.ac.il/tecs/). Really good book by the way.)
The assembler takes an input file path and removes junk (comments etc) lines.
The file is then passed to a parser then finally to a another module that creates the binary code.
This isn't too complicated, but I'd like not to have to write out a temporary file to the filesystem every time one object has finished it's processing of the input file.
I'd like to just pass the stream onto the next object.
I originally thought each class involved in the parsing / junk removing would implement IDisposable but I think this means I can't pass the stream on the next object for processing (the stream would be closed, unless I keep it all in one using statement?).
I think I'm missing something here, is there a simple way to pass streams between objects cleanly, or do I need a different approach?
Thanks in advance for any help! | In general, it is the responsibility of the consumer to properly dispose of a Disposable object. As such, if you pass off a Stream to another object, you shouldn't Dispose it - that would be the responsibility of the consumer.
So in the clear-cut scenarios, either you hold a reference to a Disposable object, in which case you should ensure that it is properly disposed; or you pass the reference to someone else and forget about it.
Then what about the cases where you need to hold a reference yourself, but still pass it along? In these cases, pass a copy of the Disposable resource - this will alow you and the consumer to manage the lifetime of the two instances independently of each other. However, if you get into this situation, you should reconsider your design, as I would call that a code smell. | If something else is using the stream after the assembler is done with it, the assembler shouldn't "own" the stream. The caller should either create a stream for the assembler (and subsequent modules) to use, or the assembler should return a new stream which it is then the caller's responsibility to close.
It would be instructive to see some more details on what your program's architecture looks like and what methods we are discussing here. | .NET streams, passing streams between objects, best practices (C#) | [
"",
"c#",
"stream",
""
] |
I've got a tree-like structure. Each element in this structure should be able to return a Enumerable of all elements it is root to. Let's call this method `IEnumerable<Foo> GetAll()`. So if we have
```
A <-- topmost root
/ \
/ \
B C
/ \ / \
D E F G
```
a call to `GetAll` on element `C` returns `{C, F, G}` (fixed order of elements would be nice, but is not needed). I guess everybody knew that already.
The current implementation of `GetAll` looks like this:
```
public IEnumerable<Foo> GetAll ()
{
yield return this;
foreach (Foo foo in MyChildren) {
foreach (Foo f in foo.GetAll ()) {
yield return f;
}
}
}
```
In an earlier implementation, I returned a List and added the child-foos using `List.AddRange()`.
My question is if the version using yield is correcly implemented or if it should be improved (esp. in terms of performance). Or is this just bad and I should stick to `List`s (or `ReadOnlyCollections`) instead? | It's certainly not ideal in terms of performance - you end up creating a lot of iterators for large trees, instead of a single iterator which knows how to traverse efficiently.
Some blog entries concerning this:
* Wes Dyer: [All about iterators](http://blogs.msdn.com/wesdyer/archive/2007/03/23/all-about-iterators.aspx)
* Eric Lippert: [Immutability in C#, part 6](http://blogs.msdn.com/ericlippert/archive/2007/12/18/immutability-in-c-part-six-a-simple-binary-tree.aspx)
* Eric again: [Immutability in C#, part 7](http://blogs.msdn.com/ericlippert/archive/2007/12/19/immutability-in-c-part-seven-more-on-binary-trees.aspx)
It's worth noting that F# has the equivalent of the proposed "`yield foreach`" with "`yield!`" | You can improve performance if you unroll recurse to stack, so you will have only one iterator:
```
public IEnumerable<Foo> GetAll()
{
Stack<Foo> FooStack = new Stack<Foo>();
FooStack.Push(this);
while (FooStack.Count > 0)
{
Foo Result = FooStack.Pop();
yield return Result;
foreach (Foo NextFoo in Result.MyChildren)
FooStack.Push(NextFoo);
}
}
``` | Performance of nested yield in a tree | [
"",
"c#",
"performance",
"ienumerable",
"yield",
""
] |
Whilst working on a UI update for a client, I noticed the dates associated with all the articles were out by a day. I figured I'd screwed something up during my changes, but to be sure, threw together a little php test file that gave me some odd results. The test file is just;
```
<?php
$date = 1246053600;
echo 'unix: ',$date,', converted: ',date('d/m/Y', $date);
?>
```
If I run the above code on my localhost I get:
> unix: 1246053600, converted:
> 26/06/2009
But if I run it on the production server I get:
> unix: 1246053600, converted:
> 27/06/2009
Notice the day difference between the two? What's happening here?! Surely converting a unix timestamp to a date doesn't have any server specific dependancies? | Your servers might be set to two different time zones, and they're interpreting the timestamp as the number of seconds since midnight january 1st 1970 *GMT*. The dates may not be off by a whole day, but just part of a day, enough to make it cross over the midnight boundary. | The issue is that the $date value you are providing is presumed to be in UTC. If you [use gmdate, you will get the same result](http://www.php.net/manual/en/function.gmdate.php) on both servers. Otherwise, the date and time displayed will be adjusted according to the servers' timezone. You can use the O (capital oh) code to print out the timezone to make the current setting on each server clear:
`echo 'unix: ',$date,', converted: ',date('d/m/Y O', $date);` | Should different servers translate unix timestamps as different dates? | [
"",
"php",
"unix",
"date",
"timestamp",
""
] |
How can I enable EL expression in JSP version 2.0? Every time I'm getting EL expression as an String literal in the JSP as an output.
Here's the DD which the container is using to sending request to servlet, and then servlet dispating request to JSP:
```
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>check</servlet-name>
<servlet-class>Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>check</servlet-name>
<url-pattern>/Momma.do</url-pattern>
</servlet-mapping>
</web-app>
```
I've not ignored any el in JSP too. Am I still missing something? | Your web.xml file looks fine for JSP 2.0. If you are having problems accessing EL on specific pages try adding the following to the top of the individual JSP page:
```
<%@ page isELIgnored="false" %>
```
Since you are using JSP 2.0 I think that EL is ignored by default so you can can add the following to your web.xml to enable it for all pages:
```
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-enabled>true</el-enabled>
<scripting-enabled>true</scripting-enabled>
</jsp-property-group>
</jsp-config>
``` | for facet 2.5
```
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<el-ignored>true</el-ignored>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</web-app>
``` | enabling el in jsp | [
"",
"java",
"jsp",
"tomcat",
"servlets",
""
] |
I have a namespace `Company.UI.Forms` where we have a form base class `BaseForm` that inherits from `System.Windows.Forms.Form`.
I need to limit the size of this form, so that if a concrete form, say `ExampleForm`, derives from `BaseForm`, it should have a fixed size in the VS designer view. The fixed size should be set or defined in some way (in the `BaseForm` ctor?) so that the derived `ExampleForm` and the designer picks it up.
Is that possible?
[Edit] The purpose is to use the base class as a template for a full screen form for a Windows CE device of known screen size, for which I want to be able to lay out child controls in the designer. | I don't believe there is any direct support for this type of scenario. All of the values which control the maximum size on a Form can be overridden by a child form. Hence there is no way to constrain it from a property perspective.
The only way I can think of is to override the size changed method and reset the size to the max size if it ever goes over. This may have some bad effects though and you should expirement with it before you settle on it as a solution. | In standard WinForms you can override the SetBoundsCore method. This code will prevent the base classes to change it at design time... but remember it can be overriden by any inherited class anyway:
```
protected override void SetBoundsCore(int x, int y,
int width, int height, BoundsSpecified specified)
{
if (this.DesignMode)
base.SetBoundsCore(x, y, 500, 490, specified);
else
base.SetBoundsCore(x, y, width, height, specified);
}
```
I've put the if because you specified to be at design time, if you don't want a resize at runtime as well remove it. | Limit the size of a user control at design time | [
"",
"c#",
"visual-studio",
"compact-framework",
"user-controls",
"design-time",
""
] |
I've this simple form:
```
<form id="commentForm" method="POST" action="api/comment">
<input type="text" name="name" title="Your name"/>
<textarea cols="40" rows="10" name="comment" title="Enter a comment">
</textarea>
<input type="submit" value="Post"/>
<input type="reset" value="Reset"/>
</form>
```
I need to add two POST parameters before send to the server:
```
var params = [
{
name: "url",
value: window.location.pathname
},
{
name: "time",
value: new Date().getTime()
}
];
```
without modifying the form, please. | To add that using Jquery:
```
$('#commentForm').submit(function(){ //listen for submit event
$.each(params, function(i,param){
$('<input />').attr('type', 'hidden')
.attr('name', param.name)
.attr('value', param.value)
.appendTo('#commentForm');
});
return true;
});
``` | you can do this without jQuery:
```
var form=document.getElementById('form-id');//retrieve the form as a DOM element
var input = document.createElement('input');//prepare a new input DOM element
input.setAttribute('name', inputName);//set the param name
input.setAttribute('value', inputValue);//set the value
input.setAttribute('type', inputType)//set the type, like "hidden" or other
form.appendChild(input);//append the input to the form
form.submit();//send with added input
``` | Adding POST parameters before submit | [
"",
"javascript",
"jquery",
"forms",
""
] |
I've always admired the original uTorrent program. It looked great, was less than 64kb, was extremely fast and had all the features I needed. Unfortunately the program is closed source (and becoming more bloated by the day) so I come to Stackoverflow for inspiration.
**What methods do you recommend in writing fast, memory efficient and elegant programs on Windows?**
While C# (and the whole .NET concept) are cool ideas I am more interested in 'purist' answers and the challenge of writing efficient, fast software for the Windows platform, much like the original uTorrent client. I don't mind allocating my own memory, doing my own garbage collection and creating my own data structures.
Recommendations on books, articles, libraries, IDEs (even efficient ways of getting more caffeine into my system) welcome. | The Windows Template Library is geared towards what you want to do. It's a light-weight, template-based C++ wrapper for the Win32 API. With it, you don't have to go through the pain of direct Win32 coding, but it doesn't add a lot of overhead like MFC. | uTorrent is written in C++ and uses the old fashioned Win32 API.
Google Chrome is also written this way, so why not download the source code and learn from their code? | Programming slim C++ programs (like uTorrent) for Windows | [
"",
"c++",
"windows",
""
] |
[This question](https://stackoverflow.com/questions/1006691/how-to-check-if-a-win32-thread-is-running-or-in-suspended-state) got me thinking about the .NET equivalent. What value is there to the `ThreadState` property of the Thread class? In this code example:
```
if (someThread.ThreadState != System.Threading.ThreadState.Running)
{
someThread = new Thread(SomeMethod);
someThread.Start();
}
```
The `someThread`'s `ThreadState` property could switch to `Running` between the `if` and the code inside the `if`, right? | ThreadState is one of those fantastic properties that look promising at first, but once you dive deep into the way in which in functions, you find that it's almost totally useless.
The main problem with ThreadState is the enumeration names are very misleading. For instance take ThreadState.Runnning. This is a really bad name because it does not actually indicate the thread is running. Instead it indicates the thread was running at some point in the recent past and may or may not still be running.
This may seem trivial but it's not. It's really easy to take the names of the enumeration literally and produces really nice looking code. However as well as the code reads, it's often based on flawed logic.
I really only use this property for debugging purposes.
This value can be useful in very limited sets of scenarios where you have some other mechanism which controls the thread you are looking at. Such as a lock or WaitHandle. But it's usually better to use another form of synchronization than relying on this property. | From [MSDN](http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx):
> Important Note:
> There are two thread state enumerations,
> System.Threading.ThreadState and
> System.Diagnostics.ThreadState.
> The thread state enumerations are only of interest in a few debugging
> scenarios.
> Your code should never use thread state to synchronize the activities of
> threads. | What value is the ThreadState Property? | [
"",
"c#",
".net",
"multithreading",
""
] |
```
link REL="SHORTCUT ICON" HREF="/images/greenTheme/favicon.ico" type="image/x-icon"
```
the above code work in firefox but doesnt work in IE, how to make it work in IE? | ```
<link href='/path/to/favicon.ico' rel='icon' type='image/vnd.microsoft.icon'/>
```
Also if you have a 57x57 pixel PNG for an iPhone
```
<link rel="apple-touch-icon" href="/apple-touch-icon.png"/>
``` | •Make sure, the path to the favicon in the header of your page is absolute, not relative.
•Delete your temporary internet files. If the folder with temporary files has reached its maximum, the favicon may not be used.
. | html icon show in firefox but cannot showed in IE | [
"",
"javascript",
"html",
"css",
""
] |
I am trying to use DOM Parser in Java to parse a small XML file I pull off the net from its uri but receive an error complaining about missing semicolon.
Here's link 108:
```
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse("url_to_the_xml_file.xml");
```
Here's the error:
```
[Fatal Error] A01.xml:6:53: The character reference must end with the ';' delimiter.
Exception in thread "main" org.xml.sax.SAXParseException: The character reference must end with the ';' delimiter.
at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:180)
at Parser.Parse(Parser.java:108)
at Parser.main(Parser.java:185)
```
parsing this line of XML
```
<title>Reduction Algorithm using the À TROUS Wavelet Transform.</title>
```
Obviously there's a semi-colon missing. Does anyone know any nice and tidy work arounds for this problem? | I would retrieve the XML separately into a byte array/string and perform a regex replace on the malformed entity before I send it to the parser.
I'm not a regex expert but searching for a &#\d{1,4}[^;] might do one half of the trick.
If you have only this entity malformed you could just `String.replaceAll("À", "À");` | Use
```
"?default=sample&page=homePage"
``` | org.xml.sax.SAXParseException: The character reference must end with the ';' delimiter. Workaround Needed | [
"",
"java",
"xml",
"parsing",
""
] |
I know the function of this keyword, but I would like to know how it works on a lower level.
Which one is faster? And do they always yield the same result? If they do, why are there two different ways?
```
// Is there an overhead? An internal try catch?
Class123 obj = someobject as Class123;
if (Class123 != null)
{
//OK
}
```
or
```
Class123 obj = null;
if (someobject is Class123)
{
obj = (Class123)someobject;
}
``` | There's no internal try-catch happening when using the `as` keyword. The functionality is built in to the compiler/CLR, as far as I know, so the type check is implicit and automated.
**Simple rule**:
Use a direct cast when *you always expect the object to have a known type* (and thus receive a helpful error if it *is* by chance of the wrong type). Use the `as` keyword when the object is *always of a known type*.
The reason for the existance of the `as` keyword is purely for the convenience of the programmer (although you are correct in suggesting that a try-catch would be slower). You could implement it yourself manually as such, as you point out:
```
var castObj = (obj is NewType) ? (NewType)obj : null;
```
This highlights the fact that the 'as' keyword is primarily there for the purpose of conciseness.
Now, the performance difference between the two is likely to be negligible. The `as` keyword is probably marginally slower because of the type check, but this is unlikely to affect code in the vast majority of situations. As oft said, premature optimisation is never a wise thing to be doing. Benchmark if you really wish, but I would advise just to use whichever method is more convenient/appropiate for your situation, and not worry about performance at all (or later if you absolutely must). | According to [MSDN: as (C# Reference)](http://msdn.microsoft.com/en-us/library/cscsdfbt.aspx):
> The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception. Consider the following expression:
```
expression as type
```
> It is equivalent to the following expression except that expression is evaluated only one time.
```
expression is type ? (type)expression : (type)null
```
---
The first variant (*as operand*) ...
```
string str1 = strAsObject as string;
if (str1 != null)
{
this.blabla(str1);
}
```
... compiles to this IL code:
```
L_0009: ldloc.1
L_000a: isinst string
L_000f: stloc.2
L_0010: ldloc.2
L_0011: ldnull
L_0012: ceq
L_0014: stloc.s CS$4$0000
L_0016: ldloc.s CS$4$0000
L_0018: brtrue.s L_0024
L_001a: nop
L_001b: ldarg.0
L_001c: ldloc.2
L_001d: call instance void TestWinFormsApplication001.Form1::blabla(string)
L_0022: nop
L_0023: nop
```
... and the second variant (*is operand + cast*) ...
```
if (strAsObject is string)
{
string str2 = (string) strAsObject;
this.blabla(str2);
}
```
... compiles to this IL code:
```
L_0024: ldloc.1
L_0025: isinst string
L_002a: ldnull
L_002b: cgt.un
L_002d: ldc.i4.0
L_002e: ceq
L_0030: stloc.s CS$4$0000
L_0032: ldloc.s CS$4$0000
L_0034: brtrue.s L_0047
L_0036: nop
L_0037: ldloc.1
L_0038: castclass string
L_003d: stloc.3
L_003e: ldarg.0
L_003f: ldloc.3
L_0040: call instance void TestWinFormsApplication001.Form1::blabla(string)
L_0045: nop
L_0046: nop
```
... so you see the only difference is the additional `castclass` code in line `L_0038`. | How does the "as" keyword work internally? | [
"",
"c#",
"clr",
""
] |
Which static analysis tools for Java has easiest extension mechanism. I checked [PMD](http://pmd.sourceforge.net/howtowritearule.html)
But the process of writing custom rules appears to be very involved.
Specifically, I want to know whether there is any tools that offers **AspectJ** like syntax for picking out interesting areas of code? I am aware of AspectJ's [`declare warning`](http://www.eclipse.org/aspectj/doc/released/progguide/semantics-declare.html#warnings-and-errors) but it appears to be limited in what it can do.
I have found a related question:
Static Analysis tool recommendation for Java?
[Static Analysis tool recommendation for Java?](https://stackoverflow.com/questions/97599/static-analysis-tool-recommendation-for-java)
The answers list many tools. But I want to find which one offers easiest option for writing custom rules.
**Edit:** So far PMD's XPath expressions suggested by Guillaume appears to be closest to what I am looking for. I will be exploring it shortly. | The real problem with "extending" a static analysis tool is "static analysis" is such a broad topic that that you need lots of machinery to do it in general: parsing, tree building, control flow graph extraction, data flow extraction, points-to analysis, interprocedural analysis, range analysis, the list goes on and on, see the tons of compiler literature on analyzing programs.
You might use pattern matching of surface syntax to focus the tool's attention on some program code, but you'll still have
to explain to the tool what you want it to "statically analyze" at that point
(and some analyses [such as points-to] require you do the analysis everywhere
first, and then just pick out the part you want).
**Moral**: don't expect extending a tool to do arbitrary analysis to be easy.
You should basically decide what kinds of analysis you care about in advance
(tainted inputs? subscript range checks? API abuse?) and find a tool that
already supports that kind of thing. At least then your "extensions" have
a chance of being simple by virtue of being similar to what the tool already does.
Our DMS Software Reengineering Toolkit is an attempt to amortize the cost of building all kinds of analysis machinery across many applications and langauges.
It provides the parsing, control/dataflow analysis and points-to analysis
to varying degrees for C, C++, Java and COBOL. And it has surface-syntax
pattern matching to help you "point".
See <http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html> | It is actually pretty easy to write custom rules for PMD. PMD provides a xPath-like syntax to find interesting area of your code, so if you have some minimal experience with XML, you will be able to get started in no time. I suggest you invest 1-2 hours in either PMD or Findbugs and come back here if you have specific questions.
We might be able to give you a better answer if you tell us exactly what kind of rules you are trying to write ... | Which static analysis tool for Java is easiest to extend? | [
"",
"java",
"static-analysis",
"extensibility",
"aspectj",
""
] |
I have 2 classes Test(Base)and Program(child). Now I am facing some problem while downcasting.
```
Test t = new Program();// upcasting-works
Program p = (Program)t;//Downcasting-works
Program q = (Program)new Test();//Downcasting -throws exception.
```
I want to know why its throwing exception? May b its very basic, but somehow I am not getting.
Is it for that new object?
Thanks. | This is expected behaviour in all OO systems. In short, you cannot downcast to something for which the dynamic type is not matched. In this line:
```
Program q = (Program)new Test();
```
You are creating a `Test` instance - the instance obviously does not match `Program` since `Test` does not derive from `Program`. At runtime, the computer detects this is the case and throws the exception.
On the other hand, you have:
```
Test t = new Program();
```
Here, you are creating a `Program` instance - the instance matches `Test` since `Program` does derive from `Test`.
Finally, and out of order, you have:
```
Program p = (Program)t;
```
In this case, `t` is a reference to `Test`, but the underlying type is really `Program` - at runtime, the computer is able to determine this is the case so the cast is allowed to work. | Every Square is a Rectangle but not vice versa. Similarly, every instance of a derived class is a valid instance of the base class but not vice versa. In your example, every `Program` is a `Test` but not all `Test`s are `Program`s.
*Note: To clarify, that doesn't mean you should inherit Square from Rectangle in OOP :) It's just an analogy. Ironically, the analogy is a well known problem in OO design.* | Why does this Upcast not work? | [
"",
"c#",
"oop",
""
] |
> **Possible Duplicates:**
> [Is LINQ to SQL DOA?](https://stackoverflow.com/questions/252683/is-linq-to-sql-doa)
I am starting a new ASP.Net project which holds all data in a SQL database. I would normally use Linq to SQL to do all my queries, updates and inserts. but as i recently found out Microsoft will no longer develop/support Linq to SQL. What would you use as an alternative?
Does anyone know why they are dropping this, as I have come to like Linq to SQL, and do you know what they will replace it with?
Any information would be great. | **Linq to SQL is not dead nor is it being replaced with EF**, they have not killed it, feel free to compare and contrast
* Linq to SQL
* Entity Framework (aka Linq to Entities)
* nHibernate or any other ORM
Pick one that works for you and stick with it, neither are dying.
FWIW, Microsoft has more developers working on Linq to SQL than it has working on MVC.net right now
I prefer Linq to SQL because I do not need to support non MSSQL db and its much lighter than EF. It doesn't support every last thing you'd need, but in my opinion (and I may get flamed for this) Linq to SQL is to MVC.net as EF is to webforms.
EF obviously has its advantages over Linq to SQL though, there are somethings that linq to sql just flat out doesn't support (cross db joins, non mssql databases, creating a type based on a view, etc). Every tool has its place.
Some decent [comparisons on the two](http://blogs.msdn.com/swiss_dpe_team/archive/2008/11/06/entity-framework-vs-linq-to-sql.aspx)
Oh and [StackOverflow was built with linq to sql](https://stackoverflow.com/questions/749358/what-was-stack-overflow-built-with-closed) | **if you use ANY technology, prepare for it to eventually fall from favor, and not be the latest technology!**
if you don't pick Linq, whatever you use will eventually be "old", and people will be asking if it is worthwhile to learn or use, since there are better things out.
if you are writing software prepare to keep learning new tech and methods, or switch careers. | Linq to SQL | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.