Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there any way to speed up the initialization of javax.xml.bind.JAXBContexts with a large (>1000) number of classes? In our XML heavy application the startup time is some 10 minutes and consists mainly of the initialization time of the JAXBContexts. :-(
We are using Sun's JAXB implementation in the JDK 1.5 and the org.jvnet.jaxb2.maven2.maven-jaxb2-plugin for the code generation from XSDs.
Clarification: The problem is not that we have many instances of a JAXBContext with the same contextpaths, but the problem is that the initialization of one single JAXBContext takes tens of seconds since it has to load and process thousands of classes. (Our XSDs are fairly large and complicated.) All JAXBContext instances have different contextpaths - we cannot reduce the number further. | The JAXB reference implementation has a sort-of-undocumented system property for exactly this reason:
```
-Dcom.sun.xml.internal.bind.v2.runtime.JAXBContextImpl.fastBoot=true
```
or for old versions prior to the package refactoring:
```
-Dcom.sun.xml.bind.v2.runtime.JAXBContextImpl.fastBoot=true
```
This instructs JAXB to skip the expensive process of pre-caching the various reflection muscles it needs to do the job. Instead, it will do all the reflection when the context gets used. This makes for a slower runtime, but considerably faster initialization, especially for large numbers of classes.
However, one part of the speed problem is unavoidable, and that's the fact that JAXB has to load every single one of your classes, and classloading is slow. This is apparent if you create a 2nd context immediately after the first, with the same configuration - you'll see it's much, much faster, having already loaded the classes.
Also, you say that you have multiple JAXBContext instances because you have multiple contextpaths. Did you realise that you can put multiple context paths into a single context? You just need to pass them all as a semicolon-delimited string when you initialize the context, e.g.
```
JaxbContext.newInstance("a.b.c:x.y.z");
```
will load the contexts `a.b.c` and `x.y.z`. It likely won't make any difference to performance, though. | In general, you should not have to create many instances of JAXBContext, as they are thread-safe after they have been configured. In most cases just a single context is fine.
So is there specific reason why many instances are created? Perhaps there was assumption they are not thread-safe? (which is understandable given this is not clearly documented -- but it is a very common pattern, need syncing during configuration, but not during usage as long as config is not changed).
Other than this, if this is still a problem, profiling bottlenecks & filing an issue at jaxb.dev.java.net (pointing hot spots from profile) would help in getting things improved.
JAXB team is very good, responsive, and if you can show where problems are they usually come up with good solutions. | JAXBContext initialization speedup? | [
"",
"java",
"performance",
"jaxb",
""
] |
I code CSS/XHTML like it should be my mother language, and I do write valid, semantic code following guidelines of accessibility and such.
But I want to learn Unobtrusive JavaScripting, but with a total non-programmer brain I need some motivation / tips / etc., like what's the best way to learn it, and how long does it take/did it take you before you could feel the power of knowledge? :)
PS: I do have an understanding on how JavaScript works and changes the DOM etc.. I think it's more about learning the syntax by head instead of having to look it up.
### See also:
> [Suggestions for someone starting javascript programming.](https://stackoverflow.com/questions/284452/suggestions-for-someone-starting-javascript-programming) | Motivation, sorry can't help there.
Syntax is learned by rote. The rules are simple, and reasonably consistent, so in truth syntax isn't that hard.
What you conflate with syntax are likely the other aspects like what properties are available on what objects, what functions to call, what does your framework provide. That, again, is basically rote memorization.
Many frameworks add a little bit of syntax through clever use of the JavaScript syntax, and you'll need to learn those as well.
But when it all comes down to it, the only way to learn this stuff is to use it.
You can't read about it, you have to do it.
Find an issue that you want to work on, a feature for your site or whatever, and attack that.
If you find a tutorial or whatever on line that does what you want, TYPE IN THE CODE, don't cut and paste it. As you type it in, question every symbol or character, try to understand why you're typing what you are typing.
Make an effort to change things, even if it's just variable names, because then you get a better idea of what things are being used for, and how they're referenced. It also lets you focus on a small part of the larger program.
If you're changing the "window1" variable to "myWindow", then at least you can look at the code as "blah blah blah window1 blah blah window1" without having to understand all of it.
Start small, don't worry about "doing it right", etc. so much as just being successful. If the way it's done doesn't bother you, then you're good. If you look at it and go "That's not quite right" because you learned something later after you started, then go back and clean it up.
At this stage, function is greater than form. Much of the form simply comes from experience. | Just use it. Really, the more time you spend reading and writing the language, the more natural it becomes. Use [Firebug](http://getfirebug.com/) or an equivalent console to test short ideas; take an existing web page and wire up events interactively from the command line, get used to the idea of writing behavioral code as a separate process from writing markup.
If you want a good book, i can recommend the excellent [jQuery in Action](http://www.manning.com/bibeault/) - yes, it's targeted at jQuery users, but the concepts apply regardless of your choice in libraries. | Learning JavaScript for a total non-programmer | [
"",
"javascript",
"unobtrusive-javascript",
""
] |
I am trying to use `TransactionScope`, but keep getting the exception below.
The app is running on a different machine than the database, if that matters. I am using SQL Server 2005.
> Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration
> for MSDTC using the Component Services Administrative tool.
```
using (TransactionScope tsTransScope = new TransactionScope())
{
//Do stuff here
tsTransScope.Complete();
}
```
**Edit**
I made some changes based on the feedback. Now I'm getting this error:
> "Error HRESULT E\_FAIL has been returned from a call to a COM component."
> "Communication with the underlying transaction manager has failed."
**Solution**
I think the accepted answer fixed the initial issue I was getting. The 2nd error seems to be specific to Entity Framework. I'll post another question for it.
**Here are the properties on the client:**
[Client http://www.portnine.com/data/images/Misc/client.jpg](http://www.portnine.com/data/images/Misc/client.jpg)
**Here are the properties on the server:**
[Server http://www.portnine.com/data/images/Misc/server.jpg](http://www.portnine.com/data/images/Misc/server.jpg) | You need to enable network DTC access as described in this [Microsoft TechNet Article](http://technet.microsoft.com/en-us/library/cc753510.aspx). This change may have to be made on both the database and application servers. Often times DTC is already turned on a database server so I'd look at the application server first.
Here is a screen shot of what we use except for the "Allow Remote Administration" option:

I have not run into the HRESULT E\_Fail issue you are now having but this article on [XP SP2 and transactions](http://blogs.msdn.com/florinlazar/archive/2004/06/18/159127.aspx) had this interesting suggestion:
> Another configuration setting that you
> need to be aware (although I consider
> it to be an uncommon scenario) is
> RestrictRemoteClients registry key. If
> the value of this key is set to 2
> (RPC\_RESTRICT\_REMOTE\_CLIENT\_HIGH) then
> MSDTC network transactions will not be
> able to work properly. MSDTC supports
> only RPC\_RESTRICT\_REMOTE\_CLIENT\_NONE
> (0) and
> RPC\_RESTRICT\_REMOTE\_CLIENT\_DEFAULT (1)
> values. See
> <http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2netwk.mspx#XSLTsection128121120120>
> for more info on
> RestrictRemoteClients.
Finally, while not specific to your issue a very important thing to note about using the `TransactionScope` class is that its default setting is to utilize a [Transaction Isolation Level of Serializable](http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Serializable). Serializable is the most restrictive of the isolation levels and frankly its surprising that it was chosen as the default. If you do not need this level of locking I would highly recommend setting the isolation level to a less restrictive option (ReadCommitted) when instantiating a `TransactionScope`:
```
var scopeOptions = new TransactionOptions();
scopeOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted;
scopeOptions.Timeout = TimeSpan.MaxValue;
using (var scope = new TransactionScope(TransactionScopeOption.Required,
scopeOptions))
{
// your code here
}
``` | Control Panel - Administrative Tools - Component Services - My Computer properties - MSDTC tab - Security Configuration tab - Network DTC Access (checked) / Allow Remote Clients (checked) / Allow Inbound (checked) / Allow Outbound (checked) / Enable TIP Transactions (checked)
Reboot computer. | How to use TransactionScope in C#? | [
"",
"c#",
".net",
"database",
"transactions",
"transactionscope",
""
] |
I'm trying to programmatically add an identity column to a table Employees. Not sure what I'm doing wrong with my syntax.
```
ALTER TABLE Employees
ADD COLUMN EmployeeID int NOT NULL IDENTITY (1, 1)
ALTER TABLE Employees ADD CONSTRAINT
PK_Employees PRIMARY KEY CLUSTERED
(
EmployeeID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
```
What am I doing wrong? I tried to export the script, but SQL Mgmt Studio does a whole Temp Table rename thing.
**UPDATE**:
I think it is choking on the first statement with "Incorrect syntax near the keyword 'COLUMN'." | Just remove `COLUMN` from `ADD COLUMN`
```
ALTER TABLE Employees
ADD EmployeeID numeric NOT NULL IDENTITY (1, 1)
ALTER TABLE Employees ADD CONSTRAINT
PK_Employees PRIMARY KEY CLUSTERED
(
EmployeeID
) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
``` | This is how Adding new column to Table
```
ALTER TABLE [tableName]
ADD ColumnName Datatype
```
**E.g**
```
ALTER TABLE [Emp]
ADD Sr_No Int
```
And If you want to make it auto incremented
```
ALTER TABLE [Emp]
ADD Sr_No Int IDENTITY(1,1) NOT NULL
``` | Alter Table Add Column Syntax | [
"",
"sql",
"sql-server",
"t-sql",
"ddl",
""
] |
This should be really simple. If I have a String like this:
```
../Test?/sample*.txt
```
then what is a generally-accepted way to get a list of files that match this pattern? (e.g. it should match `../Test1/sample22b.txt` and `../Test4/sample-spiffy.txt` but not `../Test3/sample2.blah` or `../Test44/sample2.txt`)
I've taken a look at [`org.apache.commons.io.filefilter.WildcardFileFilter`](http://commons.apache.org/io/apidocs/org/apache/commons/io/filefilter/WildcardFileFilter.html) and it seems like the right beast but I'm not sure how to use it for finding files in a relative directory path.
I suppose I can look the source for ant since it uses wildcard syntax, but I must be missing something pretty obvious here.
(**edit**: the above example was just a sample case. I'm looking for the way to parse general paths containing wildcards at runtime. I figured out how to do it based on mmyers' suggestion but it's kind of annoying. Not to mention that the java JRE seems to auto-parse simple wildcards in the main(String[] arguments) from a single argument to "save" me time and hassle... I'm just glad I didn't have non-file arguments in the mix.) | Consider DirectoryScanner from Apache Ant:
```
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/*.java"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
```
You'll need to reference ant.jar (~ 1.3 MB for ant 1.7.1). | Try [`FileUtils`](http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/FileUtils.html) from [Apache commons-io](http://commons.apache.org/io) (`listFiles` and `iterateFiles` methods):
```
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("sample*.java");
File[] files = dir.listFiles(fileFilter);
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
```
To solve your issue with the `TestX` folders, I would first iterate through the list of folders:
```
File[] dirs = new File(".").listFiles(new WildcardFileFilter("Test*.java");
for (int i=0; i<dirs.length; i++) {
File dir = dirs[i];
if (dir.isDirectory()) {
File[] files = dir.listFiles(new WildcardFileFilter("sample*.java"));
}
}
```
Quite a 'brute force' solution but should work fine. If this doesn't fit your needs, you can always use the [RegexFileFilter](http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/filefilter/RegexFileFilter.html). | How to find files that match a wildcard string in Java? | [
"",
"java",
"file",
"wildcard",
""
] |
I have a Table that stores Hierarchical information using the Adjacency List model. (uses a self referential key - example below. This Table may look [familiar](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/)):
```
category_id name parent
----------- -------------------- -----------
1 ELECTRONICS NULL
2 TELEVISIONS 1
3 TUBE 2
4 LCD 2
5 PLASMA 2
6 PORTABLE ELECTRONICS 1
7 MP3 PLAYERS 6
8 FLASH 7
9 CD PLAYERS 6
10 2 WAY RADIOS 6
```
---
**What is the best method to "flatten" the above data into something like this?**
```
category_id lvl1 lvl2 lvl3 lvl4
----------- ----------- ----------- ----------- -----------
1 1 NULL NULL NULL
2 1 2 NULL NULL
6 1 6 NULL NULL
3 1 2 3 NULL
4 1 2 4 NULL
5 1 2 5 NULL
7 1 6 7 NULL
9 1 6 9 NULL
10 1 6 10 NULL
8 1 6 7 8
```
---
Each row is one "Path" through the Hierarchy, except there is a row for *each node* (not just each *leaf node*). The category\_id column represents the current node and the "lvl" columns are its ancestors. The value for the current node must also be in the farthest right lvl column. The value in the lvl1 column will always represent the root node, values in lvl2 will always represent direct descendants of lvl1, and so on.
If possible the method to generate this output would be in SQL, and would work for n-tier hierarchies. | To do multi-level queries across a simple adjacency-list invariably involves self-left-joins. It's easy to make a right-aligned table:
```
SELECT category.category_id,
ancestor4.category_id AS lvl4,
ancestor3.category_id AS lvl3,
ancestor2.category_id AS lvl2,
ancestor1.category_id AS lvl1
FROM categories AS category
LEFT JOIN categories AS ancestor1 ON ancestor1.category_id=category.category_id
LEFT JOIN categories AS ancestor2 ON ancestor2.category_id=ancestor1.parent
LEFT JOIN categories AS ancestor3 ON ancestor3.category_id=ancestor2.parent
LEFT JOIN categories AS ancestor4 ON ancestor4.category_id=ancestor3.parent;
```
To left-align it like your example is a bit more tricky. This comes to mind:
```
SELECT category.category_id,
ancestor1.category_id AS lvl1,
ancestor2.category_id AS lvl2,
ancestor3.category_id AS lvl3,
ancestor4.category_id AS lvl4
FROM categories AS category
LEFT JOIN categories AS ancestor1 ON ancestor1.parent IS NULL
LEFT JOIN categories AS ancestor2 ON ancestor1.category_id<>category.category_id AND ancestor2.parent=ancestor1.category_id
LEFT JOIN categories AS ancestor3 ON ancestor2.category_id<>category.category_id AND ancestor3.parent=ancestor2.category_id
LEFT JOIN categories AS ancestor4 ON ancestor3.category_id<>category.category_id AND ancestor4.parent=ancestor3.category_id
WHERE
ancestor1.category_id=category.category_id OR
ancestor2.category_id=category.category_id OR
ancestor3.category_id=category.category_id OR
ancestor4.category_id=category.category_id;
```
> would work for n-tier hierarchies.
Sorry, arbitrary-depth queries are not possible in the adjacency-list model. If you are doing this kind of query a lot, you should change your schema to one of the [other models of storing hierarchical information](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/): full adjacency relation (storing all ancestor-descendent relationships), materialised path, or nested sets.
If the categories don't move around a lot (which is usually the case for a store like your example), I would tend towards nested sets. | As mentioned, SQL has no clean way to implement tables with dynamically varying numbers of columns. The only two solutions I have used before are:
1. A fixed number Self-Joins, giving a fixed number of columns (AS per BobInce)
2. Generate the results as a string in a single column
The second one sounds grotesque initially; storing IDs as string?! But when the output is formatted as XML or something, people don't seem to mind so much.
Equally, this is of very little use if you then want to join on the results in SQL. If the result is to be supplied to an Application, it Can be very suitable. Personally, however, I prefer to do the flattening in the Application rather than SQL
I'm stuck here on a 10 inch screen without access to SQL so I can't give the tested code, but the basic method would be to utilise recursion in some way;
- A recursive scalar function can do this
- MS SQL can do this using a recursive WITH statement (more efficient)
**Scalar Function (something like):**
```
CREATE FUNCTION getGraphWalk(@child_id INT)
RETURNS VARCHAR(4000)
AS
BEGIN
DECLARE @graph VARCHAR(4000)
-- This step assumes each child only has one parent
SELECT
@graph = dbo.getGraphWalk(parent_id)
FROM
mapping_table
WHERE
category_id = @child_id
AND parent_id IS NOT NULL
IF (@graph IS NULL)
SET @graph = CAST(@child_id AS VARCHAR(16))
ELSE
SET @graph = @graph + ',' + CAST(@child_id AS VARCHAR(16))
RETURN @graph
END
SELECT
category_id AS [category_id],
dbo.getGraphWalk(category_id) AS [graph_path]
FROM
mapping_table
ORDER BY
category_id
```
I haven't used a recursive WITH in a while, but I'll give the syntax a go even though I don't have SQL here to test anything :)
**Recursive WITH**
```
WITH
result (
category_id,
graph_path
)
AS
(
SELECT
category_id,
CAST(category_id AS VARCHAR(4000))
FROM
mapping_table
WHERE
parent_id IS NULL
UNION ALL
SELECT
mapping_table.category_id,
CAST(result.graph_path + ',' + CAST(mapping_table.category_id AS VARCHAR(16)) AS VARCHAR(4000))
FROM
result
INNER JOIN
mapping_table
ON result.category_id = mapping_table.parent_id
)
SELECT
*
FROM
result
ORDER BY
category_id
```
**EDIT - OUTPUT for both is the same:**
```
1 '1'
2 '1,2'
3 '1,2,3'
4 '1,2,4'
5 '1,2,5'
6 '1,6'
7 '1,6,7'
8 '1,6,7,8'
9 '1,6,9'
``` | Flatten Adjacency List Hierarchy To A List Of All Paths | [
"",
"sql",
"hierarchy",
"adjacency-list",
"flatten",
""
] |
So, if you are writing a website using Java and JSP's and didn't want users to know what language you written it in. What techniques would you use? | If you are using some sort of framework, like Struts2, you'll have an extension (\*.action, or whatever you choose) mapped to the dispatcher servlet. The dispatcher "forwards" the request to the JSP, which is in the WEB-INF directory. Users only see the URL that was directed to the servlet, and get back HTML. They can't tell what the template language was. Since you can choose whatever you like for the servlet mapping, you could make something up, or even misdirect them with something like ".php" or ".asp".
Of course, you might have some JSPs right in the web app directory, rather than in WEB-INF. You can give these a different extension, and tell the container to process them as JSPs by creating a `<jsp-property-group>` with a `url-pattern` element that specifies the fake extension in web.xml.
You'll also need to examine your container's documentation to determine how to hide any server version information that might be sent. Another thing to explore is how to change the session cookie name to something other than "jsessionid". That's a bit of a giveaway, but it's part of the Servlet specification, and some containers don't support changing it. | Along with other answers here, you'll want to make sure you're handling your application errors correctly. If you let an Exception out and the web container handles it, it'll be pretty obvious what you're using. | What tactics can I use to prevent users from discovering what language a website is written in? | [
"",
"java",
"jsp",
"spring-mvc",
"struts",
""
] |
**Is there any available C++ (or maybe C) function/class/library with only purpose to sanitize a string that might contain HTML?**
I find a lot of source code for sanitizing in C# or other languages more used in web application but nothing in C++.
I'll try to implement my own function if I don't find any available but I think an heavily tested solution would be far better.
edit> Some more precisions on my needs :
I'm getting text input from keyboard in my C++ application. Then I need to sanitize it before using it as a parameter in a javascript function call. That javascript run in a loaded html page that is automatically rendered (via Chromium) in a texture that I display via a library (Navi).
So, the javascript function I use will simply take the given text, put P tag around the text and inject it in a div like this :
```
text_display.innerHTML += text_to_add;
```
I need to sanitize the text before sending it to the web page, be it for this function or another. It just have to be sanitized before input in Chromium. | [HTML Tidy](http://tidy.sourceforge.net/) is written in c, but there are bindings for practically every language/platform, [including c++](http://users.rcn.com/creitzel/tidy.html#cplusplus). | You are asking quite the question here. Before you are going to get a good answer, you need to be clear on what exactly you want to "parse" OUT of your input. For example, you could look for any "<" chars, and convert them to something else, so they are not parsed by any HTML parser.
Or, you could search for the pattern of < and > followed by < / > pattern. (Excuse the space, I had to put it in here so the HTML parser HERE would not eat it). Then, you also need to look for the "< single element tags / >" as well.
You can actually look for valid/known HTML tags and strip THOSE out.
So, the question becomes, which method is correct for your solution? Knowing that if you make a simple parser, you may actually rip valid text out that contains greater-than, and less-than symbols.
So, here is my answer for you thus far.
If you want to simply REMOVE any HTML-esque style text, I'd recommend going with a regular expression engine (PCRE), and using it to parse your input, and remove all the matched strings. This probably the easy solution, but it does require you get and build PCRE, and there a GPL issues you need to be aware of, for your project. The parsing would probably be really easy to implement, and run quick.
The second option is to do it by walking a buffer, looking for the open HTML char (<), then parsing until you hit the first white space, then start walking, looking for the closing HTML char (>), then start walking again, looking for the matching CLOSING tag, based on what you just parsed. (Say, it's a DIV tag, you want to look for /DIV.)
I have code that does this in an STL HTML parser, but there are a lot of issues to consider going this route also. For example, you have entity codes to deal with, single element tags like IMG, P, and BR, to name a few.
If you want some REALLY great C code to look at, go look at the ClamAV project. They have an HTML parser that strips all the tags out of a page, and leaves you with JUST the text left over. (among other things it does..). Look in the file libclamav\htmlnorm.c for a great example on 'buffer walking' and parsing. It's not the fastest thing in the world, but it does work... The latest Clam might even have so much stuff tied into the HTML parser, it might actually be difficult to understand. If so, go back and look at an earlier version, like .88.4 or so. Just please be aware of the bugs in those older code bases, there are some good ones. :)
Hope this helps. | HTML Sanitization in C++ | [
"",
"c++",
"html",
"sanitization",
""
] |
I'm working on a big app (ns2) and somewhere someone put an exit(1) in there without any debug or print statements and it is being executed. I don't want to have to manually check every file that calls exit to figure out why the program is exiting. Is is possible to determine where the program exited? This is running on Linux and coded in C++. Is it possible to do something like this in gdb? | Sure. Put a breakpoint at the start of exit(3). When it breaks, look at the stack.
Second choice, run it under truss(1) (I'm pretty sure there's a Linux version of truss.)
Or [strace(1)](http://linux.die.net/man/1/strace).
### Update
In fact, I ran across another method in another question: [here's a link](http://ndevilla.free.fr/etrace/). | If you supply your own implementation of `exit()`, then that one will be used in preference to the one in the library. Build that, load it in the debugger, put a breakpoint on your `exit()`, run the program, and see where it came from.
Or as [Charlie](https://stackoverflow.com/questions/764555/determing-exit-point-of-application-c-linux/764561#764561) says, just put a breakpoint on the library `exit()`. Use the above method if you want to run some other specific bit of code instead. | Determing exit point of application. C++/Linux | [
"",
"c++",
"linux",
""
] |
In **Java**, what is the maximum size a `String` object may have, referring to the `length()` method call?
I know that `length()` return the size of a `String` as a `char []`; | Considering the [`String`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html) class' [`length`](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()) method returns an `int`, the maximum length that would be returned by the method would be [`Integer.MAX_VALUE`](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#MAX_VALUE), which is `2^31 - 1` (or approximately 2 billion.)
In terms of lengths and indexing of arrays, (such as `char[]`, which is probably the way the internal data representation is implemented for `String`s), [Chapter 10: Arrays](http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html) of [The Java Language Specification, Java SE 7 Edition](http://docs.oracle.com/javase/specs/jls/se7/html/index.html) says the following:
> The variables contained in an array
> have no names; instead they are
> referenced by array access expressions
> that use nonnegative integer index
> values. These variables are called the
> *components* of the array. If an array
> has `n` components, we say `n` is the
> *length* of the array; the components of
> the array are referenced using integer
> indices from `0` to `n - 1`, inclusive.
Furthermore, the indexing must be by `int` values, as mentioned in [Section 10.4](http://docs.oracle.com/javase/specs/jls/se7/html/jls-10.html#jls-10.4):
> Arrays must be indexed by `int` values;
Therefore, it appears that the limit is indeed `2^31 - 1`, as that is the maximum value for a nonnegative `int` value.
However, there probably are going to be other limitations, such as the maximum allocatable size for an array. | `java.io.DataInput.readUTF()` and `java.io.DataOutput.writeUTF(String)` say that a `String` object is represented by ***two bytes*** of length information and the [modified UTF-8](http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8) representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with `DataInput` and `DataOutput`.
In addition, [The specification of `CONSTANT_Utf8_info`](http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.4.7) found in the Java virtual machine specification defines the structure as follows.
```
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
```
You can find that the size of 'length' is **two bytes**.
That the return type of a certain method (e.g. `String.length()`) is `int` does not always mean that its allowed maximum value is `Integer.MAX_VALUE`. Instead, in most cases, `int` is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of `int` are converted to `int` before calculation (if my memory serves me correctly) and it is one reason to choose `int` when there is no special reason.
The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the [modified UTF-8](http://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html#modified-utf-8) representation, not the number of characters in a `String` object.
`String` objects may be able to have much more characters at runtime. However, if you want to use `String` objects with `DataInput` and `DataOutput` interfaces, it is better to avoid using too long `String` objects. I found this limitation when I implemented Objective-C equivalents of `DataInput.readUTF()` and `DataOutput.writeUTF(String)`. | String's Maximum length in Java - calling length() method | [
"",
"java",
"string",
""
] |
Basically, I was hoping to sort of keep my files sorted instead of having them all in the same folder as my executable, but referencing files in sub folders relative to my executable has proven difficult.
```
// DEFINES
#define IMAGE_BACKGROUND "\\content\\images\\background.bmp"
#define FONT_MAIN "\\content\\fonts\\sai.ttf"
```
The above code obviously does not work.
I read supposedly args[0] is somehow my path? Anyone care to elaborate a little more?
```
int main(int argc, char* args[])
{
``` | I actually solved it by using the following code, thank you all for the responses:
```
// DEFINES
#define IMAGE_BACKGROUND ".\\content\\images\\background.png"
#define IMAGE_BLUEBLOCK ".\\content\\images\\blueblock.png"
#define FONT_MAIN ".\\content\\fonts\\sai.ttf"
```
Turns out the . gets the "working path directory". | I should mention that [Boost.Filesystem](http://www.boost.org/doc/libs/1_39_0/libs/filesystem/doc/index.htm) is a nice library that can help you out. | image subdirectory in c++ | [
"",
"c++",
"image",
""
] |
### Exact duplicate:
> [Split string containing command-line parameters into string[] in C#](https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c)
---
C#: How do you configure for a string[] to accept input of a whole string the way the console's main entry point accepts it broken up?
When you execute a console application made in c#, it's main method accepts any other arguments typed into it while executing into it's string[] args parameter broken up into an array in args[].
How can you accomplish the same thing if you're not using a console application? | The Windows command API handles breaking up everything following the executable name into an array, and passes that to the executable. So from the .NET standpoint, the runtime simply accepts an already-split string from the caller.
To mimic the way the argument string is split, you need to split on spaces outside of quotes. There's a few ways to accomplish this. There's a very good way [already covered here](https://stackoverflow.com/questions/298830/split-string-containing-command-line-parameters-into-string-in-c/298990#298990). | I've had good luck with [Mono.GetOptions](http://www.talios.com/command_line_processing_with_monogetoptions.htm). I had to copy it out of the Mono project and add it as a project within my solution, but it works great. | C#: How do you configure for a string[] to accept input of a whole string the way the console's main entry point accepts it broken up? | [
"",
"c#",
".net",
"winforms",
"console",
""
] |
What would cause a jar to be added successfully to an Eclipse Java project but then at runtime some of the classes from that jar are not found with ClassNotFound exceptions? | The CLASSPATH variable at runtime is likely set incorrectly or you missed adding some classes to your jar file. | Everybody seems to be on the right track. Why don't you, while you have the jar unzipped, add the entire thing as a source folder in your eclipse project to see if you can even load it that way? Sometimes, depending on the classloader, you can get the CNFE if your class is available multiple times on the classpath... the classloader just bails because it doesn't know which one to use. | My code compiles in Eclipse but I get a ClassNotFound at runtime how can I fix it? | [
"",
"java",
"eclipse",
"jar",
"compilation",
"runtime-error",
""
] |
How can I hook in the ErrorProvider with individual cells on the DataGridView control? | I'm not sure that you can use the ErrorProvider in this manner, however the DataGridView has functionality built into it that's basically the same idea.
The idea is simple. A DataGridViewCell has an ErrorText property. What you do is, you handle the OnCellValidating event and if fails validation, you set the error text property, and you get that red error icon to show up in the cell. Here's some pseudo code:
```
public Form1()
{
this.dataGridView1.CellValidating += new DataGridViewCellValidatingEventHandler(dataGridView1_CellValidating);
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (!this.Validates(e.FormattedValue)) //run some custom validation on the value in that cell
{
this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].ErrorText = "Error";
e.Cancel = true; //will prevent user from leaving cell, may not be the greatest idea, you can decide that yourself.
}
}
``` | The problem I have with BFree's solution is that nothing shows up while the cell is in edit mode, but if I end edit, I get a data format error (because my value is a double). I solved this by attaching the ErrorProvider directly to the cell edit control like this:
```
private ErrorProvider ep = new ErrorProvider();
private void DGV_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
double val;
Control edit = DGV.EditingControl;
if (edit != null && ! Double.TryParse(e.FormattedValue.ToString(), out val))
{
e.Cancel = true;
ep.SetError(edit, "Numeric value required");
ep.SetIconAlignment(edit, ErrorIconAlignment.MiddleLeft);
ep.SetIconPadding(edit, -20); // icon displays on left side of cell
}
}
private void DGV_CellEndEdt(object sender, DataGridViewCellEventArgs e)
{
ep.Clear();
}
``` | Windows Forms - ErrorProvider + DataGridView | [
"",
"c#",
".net",
"winforms",
"datagridview",
"errorprovider",
""
] |
I am looking for lightweight multi-threading framework for C++. I found POSIX Threads.
Please, share you practical experience with POSIX threads: before I start with it I want to know its pros and cons from real people, not from wiki.
If you practically compared it with anything (maybe, better), it would be interesting to know either.
**UPD:** cross platform features are really important for me, so I would appreciate this direction described.
**UPD2:** I already have an experience with one framework for QNX / Win32, but it is not lightweight and - oh, I forgot to mention, - it is commercial, not free, but I need a free one. | I found [Boost.Threads](http://www.boost.org/doc/libs/1_38_0/doc/html/thread.html) to be really nice, especially after the 1.35 rewrite. POSIX threads on Windows is not so trivial, and it's a C API, so I would definitely prefer Boost to it. It has all the stuff you need, is portable and requires little setup. | Another C thread API is GThreads from GLib. There is a 1-to-1 mapping between some gthread and pthread calls such as pthread\_create, but gthreads have 2 big features that I have found very useful:
* thread pools and
* asynchronous queues for sending messages between threads.
The thread pools are very powerful, allowing things like dynamic resizing of the pool. See <http://library.gnome.org/devel/glib/2.20/glib-Threads.html> | POSIX threads experience? (Or recommend better one) | [
"",
"c++",
"multithreading",
"cross-platform",
"pthreads",
""
] |
In my web-application I'm using `$_SESSIONS` but sometimes, when the users hits the backspace key he gets:
> Webpage has expired
message.
Why is this happening? What can i do to avoid this? | It also has to do with the cache control directives sent to the browser.
Take a look at <http://de.php.net/manual/en/session.configuration.php#ini.session.cache-limiter> and <http://shiflett.org/articles/how-to-avoid-page-has-expired-warnings> to learn more about the cache settings.
<http://shiflett.org/articles/how-to-avoid-page-has-expired-warnings>:
> Recap
To avoid "Page Has Expired" warnings, set session.cache\_limiter to private, and make sure that any form using the POST method submits to an intermediate processing page that redirects the user to a different URL. | This doesn't have anything to do with `$_SESSION` variables, it has to do with you transferring information between pages using POST method. If you want to avoid it you need to use GET method instead of POST. | "Webpage has expired" $_SESSIONS in PHP | [
"",
"php",
"session",
""
] |
What are some tips I can use to avoid memory leaks in my applications? Are there any gotchas or pitfalls that I can look out for? | Call Dispose on IDisposable objects or use the `using` clause. That should take care of most of the leaks I can think of. | Watch that you remove any event handlers that you use. In .NET, they are the most common cause of leaked memory. | How to avoid Memory Leaks? | [
"",
"c#",
"memory-leaks",
""
] |
Alright, I have tried a bunch of times the
```
python setup.py install
```
command from my command prompt
And when trying this:
```
from SimPy.Simulation import *
```
on Idle, I get this:
```
Traceback (most recent call last):
File "C:/Python30/pruebas/prueba1", line 1, in <module>
from SimPy.Simulation import *
File "C:\Python30\SimPy\Simulation.py", line 320
print 'SimPy.Simulation %s' %__version__,
^
SyntaxError: invalid syntax
>>>
``` | Not every module supports python 3 - in fact, 90% or more of the modules are for 2.x now.
you should use 2.5 or 2.6 for this module, or find a simpy that is compatible with 3.0.
you can also run the 2->3 upgrade script to modify your simpy source, but I don't suggest doing that. | I have a similar error, and I Installed python 2.6.4, so I don't think you can solve your problem using an older version of python.
```
alumno@ubuntu:/usr/local/SimPy/SimPy$ python carro.py
Traceback (most recent call last):
File "carro.py", line 2, in <module>
from SimPy.Simulation import *
ImportError: No module named SimPy.Simulation
```
Python 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:55:11)
[GCC 4.4.1] on linux2 | What is wrong with this SimPy installation? | [
"",
"python",
"windows",
"installation",
"simpy",
""
] |
In C#, is it possible to mark an overridden virtual method as final so implementers cannot override it? How would I do it?
An example may make it easier to understand:
```
class A
{
abstract void DoAction();
}
class B : A
{
override void DoAction()
{
// Implements action in a way that it doesn't make
// sense for children to override, e.g. by setting private state
// later operations depend on
}
}
class C: B
{
// This would be a bug
override void DoAction() { }
}
```
Is there a way to modify B in order to prevent other children C from overriding DoAction, either at compile-time or runtime? | Yes, with "sealed":
```
class A
{
abstract void DoAction();
}
class B : A
{
sealed override void DoAction()
{
// Implements action in a way that it doesn't make
// sense for children to override, e.g. by setting private state
// later operations depend on
}
}
class C: B
{
override void DoAction() { } // will not compile
}
``` | You can mark the method as `sealed`.
<http://msdn.microsoft.com/en-us/library/aa645769(VS.71).aspx>
```
class A
{
public virtual void F() { }
}
class B : A
{
public sealed override void F() { }
}
class C : B
{
public override void F() { } // Compilation error - 'C.F()': cannot override
// inherited member 'B.F()' because it is sealed
}
``` | is it possible to mark overridden method as final | [
"",
"c#",
".net",
"inheritance",
""
] |
I have the following bit of code to create an automatically resized text input:
```
// setup quick jump input
$("#goto").keydown(function(e){
var size = $(this).val().length;
// sanity
if ( size < 1 ) {
size = 1;
}
$(this).attr("size",size);
// if enter then GOTO->
if ( e.keyCode == 13 ) {
window.location.href = "/" + $(this).val();
}
});
```
HTML:
```
<input type="text" id="goto" size="1" name="goto" />
```
**Problem:**
Resizing the input doesn't work in Safari or Chrome, just Firefox and Opera. I'm using jquery 1.3.2 and would like to know if it's a bug in jquery or my implementation.
EDIT: sorry I wasn't clear enough at first - it's the part where I'm trying to update the size of the input on the fly that is broken. My bad. Thanks for the feedback so far, some very useful links there. | I doubt that the size attribute would work cross browser. I would switch to setting the maxlength and css width of the input field rather than changing the size attribute.
Looks like a bug/unsupported feature in webkit. Which Safari/Chrome share. | According to the jQuery documentation on [`keydown()`](http://docs.jquery.com/Events/keydown#fn):
```
// Different browsers provide different codes
// see here for details: http://unixpapa.com/js/key.html
// ...
```
Have you checked [the page referenced](http://unixpapa.com/js/key.html) to see if Safari/Chrome/Webkit have different values for the Enter key? | Safari and Chrome: problem editing input 'size' attribute on the fly | [
"",
"javascript",
"jquery",
"safari",
"google-chrome",
""
] |
Is there a way to auto-cast Spring beans to the class defined in the application context XML? I'd like to avoid putting type information about the beans in 2 places.... in the xml configuration file and also in the code as a cast.
For instance, given this config file
```
<bean id="bean-name" class="SimpleSpringBean" scope="prototype">
<property name="myValue" value="simple value"></property>
</bean>
```
Can I call `ApplicationContext.getBean("bean-name")` in such a way as to avoid directly casting the return type to `SimpleStringBean`. I know I can also call `ApplicationContext.getBean("bean-name", SimpleSpringBean.class)` to avoid the cast itself, but I still have the type info in 2 places.
It seems that Spring can get the class info (`ApplicationContext.getType`) or by getting the type from the bean itself, but no way to automatically cast the type without programmer intervention. | I agree with Sii, you should avoid calling getBean as much as you can. Just wire your beans to classes that depends on them.
Still, if you have a single class that holds the application context, you can provide a wrapper generic method like the following:
```
class MyContextHolder{
ApplicationContext appContext;
......
@SuppressWarnings("unchecked")
public static <T> T getBean(String beanName)
{
return (T)appContext.getBean(beanName);
}
}
```
Then you can call it without casting
```
MyClass mc = MyContextHolder.getBean("myClassBean");
``` | The answer is you shouldn't be using ApplicationContext.getBean() at all if it's possible, and bear with the one place you have to in the bootstrap code. (Generally, you should never need to use getBean() outside of your application's entry points.)
Also, what you're asking is likely impossible in the Java language at all. Casting is a compile-time feature, combined with a runtime check. The return type of getBean() simply must be known at compile time. Even if Spring can determine the type of an object, it can't change its own method signatures at runtime.
Another thing is that even if this were possible, the feature wouldn't be all that useful. Because Spring AOP is implemented using dynamic proxies, you nearly always want Spring to hand you an instance of an interface the bean implements (which could be an AOP proxy), not of the implementation class. | Auto-cast Spring Beans | [
"",
"java",
"spring",
"casting",
"javabeans",
""
] |
According to the [official documentation](http://msdn.microsoft.com/en-us/library/ms171536.aspx), the KeyDown event on a Windows Forms control occurs only once, but it is easy to demonstrate that the event fires continually aslong as a key is held down:
```
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
label1.Text = string.Format("{0}", globalCounter++);
}
```
How can you consume the event so that it fires only once? | I'm generally a VB guy, but this seems to work for me as demo code, using the form itself as the input source:
```
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private bool _keyHeld;
public Form1()
{
InitializeComponent();
this.KeyUp += new KeyEventHandler(Form1_KeyUp);
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
this._keyHeld = false;
}
void Form1_KeyUp(object sender, KeyEventArgs e)
{
this._keyHeld = false;
}
void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (!this._keyHeld)
{
this._keyHeld = true;
if (this.BackColor == Control.DefaultBackColor)
{
this.BackColor = Color.Red;
}
else
{
this.BackColor = Control.DefaultBackColor;
}
}
else
{
e.Handled = true;
}
}
}
}
```
I think the logic gets a little sketchy if you're holding down multiple keys at a time, but that seems to only fire the event from the last key that was pressed anyway, so I don't think it becomes an issue.
I tested this in a TextBox in VB, and it worked fine. Wasn't sure on the inheritance conventions I should follow in c#, so I left it as a straight Form for this answer.
Apologies for any gross code formatting errors, again, this isn't my usual language. | since the multiple occourrence of KeyDown is due to the keyrepeat settings of Windows, I think that you should somehow track the KeyUp event of that key also to know that the key has been released. | How can I prevent the keydown event of a form in C# from firing more than once? | [
"",
"c#",
"winforms",
"events",
"keyboard",
""
] |
I am totally new to the subject of cron jobs so I have no idea where to start learning about them; when, why, or how to use them with my Zend Framework application, or PHP in general.
Can anyone explain the process, with an example, or recommend some good resources to get started? | Cron jobs is a mechanism to automate tasks in Linux operating system. And has pretty little to do witn Zend Framework. The framework can help you develop an advanced cron task in php though. But then you will have to set up your cron job in the shell.
Googling for "how to set up cron job" revealed this link at the top:
<http://www.adminschoice.com/docs/crontab.htm>
I'm sure this article will help you.
P.S.
As a command to execute you should put something like:
`/usr/local/bin/php -f <path_to_your_php_script>`
where the first path is the full path to your php cli executable, which may differ on your machine. You can make sure by issuing this command:
`which php`
Good luck with cron jobs ;) | Maybe a real-life example would help. A few years ago, I worked on an event calendar project using the Zend Framework. In this calendar, a user could create an event and attach 1 or more dates to the event. Naturally, I implemented this as a many-to-one join in my database, but this meant that in order to attach a date, the event had to exist first. However I wanted to allow users to add dates *while* they were creating the event, not *after* they created an event. In other words, I wanted the user to edit all aspects of an event at the same time, and submit only when they clicked "save."
I solved the problem by inserting a new empty event record into the database when the user begins creating an event record. This empty record gets filled in and saved when the user clicks "save", or is deleted when the user clicks "cancel". The trouble occurred when users navigated away without clicking "cancel", and the empty event record was left in the database. Eventually, the database would fill up with these meaningless empty events, and things might get ugly.
I wrote a function called "maintenance()", which, among other things, deleted all unsaved records older than 24 hours. I set up a cron job that ran nightly and executed a command-line php script that ran maintenance().
Other things that you might use a cron job for:
* Send a batch of emails to new users. (every 5 minutes?)
* Update user statistics (every hour?)
* Perform resource-intensive operations when the servers aren't slammed with traffic (Every night at midnight, or once a week on sunday nights?)
* Anything other event that doesn't occur in response to a user request (what Jeff calls "out of band"). | Getting started with cron jobs and PHP (Zend Framework) | [
"",
"php",
"zend-framework",
"cron",
"queue",
"scheduled-tasks",
""
] |
I have a web application that uses a number of WCF Services. I deploy my web application in various environments (dev, UAT, production etc). The URL of each WCF Service is different for each environment. I am using .NET 3.5 and`basicHttpBinding`s
The web application uses a framework to support machine-specific settings in my web.config file. When instantiating an instance of a WCF Service client I call a function that creates the instance of the WCF Service client using the constructor overload that takes the arguments:
```
System.ServiceModel.Channels.Binding binding,
System.ServiceModel.EndpointAddress remoteAddress
```
In essence the `<system.serviceModel><bindings><basicHttpBinding><binding>` configuration in web.config has been replicated in C# code.
This approach works well.
However, I now have to enhance this approach to work with a WCF service that uses an X509 certificate. This means that I have to replicate the following additional settings in web.config in C# code:
```
<!-- inside the binding section -->
<security mode="Message">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="Certificate" algorithmSuite="Default" />
</security>
<behaviors>
<endpointBehaviors>
<behavior name="MyServiceBehaviour">
<clientCredentials>
<clientCertificate storeLocation="LocalMachine" storeName="My"
x509FindType="FindByThumbprint" findValue="1234abcd" />
<serviceCertificate>
<defaultCertificate storeLocation="LocalMachine" storeName="My"
x509FindType="FindByThumbprint" findValue="5678efgh" />
<authentication trustedStoreLocation="LocalMachine"
certificateValidationMode="None" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
</behaviors>
```
I am having some difficulty figuring out how to code this configuration in C#.
Two questions
* Can anyone recommend a better approach for managing WCF Service reference URLs across multiple environments?
* Alternatively, any suggestions on how to replicate the above web.config section in C# will be welcomed | The following code replicates the configuration in my original question:
```
myClient.ClientCredentials.ClientCertificate.SetCertificate(
StoreLocation.LocalMachine,
StoreName.My,
X509FindType.FindByThumbprint,
"1234abcd");
myClient.ClientCredentials.ServiceCertificate.SetDefaultCertificate(
StoreLocation.LocalMachine,
StoreName.My,
X509FindType.FindByThumbprint,
"5678efgh");
myClient.ClientCredentials.ServiceCertificate.Authentication.TrustedStoreLocation = StoreLocation.LocalMachine;
myClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
```
In the production code the two thumbprint values are stored in `appSettings` in the web.config file. | One possible approach would be to "externalize" certain parts of your <system.serviceModel> configuration into external files, one per environment.
E.g. we have "bindings.dev.config" and "bindings.test.config", which we then reference in our main web.config like this:
```
<system.serviceModel>
<bindings configSource="bindings.dev.config" />
</system.serviceModel>
```
That way, all you need to change from DEV to PROD is this one line of config XML.
Basically, in .NET 2.0 config, any configuration element can be "externalized". You cannot however externalize configGroups (such as "system.serviceModel") directly - you have to be on the "configuration element" level.
Marc
EDIT: OK, so *NO* config edit changes to switch between environments.....
In that case, you probably have to dream up a naming scheme, e.g. name your bindings, behaviors and endpoints in such a way, that you can distinguish them at runtime.
Something like:
```
<bindings>
<binding name="Default_DEV">
.....
</binding>
<binding name="Default_PROD">
.....
</binding>
</bindings>
```
that way, you could build up the name of the element you want (e.g. binding "Default\_PROD") from your code and the environment you're running in, and then grab the according config from the config file which contains all the config settings for all environments. | Changing WCF Service reference URL based on environment | [
"",
"c#",
".net",
"wcf",
"web-config",
""
] |
How can I get the username/login name in Java?
This is the code I have tried...
```
try{
LoginContext lc = new LoginContext(appName,new TextCallbackHandler());
lc.login();
Subject subject = lc.getSubject();
Principal principals[] = (Principal[])subject.getPrincipals().toArray(new Principal[0]);
for (int i=0; i<principals.length; i++) {
if (principals[i] instanceof NTUserPrincipal || principals[i] instanceof UnixPrincipal) {
String loggedInUserName = principals[i].getName();
}
}
}
catch(SecurityException se){
System.out.println("SecurityException: " + se.getMessage());
}
```
I get a `SecurityException` when I try to run this code. Could someone please tell me whether I'm heading in the right direction, and help me to understand the problem. | ```
System.getProperty("user.name");
``` | in Unix:
```
new com.sun.security.auth.module.UnixSystem().getUsername()
```
in Windows:
```
new com.sun.security.auth.module.NTSystem().getName()
```
in Solaris:
```
new com.sun.security.auth.module.SolarisSystem().getUsername()
``` | Get login username in java | [
"",
"java",
"authentication",
""
] |
I have DateTime variable, and I need to get ONLY the time value from that variable.
How can I do that in C#?
Thanks, | You can try this....
```
someDateTime.ToString("hh:mm:ss");
``` | Check `TimeOfDay` property of the `DateTime` object. | How to get the time value from DateTime datatype | [
"",
"c#",
""
] |
I wanted to create search engine for my webpage, but during indexing on server it crashes with errors :
```
Warning: opendir(/admin/lucene/) [function.opendir]: failed to open dir: Too many open files in /admin/includes/Zend/Search/Lucene/Storage/Directory/Filesystem.php on line 159
Warning: readdir(): supplied argument is not a valid Directory resource in /admin/includes/Zend/Search/Lucene/Storage/Directory/Filesystem.php on line 160
Warning: closedir(): supplied argument is not a valid Directory resource in /admin/includes/Zend/Search/Lucene/Storage/Directory/Filesystem.php on line 167
Fatal error: Ignoring exception from Zend_Search_Lucene_Proxy::__destruct() while an exception is already active (Uncaught Zend_Search_Lucene_Exception in /admin/includes/Zend/Search/Lucene/Storage/File/Filesystem.php on line 66) in /admin/test.php on line 549
```
I am using newest version of ZF. Is there code solution for such error - I run script on localhost and it works great.
Thanks for any help. | It seems the problem is in the large number of segments in the index.
Could you check how much files does index folder contain?
There are two ways to solve this problem:
a) Optimize index more often.
b) Use another MaxBufferedDocs/MergeFactor parameters. See [Zend\_Search\_Lucene documentation](http://framework.zend.com/manual/en/zend.search.lucene.index-creation.html#zend.search.lucene.index-creation.optimization) for details.
If it doesn't help, please register JIRA issue for the problem. | PHP has hit the limit on the number of files it can have open at once it seems might be an option to change in php.ini, could be an OS (quota) limit or you might be able to tell the indexer to slow down and not have so many files open simultaneously. | Zend_Search_Lucene crashes during indexing | [
"",
"php",
"zend-framework",
"lucene",
""
] |
I'm new to C++ Templates, and am finding it hard to understand and debug them. What are some good resources for doing both/either? | I recommend the excellent book [C++ Templates - The Complete Guide](http://www.josuttis.com/tmplbook/tmplbook.html) by Vandevoorde and Josuttis. | [Alexandrescu](http://erdani.org/publications/) is a wizard of templates. He has a lot of write-ups (many of which is freely available on his web-site and other sites) and some books.
Boost [Documentation](http://www.boost.org/doc/) and [Boost Cookbook](http://www.boostcookbook.com/) is a good site to start with once you are comfortable with templates and feel like graduating to Boost. | Resources for C++ Templates | [
"",
"c++",
"templates",
""
] |
Using this code, the following execution yields strange results:
```
C 100
R
W
```
The text file's first line defines the number of elements to read from it, and it contains a few values under 15, but every time I run this, the first value in my array is always printed out as 87 (the ASCII value for 'W'). If I change the 'W' functionality to 'X', then the first result in the array is 88.
```
#include <iostream>
#include <fstream>
using namespace std;
int arrayLength;
class ELEMENT
{
public:
int key;
};
class HEAP
{
public:
int capacity;
int size;
ELEMENT H [];
};
HEAP initialize(int n)
{
HEAP h;
h.capacity = n;
h.size = 0;
return h;
}
void buildHeap(HEAP &h, ELEMENT *a)
{
h.size = arrayLength;
for (int i = 1; i <= arrayLength; i++)
{
h.H[i] = a[i];
}
for (int i = h.size/2; i >= 1; i--)
{
// HEAPIFY HERE
}
}
void printHeap(HEAP &h)
{
cout << "Capacity:\t" << h.capacity << endl;
cout << "Size:\t\t" << h.size << endl;
cout << "|";
for (int i = 1; i <= h.size; i++)
{
cout << " ";
cout << h.H[i].key << " |";
}
cout << endl;
}
int main()
{
char c;
int val;
HEAP h;
while (c != 'S')
{
cin >> c;
switch (c)
{
case 'S':
break;
case 'C':
cin >> val;
h = initialize(val);
break;
case 'W':
printHeap(h);
break;
case 'R':
{
ifstream infile;
infile.open("HEAPinput.txt");
infile >> arrayLength;
ELEMENT* a = new ELEMENT[arrayLength];
for (int i = 1; i <= arrayLength; i++)
infile >> a[i].key;
infile.close();
buildHeap(h, a);
}
break;
}
}
return 0;
}
```
It is being compiled using g++ on a Unix server.
EDIT:
To clarify:
With a text file with the following contents (space = new line):
```
12 9 10 11 12 8 7 6 5 4 3 2 1
```
The output is:
```
Capacity: 100
Size: 12
| 87 | 10 | 11 | 12 | 8 | 7 | 6 | 5 | 4 | 3 | 2 | 1 |
```
So it's working except for that first element. | Whatever you think
```
ELEMENT H [];
```
is doing, it probably isn't. C++ does not support dynamic arrays - you need to use the std::vector class.
And BTW, C++ by convention uses UPPERCASE to name pre-processor macros and constants. You should use mixed case to name your classes. | In addition to the wrong use of arrays: it would not be a bad idea to make initialize(), buildHeap(), and printHeap() member functions of heap. | Strange output after reading from a file | [
"",
"c++",
""
] |
Sometimes it works sometimes not:
```
template <class T>
void f(T t) {}
template <class T>
class MyClass {
public:
MyClass(T t) {}
};
void test () {
f<int>(5);
MyClass<int> mc(5);
f(5);
MyClass mc(5); // this doesn't work
}
```
Is there a way to hack around the example above? I.e. force the compiler to infer the template parameter from constructor parameter.
Will this be fixed in the future, or is there a good reason not to?
What is the general rule when compiler can infer template parameter? | Template parameters can be inferred for *function templates* when the parameter type can be deduced from the template parameters
So it can be inferred here:
```
template <typename T>
void f(T t);
template <typename T>
void f(std::vector<T> v);
```
but not here:
```
template <typename T>
T f() {
return T();
}
```
And not in *class templates*.
So the usual solution to your problem is to create a wrapper function, similar to the standard library function `std::make_pair`:
```
template <class T>
class MyClass {
public:
MyClass(T t) {}
void print(){
std::cout<<"try MyClass"<<std::endl;
}
};
template <typename T>
MyClass<T> MakeMyClass(T t) { return MyClass<T>(t); }
```
and then call `auto a = MakeMyClass(5);` to instantiate the class. | Read up on [Template Argument Deduction](http://accu.org/index.php/journals/409) (and [ADL or Koenig lookup](http://en.wikipedia.org/wiki/Argument_dependent_name_lookup)). | When a compiler can infer a template parameter? | [
"",
"c++",
"templates",
""
] |
While tuning the application, I found this routine that strips XML string of CDATA tags and replaces certain characters with character references so these could be displayed in a HTML page.
The routine is less than perfect; it will leave trailing space and will break with StringOutOfBounds exception if there is something wrong with the XML.
I have created a few unit tests when I started working on the routing, but the present functionality can be improved, so these serve more of a reference.
The routine needs refactoring for sanity reasons. But, the real reason I need to fix this routine is to improve a performance. It has become a serious performance bottleneck in the application.
```
package engine;
import junit.framework.Assert;
import junit.framework.TestCase;
public class StringFunctionsTest extends TestCase {
public void testEscapeXMLSimple(){
final String simple = "<xml><SvcRsData>a<![CDATA[<sender>John & Smith</sender>]]></SvcRsData></xml> ";
final String expected = "<xml><SvcRsData>a<sender>John & Smith</sender></SvcRsData></xml> ";
String result = StringFunctions.escapeXML(simple);
Assert.assertTrue(result.equals(expected));
}
public void testEscapeXMLCDATAInsideCDATA(){
final String stringWithCDATAInsideCDATA = "<xml><SvcRsData>a<![CDATA[<sender>John <![CDATA[Inner & CD ]]>& Smith</sender>]]></SvcRsData></xml> ";
final String expected = "<xml><SvcRsData>a<sender>John <![CDATA[Inner & CD & Smith</sender>]]></SvcRsData></xml> ";
String result = StringFunctions.escapeXML(stringWithCDATAInsideCDATA);
Assert.assertTrue(result.equals(expected));
}
public void testEscapeXMLCDATAWithoutClosingTag(){
final String stringWithCDATAWithoutClosingTag = "<xml><SvcRsData>a<![CDATA[<sender>John & Smith</sender></SvcRsData></xml> ";
try{
String result = StringFunctions.escapeXML(stringWithCDATAWithoutClosingTag);
}catch(StringIndexOutOfBoundsException exception){
Assert.assertNotNull(exception);
}
}
public void testEscapeXMLCDATAWithTwoCDATAClosingTags(){
final String stringWithCDATAWithTwoClosingTags = "<xml><SvcRsData>a<![CDATA[<sender>John Inner & CD ]]>& Smith</sender>]]>bcd & efg</SvcRsData></xml> ";
final String expectedAfterSecondClosingTagNotEscaped = "<xml><SvcRsData>a<sender>John Inner & CD & Smith</sender>]]>bcd & efg</SvcRsData></xml> ";
String result = StringFunctions.escapeXML(stringWithCDATAWithTwoClosingTags);
Assert.assertTrue(result.equals(expectedAfterSecondClosingTagNotEscaped));
}
public void testEscapeXMLSimpleTwoCDATA(){
final String stringWithTwoCDATA = "<xml><SvcRsData>a<![CDATA[<sender>John & Smith</sender>]]>abc<sometag>xyz</sometag><sometag2><![CDATA[<recipient>Gorge & Doe</recipient>]]></sometag2></SvcRsData></xml> ";
final String expected = "<xml><SvcRsData>a<sender>John & Smith</sender>abc<sometag>xyz</sometag><sometag2><recipient>Gorge & Doe</recipient></sometag2></SvcRsData></xml> ";
String result = StringFunctions.escapeXML(stringWithTwoCDATA);
Assert.assertTrue(result.equals(expected));
}
public void testEscapeXMLOverlappingCDATA(){
final String stringWithTwoCDATA = "<xml><SvcRsData>a<![CDATA[<sender>John & <![CDATA[Smith</sender>]]>abc<sometag>xyz</sometag><sometag2><recipient>Gorge & Doe</recipient>]]></sometag2></SvcRsData></xml> ";
final String expectedMess = "<xml><SvcRsData>a<sender>John & <![CDATA[Smith</sender>abc<sometag>xyz</sometag><sometag2><recipient>Gorge & Doe</recipient>]]></sometag2></SvcRsData></xml> ";
String result = StringFunctions.escapeXML(stringWithTwoCDATA);
Assert.assertTrue(result.equals(expectedMess));
}
}
```
---
This is the function:
```
package engine;
public class StringFunctions {
public static String escapeXML(String s) {
StringBuffer result = new StringBuffer();
int stringSize = 0;
int posIniData = 0, posFinData = 0, posIniCData = 0, posFinCData = 0;
String stringPreData = "", stringRsData = "", stringPosData = "", stringCData = "", stringPreCData = "", stringTempRsData = "";
String stringNewRsData = "", stringPosCData = "", stringNewCData = "";
short caracter;
stringSize = s.length();
posIniData = s.indexOf("<SvcRsData>");
if (posIniData > 0) {
posIniData = posIniData + 11;
posFinData = s.indexOf("</SvcRsData>");
stringPreData = s.substring(0, posIniData);
stringRsData = s.substring(posIniData, posFinData);
stringPosData = s.substring(posFinData, stringSize);
stringTempRsData = stringRsData;
posIniCData = stringRsData.indexOf("<![CDATA[");
if (posIniCData > 0) {
while (posIniCData > 0) {
posIniCData = posIniCData + 9;
posFinCData = stringTempRsData.indexOf("]]>");
stringPreCData = stringTempRsData.substring(0,
posIniCData - 9);
stringCData = stringTempRsData.substring(posIniCData,
posFinCData);
stringPosCData = stringTempRsData.substring(
posFinCData + 3, stringTempRsData.length());
stringNewCData = replaceCharacter(stringCData);
stringTempRsData = stringTempRsData.substring(
posFinCData + 3, stringTempRsData.length());
stringNewRsData = stringNewRsData + stringPreCData
+ stringNewCData;
posIniCData = stringTempRsData.indexOf("< from [Apache Commons](http://commons.apache.org/). It contains an [`escapeXML`](http://commons.apache.org/lang/api-release/org/apache/commons/lang/StringEscapeUtils.html#escapeXml(java.lang.String)) method. | it looks to me that you are doing something that has already been done before, probably in apache commons.
Your function is so convoluted that im not sure if you are really 'escapingXML' or something something more. if all you are doing is escaping xml, then you should google for a better implementation. | How to refactor, fix and optimize this character replacement function in java | [
"",
"java",
"string",
"optimization",
"refactoring",
"char",
""
] |
I have two local data sources that I can push into the report. Works no problem. But how do I set up the report? One data source contains a list of employees, and info about them. The other contains a bunch of working hours for each employee.
I would like to use a table for the list of employees, and then have another table for the working hours beneath each employee (with their working hours).
Is this even possible? Do I have to use a Sub-Report? Would I have to merge them into one datasource? =/ | As far as I can tell, it is impossible to nest one dataset inside of another one without using a subreport.
This means you need to do one of two things:
1. Refactor your two datasources into a single datasource. For example, perform a join between the employees and the working hours for each employee. You can then use the grouping properties of the Table object to format the list the way you want it.
2. If joining the two data sources is not practical, you can use subreports to accomplish what you want. Create a subreport containing the working hours data source and give it a parameter for the current employee. Filter the working hours by this parameter.
In your parent report, you can place the subreport in the list, and pass the employee ID for the current row as a parameter.
Note that there are a few formatting quirks involved with using subreports. I've been able to work around them in most cases, but the preferred method would definitely be number one above. | Adding a new answer to make sure a notification is sent for it.
Using a subreport is the easiest method when it works. You can simply drag and drop a subreport onto a table cell, and it will fill that cell's content area. Right-clicking on the subreport will allow you to edit the parameters for the subreport. Like most values in SSRS, the parameters can be set to expressions which use the fields in the table.
Within the subreport, just filter your results to show only the records associated with the employee who was passed in as a parameter.
The other route you can take is to merge your two datasources using a join. This will give you data something like this:
```
employee1 time1.1
employee1 time1.2
employee1 time1.3
employee1 time1.4
employee2 time2.1
employee2 time2.2
employee2 time2.3
```
You can then create a group on the repeated columns (employee in this example), and enable the HideDuplicates property on those columns. The result will look like this:
```
employee1 time1.1
time1.2
time1.3
time1.4
employee2 time2.1
time2.2
time2.3
``` | SSRS: Master-detail report with two datasources | [
"",
"c#",
"reporting-services",
"report",
"objectdatasource",
""
] |
Can we pass ArrayLists as arguments to methods in C#? | Absolutely. However, you rarely should. These days you should almost *always* use generic types, such as `List<T>`.
Additionally, when declaring the *parameters* of a method, it's worth using interfaces where you can. For instance, if you had a method like this:
```
public void SomeMethod(ArrayList list)
```
then anyone calling it is *forced* to use `ArrayList`. They can't use `List<T>` even if they want to. If, on the other hand, you declare your method as:
```
public void SomeMethod(IList list)
```
then they can use generics even if your code doesn't know about them. | Sure, why not:
```
public void SomeMethod(ArrayList list)
{
// your code here
}
```
But as Jon S. mentioned using interfaces is preferred instead of hard coded types.
```
public void SomeMethod(IList list)
{
// your code here
}
```
**See also**:
* [Interfaces (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/ms173156.aspx)
* [Generic Interfaces (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/kwtft8ak.aspx) | ArrayList in C# | [
"",
"c#",
"arraylist",
""
] |
I need to transfer some data from our CRM system into the [Microsoft Dynamics C5](http://en.wikipedia.org/wiki/Microsoft_Dynamics_C5) accountance system.
Is this possible? Writing directly in a SQL database and such hacks will be fine for me as well. | I am surprised no one had this need.
Anyway after talking to a consultant I found out that there are two ways to solve it.
1. Install C5 on a SQL server you manage and manipulate the data directly.
2. Default C5 install with a Native DB and buy the C5 ODBC module that makes it
possible to manipulate the data through ODBC. | Inserting data directly to a Dynamics C5 SQL database - will give you problems if you don't remember to use a correct LXBENUMMER/ROWNUMBER.
You have to use a unique number for each row. Rownumbers are managed by the table XALSEQ.
Remember that empty strings must contain a CHAR(2).
Otherwise you could look at XU4N - that will give you a .NET entry to the Dynamics C5 application (not the data-layer).
www.dns-it.dk/xu4n
Regards
Erling Damsgaard | Inserting data in Microsoft Dynamics C5 from C# | [
"",
"c#",
""
] |
I'm writing to Excel file using OLEDB (C#).
What I need is just RAW data format.
I've noticed all cells (headers and values) are prefixed by apostrophe (')
Is it a way to avoid adding them in all text cells?
**Here is my connection string:**
```
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
filePath + ";Extended Properties='Excel 8.0;HDR=Yes'";
```
**I've tried use IMEX=1 like this:**
```
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
```
But after that I'm receiving below error:
*The Microsoft Jet database engine could not find the object
'C:\Temp\New Folder\MF\_2009\_04\_19\_2008-11-182009\_DMBHCSAM1118.xls'.
Make sure the object exists and that you spell its name and the path name correctly.*
**Finally I've tried use IMEX=0 like this:**
```
string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
filePath + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=0\"";
```
This time no exeptions raised.
***Unfortunately there is still problem with apostrophes
(so each my values looks as: '123, 'abc etc...)***
Any idea? | <http://support.microsoft.com/kb/257819> has a statement to the effect that this behaviour might be unavoidable when inserting text into Excel via ADO:
> **A caution about editing Excel data with ADO**: When you insert text data into Excel with ADO, the text value is preceded with a single quote. This may cause problems later in working with the new data.
Is the data explicitly text, might it be coerced into a numeric format? (clutching at straws...) | Could you just use the Excel DSN? It seems to be pretty ubiquitous. I don't know .NET, so take this with a grain of salt, but here's my connection string for an OLEDB Query straight from a stock table:
```
"Provider=MSDASQL.1;Persist Security Info=True;Extended Properties
=""DSN=Excel Files;DBQ=" & filePath & "\" & fileName &
";DriverId=1046;MaxBufferSize=2048;PageTimeout=5;"""
```
And I used this basic INSERT statement:
```
INSERT INTO rngOutput VALUES (1, 'ABC', '$1.00', 1300)
```
When I did this, I didn't have any apostrophes in my data range. I'm also using Excel 2007, and I see you're using Excel 8.0 as your driver?
Hopefully that nudges you toward a solution! | OLEDB, Writing Excel cell without leading apostrophe | [
"",
"c#",
".net",
"excel",
"oledb",
"apostrophe",
""
] |
I can't figure out how to handle exception for python 'with' statement. If I have a code:
```
with open("a.txt") as f:
print f.readlines()
```
I really want to handle 'file not found exception' in order to do something. But I can't write
```
with open("a.txt") as f:
print f.readlines()
except:
print 'oops'
```
and can't write
```
with open("a.txt") as f:
print f.readlines()
else:
print 'oops'
```
Enclosing `with` in a try/except statement doesn't work either, and an exception is not raised. What can I do in order to process failure inside `with` statement in a Pythonic way? | This solution will keep the with-block-code outside of the try-except-clause.
```
try:
f = open('foo.txt')
except FileNotFoundError:
print('error')
else:
with f:
print f.readlines()
``` | The best "Pythonic" way to do this, exploiting the `with` statement, is listed as Example #6 in [PEP 343](http://www.python.org/dev/peps/pep-0343/), which gives the background of the statement.
```
from contextlib import contextmanager
@contextmanager
def opened_w_error(filename, mode="r"):
try:
f = open(filename, mode)
except IOError, err:
yield None, err
else:
try:
yield f, None
finally:
f.close()
```
Used as follows:
```
with opened_w_error("/etc/passwd", "a") as (f, err):
if err:
print "IOError:", err
else:
f.write("guido::0:0::/:/bin/sh\n")
``` | Catching an exception while using a Python 'with' statement | [
"",
"python",
"exception",
""
] |
Allright, doing some project with few friends, and I need some standard for naming things in c++. Does anyone have any good naming scheme for c++ that is well thought-out and not made in like 10min.
Example, int\* house should be named int\* house\_p, so that when someone reads the code, he doesn't need to scroll all the time wondering if a thing is a pointer, array, matrix, or whatever...
Post your well thought-out naming schemes that you are using ! | > Example, int\* house should be named
> int\* house\_p, so that when someone
> reads the code, he doesn't need to
> scroll all the time wondering if a
> thing is a pointer, array, matrix, or
> whatever...
But what if its type changes - are you going to go through all your code and change the names of all the variables. And what if the variable is an instance of a complex type:
```
ComplicatedDerivativeFinancialInstrument x;
```
What suffix will you use?
What you are asking about is known as [Hungarian notation](http://en.wikipedia.org/wiki/Hungarian_notation) - its use in C++ is almost universally considered to be A Bad Idea. | In C++, when designing/refactoring code, it's quite common to change from a pointer (`int*`) to a reference (`int&`). If you had [repeated yourself](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) by including a suffix on the variable name indicating that it's a pointer, you would then have to change that to something else, all over the place. That seems like so much pointless make-work, that just makes the code harder to edit and shape into what you want.
You shouldn't need that kind of reminder; it will be quite clear from usage if a variable is a pointer or not, for instance. | Naming functions, methods, pointers, variables, arrays etc in C++ | [
"",
"c++",
"naming",
""
] |
When doing validation in JavaScript, how do I keep validation methods that need to handle a bunch of contingencies from becoming unruly?
For example, I have a form with a field that has validation that checks:
* is the new value a number?
* Is the value in another field on the
form > 0 when the current field > 0
* Is another field on the form == 1 and
the current field == 0
* Is another field on the form == true
and the current field is Mod another
field == 0
Etc.
Currently, I've got a method with a bunch of if/else statements.
I could break each check out into it's own method and call it from the main validation method, but that would create a ton of new methods.
**Update**: regardless of whether I use a framework or individual methods, am I still resigned to having the calling validation method filled with If/Else or Switch statements with alert boxes for the failing validations? | Sounds like you might want a rudimentary state machine. One thing you might consider is breaking the validators into the simplest forms:
```
function validator(op, options, pass, fail) {
if (op(options)) {
pass(options);
} else {
fail(options);
}
}
```
Then you can chain them together to form more complex systems.
```
function isFooChecked(options) {
return $(options.foo).is(':checked');
}
function sayHi(options) {
alert('hi ' + options.name);
}
function fail(options) {
alert(options.name + ' was bad');
}
function validateName() {
validator(isFooChecked, { foo: '#someField', name: $('#nameField').val() }, sayHi, fail);
}
```
You'll still have a lot of code, but if you do it right, functions should be small and easy to understand. | Why re-invent the wheel? I would suggest the [jQuery Validation Plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/). Check out the [demo pages](http://jquery.bassistance.de/validate/demo/) as well | Designing Javascript validation methods | [
"",
"javascript",
"validation",
""
] |
I have a primary key that I don't want to auto increment (for various reasons) and so I'm looking for a way to simply increment that field when I INSERT. By simply, I mean without stored procedures and without triggers, so just a series of SQL commands (preferably one command).
Here is what I have tried thus far:
```
BEGIN TRAN
INSERT INTO Table1(id, data_field)
VALUES ( (SELECT (MAX(id) + 1) FROM Table1), '[blob of data]');
COMMIT TRAN;
* Data abstracted to use generic names and identifiers
```
However, when executed, the command errors, saying that
> "Subqueries are not allowed in this
> context. only scalar expressions are
> allowed"
So, how can I do this/what am I doing wrong?
---
EDIT: Since it was pointed out as a consideration, the table to be inserted into is guaranteed to have at least 1 row already. | You understand that you will have collisions right?
you need to do something like this and this might cause deadlocks so be very sure what you are trying to accomplish here
```
DECLARE @id int
BEGIN TRAN
SELECT @id = MAX(id) + 1 FROM Table1 WITH (UPDLOCK, HOLDLOCK)
INSERT INTO Table1(id, data_field)
VALUES (@id ,'[blob of data]')
COMMIT TRAN
```
To explain the collision thing, I have provided some code
first create this table and insert one row
```
CREATE TABLE Table1(id int primary key not null, data_field char(100))
GO
Insert Table1 values(1,'[blob of data]')
Go
```
Now open up two query windows and run this at the same time
```
declare @i int
set @i =1
while @i < 10000
begin
BEGIN TRAN
INSERT INTO Table1(id, data_field)
SELECT MAX(id) + 1, '[blob of data]' FROM Table1
COMMIT TRAN;
set @i =@i + 1
end
```
You will see a bunch of these
Server: Msg 2627, Level 14, State 1, Line 7
Violation of PRIMARY KEY constraint 'PK\_\_Table1\_\_3213E83F2962141D'. Cannot insert duplicate key in object 'dbo.Table1'.
The statement has been terminated. | Try this instead:
```
INSERT INTO Table1 (id, data_field)
SELECT id, '[blob of data]' FROM (SELECT MAX(id) + 1 as id FROM Table1) tbl
```
I wouldn't recommend doing it that way for any number of reasons though (performance, transaction safety, etc) | Possible to implement a manual increment with just simple SQL INSERT? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"language-agnostic",
"insert",
""
] |
I am opening different types of images like (8 and 16 bit) and they are (Monocrome, RGB ,palette color).
I have raw pixel data of these images.
I create bitmap like this for 8 bit images.
```
//for monocrome images i am passing PixelFormat.Format8bppIndexed.
//for RGB images i am passing PixelFormat.Format24bppRgb
PixelFormat format = PixelFormat.Format8bppIndexed;
Bitmap bmp = new Bitmap(Img_Width, Img_Height,format);
Rectangle rect = new Rectangle(0, 0, Img_Width, Img_Height);
//locking the bitmap on memory
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
// copy the managed byte array to the bitmap's image data
Marshal.Copy(rawPixel, 0, bmpData.Scan0, rawPixel.Length);
bmp.UnlockBits(bmpData);
```
---
The problem is that when i draw that bmp image then it differs in color than original.
So is there any way to apply lut (lookup table) on that colored images.
i want any unsafe code because i tried getixel and setPixel and they are very slow.
I also dont want Image.fromSource() methods. | i solved this problem see how.
Somewhere i read that GDI+ return BGR value not the RGB.
So i reverse the order and amazing everything fine.
But it is little bit slow.
```
PixelFormat format = PixelFormat.Format8bppIndexed;
Bitmap bmp = new Bitmap(Img_Width, Img_Height,format);
Rectangle rect = new Rectangle(0, 0, Img_Width, Img_Height);
//locking the bitmap on memory
BitmapData bmpData = bmp.LockBits(rect, ImageLockMode.ReadWrite, format);
Marshal.Copy(rawPixel, 0, bmpData.Scan0, rawPixel.Length);
int stride = bmpData.Stride;
System.IntPtr Scan0 = bmpData.Scan0;
unsafe
{
byte* p = (byte*)(void*)Scan0;
int nOffset = stride - bmp.Width * SAMPLES_PER_PIXEL ;
byte red, green, blue;
for (int y = 0; y < bmp.Height; ++y)
{
for (int x = 0; x < bmp.Width; ++x)
{
blue = p[0];
green = p[1];
red = p[2];
p[0] = red;
p[1] = green;
p[2] = blue;
p += 3;
}
p += nOffset;
}
}
////unlockimg the bitmap
bmp.UnlockBits(bmpData);
```
thanks
Can anybody is having some faster code than that. | Take a look at the bitmap's [`Image.Palette`](http://msdn.microsoft.com/en-us/library/system.drawing.image.palette.aspx) property. | How apply Color Lut over bitmap image in c# | [
"",
"c#",
"imaging",
""
] |
Say I have a few tables in the MSSQL database, each with about 5-10 attributes. There are some simple associations between the tables, but each of the table have 500,000 to 1,000,000 rows.
There is an algorithm that runs on that data (all of it), so before running the algorithm, I have to retrieve all the data from the database. The algorithm does not change the data, only reads it, so I just need to retrieve the data.
I am using LINQ to SQL. To retrieve all the data takes about two minutes. What I want to know is whether the serialization to file and then deserialization (when needed) would actually load the data faster.
The data is about 200 MB, and I don't mind saving it to disk. So, would it be faster if the objects were deserialized from the file or by using LINQ 2 SQL DataContext?
Any experiences with this? | I would argue that LINQtoSQL may not be the best choice for this kind of application. When you are talking about so many objects, you incur quite some overhead creating object instances (your persistent classes).
I would choose a solution where a stored procedure retrieves only the necessary data via ADO.NET, the application stores it in memory (memory is cheap nowadays, 200MB should not be a problem) and the analyzing algorithm is run on the in-memory data.
I don't think you should store the data on file. In the end, your database is also simply one or more files that are read by the database engine. So you either
* let the database engine read your data and you analyze it, or
* let the database engine read your data, you write it to file, you read the file (reading the same data again, but now you do it yourself) and you analyze the data
The latter option involves a lot of overhead without any advantages as far as I can see.
EDIT: If your data changes very infrequently, you may consider preprocessing your data before analyzing and caching the preprocessed data somewhere (in the database or on the file system). This only makes sense if your preprocessed data can be analyzed (a lot) faster than the raw data. Maybe some preprocessing can be done in the database itself. | You should try to use ADO.NET directly without the LINQ to SQL layer on top of it, i.e. using an `SqlDataReader` to read the data.
If you work sequentially with the data, you can get the records from the reader when you need them without having to read them all into memory first. | Linq to SQL vs Serialization | [
"",
"c#",
"sql-server",
"linq-to-sql",
"serialization",
""
] |
I understand that with javascript you can select the contents of a textbox with the following code (in jQuery):
```
$("#txt1").select();
```
Is there a way to do the opposite? To deselect the content of a textbox? I have the focus event of a series of textboxes set to select the contents within them. There are times now that I want to focus a particular textbox WITHOUT selecting it. What I am planning on doing is calling the focus event for this particular textbox, but then follow it with a call to deselect it.
```
$("input[type=text]").focus(function() {
$(this).select();
});
//code....
$("#txt1").focus();
//some code here to deselect the contents of this textbox
```
Any ideas?
Thanks! | what about this:
```
$("input").focus(function(){
this.selectionStart = this.selectionEnd = -1;
});
``` | If you just assign the value of the textbox to itself, it should deselect the text. | Deselect contents of a textbox with javascript | [
"",
"javascript",
"jquery",
"dom",
"focus",
""
] |
I have the following [script](http://jqueryfordesigners.com/slide-out-and-drawer-effect/) in my homepage
```
$(function () { // same as $(document).ready(function () { })
// assuming we have the open class set on the H2 when the HTML is delivered
$('li.drawer h2:not(.open)').next().hide();
$('h2.drawer-handle').click(function () {
// find the open drawer, remove the class, move to the UL following it and hide it
$('h2.open').removeClass('open').next().hide();
// add the open class to this H2, move to the next element (the UL) and show it
$(this).addClass('open').next().show();
});
});
```
It works in Safari, but not in Firefox 3.08/3.1 beta3.
**How can you get the above jQuery script work in Firefox?**
[edit]
**First lines of my index.html**
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"/>
<link href="template.css" type="text/css" rel="stylesheet"/>
<title>Abc</title>
<script type="text/javascript" src="jquery.js" />
<script type="text/javascript">
! - - - - Above Code is at Here - - - - -
</script>
</head>
```
**The body of index.html**
```
<body>
<div class="mainbody">
<h1 class="myheader">Test</h1>
<p>Test</p>
<ul class="drawers">
<li class="drawer">
<h2 class="drawer-handle open">Contact info</h2>
<ul>
<li>name
</li>
<li>
<div class="">aaa
</div>
</li>
</ul>
</li>
<li class="drawer">
<h2 class="drawer-handle">Unpublished</h2>
<ul>
<li class="italic">
<i>A</i> (2009).
</li>
<li class="italic">
<i>aaa</i> (2008).
</li>
</ul>
</li>
<li class="drawer">
<h2 class="drawer-handle">Recent projects</h2>
<ul>
<li class="italic">
Websites
</li>
<li class="italic">
Search
<form action="http://www.google.com/cse" id="cse-search-box">
<div>
<input type="hidden" name="cx" value="8834479:1qd7hky6khe" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="31" />
<input type="submit" name="sa" value="Search" />
</div>
</form>
<script type="text/javascript" src="http://www.google.com/coop/cse/brand?form=cse-search-box&lang=en"></script>
</li>
</ul>
</li>
</ul>
</div>
</body>
</html>
``` | I got the code to work in Firefox by replacing the following
```
<script type="text/javascript" src="jquery.js" />
```
to
```
<script type="text/javascript" src="jquery.js"></script>
``` | It works for me in Firefox 3.0.9
What exactly is not working? | Unable to get a jQuery script work in Firefox | [
"",
"javascript",
"jquery",
"firefox",
"safari",
""
] |
I admit I haven't grokked F# yet. But in the 30,000 foot descriptions, they keep talking about easy to test code that doesn't have mutable state. Is that the same as static methods?
Could I get the benefit of F# by writing some of my code in classes with all static methods?
I'm just looking for the short answer, I know whole books exist on the topic. | You could certainly write C# code immutably, but that's nothing to do with static functions. Immutability are things like having a struct or object that only "changes state" by making a copy of itself and having the copy be different. | Absolutely no, immutability has nothing to do with methods being static or instance. `String`, being an immutable class, has plenty of instance methods, which, in a very functional manner, return a new instance of `String` class, rather than modifying anything.
You could try to emulate F# by using functional decomposition, but this will still be pretty imperative code. | Can I get the same benefits of functional programming (F#) by using more static methods in C#? | [
"",
"c#",
"f#",
"static-methods",
""
] |
I've heard that it's not a good idea to make elements global in JavaScript. I don't understand why. Is it something IE can't handle?
For example:
```
div = getElementById('topbar');
``` | I don't think that's an implementation issue, but more a good vs bad practice issue. Usually global \* is bad practice and should be avoided (global variables and so on) since you never really know how the scope of the project will evolve and how your file will be included.
I'm not a big JS freak so I won't be able to give you the specifics on exactly why JS events are bad but [Christian Heilmann talks about JS best practices here](http://www.slideshare.net/cheilmann/javascript-best-practices-1041724), you could take a look. Also try googling "JS best practices"
Edit: Wikipedia about global variables, that could also apply to your problem :
> [global variables] are usually
> considered bad practice precisely
> because of their nonlocality: a global
> variable can potentially be modified
> from anywhere, (unless they reside in
> protected memory) and any part of the
> program may depend on it. A global
> variable therefore has an unlimited
> potential for creating mutual
> dependencies, and adding mutual
> dependencies increases complexity. See
> Action at a distance. However, in a
> few cases, global variables can be
> suitable for use. For example, they
> can be used to avoid having to pass
> frequently-used variables continuously
> throughout several functions.
via <http://en.wikipedia.org/wiki/Global_variable> | > Is it something IE can't handle?
**No** it is not an IE thing. You can never assume that your code will be the only script used in the document. So it is important that you make sure your code does not have global function or variable names that other scripts can override.
Refer to [Play Well With Others](http://74.125.93.132/search?q=cache:zzyCvm7mUdcJ:icant.co.uk/articles/seven-rules-of-unobtrusive-javascript/+why+not+make+events+global+in+js&cd=1&hl=en&ct=clnk&gl=us&client=firefox-a) for examples. | Why is it bad to make elements global variables in Javascript? | [
"",
"javascript",
"internet-explorer",
"variables",
"events",
"global",
""
] |
I'm currently implementing a radix tree/patricia trie (whatever you want to call it). I want to use it for prefix searches in a dictionary on a severely underpowered piece of hardware. It's supposed to work more or less like auto-completion, i. e. showing a list of words that the typed prefix matches.
My implementation is based [on this article](http://www.codeproject.com/KB/string/PatriciaTrieTemplateClass.aspx), but the code therein doesn't include prefix searches, though the author says:
> [...] Say you want to enumerate all the nodes that have keys with a common prefix "AB". You can perform a depth first search starting at that root, stopping whenever you encounter back edges.
But I don't see how that is supposed to work. For example, if I build a radix tree from these words:
> illness
> imaginary
> imagination
> imagine
> imitation
> immediate
> immediately
> immense
> in
I will get the exact same "best match" for the prefixes "i" and "in" so that it seems difficult to me to gather all matching words just by traversing the tree from that best match.
Additionally, there is a [radix tree implementation in Java](http://code.google.com/p/radixtree/) that has an implemented prefix search in [RadixTreeImpl.java](http://code.google.com/p/radixtree/source/browse/trunk/RadixTree/src/ds/tree/RadixTreeImpl.java). That code explicitly checks all nodes (starting from a certain node) for a prefix match - it actually compares bytes.
Can anyone point me to a detailed description on implementing a prefix search on radix trees? Is the algorithm used in the Java implementation the only way to do it? | Think about what your trie encodes. At each node, you have the path that lead you to that node, so in your example, you start at Λ (that's a capital Lambda, this greek font kind of sucks) the root node corresponding to an empty string. Λ has children for each letter used, so in your data set, you have one branch, for "i".
* Λ
* Λ→"i"
At the "i" node, there are two children, one for "m" and one for "n". The next letter is "n", so you take that,
* Λ→"i"→"n"
and since the only word that starts "i","n" in your data set *is* "in", there are no children from "n". That's a match.
Now, let's say the data set, instead of having "in", had "infindibulum". (What SF I'm referencing is left as an exercise.) You'd still get to the "n" node the same way, but then if the next letter you get is "q", you know the word doesn't appear in your data set at all, because there's no "q" branch. At that point, you say "okay, no match." (Maybe you then start adding the word, maybe not, depending on the application.)
But if the next letter is "f", you can keep going. You can short circuit that with a little craft, though: once you reach a node that represents a unique path, you can hang the *whole string* off that node. When you get to that node, you know that the rest of the string *must* be "findibulum", so you've used the prefix to match the whole string, and return it.
How your you use that? in a lot of non-UNIX command interpreters, like the old VAX DCL, you could use any unique prefix of a command. So, the equivalent of *ls(1)* was `DIRECTORY`, but no other command started with DIR, so you could type `DIR` and that was as good as doing the whole word. If you couldn't remember the correct command, you could type just 'D', and hit (I think) ESC; the DCL CLI would return you *all* the commands that started with `D`, which it could search extremely fast. | It turns out the GNU extensions for the standard c++ lib includes a Patricia trie implementation. It's found under the policy-based data-structures extension. See <http://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/trie_based_containers.html> | Prefix search in a radix tree/patricia trie | [
"",
"c++",
"algorithm",
"prefix",
"patricia-trie",
""
] |
I want to send a HTTP GET to `http://example.com/%2F`. My first guess would be something like this:
```
using (WebClient webClient = new WebClient())
{
webClient.DownloadData("http://example.com/%2F");
}
```
Unfortunately, I can see that what is actually sent on the wire is:
```
GET // HTTP/1.1
Host: example.com
Connection: Keep-Alive
```
So <http://example.com/%2F> gets translated into <http://example.com//> before transmitting it.
Is there a way to actually send this GET-request?
The OCSP-protocol mandates sending the url-encoding of a base-64-encoding when using OCSP over HTTP/GET, so it is necessary to send an actual %2F rather than an '/' to be compliant.
**EDIT:**
Here is the relevant part of the OCSP protocol standard ([RFC 2560](http://www.ietf.org/rfc/rfc2560.txt) Appendix A.1.1):
> An OCSP request using the GET method is constructed as follows:
>
> > GET {url}/{url-encoding of base-64 encoding of the DER encoding of the OCSPRequest}
I am very open to other readings of this, but I cannot see what else could be meant. | By default, the `Uri` class will not allow an escaped `/` character (`%2f`) in a URI (even though this appears to be legal in my reading of [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986)).
```
Uri uri = new Uri("http://example.com/%2F");
Console.WriteLine(uri.AbsoluteUri); // prints: http://example.com//
```
(Note: [don't use Uri.ToString](https://faithlife.codes/blog/2010/08/uritostring_must_die/) to print URIs.)
According to the [bug report for this issue](https://connect.microsoft.com/VisualStudio/feedback/details/511010/erroneous-uri-parsing-for-encoded-reserved-characters-according-to-rfc-3986) on Microsoft Connect, this behaviour is by design, but you can work around it by adding the following to your app.config or web.config file:
```
<uri>
<schemeSettings>
<add name="http" genericUriParserOptions="DontUnescapePathDotsAndSlashes" />
</schemeSettings>
</uri>
```
(Reposted from <https://stackoverflow.com/a/10415482> because this is the "official" way to avoid this bug without using reflection to modify private fields.)
**Edit:** The Connect bug report is no longer visible, but the [documentation for `<schemeSettings>`](http://msdn.microsoft.com/en-us/library/ee656539.aspx) recommends this approach to allow escaped `/` characters in URIs. Note (as per that article) that there may be security implications for components that don't handle escaped slashes correctly. | This is a terrible hack, bound to be incompatible with future versions of the framework and so on.
But it works!
(on my machine...)
```
Uri uri = new Uri("http://example.com/%2F");
ForceCanonicalPathAndQuery(uri);
using (WebClient webClient = new WebClient())
{
webClient.DownloadData(uri);
}
void ForceCanonicalPathAndQuery(Uri uri){
string paq = uri.PathAndQuery; // need to access PathAndQuery
FieldInfo flagsFieldInfo = typeof(Uri).GetField("m_Flags", BindingFlags.Instance | BindingFlags.NonPublic);
ulong flags = (ulong) flagsFieldInfo.GetValue(uri);
flags &= ~((ulong) 0x30); // Flags.PathNotCanonical|Flags.QueryNotCanonical
flagsFieldInfo.SetValue(uri, flags);
}
``` | GETting a URL with an url-encoded slash | [
"",
"c#",
".net",
"http",
"base64",
"url-encoding",
""
] |
I am trying to connect to SQL Server 2008 (not express) with PHP 5.2.9-2 on Windows XP sp2. I can connect to the remote SQL Server fine from SQL Server Management Studio from the same machine.
My first attempt was this:
```
$conn = new PDO("mssql:host={$host};dbname={$db}", $user, $pass);
```
Which gives this error:
```
PHP Fatal error:
Uncaught exception 'PDOException' with message
'SQLSTATE[0100] Unable to connect: SQL Server is unavailable or does not exist.
Access denied. (severity 9)'
```
Second attempt (found on [experts-exchange](http://www.google.co.uk/search?q=Q_23833867%20experts%20exchange))
```
$conn = new PDO("odbc:Driver={SQL Server Native Client 10.0};Server={$host};Database={$db};Uid={$user};Pwd={$pass}",
$user, $pass);
```
This works, but I can't use `PDO::lastInsertId()`, which I would like to be able to:
```
Driver does not support this function: driver does not support lastInsertId()
```
Do you have any suggestions? Any help would be greatly appreciated. | i'm pretty sure that pdo with the mssql data server type requires dblib to connect. do you have dblib installed on the machine? make sure you can find ntwdblib.dll somewhere in the path on your system. i know this doesn't jive with the error message you're getting, but i'm not sure i trust the error message. | I updated ntwdblib.dll as suggested [here](http://www.theregister.co.uk/2008/04/24/database_connection_php/) and it now works.
Unfortunately I still can't use `PDO::lastInsertId()` because apparently this driver does not support it either, so it wasn't really worth the hassle. I can however use the equivalent `SELECT @@IDENTITY as Id`. | Connect to SQL Server 2008 with PDO | [
"",
"php",
"sql-server",
"pdo",
""
] |
I have the following the query running dynamically
```
SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = 'na' then 0 else 1 end, Make , Model, Year DESC
```
This is returning the following error:
> Error Executing Database Query.
> [Macromedia][SQLServer JDBC
> Driver][SQLServer]Incorrect syntax
> near 'na'. | are you running this query dynamically?, if so you might need to escape the quotes around 'na':
```
SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = ''na'' then 0 else 1 end, Make , Model, Year DESC
``` | works for me
here is repo script
```
use tempdb
go
create table Vehicles(DKID int,ImageName1 varchar(50),
Make int, Model int, Year int)
insert Vehicles values (69954,'na',1,1,2007)
insert Vehicles values(69954,'bla',1,1,2008)
go
SELECT *
FROM Vehicles
WHERE (DKID IN (69954))
ORDER BY case when ImageName1 = 'na' then 0 else 1 end,
Make , Model, Year DESC
``` | SQL Server- ORDER BY CASE | [
"",
"sql",
"sql-server",
""
] |
We currently facing some stability issues with our develop web application product. This product was built in part by our partner contractor, and we want to have a good standard metric for stability. The issues we have been facing is constant crashing. The web application is unable to identify when there are more request than it can handle, it builds up memory (like a memory leak) and later it dies without any type of possible recovery.
We would like to write a very simple measurement for our partner contractor to meet. We thought about a few ideas:
* A system that is able to identify high loads of request and serve server unavailable try again pages, until it recovers from the high load.
* A set number of users concurrent or pageviews that will allow us to have a clear metric of when to use scalability options like Load Balancer and Caching.
At this moment we have to use caching and load balancing to be able to recycle the web applications every x hours (depending on the load) so they don't die constantly.
Thanks for your help. | "High load" is really hard to define.
It's much, much easier for you to determine what the minimally acceptable service levels are.
1. Minimum number of concurrent requests.
2. Maximum time to serve a request.
3. Minimum number of requests per hour.
Simple service levels like that are easy to measure, easy to simulate and easy to write into a contract. Any lawyer or accountant can review the results of a load test and say they did or did not meet the minimums. No deep technical knowledge needed at all.
Note that when you do this, "minimums become maximums". If you say they must serve a minimum of 10,000 requests per hour, your testing will often reveal that's the maximum, also.
So define your minimums and maximums from your business model. How many do you need to keep people happy and productive? Asking for more is silly. Asking for fewer means unhappy or unproductive users. | Typically, I've seen these performance type requirements built into the specification... "the system should support x amount of concurrent users" or "x number of requests per hour".
These things can be easily tested and verified using something like LoadRunner or you can roll your own similar load tester using something like HttpUnit. | What is a good standard metric for stability in a web application? | [
"",
"java",
"web-applications",
"tomcat",
"stability",
""
] |
Given the date, 2009/04/30, in one of the rows I want to retrieve all dates <= 2009/04/30 and >= 2009/04/30. The sql statements are like this:
```
select dateColumn from someTable where dateColumn <= '2009/4/30'
select dateColumn from someTable where dateColumn >= '2009/4/30'
```
The above 2 statements run but the first statement returns all dates below 2009/04/30, it seems to be excluding the date even though it appears in the DB. Any idea why this may be happening? How would I compare the date portion of the DateTime object in sql? | `SQL Server` stores dates along with time.
```
select dateColumn from someTable where dateColumn <= '2009/4/30'
```
returns all dates less or equal to `2009/4/30 00:00:00`.
If your date is at least `1/300` seconds greater, e. g. `2009/4/30 00:00:00.003`, it will not be returned.
You need to select like this:
```
select dateColumn from someTable where dateColumn < '2009/5/01'
```
or like this:
```
select dateColumn from someTable where dateColumn < DATEADD(day, 1, '2009/4/30')
``` | Does the column contain time data? As written, the first query will return records where dateColumn is less than or equal to 2009/4/30 at 12:00 AM (midnight). You can use CAST or CONVERT to compare time portions only, but in this case the simplest answer is to change the first query to:
```
select dateColumn from someTable where dateColumn < '2009/5/1'
``` | Issue with retrieving DateTime object using Sql | [
"",
"sql",
"sql-server",
""
] |
I am using resharper to do a big refactoring and i keep going from file to file and adding the same namespace over and over again in the "using" section
is there anyway to add a "using" statement to every single file in a folder, namespace or project? Even though some files wont need the reference, most do, so it will save lots of time. | I'd try a regex in the "Find and Replace" dialog:
Replace
```
^using System;$
```
with
```
using System;\nusing xxx;
```
This works only for files using the System namespace, but maybe you find another common namespace or structure element. After doing so you can refactor all files in your solution(/folder) with the resharper. That will remove doubled usings.
**Update**: Did you introduce new namespaces for existing types? There is a refactor function called "move". It will move your type to a new namespace and preserve the references. | * Open ReSharper Options / Languages / C# / Namespace Imports
* Add "Namespaces that should always be imported"
* Run Code Cleanup against solution or project. You may want to create profile (Options / Tools / Code Cleanup) with only Optimize Using Directives module. | How do i automate adding a "using" statement to every files in a folder, namespace or project with Visual Studio 2005 / resharper | [
"",
"c#",
"visual-studio",
"resharper",
""
] |
Given the string below:
```
string str = "1,2,3";
```
Will this be the best extension to convert it to an `int` array?
```
static class StringExtensions
{
public static int[] ToIntArray(this string s)
{
return ToIntArray(s, ',');
}
public static int[] ToIntArray(this string s, char separator)
{
string[] ar = s.Split(separator);
List<int> ints = new List<int>();
foreach (var item in ar)
{
int v;
if (int.TryParse(item, out v))
ints.Add(v);
}
return ints.ToArray();
}
}
``` | It really depends what you want to do with the non-integer strings. At the moment you silently drop them. Personally, I'd want it to error. This also lets you use the more terse:
```
public static int[] ToIntArray(this string value, char separator)
{
return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
}
``` | This approach is very terse, and will throw a (not very informative) `FormatException` if the split string contains any values that can't be parsed as an int:
```
int[] ints = str.Split(',').Select(s => int.Parse(s)).ToArray();
```
If you just want to silently drop any non-int values you could try this:
```
private static int? AsNullableInt(string s)
{
int? asNullableInt = null;
int asInt;
if (int.TryParse(s, out asInt))
{
asNullableInt = asInt;
}
return asNullableInt;
}
// Example usage...
int[] ints = str.Split(',')
.Select(s => AsNullableInt(s))
.Where(s => s.HasValue)
.Select(s => s.Value)
.ToArray();
``` | Is this the best way in C# to convert a delimited string to an int array? | [
"",
"c#",
"string",
""
] |
Currently to me, LINQ is just a loose and amorphous cloud of concepts, usually about data access but also in combination with lambda expressions, delegates, anonymous functions and extension methods, it is about string and collection manipulation, so I want to pin it down.
**When I write the following code, can I say I am "using LINQ" or not?**
```
List<string> words = new List<string>() { "one", "two", "three" };
words.ForEach(word => Console.WriteLine(word.ToUpper()));
```
e.g. the "**ForEach**" method is widely referred to as a "LINQ method" yet its home is in **System.Collections.Generic.List** and not **System.Linq**. | It's not part of LINQ - it existed in .NET 2.0, well before LINQ. It's LINQ-like, but I wouldn't say it's part of LINQ.
On the other hand, if you implement your own `IEnumerable<T>` extension method `ForEach` (like in MoreLINQ) that *could* be regarded as a non-standard LINQ operator... | ForEach is not LINQ, it's just a method that takes a delegate. Been there since .NET 2.0. | Is List.ForEach technically a part of LINQ or not? | [
"",
"c#",
"linq",
""
] |
How do I access a private attribute of a parent class from a subclass (without making it public)? | My understanding of Python convention is
* \_member is protected
* \_\_member is private
Options for if you control the parent class
* Make it protected instead of private
since that seems like what you really
want
* Use a getter (@property def
\_protected\_access\_to\_member...) to limit the protected access
If you don't control it
* Undo the name mangling. If you
dir(object) you will see names
something like \_Class\_\_member which is
what Python does to leading \_\_ to
"make it private". There isn't
truly private in python. This is probably considered evil. | # Two philosophies of protection
Some language designers subscribe to the following assumption:
> *"Many programmers are irresponsible, dim-witted, or both."*
These language designers will feel tempted to protect programmers from each other by introducing a `private` specifier into their language.
Shortly later they recognize that this is often too inflexible and introduce `protected` as well.
Language designers such as Python's Guido van Rossum, in contrast, assume that programmers are responsible adults and capable of good judgment (perhaps not always, but typically).
They find that everybody should be able to access the elements of a program if there is a need to do that, so that the language does not get in the way of doing the right thing.
(The only programming language that can reliably get in the way of doing the *wrong* thing is the [NULL](http://www.netfunny.com/rhf/jokes/new90/nullang.html) language)
Therefore, `_myfield` in Python means something like "The designer of this module is doing some non-obvious stuff with this attribute, so please do not modify it and stay away from even reading it if you can -- suitable ways to access relevant information have been provided (or so we hope)."
In case you are not able to stay away from accessing `_myfield` (such as in special cases in a subclass), you simply access it. | Python "protected" attributes | [
"",
"python",
""
] |
I have a Django view, which receives part of its data from an external website, which I parse using urllib2/BeautifulSoup.
This operation is rather expensive so I cache it using the low-level cache API, for ~5 minutes. However, each user which accesses the site after the cached data expires will receive a significant delay of a few seconds while I go to the external site to parse the new data.
Is there any way to load the new data lazily so that no user will ever get that kind of delay? Or is this unavoidable?
*Please note that I am on a shared hosting server, so keep that in mind with your answers.*
**EDIT:** thanks for the help so far. However, I'm still unsure as to how I accomplish this with the python script I will be calling. A basic test I did shows that the django cache is not global. Meaning if I call it from an external script, it does not see the cache data going on in the framework. Suggestions?
**Another EDIT:** coming to think of it, this is probably because I am still using local memory cache. I suspect that if I move the cache to memcached, DB, whatever, this will be solved. | So you want to schedule something to run at a regular interval? At the cost of some CPU time, you can use [this simple app](http://code.google.com/p/django-cron/wiki/Install).
Alternatively, if you can use it, the [cron job](http://www.thesitewizard.com/general/set-cron-job.shtml) for every 5 minutes is:
```
*/5 * * * * /path/to/project/refresh_cache.py
```
Web hosts provide different ways of setting these up. For cPanel, use the Cron Manager. For Google App Engine, use [`cron.yaml`](http://code.google.com/appengine/docs/python/config/cron.html). For all of these, you'll need to [set up the environment](http://superjared.com/entry/django-and-crontab-best-friends/) in `refresh_cache.py` first.
By the way, responding to a user's request is considered lazy caching. This is pre-emptive caching. And don't forget to cache long enough for the page to be recreated! | "I'm still unsure as to how I accomplish this with the python script I will be calling. "
The issue is that your "significant delay of a few seconds while I go to the external site to parse the new data" has nothing to do with Django cache at all.
You can cache it everywhere, and when you go to reparse the external site, there's a delay. The trick is to NOT parse the external site while a user is waiting for their page.
The trick is to parse the external site *before* a user asks for a page. Since you can't go back in time, you have to periodically parse the external site and leave the parsed results in a local file or a database or something.
When a user makes a request you already have the results fetched and parsed, and all you're doing is presenting. | Django caching - can it be done pre-emptively? | [
"",
"python",
"django",
"caching",
""
] |
I have a HTTP sever in one program and my basic application in another one. Both of them are loops, so I have no idea how to:
1. Write a script that would start the app and then the HTTP server;
2. Make these programs exchange data in operation.
How are these things usually done? I would really appriciate Python solutions because my scripts are written in Python.
1. Does a user make an http request which queries the app for some data and return a result? **Yes**
2. Does the app collect data and store it somewhere? **The app and the HTTP Server both use SQLite database. However the DBs may be different.** | Before answering, I think we need some more information:
1. Is there a definable pipeline of information here?
1. Does a user make an http request which queries the app for some data and return a result?
2. Does the app collect data and store it somewhere?
There are a few options depending on how you're actually using them. Sockets is an option or passing information via a file or a database.
**[Edit]** Based on your reply I think there's a few ways you can do it:
1. If you can access the app's database from the web server you could easily pull the information you're after from there. Again it depends what information it is that you want to exchange.
2. If your app just needs to give the http server some results, you could write them into a results table in the http server's db.
3. Use pipe's or sub processes as other people have suggested to exchange data with the background app directly.
4. Use a log file which your app can write to and your http server read from.
Some more questions:
1. Do you need two-way communication here or is the http server just displaying results?
2. What webserver are you using?
3. What processing languages do you have available on it?
Depending on how reliant the two parts can be, it might be best to write a new app to check the database of your app for changes (using hooks or polling or whatever) and post relevent information into the http server's own database. This has the advantage of leaving the two parts less closely coupled which is often a good thing.
I've got a webserver (Apache 2) which talks to a Django app using the fastcgi module. Have a look at [the section in djangobook on fastcgi](http://www.djangobook.com/en/2.0/chapter12/). Apache uses sockets (or regular tcp) to talk to the background app (Django).
**[Edit 2]** Oops - just spotted that your webserver is a python process itself. If it's all python then you could [launch each in it's own thread](http://www.tutorialspoint.com/python/python_multithreading.htm) and pass them both [Queue](http://docs.python.org/library/queue.html) objects which allow the two processes to send each other information in either a blocking or non-blocking manner. | a) You can start applications using **os.system**:
```
os.system("command")
```
or you can use the **subprocess** module. More information [here](http://docs.python.org/library/subprocess.html).
b) use sockets | How to make two python programs interact? | [
"",
"python",
"multithreading",
"ipc",
"process",
"interaction",
""
] |
If I am extending an existing ThreadFactory implementation, how would I go able ensuring that all threads created would have the same prefix? I'm sick and tired of looking at `Thread-9` in my logs and would like to distinguish between threads more easily.
Does anyone have any suggestions as to how to go about this? | Provide your own implementation of the ThreadFactory interface:
```
pool = Executors.newScheduledThreadPool(numberOfThreads, new TF());
class TF implements ThreadFactory {
public synchronized Thread newThread(Runnable r) {
Thread t = new Thread(r) ;
t.setName("Something here....");
return t;
}
}
``` | You should use your own custom thread factory. The default factories are not much of use. Implement a ThreadFactoryBuilder to create you custom thread factories that allows you to do the following:
1. Have custom thread names
2. Have choice of threads - User or Daemon threads
3. Have choice of Thread Priority
4. Have flexibility to set uncaught exception handlers
You have a sample ThreadFactoryBuilder implementation in the following post which you can use.
<http://wilddiary.com/understanding-java-threadfactory-creating-custom-thread-factories/> | How do I customize all the names of the child threads of a ThreadFactory in Java? | [
"",
"java",
"multithreading",
""
] |
All platforms welcome, please specify the platform for your answer.
A similar question: [How to programmatically get the CPU cache page size in C++?](https://stackoverflow.com/q/150294) | You can use [std::hardware\_destructive\_interference\_size](https://en.cppreference.com/w/cpp/thread/hardware_destructive_interference_size) since C++17.
Its defined as:
> Minimum offset between two objects to avoid false sharing. Guaranteed
> to be at least alignof(std::max\_align\_t) | On Linux (with a reasonably recent kernel), you can get this information out of /sys:
```
/sys/devices/system/cpu/cpu0/cache/
```
This directory has a subdirectory for each level of cache. Each of those directories contains the following files:
```
coherency_line_size
level
number_of_sets
physical_line_partition
shared_cpu_list
shared_cpu_map
size
type
ways_of_associativity
```
This gives you more information about the cache then you'd ever hope to know, including the cacheline size (`coherency_line_size`) as well as what CPUs share this cache. This is very useful if you are doing multithreaded programming with shared data (you'll get better results if the threads sharing data are also sharing a cache). | Programmatically get the cache line size? | [
"",
"c++",
"c",
"caching",
"operating-system",
"systems-programming",
""
] |
I have a simple SQL table which has a DateTime column. I would like to update all the rows (>100000 rows) with a random date. Is there a simple way to do this a SQL Query? | Use this to generate a smalldatetime between 01 Jan 1900 and 06 Jun 2079 (not checked, SQL not installed)
```
DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)
```
NEWID is better then trying to use RAND: RAND does not generate different values row in a single SELECT or UPDATE (well it didn't in SQL 2000, in case behaviour has changed).
Edit: like this
```
UPDATE
table
SET
datetimecol = DATEADD(day, (ABS(CHECKSUM(NEWID())) % 65530), 0)
```
Edit: changed 65535 to 65530 and added ABS to avoid overflow at upper limit of range | I will complement the answers below,
```
SELECT DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '2000-01-01')
FROM your_table
```
This generates dates starting from 2000-01-01, and you can change the amount of days in the modulus value, I put 3650 (about 10 years), this approach doesn't overflow.
If you want to update, then
```
UPDATE your_table
SET your_date_field = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 3650), '2000-01-01')
WHERE your_conditions
``` | How to update rows with a random date | [
"",
"sql",
"sql-server",
""
] |
What would be the difference between these two seemingly similar declarations?
When would you choose one syntax over another?
Is there any specific reason to choose one over the other?
Any performance penalties incurred for either case?
```
public void Import<T>(
Func<IEnumerable<T>> getFiles, Action<T> import)
where T : IFileInfo
{
// Import files retrieved through "getFiles"
}
public void Import(
Func<IEnumerable<IFileInfo>> getFiles, Action<IFileInfo> import)
{
// Import files retrieved through "getFiles"
}
``` | The difference is that the first would allow you to pass in something which used a more concrete type implementing `IFileInfo`. For example:
```
Func<IEnumerable<SpecialFileInfo>> lister = () => ListFiles();
Import(lister, file => Console.WriteLine(file.SpecialProperty));
```
(Where `SpecialProperty` is a property which exists on `SpecialFileInfo` but not `IFileInfo`.) You couldn't do this with the latter form.
There is a very slight execution-time penalty for generic methods and types - it will be JITted once for different each value type `T` type argument (don't forget a value type could implement `IFileInfo`) and once for all reference type (i.e. once it's been JITted or one reference type, it won't need to be JITted again). This will almost certainly be negligible in your real application though. | Although this questions has already been answered: Maybe you want to go with a less restrictive solution:
```
public void Import<T,S>(
Func<IEnumerable<S>> getFiles, Action<T> import)
where T : IFileInfo
where S : T
{
// Import files retrieved through "getFiles"
}
```
This one allows an `Action<IFileInfo>` and an `Func<IEnumerable<ConcreteFileInfo>>` to be passed. | Parameter type using Generics constraint VS Explicit type declaration | [
"",
"c#",
".net",
"generics",
""
] |
See the code below. If I initialize more than one entity context, then I get the following exception on the **2nd set of code only**. If I comment out the second set it works.
> {"The underlying provider failed on Open."}
>
> Inner: {"Communication with the underlying transaction manager has failed."}
>
> Inner: {"Error HRESULT E\_FAIL has been returned from a call to a COM component."}
Note that this is a sample app and I know it doesn't make sense to create 2 contexts in a row. However, the production code does have reason to create multiple contexts in the same `TransactionScope`, and this cannot be changed.
**Edit**
Here is a previous question of me trying to set up MS-DTC. It seems to be enabled on both the server and the client. I'm not sure if it is set up correctly. Also note that one of the reasons I am trying to do this, is that existing code within the `TransactionScope` uses ADO.NET and Linq 2 Sql... I would like those to use the same transaction also. (That probably sounds crazy, but I need to make it work if possible).
[How do I use TransactionScope in C#?](https://stackoverflow.com/questions/794364/how-do-i-use-transactionscope-in-c)
**Solution**
*Windows Firewall was blocking the connections to MS-DTC.*
```
using(TransactionScope ts = new System.Transactions.TransactionScope())
{
using (DatabaseEntityModel o = new DatabaseEntityModel())
{
var v = (from s in o.Advertiser select s).First();
v.AcceptableLength = 1;
o.SaveChanges();
}
//-> By commenting out this section, it works
using (DatabaseEntityModel o = new DatabaseEntityModel())
{
//Exception on this next line
var v = (from s1 in o.Advertiser select s1).First(); v.AcceptableLength = 1;
o.SaveChanges();
}
//->
ts.Complete();
}
``` | Your MS-DTC (Distributed transaction co-ordinator) is not working properly for some reason. MS-DTC is used to co-ordinate the results of transactions across multiple heterogeneous resources, including multiple sql connections.
Take a look at [this link](http://social.msdn.microsoft.com/Forums/en-US/windowstransactionsprogramming/thread/71f7a219-c85d-4a04-973b-c73464f59606) for more info on what is happening.
Basically if you make sure your MS-DTC is running and working properly you should have no problems with using 2 ADO.NET connections - whether they are entity framework connections or any other type. | You can avoid using a distributed transaction by managing your own EntityConnection and passing this EntityConnection to your ObjectContext. Otherwise check out these.
<http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=580828&SiteID=1&mode=1>
<http://forums.microsoft.com/msdn/showpost.aspx?postid=113669&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=1>
```
EntityConnection conn = new EntityConnection(ConnectionString);
using (TransactionScope ts = new TransactionScope())
{
using (DatabaseEntityModel o = new DatabaseEntityModel(conn))
{
var v = (from s in o.Advertiser select s).First();
v.AcceptableLength = 1;
}
//-> By commenting out this section, it works
using (DatabaseEntityModel o = new DatabaseEntityModel(conn))
{
//Exception on this next line
var v = (from s1 in o.Advertiser select s1).First();
v.AcceptableLength = 1;
}
//->
ts.Complete();
}
``` | Why doesn't TransactionScope work with Entity Framework? | [
"",
"c#",
".net",
"entity-framework",
"transactions",
"transactionscope",
""
] |
I have a simple Class Hierarchy that I am trying to get to work with Hibernate/JPA.
Basically what I want is for the MovementData to be in its own Table with a FK to the integer id of the Main Vehicle Table in the Database.
Am I doing something wrong? How else can I accomplish something similar?
I am pretty sure I am following the JPA spec. (EJB3 In Action says this should work: [EJB3 In Action: @SecondaryTable](http://books.google.com/books?id=j4Qf2iLL488C&pg=PA266&vq=%40secondarytable&dq=ejb3+in+action&source=gbs_search_s&cad=0)
Here is a portion of the exception I am getting:
```
SEVERE: an assertion failure occured (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session)
org.hibernate.AssertionFailure: Table MOVEMENT_DATA not found
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.getTableId(JoinedSubclassEntityPersister.java:480)
at org.hibernate.persister.entity.JoinedSubclassEntityPersister.<init>(JoinedSubclassEntityPersister.java:259)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:87)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:261)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1327)
```
Here is some of the logging info from Hibernate that pertains to the Vehicle... It looks like it is recognizing everything fine.. Then it throws the exception for some reason.
```
INFO: Binding entity from annotated class: com.dataobject.Vehicle
FINE: Import with entity name Vehicle
INFO: Bind entity com.dataobject.Vehicle on table VEHICLE
INFO: Adding secondary table to entity com.dataobject.Vehicle -> MOVEMENT_DATA
FINE: Processing com.dataobject.Vehicle property annotation
FINE: Processing annotations of com.dataobject.Vehicle.id
FINE: Binding column id. Unique false. Nullable false.
FINE: id is an id
FINE: building SimpleValue for id
FINE: Building property id
FINEST: Cascading id with null
FINE: Bind @Id on id
FINE: Processing annotations of com.dataobject.Vehicle.color
FINE: Binding column COLOR. Unique false. Nullable true.
FINE: binding property color with lazy=false
FINE: building SimpleValue for color
FINE: Building property color
FINEST: Cascading color with null
FINE: Processing annotations of com.dataobject.Vehicle.movementData
FINE: Binding column movementData. Unique false. Nullable true.
FINE: Binding component with path: com.dataobject.Vehicle.movementData
FINE: Processing com.dataobject.MovementData property annotation
FINE: Processing annotations of com.dataobject.MovementData.latitude
FINE: Column(s) overridden for property latitude
FINE: Binding column LATITUDE. Unique false. Nullable true.
FINE: binding property latitude with lazy=false
FINE: building SimpleValue for latitude
FINE: Building property latitude
FINEST: Cascading latitude with null
FINE: Processing annotations of com.dataobject.MovementData.longitude
FINE: Column(s) overridden for property longitude
FINE: Binding column LONGITUDE. Unique false. Nullable true.
FINE: binding property longitude with lazy=false
FINE: building SimpleValue for longitude
FINE: Building property longitude
FINEST: Cascading longitude with null
FINE: Processing annotations of com.dataobject.MovementData.speed
FINE: Column(s) overridden for property speed
FINE: Binding column SPEED. Unique false. Nullable true.
FINE: binding property speed with lazy=false
FINE: building SimpleValue for speed
FINE: Building property speed
FINEST: Cascading speed with null
FINE: Processing annotations of com.dataobject.MovementData.timeOfPosition
FINE: Column(s) overridden for property timeOfPosition
FINE: Binding column TIME_OF_POSITION. Unique false. Nullable true.
FINE: binding property timeOfPosition with lazy=false
FINE: building SimpleValue for timeOfPosition
FINE: Building property timeOfPosition
FINEST: Cascading timeOfPosition with null
FINE: Building property movementData
FINEST: Cascading movementData with null
FINE: Processing annotations of com.dataobject.Vehicle.numWheels
FINE: Binding column NUM_WHEELS. Unique false. Nullable true.
FINE: binding property numWheels with lazy=false
FINE: building SimpleValue for numWheels
FINE: Building property numWheels
FINEST: Cascading numWheels with null
INFO: Binding entity from annotated class: com.dataobject.Car
FINE: Binding column id. Unique false. Nullable false.
FINE: Subclass joined column(s) created
FINE: Import with entity name Car
INFO: Bind entity com.dataobject.Car on table CAR
FINE: Processing com.dataobject.Car property annotation
FINE: Processing annotations of com.dataobject.Car.make
FINE: Binding column MAKE. Unique false. Nullable true.
FINE: binding property make with lazy=false
FINE: building SimpleValue for make
FINE: Building property make
```
**Vehicle is the Parent Class**
```
/**
* Entity implementation class for Entity: Vehicle
*
*/
@Entity
@Table(name="VEHICLE")
@Inheritance(strategy=InheritanceType.JOINED)
@SecondaryTable(name="MOVEMENT_DATA",
pkJoinColumns = {
@PrimaryKeyJoinColumn(name = "ID")
}
)
public class Vehicle implements Serializable {
private int numWheels;
private String color;
private int id;
private MovementData movementData;
private static final long serialVersionUID = 1L;
public Vehicle() {
super();
}
@Embedded
@AttributeOverrides( {
@AttributeOverride(
name = "speed",
column = @Column(name = "SPEED",
table = "MOVEMENT_DATA")
),
@AttributeOverride(
name = "timeOfPosition",
column = @Column(name = "TIME_OF_POSITION",
table = "MOVEMENT_DATA")
),
@AttributeOverride(
name = "longitude",
column = @Column(name = "LONGITUDE",
table = "MOVEMENT_DATA")
),
@AttributeOverride(
name = "latitude",
column = @Column(name = "LATITUDE",
table = "MOVEMENT_DATA")
)
})
public MovementData getMovementData() {
return movementData;
}
public void setMovementData(MovementData movementData) {
this.movementData = movementData;
}
@Column(name="NUM_WHEELS")
public int getNumWheels() {
return this.numWheels;
}
public void setNumWheels(int numWheels) {
this.numWheels = numWheels;
}
@Column(name="COLOR")
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
@Id
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
}
```
**Car extends Vehicle**
```
/**
* Entity implementation class for Entity: Car
*/
@Entity
@Table(name="CAR")
public class Car extends Vehicle implements Serializable {
private String make;
private static final long serialVersionUID = 1L;
public Car() {
super();
}
/**
* @return
*/
@Column(name="MAKE")
public String getMake() {
return this.make;
}
/**
* @param make
*/
public void setMake(String make) {
this.make = make;
}
}
```
**MovementData is Embedded in Vehicle**
```
@Embeddable
public class MovementData implements Serializable {
private double speed;
private Date timeOfPosition;
private double latitude;
private double longitude;
private static final long serialVersionUID = 1L;
public MovementData() {
super();
}
/**
* @return
*/
@Column(name="SPEED")
public double getSpeed() {
return this.speed;
}
/**
* @param speed
*/
public void setSpeed(double speed) {
this.speed = speed;
}
/**
* @return
*/
@Column(name="TIME_OF_POSITION")
public Date getTimeOfPosition() {
return this.timeOfPosition;
}
/**
* @param timeOfPosition
*/
public void setTimeOfPosition(Date timeOfPosition) {
this.timeOfPosition = timeOfPosition;
}
/**
* @return
*/
@Column(name="LONGITUDE")
public double getLongitude() {
return this.longitude;
}
/**
* @param longitude
*/
public void setLongitude(double longitude) {
this.longitude = longitude;
}
/**
* @return
*/
@Column(name="LATITUDE")
public double getLatitude() {
return this.latitude;
}
/**
* @param latitude
*/
public void setLatitude(double latitude) {
this.latitude = latitude;
}
}
```
**Persistence Unit:**
```
<properties>
<!-- The database dialect to use -->
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<!-- drop and create tables at deployment -->
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<!-- Hibernate Query Language (HQL) parser. -->
<!-- property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.EhCacheProvider" /-->
<!-- property name="hibernate.cache.provider_class" value="org.hibernate.cache.JbossCacheProvider" /-->
<property name ="hibernate.show_sql" value="false" />
<property name ="hibernate.format_sql" value="false" />
<property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.SingletonEhCacheProvider" />
</properties>
``` | During development its often convenient to have this property enabled:
```
cfg.setProperty(Environment.HBM2DDL_AUTO, "update");
```
where cfg is my AnnotationConfiguration.
Your problem will most likely be solved by enabling this property. | I would try breaking this down to find the issue. Try making movement data into an entity instead of an embeddable class. Make sure that it can stand on its own and then change it back to embeddable.
Although its not really the relationship that you want, you might try making MovementData the root parent and have Vehicle inherit off of MovementData. That way you would only be working with
```
@Inheritance(strategy=InheritanceType.JOINED)
```
instead of inheritance plus secondaryTable. It would simplify the relationship but still include all of the tables. | Splitting Hibernate Entity among 2 Tables | [
"",
"java",
"hibernate",
"jpa",
"jakarta-ee",
"orm",
""
] |
Given the following HTML fragment:
```
<form id="aspnetForm" onsubmit="alert('On Submit Run!'); return true;">
```
I need to remove/clear the handler for the onsubmit event and register my own using jQuery or any other flavor of JavaScript usage. | To do this without any libraries:
```
document.getElementById("aspnetForm").onsubmit = null;
``` | With jQuery
```
$('#aspnetForm').unbind('submit');
```
And then proceed to add your own. | How to Clear/Remove JavaScript Event Handler? | [
"",
"javascript",
"html",
"dom-events",
""
] |
I want to make a long list short by hiding some elements in long sub-lists without adding extra processing on the server side. The problem is that the markup that comes from the server is not controlled by me and is not designed in a way to make my job easy. here is the code
```
<ul id="long-list">
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="header"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="header"></li>
<li class="item"></li>
.
.
.
</ul>
```
As you've notices the headers are sibling to the items. Now, I want to have a jQuery code that shows only 3 items after each header and hide the rest to make the list shorter and more usable.
Here is my try which is **not** working:
```
$('#long-list li.header ~ li.item:gt(3)').hide();
$('#long-list li.header ~ li.item:lt(3)').show();
$('#long-list li.header').show();
```
The extra feature is adding a node at bottom of each section that has hidden items, saying how many items has been hidden, say "5 more..." | This is how I've implemented it. Note that it has some other features like adding a node at the end of sub lists that have hidden items, saying x items are hidden and bind an onclick event to toggle hidden items.
```
if ($('#list li.header')[0]) {
var i = -1000;
$("#list > li").each(function(){
if ($(this).hasClass("header")) {
(i>3) && ($(this).before( "<li class='more'>" + (i-3) + " more...</li>").bind("click", toggle_more() ) );
i = 0;
}
else {
i = i+1;
}
$(this).toggle(i<=3);
});
}
```
It's basically based on what svinto said above. I still look for a better performance. Anyhow, right now I'm happy with the results.
Initiating i with -1000 ensures that we'll not hide items at the top of the list that do not have any header. as soon as we reach a header we'll set the i to zero and start counting. | Might be possible to do better, but this should work:
```
var i = 0;
$("#long-list li.header:first").nextAll("li").each(function(){
i = $(this).hasClass("header") ? 0 : i+1;
$(this).toggle(i<=3);
});
```
(Updated to not hide items before the first header.) | Hiding Extra Items in a list using jQuery in a tricky situation (markup is not ideal) | [
"",
"javascript",
"jquery",
""
] |
Is it possible to create a table (from a JPA annotated Hibernate `@Entity`) that does not contain a primary key / Id?
I know this is not a good idea; a table should have a primary key. | I found that its not possible to do so. So bad luck for those working with legacy systems.
If you reverse engineer (create JPA annotated entities from existing JDBC connection) the table will create two Java classes, one Entity and with one field; id, and one embeddable id containing all the columns from your relation. | Roger's self-answer is correct. To elaborate a bit on what is meant (I wasn't clear on it at first and figured this would help):
Say you have you have a table Foo as such:
```
TABLE Foo (
bar varchar(20),
bat varchar(20)
)
```
Normally, you can write a class w/Annotations to work with this table:
```
// Technically, for this example, the @Table and @Column annotations
// are not needed, but don't hurt. Use them if your column names
// are different than the variable names.
@Entity
@Table(name = "FOO")
class Foo {
private String bar;
private String bat;
@Column(name = "bar")
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
@Column(name = "bat")
public String getBat() {
return bat;
}
public void setBat(String bat) {
this.bat = bat;
}
}
```
.. But, darn. This table has nothing we can use as an id, and it's a legacy database that we use for [insert vital business function]. I don't think they'll let me start modifying tables in order for me to use hibernate.
You can, instead, split the object up into a hibernate-workable structure which allows the entire row to be used as the key. (Naturally, this assumes that the row is unique.)
Split the Foo object into two thusly:
```
@Entity
@Table(name = "FOO")
class Foo {
@Id
private FooKey id;
public void setId(FooKey id) {
this.id = id;
}
public void getId() {
return id;
}
}
```
and
```
@Embeddable
class FooKey implements Serializable {
private String bar;
private String bat;
@Column(name = "bar")
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
@Column(name = "bat")
public String getBat() {
return bat;
}
public void setBat(String bat) {
this.bat = bat;
}
```
}
.. And that should be it. Hibernate will use the Embeddable key for its required identity and you can make a call as normal:
```
Query fooQuery = getSession().createQuery("from Foo");
```
Hope this helps first-timers with getting this working. | Hibernate and no PK | [
"",
"java",
"database",
"hibernate",
"jpa",
""
] |
I'm setting up a GUI where I need to take information inputted from form elements and manipulate the information. This requires me to use some elements to access others.
For example, I have an input box (`JTextField`) and a button (`JButton`) beside it. When the button is pressed, I need to be able to manipulate the text entered into the input box. Everything I've tried to do so far to get this done has failed.
This is what my code looks like right now (I've embedded my questions in the comments):
```
public class MyClass
{
public static void main(String args[])
{
// Form elements are in here
JTextField myTextField = new JTextField(10);
JButton myTextFieldSubmit = new JButton("Submit");
myTextFieldSubmit.addActionListener(new ListenerClass());
}
}
class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// This is what happens when these elements are used
// I need to be able to access the form elements from MyClass in here, but this doesn't seem possible with my current setup
// For example, when the Submit button is pressed, I need to be able to myTextField.getText() and edit MyClass members
// How should my setup be changed to accommodate these needs?
}
}
```
Thanks for any help! | This is very much a variable scope issue.
Currently, the text field and button are in the scope of the `main` method, so having a separate class for the `ActionListener` will mean that it will not have access to those variables.
There are a few ways to achieve this:
(1) Make an inner class `ListenerClass` in `MyClass`, and turn the `myTextField` and `myTextFieldSubmit` into instance fields of `MyClass`.
```
public class MyClass
{
final static JTextField myTextField = new JTextField(10);
final static JButton myTextFieldSubmit = new JButton("Submit");
public static void main(String args[])
{
myTextFieldSubmit.addActionListener(new ListenerClass());
}
static class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
myTextField.setText("");
}
}
}
```
(2) Make an anonymous inner class in the `main` method, and this will allow `myTextField` and `myTextFieldSubmit` to remain in the same place, as long as they are declared `final`.
```
public class MyClass
{
public static void main(String args[])
{
final JTextField myTextField = new JTextField(10);
final JButton myTextFieldSubmit = new JButton("Submit");
myTextFieldSubmit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
myTextField.setText("");
}
});
}
}
```
(3) Make a local class that is local to the `main` method. Again, this will require the text field and button to be declared `final` to allow access from the inner class.
```
public class MyClass
{
public static void main(String args[])
{
final JTextField myTextField = new JTextField(10);
final JButton myTextFieldSubmit = new JButton("Submit");
class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
myTextField.setText("");
}
}
myTextFieldSubmit.addActionListener(new ListenerClass());
}
}
```
(4) Handing an reference to the `ListenerClass`, for example in the constructor, and also making `myTextField` and `myTextFieldSubmit` an instance variable.
```
public class MyClass
{
JTextField myTextField = new JTextField(10);
JButton myTextFieldSubmit = new JButton("Submit");
public MyClass()
{
myTextFieldSubmit.addActionListener(new ListenerClass(this));
}
public static void main(String args[])
{
new MyClass();
}
}
class ListenerClass implements ActionListener
{
MyClass myClass;
public ListenerClass(MyClass myClass)
{
this.myClass = myClass;
}
public void actionPerformed(ActionEvent e)
{
myClass.myTextField.setText("");
}
}
```
(5) Make `myTextField` and `myTextFieldSubmit` into `static` fields, and allow direct access from the `ListerClass`.
```
public class MyClass
{
static JTextField myTextField = new JTextField(10);
static JButton myTextFieldSubmit = new JButton("Submit");
public static void main(String args[])
{
myTextFieldSubmit.addActionListener(new ListenerClass());
}
}
class ListenerClass implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
MyClass.myTextField.setText("");
}
}
```
There still probably are more ways to achieve this, and there may be better ways to implement this. The choice of which approach you take really depends up on the desired design of the application. | You can pass in a reference to `MyClass` in the constructor to `ListenerClass`. | How can I use listeners to access other elements? | [
"",
"java",
"user-interface",
"listeners",
""
] |
I have a class that I have serialized to disk on local users machines. I need to refactor this class and I changed all objects (anything except enums, string, numbers) to interfaces. Underneath it is still the same concrete class. my concern is breaking existing users persistance
From:
```
public class Foo
{
public double Count;
public State MyState;
}
```
To
```
public class IFoo
{
public double Count;
public IState MyState;
}
```
but now I am getting errors from the serialization code that says "can't serialize because its an interface"
the error states:
**"There was an error reflecting type 'Foo'."
"Cannot serialize member 'Foo.My' of type 'IState', see inner exception for more details."**
what is the best way around this? | You cannot serialize interfaces because the amount of types that can implement the interface is infinite and the serializer does not know what concrete type it is.
```
class A : IFoo {}
class B : IFoo {}
class C : IFoo {}
//snip//
IFoo f = new A();
f = new B();
f = new C();
```
You must specify if you are serializing A,B or C.
Another way to think of it is when deserializing to IFoo, how would you know which to create ... A, B or C .. etc? | I think you will have to handle serialization explicitly by implementing ISerializable. Think about how deserialization can determine what concrete class to use for IState. It does not know. That's why you would need to handle serialization on your own. | Refactoring class to interface without breaking serialization in C# | [
"",
"c#",
".net",
"serialization",
"refactoring",
""
] |
I need to modify the vertical and horizontal resolutions without changing the image dimensions. | Check out the [Bitmap.SetResolution](http://msdn.microsoft.com/en-us/library/system.drawing.bitmap.setresolution.aspx) Method. | If all you have is GDI, have a look at this [link](http://www.codeproject.com/KB/GDI-plus/imageresize.aspx).
You can save the [Bitmap](http://msdn.microsoft.com/en-us/library/9t4syfhh.aspx) to a JPEG file using this snippet:
```
bmp.Save("picture.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
``` | Change the resolution of a jpeg image using C# | [
"",
"c#",
"jpeg",
"resolution",
""
] |
I've read about it, I understand it's basic function--I'd like to know an example of a common, real-life use for this pattern.
For reference, I work mostly with business applications, web and windows, using the Microsoft stack. | Think of an Itinerary builder. There are lots of things you can add to you Itinerary like hotels, rental cars, airline flights and the cardinality of each is 0 to \*. Alice might have a car and hotel while Bob might have two flights, no car and three hotels.
It would be very hard to create an concrete factory or even an abstract factory to spit out an Itinerary. What you need is a factory where you can have different steps, certain steps happen, others don't and generally produce very different types of objects as a result of the creation process.
In general, you should start with factory and go to builder only if you need higher grain control over the process.
Also, there is a good description, code examples and UML at [Data & Object Factory](http://www.dofactory.com/Patterns/PatternBuilder.aspx). | Key use cases:
* When the end result is immutable, but
doing it all with a constructor would
be too complicated
* When I want to partially build
something and reuse that partially
built thing, but customize it at
the end each time
* When you start with the factory pattern, but the thing being built by
the factory has too many permutations
In summary, builder keeps your constructors simple, yet permits immutability.
You said C#, but here's a trivial Java example:
```
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World!");
System.out.println(sb.toString());
```
As opposed to:
```
String msg = "";
msg += "Hello";
msg += " ";
msg += "World!";
System.out.println(msg);
``` | What is a real-life use for the builder design pattern? | [
"",
"c#",
"design-patterns",
"architecture",
""
] |
I've inherited some code at work that has a really bad smell. I'm hoping to find the most painless solution possible.
Is there a way to check if some arbitrary number is a valid element in an array?
Example - I need to check if array[25] exists.
Preferably I would prefer to do this without doing a foreach() through the array to find the rows.
Is there a way to do this, or am I stuck with a *foreach* loop? | Test the length
```
int index = 25;
if(index < array.Length)
{
//it exists
}
``` | You can use [LINQ](https://en.wikipedia.org/wiki/Language_Integrated_Query) to achieve that too:
```
var exists = array.ElementAtOrDefault(index) != null;
``` | Does an index of this array exist? | [
"",
"c#",
"arrays",
"indexing",
""
] |
Is it possible to access the previous element generated in a [list comprehension](https://en.wikipedia.org/wiki/List_comprehension#Python)?
I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.
```
previous = initialization_value
cipher = []
for element in message:
previous = element ^ previous ^ key
cipher.append(previous)
```
I feel like it should be possible to turn this into a list comprehension, but I am not exactly sure how to handle both the initial value or accessing the previous value generated.
Is it possible and if so what would the comprehension be? | There isn't a good, Pythonic way to do this with a list comprehension. The best way to think about list comprehensions is as a replacement for `map` and `filter`. In other words, you'd use a list comprehension whenever you need to take a list and
* Use its elements as input for some expression (e.g. squaring the elements)
* Remove some of its elements based on some condition
What these things have in common is that they each only look at a single list element at a time. This is a good rule of thumb; even if you could theoretically write the code you showed as a list comprehension, it would be awkward and unpythonic. | As a generator:
```
def cypher(message, key, seed):
for element in message:
seed = element ^ seed ^ key
yield seed
list(cypher(message, key, initial_seed))
``` | Python list comprehension - access last created element | [
"",
"python",
""
] |
After wasting two days with [this question](https://stackoverflow.com/questions/768030/simple-httpwebrequest-over-ssl-https-gives-404-not-found-under-c) (and trying to make it work), I've decided to take a step back and ask a more basic question, because apparently there's something I don't know or I'm doing wrong.
The requirements are simple, *I need to make an HTTP post (passing a few values) over https* from C#.
The website (if given the appropriate values) will return some simple html and a response code. (i'll show these later).
It's really **that** simple. The "webservice" works. I have a php sample that works and successfully connects to it. I also have a Dephi "demo" application (with source code) that also works. And finally I have the demo application (binary) from the company that has the "service", that also works of course.
But I need to do it through C#. That that sounds so simple, it is not working.
For testing purposes I've created a simple console app and a simple connect method. I've tried like 7 different ways to create an HTTP request, all more or less the same thing, different implementation (Using WebClient, using HttpWebRequest, etc).
Every method works, **except** when the URI begins with 'https'.
I get a webexception saying that the remote server returned 404. I've installed Fiddler (as suggested by a SO user), and investigated a little bit the traffic. The 404 is because I am passing something wrong, because as I mentioned later, the 'service' works. I'll talk about the fiddler results later.
The URL where I have to POST the data is: <https://servicios.mensario.com/enviomasivo/apip/>
And this is the POST data: (the values are fakes)
usuario=SomeUser&clave=SomePassword&nserie=01234567890123456789&version=01010000&operacion=220
The server might return a two/three lines response (sorry about the spanish, but the company is from Spain). Here's a sample of a possible response:
```
HTTP/1.1 200 OK
Content-Type: text/plain
01010000 100 BIEN
998
```
And here's another
```
HTTP/1.1 200 OK
Content-Type: text/plain
01010000 20 AUTENTIFICACION NEGATIVA
Ha habido un problema en la identificación ante el servidor. Corrija sus datos de autentificacion.
```
The 1st one means OK, and the 2nd one is Auth Failure.
As you can see the task is quite *easy*, only it doesn't work. If I use fiddler, I see that there's some sort of SSL stuff going on in the connection and then everything works fine. However, as far as I've read, .NET handles all that stuff for us (*yes, i've added the callback to always validate invalid certs*). I don't understand what I'm doing wrong. I can post/email the code, but what I'd like to know is very simple:
**How can you make a POST over SSL using C# and a "simple" HttpWebRequest and later have the response in a string/array/Whatever for processing?**
Trust me when I say I've been googling and Stackoverflowing for two days. I don't have any sort of proxy. The connection passes through my router. Standard ports. Nothing fancy. My Machine is inside a VMWare virtual machine and is Windows Vista, but given that the sample applications (php, delphi, binary) all work without an issue, I cannot see that as a problem).
The different samples (sans the binary) are available [here](http://www.mensario.com/SEMPROTP/SDK/) if anyone wants to take a look at them.
I'd appreciate any help. If anyone wants to try with a "real" username, I have a demo user and I could pass you the user/pass for testing purposes. I only have *one* demo user (the one they gave me) and that's why I'm not pasting it here. I don't want to flood the user with tests ;)
I've tried (within the samples) using UTF8 and ASCII, but that didn't change anything.
I am 100% positive that there's something I have to do with SSL and I am not doing it because I don't know about it.
Thanks in **advance**.
Martín. | see my answer to your other question. I believe your problem may not be your C# code. The web service URL accually returns a 404 with several other tools I used, but it returns the response you indicated if you leave off the trailing slash from the web service URL, so I suggest trying that.
Oddly, it doesn't seem to matter if the trailing URL is there when not doing SSL. Something strange with that web server, I guess. | I was battling with the exact same problem a bit earlier (although in compact framework). Here's my question and my own answer to it:
[Asynchronous WebRequest with POST-parameters in .NET Compact Framework](https://stackoverflow.com/questions/768641/asynchronous-webrequest-with-post-parameters-in-net-compact-framework)
My version is asynchronous, so it's a bit more complex than what you're looking for, but the idea remains.
```
private string sendRequest(string url, string method, string postdata) {
WebRequest rqst = HttpWebRequest.Create(url);
// only needed, if you use HTTP AUTH
//CredentialCache creds = new CredentialCache();
//creds.Add(new Uri(url), "Basic", new NetworkCredential(this.Uname, this.Pwd));
//rqst.Credentials = creds;
rqst.Method = method;
if (!String.IsNullOrEmpty(postdata)) {
//rqst.ContentType = "application/xml";
rqst.ContentType = "application/x-www-form-urlencoded";
byte[] byteData = UTF8Encoding.UTF8.GetBytes(postdata);
rqst.ContentLength = byteData.Length;
using (Stream postStream = rqst.GetRequestStream()) {
postStream.Write(byteData, 0, byteData.Length);
postStream.Close();
}
}
((HttpWebRequest)rqst).KeepAlive = false;
StreamReader rsps = new StreamReader(rqst.GetResponse().GetResponseStream());
string strRsps = rsps.ReadToEnd();
return strRsps;
}
``` | Posting using POST from C# over https | [
"",
"c#",
".net",
"ssl",
"post",
"httpwebrequest",
""
] |
I'm generating regular expressions dynamically by running through some xml structure and building up the statement as I shoot through its node types. I'm using this regular expression as part of a Layout type that I defined. I then parse through a text file that has an Id in the beginning of each line. This id points me to a specific layout. I then try to match the data in that row against its regex.
Sounds fine and dandy right? The only problem is it is matching strings extremely slow. I have them set as compiled to try and speed things up a bit, but to no avail. What is baffling is that these expressions aren't that complex. I am by no means a RegEx guru, but I know a *decent* amount about them to get things going well.
Here is the code that generates the expressions...
```
StringBuilder sb = new StringBuilder();
//get layout id and memberkey in there...
sb.Append(@"^([0-9]+)[ \t]{1,2}([0-9]+)");
foreach (ColumnDef c in columns)
{
sb.Append(@"[ \t]{1,2}");
switch (c.Variable.PrimType)
{
case PrimitiveType.BIT:
sb.Append("(0|1)");
break;
case PrimitiveType.DATE:
sb.Append(@"([0-9]{2}/[0-9]{2}/[0-9]{4})");
break;
case PrimitiveType.FLOAT:
sb.Append(@"([-+]?[0-9]*\.?[0-9]+)");
break;
case PrimitiveType.INTEGER:
sb.Append(@"([0-9]+)");
break;
case PrimitiveType.STRING:
sb.Append(@"([a-zA-Z0-9]*)");
break;
}
}
sb.Append("$");
_pattern = new Regex(sb.ToString(), RegexOptions.Compiled);
```
The actual slow part...
```
public System.Text.RegularExpressions.Match Match(string input)
{
if (input == null)
throw new ArgumentNullException("input");
return _pattern.Match(input);
}
```
A typical "\_pattern" may have about 40-50 columns. I'll save from pasting the entire pattern. I try to group each case so that I can enumerate over each case in the Match object later on.
Any tips or modifications that could drastically help? Or is this running slowly to be expected?
EDIT FOR CLARITY: Sorry, I don't think I was clear enough the first time around.
I use an xml file to generate regex's for a specific layout. I then run through a file for a data import. I need to make sure that each line in the file matches the pattern it says its supposed to be. So, patterns could be checked against multiple times, possible thousands. | You are parsing a 50 column CSV file (that uses tabs) with regex?
You should just remove duplicate tabs, then split the text on \t. Now you have all of your columns in an array. You can use your ColumnDef object collection to tell you what each column is.
**Edit:** Once you have things split up, you could optionally use regex to verify each value, this should be much faster than using the giant single regex.
**Edit2:** You also get an additional benefit of knowing exactly what column(s) is badly formated and you can produce an error like "Sytax error in column 30 on line 12, expected date format." | Some performance thoughts:
* use `[01]` instead of `(0|1)`
* use non-capturing groups `(?:`*`expr`*`)` instead of capturing groups (if you really need grouping)
---
**Edit** As it seems that your values are separated by whitespace, why don’t you split it up there? | Dynamically Built Regular Expressions are running extremely slow! | [
"",
"c#",
".net",
"xml",
"regex",
"performance",
""
] |
I have two controller actions with the same name but with different method signatures. They look like this:
```
//
// GET: /Stationery/5?asHtml=true
[AcceptVerbs(HttpVerbs.Get)]
public ContentResult Show(int id, bool asHtml)
{
if (!asHtml)
RedirectToAction("Show", id);
var result = Stationery.Load(id);
return Content(result.GetHtml());
}
//
// GET: /Stationery/5
[AcceptVerbs(HttpVerbs.Get)]
public XmlResult Show(int id)
{
var result = Stationery.Load(id);
return new XmlResult(result);
}
```
My unit tests have no issue with calling one or the other controller action, but my test html page throws a System.Reflection.AmbiguousMatchException.
```
<a href="/Stationery/1?asHtml=true">Show the stationery Html</a>
<a href="/Stationery/1">Show the stationery</a>
```
What needs to change to make this work? | Just have one method like this.
```
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Show(int id, bool? asHtml)
{
var result = Stationery.Load(id);
if (asHtml.HasValue && asHtml.Value)
return Content(result.GetHtml());
else
return new XmlResult(result);
}
``` | [Heres a link you may find userful.](https://stackoverflow.com/questions/436866/can-you-overload-controller-methods-in-asp-net-mvc) It talks about overloading the MVC Controllers. | How can I avoid AmbiguousMatchException between two controller actions? | [
"",
"c#",
".net",
"asp.net-mvc",
"controller",
""
] |
I am using Socket communication in one of my Java applications.As I know if the program meets any abnormal termination the listening ports does not get closed and the program cannot be started back because it reports "Port already open.."
Do I have anyway to handle this problem? What is the general way used to handle this matter? | It sounds like your program is listening on a socket. Normally, when your program exits the OS closes all sockets that might be open (including listening sockets). However, for listening sockets the OS normally reserves the port for some time (several minutes) after your program exits so it can handle any outstanding connection attempts. You may notice that if you shut down your program abnormally, then come back some time later it will start up just fine.
If you want to avoid this delay time, you can use `setsockopt()` to configure the socket with the SO\_REUSEADDR option. This tells the OS that you know it's OK to reuse the same address, and you won't run into this problem.
You can set this option in Java by using the [`ServerSocket.setReuseAddress(true)`](http://java.sun.com/j2se/1.4.2/docs/api/java/net/ServerSocket.html#setReuseAddress(boolean)) method. | You want to set the SO\_REUSEADDR flag on the socket.
See [setReuseAddress()](https://docs.oracle.com/javase/1.5.0/docs/api/java/net/ServerSocket.html#setReuseAddress(boolean)). | How do I close a port in a case of program termination? | [
"",
"java",
"multithreading",
"sockets",
"jvm",
""
] |
The error is at this line :
```
dataArray[iLedMatrix][iRow] |= (byte)(bufferPattern[iRow]) & (1<<7);
```
**dataArray** is : byte dataArray[NUMBER\_LED\_MATRIX][NUMBER\_ROW\_PER\_MATRIX];
**bufferPattern** is : const patternp \* bufferPattern;
**patternp** is a typedef of the type : typedef prog\_uchar patternp[NUM\_ROWS];
I can see in the Reference that prog\_uchar is 1 byte ( 0 to 255 ). So I do not understand the error about losing precision? Any idea? | The problem is in this sub expression
```
(byte)(bufferPattern[iRow])
```
The variable bufferPattern is of type `const patternp *` so when the indexer is applied the result is patternp. The type "patternp" is typedef to prog\_uchar[]. So in actuality this expression is saying
> Cast a prog\_uchar\* to a byte
Byte is almost certainly a single byte value and prog\_uchar\* is the platform specific pointer type (either 4 or 8 bytes). This does indeed result in a loss of precision. Perhaps you meant to dereferenc this value?
```
(byte)(*(bufferPattern[iRow]))
``` | You are trying to cast from a pointer type to byte. A pointer type is usually represented on 4 bytes (32 bit OS) or 8 bytes (64 bits), and you are trying to convert its address value to 1 byte. | error: cast from 'const prog_uchar*' to 'byte' loses precision? | [
"",
"c++",
"c",
"avr",
""
] |
I have observed a great difference in Sun Java performance when code is compiled through jdk1.6 as compared to jdk1.5 or jdk1.4 (over 4 folds)
What changes and optimizations have been done? Is there anything worth taking home from these changes which will help to boost our application performance.
Thanks for replying | See: [Java SE 6 Performance White Paper](https://www.oracle.com/java/technologies/javase/6performance.html). | You might be interested in a recent [Java Posse interview](http://javaposse.com/index.php?post_id=454436) with engineers from AMD. They talk about advances in machine architecture and HotSpot over the last few years. They also discuss some benchmarks that match your observations.
The "take-away" from these engineers was that developers can best help HotSpot do its magic by following common idioms and writing straightforward code. Clever optimizations by a developer that work in one release might prevent HotSpot from doing much better optimization in a later version. | Vast difference in Java Performance from 1.4 to 1.6 | [
"",
"java",
"performance",
""
] |
I'm looking for a well-supported multithreaded Python HTTP server that supports chunked encoding replies. (I.e. "Transfer-Encoding: chunked" on responses). What's the best HTTP server base to start with for this purpose? | Twisted supports [chunked transfer encoding (API link)](http://twistedmatrix.com/documents/current/api/twisted.web.http._ChunkedTransferEncoding.html) (see also the API doc for [HTTPChannel](http://twistedmatrix.com/documents/current/api/twisted.web.http.HTTPChannel.html)). There are a number of production-grade projects using Twisted (for example, Apple uses it for the iCalendar server in Mac OS X Server), so it's quite well supported and very robust. | Twisted supports chunked transfer and it does so transparently. i.e., if your request handler does not specify a response length, twisted will automatically switch to chunked transfer and it will generate one chunk per call to Request.write. | Python HTTP server that supports chunked encoding? | [
"",
"python",
"http",
"chunked-encoding",
""
] |
Having just wrapped up a GWT-1.5 based project, I'm taking a look at what we'll have to do to migrate to 1.6. I'm very surprised to see that GWT seems to want to write its compiled output to the war directory, where you would normally have items under source control.
What's the reason behind this? Did Google really think this was a good idea? Is there a workaround to keep source code separate from compiler-generated artifacts? Is there some other reason for this that I'm missing?
**EDIT**:
It's been suggested that I use the `-war` option to specify an output directory. I wrote some ANT scripts, and have this mostly working. I've had to copy over my static resources such as HTML, JSPs, etc into this directory (I'm using `target/war,` maven-style). Is that what most people are doing? Or are you just letting GWT write its output into your source-code-controlled `war` dir, and telling your VCS to ignore the non-version-controlled files? It occurred to me that there might be some benefit to letting GWT write to this dir directly, since then Jetty could automatically notice changes to JSPs, HTML etc, and avoid having to do a copy to make these changes visible. | Salvador Diaz has provided [an excellent solution](http://blog.salvadordiaz.fr/2009/04/29/keep-your-source-tree-clean-gwt/) to this. | Use the "-war" option to control where the output goes.
FYI: The Wiki has the [design doc](http://code.google.com/p/google-web-toolkit/wiki/WAR_Design_1_6) which will, hopefully, give you a bit of insight as to what they were thinking.
See also the [Release Notes](http://code.google.com/webtoolkit/doc/1.6/ReleaseNotes_1_6.html) which discuss the new project layout, as well as some things to watch out for with this change. | GWT 1.6 project war layout- mixing source code & compiler-generated artifacts? | [
"",
"java",
"gwt",
"war",
""
] |
We've run across a slightly odd situation. Basically there are two tables in one of our databases that are fed tons and tons of logging info we don't need or care about. Partially because of this we're running out of disk space.
I'm trying to clean out the tables, but it's taking forever (there are still 57,000,000+ records after letting this run through the weekend... and that's just the first table!)
Just using delete table is taking forever and eats up drive space (I believe because of the transaction log.) Right now I'm using a while loop to delete records X at a time, while playing around with X to determine what's actually fastest. For instance X=1000 takes 3 seconds, while X=100,000 takes 26 seconds... which doing the math is slightly faster.
But the question is whether or not there is a better way?
(Once this is done, going to run a SQL Agent job go clean the table out once a day... but need it cleared out first.) | **[TRUNCATE](http://www.tsqltutorials.com/truncate-table.php)** the table or disable indexes before deleting
```
TRUNCATE TABLE [tablename]
```
Truncating will remove all records from the table without logging each deletion separately. | To add to the other responses, if you want to hold onto the past day's data (or past month or year or whatever), then save that off, do the TRUNCATE TABLE, then insert it back into the original table:
```
SELECT
*
INTO
tmp_My_Table
FROM
My_Table
WHERE
<Some_Criteria>
TRUNCATE TABLE My_Table
INSERT INTO My_Table SELECT * FROM tmp_My_Table
```
The next thing to do is ask yourself why you're inserting all of this information into a log if no one cares about it. If you really don't need it at all then turn off the logging at the source. | What is the best way to delete all of a large table in t-sql? | [
"",
"sql",
"sql-server-2005",
""
] |
I'm wondering if there is a defined standard for what the default action is of various HTML elements. I've looked at the [W3C's HTML specification](http://www.w3.org/TR/1999/REC-html401-19991224/cover.html) and while they are very precise with what attributes can be used with elements (and also some behavioural stuff such as exactly what gets included with form submission) there's nothing about the behaviour of elements. I've also checked out the [Mozilla JS reference](https://developer.mozilla.org/En/DOM), and found nothing there either.
In particular I'm looking for the default behaviour of a form submit button; I've seen in different places that its default action is to submit the form and alternatively that its default action is not to submit the form but rather to get focus. Accordingly, there seems to be no consensus on whether `onclick="return false;"` for a submit button will stop form submission or not.
(Edit for clarity - I'm not trying to do any form-level validation on the submit's `onclick` or anything like that; if I were, I'd be using the form's `onsubmit` instead. I really am specifically interested in catching clicks on the button and potentially not having it submit the form in this case. This might end up requiring the button's `onclick` set some state that the form's `onsubmit` inspects, but if I can just `return false` then that's great. Even if not, it would then be critical what order the `onsubmit` and `onclick` handlers get fired (i.e. does the button dispatch the submit before running its click handler?) which again I haven't seen specified anywhere.)
While it would be simply to code up a test, I'd rather rely on specs/documented behaviour rather than the results of a trivial test that would undoubtedly miss any subtleties should they exist. In particular, I ran a quick test last week that seemed to show it *didn't* stop form submission, but running one today shows that it *does*. I have had no luck finding any sort of authoritative resource as to what browsers *actually do* when you interact with their elements (e.g. what the default action is, whether the onclick handler for a submit button fires before or after the form submission dispatch, etc.)
Any advice as to where to look in this case would be welcome. | The relevant documents are [DOM3 Events](http://www.w3.org/TR/DOM-Level-3-Events/events.html) and the [HTML 5 specification](http://www.whatwg.org/specs/web-apps/current-work/multipage/).
They might not have all information you need, but should. So if you find them lacking, please [request those behaviors to be specified](http://www.whatwg.org/mailing-list). | why use a Submit button at all? why not just use a button? `<input type="button" onclick="function(){if(allCriteriaIsMet()) this.form.submit()}" value="click me"/>`
or am I missing something? | Is there a standard resource for the "default action" of HTML elements? | [
"",
"javascript",
"html",
"events",
"documentation",
"standards",
""
] |
I'm having a problem. Basically, when a user clicks an 'Edit' link on a page, the following Jquery code runs:
```
$("#saveBtn").click(function () {
saveQuestion(id);
});
```
By doing this, the onClick event of the save button calls the `saveQuestion()` method and passes on the ID of the question for which the 'Edit' link was clicked.
But if in the same session the user clicks edit on 2 questions, then instead of overwriting the previous `click` event handler, it instead causes 2 event handlers to run, one which might call `saveQuestion(1)` and the other might call `saveQuestion(2)`. By doing this 1 question overwrites the other.
Is there a way to remove all previous `click` events that have been assigned to a button? | You would use [off()](http://api.jquery.com/off/) to remove an event like so:
```
$("#saveBtn").off("click");
```
but this will remove *all click events* bound to this element. If the function with SaveQuestion is the only event bound then the above will do it. If not do the following:
```
$("#saveBtn").off("click").click(function() { saveQuestion(id); });
``` | > Is there a way to remove all previous click events that have been assigned to a button?
```
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
``` | How to remove all click event handlers using jQuery? | [
"",
"javascript",
"jquery",
"click",
""
] |
I would like to use a regular expression to match all words with more that one character, as opposed to words entirely made of the same char.
This should not match: ttttt, rrrrr, ggggggggggggg
This should match: rttttttt, word, wwwwwwwwwu | The following expression will do the trick.
```
^(?<FIRST>[a-zA-Z])[a-zA-Z]*?(?!\k<FIRST>)[a-zA-Z]+$
```
* capture the first character into the group `FIRST`
* capture some more characters (lazily to avoid backtracking)
* ensure that that the next character is different from `FIRST` using a negative lookahead assertion
* capture all (at least one due to the assertion) remaining characters
Note that is sufficient to look for a character that is different from the first one, because if no character is different from the first one, all characters are equal.
You can shorten the expression to the following.
```
^(\w)\w*?(?!\1)\w+$
```
This will match some more characters other than [a-zA-Z]. | I would add all unique words to a list and then used this regex
> \b(\w)\1+\b
to grab all one character words and get rid of them | How can you match words with more than one character? | [
"",
"c#",
"regex",
""
] |
Is there any point in having a com.myco.myproj.MyProjRuntimeException,
which completley extends RuntimeException? | **Yes. *Do* throw *unchecked* exceptions, and subclass them.**
There is much talk about whether checked exceptions are really any good. In a nutshell, if I throw a checked exception, does my client really have anything to do with it?
Unchecked exceptions are a good way to notify your clients about exceptional situations (including illegal pre-conditions), and yet not burdening them with the need to wrap calls to your API with try-catch blocks, which most of the time basically serve no purpose, other than debugging, tracing, etc.
So why not throw a `RuntimeException`? It's not *elegant*, and it's *less readable*. Make it your own exception which derives from it, even if it's for no reason other than being more specific when throwing the exception. | It depends on if you want to handle the exceptional condition differently than other exceptions farther up the call stack. If you intend to catch and handle the exception, then I'd recommend creating the custom type. It makes for more legible code and cleaner catch clauses. If you're not going to catch the exception, then there's probably little reason to create a new type. | Why have a project specific RuntimeException? | [
"",
"java",
"exception",
""
] |
I'd like to convert kilos into pounds and ounces e.g. if a user enters 10 kg then the function should return 22 lb and 0.73 oz
Any ideas? | Based on @dlamblin's answer, here's a function that returns the pounds and ounces in a structure.
```
function kToLbs(pK) {
var nearExact = pK/0.45359237;
var lbs = Math.floor(nearExact);
var oz = (nearExact - lbs) * 16;
return {
pounds: lbs,
ounces: oz
};
}
var imperial = kToLbs(10);
alert("10 kg = " + imperial.pounds + " lbs and " + imperial.ounces + " oz.");
```
Here's how you would go the other way:
```
function lbsAndOzToK(imperial) {
var pounds = imperial.pounds + imperial.ounces / 16;
return pounds * 0.45359237;
}
var kg = lbsToK({ pounds: 10, ounces: 8 });
alert("10 lbs and 8 oz = " + kg + " kg.");
``` | ```
function kgToPounds(value) {
return value * ?conversionValue?;
}
```
Replace `?conversionValue?` to whatever the rate needs to be.
```
function poundsToOunces(value) {
return value * 16;
}
```
Not really hard stuff, this. | function for converting kilograms to pounds and ounces | [
"",
"javascript",
"data-conversion",
"units-of-measurement",
""
] |
I am using an ASP.NET `GridView` control with a `TemplateColumn` which has a `TextBox` in the `ItemTemplate`. I am binding the `Text` of the `TextBox` with the values from database. The database holds these values with five decimal points, and for the interface I would like to display only two decimals.
The user can make changes to this grid. When I'm saving, I would like to be able to get all five decimals for the values that are not changed. Since it is displayed as two decimals, I was only able to read two decimals on postback? Is there a way around this other than saving the actual value in a hidden variable?
Thanks,
sridhar | I have a [formatCurrency](http://bendewey.wordpress.com/2008/11/11/jquery-formatcurrency-plugin/) plugin that could help you out here. What you'll want to do is display the data in a textbox and use a hiddenfield to bind the data. This way, not only do you retain the decimal places, but you can accept more than two decimal places as input.
Here is a sample that should work.
```
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js">
</script>
<script type="text/javascript" src="jquery.formatCurrency.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('.editNumber').formatCurrency();
$('.editNumber').blur(function(e) {
var val = $(this).toNumber();
$(this).next('input:hidden').val(val)
.end().formatCurrency();
});
});
</script>
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" CssClass="editNumber" ID="EditNumber" Text='<%# Eval("Price") %>' />
<asp:HiddenField runat="server" ID="HiddenNumber" Value='<%# Bind("Price") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
``` | You could always validate that the data has indeed changed at all in that column before updating it.
You could potentially add some sort of stored SQL procedure that would take the place of the column name that would do the compare before hand? Seems like a stretch.
Otherwise, yeah, a hidden field with some extra processing being done to hide/modify the original data of the field seems like the only answer. Anyway you cut it, there's going to be some quirky logic somewhere (whether it's in the database, or code that runs when you perform the post, or in some hidden field). | How do I display only two decimals in a textbox and still read 5 decimals? | [
"",
"javascript",
"jquery",
"asp.net-ajax",
""
] |
I'm trying to figure out how to search AD from C# similarly to how "Find Users, Contacts, and Groups" works in the Active Directory Users and Computers tool. I have a string that either contains a group name, or a user's name (usually in the format firstname middleinitial [if they have one] lastname, but not always). Even if I do a seperate query for groups vs. users, I can't come up with a way to search that captures most user accounts. The Find Users, Contacts, and Groups tool brings them back almost every time. Anyone have any suggestions?
I already know how to use the DirectorySearcher class, the issue is that I can't find a query that does what I'd like. Neither cn nor samaccount name has anything to do with the user's name in this, so I'm unable to search on those. Splitting things up and searching on sn and givenName doesn't catch anywhere near as much as that tool does. | Are you on .NET 3.5 ? If so - AD has great new features in .NET 3.5 - check out this article [Managing Directory Security Principals in .NET 3.5](http://msdn.microsoft.com/en-us/magazine/cc135979.aspx#S8) by Ethan Wilanski and Joe Kaplan.
One of the big new features is a "PrincipalSearcher" class which should greatly simplify finding users and/or groups in AD.
If you cannot use .NET 3.5, one thing that might make your life easier is called "Ambiguous Name Resolution", and it's a little known special search filter that will search in just about any name-related attribute all at once.
Specify your LDAP search query like this:
```
searcher.Filter = string.Format("(&(objectCategory=person)(anr={0}))", yourSearchTerm)
```
Also, I would recommend filtering on the "objectCategory" attribute, since that's single-valued and indexed by default in AD, which is a lot faster than using "objectClass".
Marc | System.DirectoryServices has two namespaces...DirectoryEntry and DirectorySearcher.
More info on the DirectorySearcher here:
<http://msdn.microsoft.com/en-us/library/system.directoryservices.directorysearcher.aspx>
You can then use the Filter property to filter by Group, user etc...
So if you wanted to filter by account name you would set the .Filter to:
```
"(&(sAMAccountName=bsmith))"
```
and run the FilterAll method. This will return a SearchResultCollection that you can loop through and pull information about the user. | How can you find a user in active directory from C#? | [
"",
"c#",
"active-directory",
""
] |
I have 2 radios:
```
<input id="a_15_0" type="radio" value="abc" name="a_15"/>
<input id="a_15_1" type="radio" value="xyz" name="a_15"/>
```
Both are unselected. I have only the name of the radio, i.e `a_15`, but not the IDs.
**1)** How can I get the value of the selected option of this radio? E.g if the user clicked 'xyz', how can I get it? Right now I'm using:
```
var val=$('[name="a_15"]').val();
```
Which always gives abc even when xyz is selected.
**2)** How can I get xyz to be selected through javascript, without knowing the ID of the radio which says xyz? Doing:
$('[name="a\_15"]').val('xyz');
Changes the value of both radios to xyz rather than selecting the one whose value had been xyz.
Do I need to use `document.myForm.a_15.value`? Would that work consistently? | Have you tried using the val() in conjunction with the :checked selector?
```
$('[name="a_15"]:checked').val();
```
As for setting the selection based on the value, you may have to perform a multiple attribute tests?
```
$('[name="a_15"][value="xyz"]').get(0).checked = true;
``` | 1)
try
```
var val = $('input[name=a_15]:checked').val();
```
[jQuery docs on checked pseudo-class](http://docs.jquery.com/Selectors/checked)
2) the only solution I found is
```
$('input[name=a_15][value=xyz]').get(0).checked=true
``` | Headaches with radios in Jquery | [
"",
"javascript",
"jquery",
""
] |
I'm using C++ without .NET on Win32, how can I download an image over HTTP from a website without having to re-invent the wheel? Is there an API or library that provides a single function to do this?
<http://mywebsite/file.imgext> --> C:\path\to\dir\file.imgext | You could use [cURLpp](http://curlpp.org/)
I havn't used it yet, but [example20](http://curlpp.org/index.php/examples/70-example-20) looks like it could solve your problem. | WinInet APIs are easier than you think
Here is a complete win32 console program. Can be built with with VS 2010 Express and down loading windows SDK to get WinInit.
---
```
// imaged.cpp : Defines the entry point for the console application.
//
// Copy file from internet onto local file
// Uses Wininet API
// program takes 1 mandatory command line argument - URL string
// it downloads ito the current directory, or whatever is passed
// as the second parameter to DownloadURLImage.
// optional parameter, the name of the file (excluding path), by default it uses the
// filename from the URL string.
#include "stdafx.h"
#include <iostream>
#include <windows.h>
#include <WinInet.h> // from SDK
#include "string.h"
//#include<TCHAR.H>
//#include "Tchar.h"
using namespace std ;
int convertURLtofname (TCHAR * szURL, TCHAR * szname )
// extract the filename from the URL
{
char aszfilename [100];
HRESULT result;
char achar[3], aszURL [100];
size_t nchars, i, j;
int fresult;
fresult = 0;
nchars= _tcslen(szURL);
i= nchars -1;
while ((i > 0) && (szURL[i] != '/') && (szURL[i] != '\\')) {i--;}
j= 0; i++;
while (i < nchars) { szname [j++]= szURL[i++]; }
szname[j]=_T('\0');
// wcstombs ( aszfilename, szname, 100 );
// cout << aszfilename << endl;
//----------------------------------------------
return fresult ;
}
int determinepathfilename (TCHAR * szURL, TCHAR * szpath, TCHAR * szname, TCHAR * szpathfilename)
{
// use path and filename when supplied. If filename (e.g. funkypic.jpg) is not supplied, then the
// filename will be extracted from the last part of the URL
int result ;
result= 0;
TCHAR szname_copy [100] ;
if ((szname == NULL) || (szname[0] == '\0'))
convertURLtofname (szURL, szname_copy);
else
_tcscpy (szname_copy, szname);
if ((szpath == NULL) || (szpath[0] == '\0'))
_tcscpy (szpathfilename, szname_copy);
else
{
_tcscpy (szpathfilename, szpath);
_tcscat (szpathfilename, szname_copy);
}
return result ;
}
bool GetFile (HINTERNET hOpen, // Handle from InternetOpen()
TCHAR *szURL, // Full URL
TCHAR * szpath,
TCHAR * szname)
{
DWORD dwSize;
TCHAR szHead[15];
BYTE * szTemp[1024];
HINTERNET hConnect;
FILE * pFile;
TCHAR szpathfilename [100] ;
szHead[0] = '\0';
if ( !(hConnect = InternetOpenUrl( hOpen, szURL, szHead, 15, INTERNET_FLAG_DONT_CACHE, 0)))
{
std::cout << "Error: InternetOpenUrl" << std::endl;
return 0;
}
determinepathfilename (szURL, szpath, szname, szpathfilename);
if ( !(pFile = _tfopen (szpathfilename, _T("wb") ) ) )
{
std::cerr << "Error _tfopen" << std::endl;
return false;
}
do
{
// Keep copying in 1024 bytes chunks, while file has any data left.
// Note: bigger buffer will greatly improve performance.
if (!InternetReadFile (hConnect, szTemp, 1024, &dwSize) )
{
fclose (pFile);
std::cerr << "Error InternetReadFile" << std::endl;
return FALSE;
}
if (!dwSize)
break; // Condition of dwSize=0 indicate EOF. Stop.
else
fwrite(szTemp, sizeof (BYTE), dwSize , pFile);
} // do
while (TRUE);
fflush (pFile);
fclose (pFile);
return TRUE;
}
int DownloadURLImage (TCHAR * szURL, TCHAR * szpath, TCHAR * szname)
{ int result ;
HINTERNET hInternet;
result= 0;
hInternet= InternetOpen (_T("imaged"),
INTERNET_OPEN_TYPE_DIRECT, //__in DWORD dwAccessType
NULL, //__in LPCTSTR lpszProxyName,
NULL, //__in LPCTSTR lpszProxyBypass,
NULL //_in DWORD dwFlags
);
GetFile (hInternet, szURL, szpath, szname) ;
InternetCloseHandle(hInternet);
return result ;
}
int _tmain(int argc, _TCHAR* argv[])
{
if (argc == 2)
{
DownloadURLImage (argv[1], NULL, NULL);
//DownloadURLImage (argv[1], _T"C:/", NULL);
}
else if (argc == 3)
{
DownloadURLImage (argv[1], NULL, argv[2]);
//DownloadURLImage (argv[1], _T"C:/", argv[2]);
}
else
{
cout << "Usage: imaged <image URL>" << endl ;
}
system("pause") ;
return 0;
}
``` | How to download an image from an URL to a local dir? | [
"",
"c++",
"http",
"download",
""
] |
We all know the usual use of templates to design containers and we all know that you can do things with templates that will make your head spin.
When I first encoutered static polymorphism I was really struck on what you can do with templates. It's obvious that templates are useful for more than for designing containers. I bought Andrei's "Modern C+ Design" but sadly haven't yet found the time or concentration to read it but I'm sure it offers a wealth of brilliant uses of templates.
IMHO [this](https://stackoverflow.com/questions/731832/interview-question-ffn-n/733474#733474) is also a very clever use of templates.
What's the most ingenious use of templates you've ever encountered? | [boost's Spirit](http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/quick_start.html) meta programming for creating a parser's grammar. | [Boost's `foreach` explained by its author.](http://www.artima.com/cppsource/foreach.html) | What's the most brilliant use of templates you've ever encountered? | [
"",
"c++",
"templates",
""
] |
I am taking on a project where all the Exceptions have been placed in a separate package `com.myco.myproj.exceptions`.
Is this good practice? | I would expect the exceptions for a package to exist within that package. e.g.
```
com.oopsconsultancy.models.pricing
```
would contain pricing models and related exceptions. Anything else seems a bit counter-intuitive. | It is a bad practice.
It is a coincidental grouping. Packages should be coherent. Don't group exceptions, interfaces, enum, abstract classes, etc., into their own package. Group related concepts instead. | Should Exceptions be placed in a separate package? | [
"",
"java",
"exception",
""
] |
I'm trying to use this code:
```
var field="myField";
vals[x]=document.myForm.field.value;
```
In the html code I have
```
<form name="myForm">
<input type='radio' name='myField' value='123' /> 123
<input type='radio' name='myField' value='xyz' /> xyz
</form>
```
But this gives me the error:
```
document.myForm.field is undefined
```
How can I get `field` to be treated as a variable rather than a field? | Assuming that your other syntax is correct (I havne't checked), this will do what you want:
```
var field="myField";
vals[x]=document.myForm[field].value;
```
In JS, the bracket operator is a get-property-by-name accessor. You can read more about it [here](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Member_Operators). | Use the elements[] collection
```
document.forms['myForm'].elements[field]
```
[elements collection in DOM spec](http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-40002357)
BTW. If you have two fields with the same name, to get the value of any field, you have to read from:
```
var value = document.forms['myForm'].elements[field][index_of_field].value
```
eg.
```
var value = document.forms['myForm'].elements[field][0].value
```
and, if you want to get value of selected radio-button you have to check which one is selected
```
var e = document.forms['myForm'].elements[field];
var val = e[0].checked ? e[0].value : e[1].checked ? e[1].value : null;
``` | How to parse a variable in Javascript | [
"",
"javascript",
"jquery",
""
] |
How can one easily iterate through all nodes in a TreeView, examine their .Checked property and then delete all checked nodes?
It seems straightforward, but you aren't supposed to modify a collection through which you are iterating, eliminating the possibility of a "foreach" loop. (The .Nodes.Remove call is modifying the collection.) If this is attempted, the effect is that only about half of the .Checked nodes are removed.
Even if one were to use two passes: first creating a list of temporary indexes, and then removing by index on the second pass -- the indexes would change upon each removal, invaliding the integrity of the index list.
So, what is the most efficient way to do this?
Here is an example of code that looks good, but actually only removes about half of the .Checked nodes.:
```
foreach (TreeNode parent in treeView.Nodes)
{
if (parent.Checked)
{
treeView.Nodes.Remove(parent);
}
else
{
foreach (TreeNode child in parent.Nodes)
{
if (child.Checked) parent.Nodes.Remove(child);
}
}
}
```
(Yes, the intention is only to prune nodes from a tree that is two levels deep.) | This will remove the nodes after enumerating them, and can be used recursively for n-tiers of nodes.
```
void RemoveCheckedNodes(TreeNodeCollection nodes)
{
List<TreeNode> checkedNodes = new List<TreeNode>();
foreach (TreeNode node in nodes)
{
if (node.Checked)
{
checkedNodes.Add(node);
}
else
{
RemoveCheckedNodes(nodes.ChildNodes);
}
}
foreach (TreeNode checkedNode in checkedNodes)
{
nodes.Remove(checkedNode);
}
}
``` | Try walking through the nodes backwards. That way your index doesn't increase past your node size:
```
for( int ndx = nodes.Count; ndx > 0; ndx--)
{
TreeNode node = nodes[ndx-1];
if (node.Checked)
{
nodes.Remove(node);
}
// Recurse through the child nodes...
}
``` | How to Efficiently Delete Checked Items from a TreeView? | [
"",
"c#",
".net",
"winforms",
"treeview",
"iteration",
""
] |
I am working on a project where I have to find out the keyword density of thepage on the basis of URL of that page. I googled a lot but no help and scripts were found, I found a paid tool <http://www.selfseo.com/store/_catalog/php_scripts/_keyword_density_checker_php_script>
But I am not aware actually what "keyword Density of a page" actually means? and also please tell me how can we create a PHP script which will fetch the keyword density of a web page.
Thanks | "Keyword density" is simply the frequency that the word occurs given as a percentage of the total number of words. The following PHP code will output the density of each word in a string, `$str`. It demonstrates that keyword density is not a complex calculation, it can be done in a few lines of PHP:
```
<?php
$str = "I am working on a project where I have to find out the keyword density of the page on the basis of URL of that page. But I am not aware actually what \"keyword Density of a page\" actually means? and also please tell me how can we create a PHP script which will fetch the keyword density of a web page.";
// str_word_count($str,1) - returns an array containing all the words found inside the string
$words = str_word_count(strtolower($str),1);
$numWords = count($words);
// array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
$word_count = (array_count_values($words));
arsort($word_count);
foreach ($word_count as $key=>$val) {
echo "$key = $val. Density: ".number_format(($val/$numWords)*100)."%<br/>\n";
}
?>
```
Example output:
```
of = 5. Density: 8%
a = 4. Density: 7%
density = 3. Density: 5%
page = 3. Density: 5%
...
```
To fetch the content of a webpage you can use [file\_get\_contents](http://php.net/manual/en/function.file-get-contents.php) (or [cURL](http://php.net/manual/en/book.curl.php)). As an example, the following PHP code lists all keywords above 1% density on this webpage:
```
<?php
$str = strip_tags(file_get_contents("http://stackoverflow.com/questions/819166"));
$words = str_word_count(strtolower($str),1);
$word_count = array_count_values($words);
foreach ($word_count as $key=>$val) {
$density = ($val/count($words))*100;
if ($density > 1)
echo "$key - COUNT: $val, DENSITY: ".number_format($density,2)."%<br/>\n";
}
?>
```
I hope this helps. | Or you can try this: <http://code.eyecatch-up.de/?p=155>
**Update:** Relocated the class to <http://code.google.com/p/php-class-keyword-density-check/>
```
<?php
include 'class/class.keywordDensity.php'; // Include class
$obj = new KD(); // New instance
$obj->domain = 'http://code.eyecatch-up.de'; // Define Domain
print_r ($obj->result());
?>
```
above code returns:
```
Array
(
[0] => Array
(
[total words] => 231
)
[1] => Array
(
[keyword] => display
[count] => 14
[percent] => 6.06
)
and so on...
```
works with local and remote files. | What is Keyword Density and how to create a script in PHP? | [
"",
"php",
"seo",
"keyword",
""
] |
Now unfortunately due to the fact that WinCE Usb Device Arrival / Removal exposes itself via WindowsMessages I have to ensure that a certain (non-UI) component is **not** created on a background thread. I would like to assert this via an exception but am lacking the code for the assertion.
This component creates a MessageWindow\* and uses it to receive usb arrived/removed messages. The issue is if someone creates this component on a background thread (not necessarily; IsBackground = true) when the thread exits the window will be destroyed.
Any ideas?
\*as an aside I *still* don't know why Form doesn't inherit from this class
**Update**
I think my version 1 wasn't very clear. So this is v2.
When you create a MessageWindow or a Form for that matter on a thread, when that thread exits the Window/Form is destroyed.
My component is creating a "hidden" message window to intercept some important events, ergo I do not wish for it to be destroyed. Therefore I must somehow ensure that the code that creates the form is running on the "Main UI" thread.
If possible i'd like to avoid passing down a reference to the "main" form to this component as it is (architecturally speaking) supposed to be miles away from the UI.
**Update**
Moving logging question to a separate Q. | Ok, I understand that you don't want for your component to "know" about the main window -- makes sense.
How about this: How about if you make sure that you always instance your component on the main thread? You component will create it's listener window on the constructor's thread.
If you do that, then you just need to make sure that you call the constructor from the main thread. I'm making some assumptions about your code, but I'm guessing that you must have some class in your architecture that knows about both the UI and your component. Create your component there, using a callback, and the main form's InvokeRequired/Invoke methods. | In forms, you use the [InvokeRequired](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx) property. | How can you tell if you're on the Main UI thread? (In CF) | [
"",
"c#",
".net",
"compact-framework",
""
] |
Does anyone have any advice for migrating a PowerBuilder 10 business application to .NET?
My company is considering migrating a legacy PB application to .NET (C#) and I am just wondering if anyone has any experience - good or bad - that you would like to share.
The application is rather large with 10 PBL libraries, some PFC as well as custom frameworks. There are a large number of DLL calls being made as well. Finally, it uses a Microsoft SQL Server database.
We have discussed porting the "core" application code to .NET and then porting more advanced functionality across as-needed. | When I saw the title, I was just going to lurk, being a renowned PB bigot. Oh well. Thanks for the vote of confidence, Bernard.
My first suggestion would be to ditch the language of self-deception. If I eat half of a "lite" cheesecake, I'm still going to lose sight of my belt. A migration can take as little as 10 minutes. What you'll be doing is a *rewrite*. The **time** needs to be measured as a rewrite. The **risk** needs to be measured as a rewrite. And the **design effort** should be measured as a rewrite.
Yes, I said design effort. "Migrate" conjures up images of pumping code through some black box with a translation mirroring the original coming out the other side. Do you want to replicate the same design mistakes that were made back in 1994 that you've been *living with* for years? Even with excellent quality code, I'd guess that excellent design choices in PowerBuilder may be awful design choices in C#. Does a straight conversion neglect the power and strengths of the platform? Will you be *living with* the consequences of neglecting a good C# design for the next 15 years?
---
That rant aside, since you don't mention your motivation for moving "to .NET," it's hard to suggest what options you might have to mitigate the risk of a rewrite. If your management has simply decided that PowerBuilder developers smell bad and need to be expunged from the office, then good luck on the rewrite.
If you simply want to deploy Windows Forms, Web Forms, Assemblies or .NET web services, or to leverage the .NET libraries, then as Paul mentioned, moving to 11.0 or 11.5 could get you there, with an effort closer to a migration. (I'd suggest again reviewing and making sure you've got a good design for the new platform, particularly with Web Forms, but that effort should be significantly smaller than a rewrite.) If you want to deploy a WPF application, I know a year is quite a while to wait, but looking into PowerBuilder 12 might be worth the effort. Pulled off correctly, the WPF capability may put PowerBuilder into a unique and powerful position.
If a rewrite is guaranteed to be in your future (showers seem cheaper), you might want to phase the conversion. DataWindow.NET makes it possible to to take your DataWindows with you. (My pet theory of the week is that PowerBuilder developers take the DataWindow for granted until they have to reproduce all the functionality that comes built in.) Being able to drop in pre-existing, pre-tested, multi-row, scrollable, minimal resource consuming, printable, data-bound dynamic UI, generating minimal SQL with built-in logical record locking and database error conversion to events, into a new application is a big leg up.
You can also phase the transition by converting your PowerBuilder code to something that is consumable by a .NET application. As mentioned, you can produce COM objects with the PB 10 you've got, but will have to move to 11.0 or 11.5 to produce assemblies. The value of this may depend on how well partitioned your application is. If your business logic snakes through GUI events and functions instead of being partitioned out to non-visual objects (aka custom classes), the value of this may be questionable. Still, this is a design *faux pas* that should probably be fixed before a full conversion to C#; this is something that can be done while still maintaining the PowerBuilder application as a preliminary step to a phased and then a full conversion.
No doubt I'd rather see you stay with PowerBuilder. Failing that, I'd like to see you succeed. Just remember, once you take that first bite, [you'll have to finish it](http://www.supersizedmeals.com/food/images/articles/20061215-Heart_Attack_Grill_2.jpg).
Good luck finding that belt,
Terry.
---
I see you've mentioned moving "core components" to .NET to start. As you might guess by now, I think a staged approach is a wise decision. Now the definition of "core" may be debatable, but how about a contrary point of view. Food for thought? (Obviously, this was the wrong week to start a diet.) Based on where PB is right now, it would be hard to divide your application between PB and C# along application functionality (e.g. Accounts Receivable in PB, Accounts Payable in C#). A division that may work is GUI vs business logic. As mentioned before, pumping business logic out of PB into executables C# can consume is already possible. How about building the GUI in C#, with the DataWindows copied from PB and the business logic pumped out as COM objects or assemblies? Going the other way, to consume .NET assemblies in PB, you'll either have to move up to 11.x and migrate to Windows Forms, or put them in a [COM callable wrapper](http://pbdj.sys-con.com/node/258395).
Or, just train your C# developers in PowerBuilder. This just may be a rumour, but I hear the new PowerBuilder marketing tag line will be "So simple, even a C# developer can use it." ;-) | I think gbjbaanb gave you a good answer above.
Some other questions worth considering:
* Is this PB10 app a new, well-written PB10 app, or was it one made in 1998 in PB4, then gradually converted to PB10 over the years? A well-written app should have some decent segregation between the business logic and the GUI, and you should be able to systematically port your code to .Net. At least, it should be a lot easier than if this is a legacy PB app, in which case it would be likely that you'd have tons of logic buried in buttons, datawindows, menus, and who knows what else. Not impossible, but more difficult to rework.
* How well is the app running? If it's OK and stable, and doesn't need a lot of new features, then maybe it doesn't need rewriting. Or, as gbjbaanb said, you can put .Net wrappers around some pieces and then expose the functionality you need without a full rewrite. If, on the other hand, your app is cantankerous, nasty, not really satisfying business needs, and is making your users inefficient, then you might have a case for rewriting, or perhaps some serious refactoring and then some enhancements. There are PB guys serving sentences, er, I mean, making a living with the second scenario.
I'm not against rewrites if the software is exceedingly poor and is negatively affecting the company's business, but even then gradual adjustments and improvements are a less risky way to achieve system evolution.
Also, don't bail on this thread until after Terry Voth posts. He's on StackOverflow and is one of the top PB guys. | Porting a PowerBuilder Application to .NET | [
"",
"c#",
".net",
"migration",
"powerbuilder",
"powerbuilder-conversion",
""
] |
In JavaScript, why does `isNaN(" ")` evaluate to `false`, but `isNaN(" x")` evaluate to `true`?
I’m performing numerical operations on a text input field, and I’m checking if the field is `null`, `""`, or `NaN`. When someone types a handful of spaces into the field, my validation fails on all three, and I’m confused as to why it gets past the `isNaN` check. | JavaScript interprets an empty string as a 0, which then fails the isNAN test. You can use parseInt on the string first which won't convert the empty string to 0. The result should then fail isNAN. | You may find this surprising or maybe not, but here is some test code to show you the wackyness of the JavaScript engine.
```
document.write(isNaN("")) // false
document.write(isNaN(" ")) // false
document.write(isNaN(0)) // false
document.write(isNaN(null)) // false
document.write(isNaN(false)) // false
document.write("" == false) // true
document.write("" == 0) // true
document.write(" " == 0) // true
document.write(" " == false) // true
document.write(0 == false) // true
document.write(" " == "") // false
```
so this means that
```
" " == 0 == false
```
and
```
"" == 0 == false
```
but
```
"" != " "
```
Have fun :) | Why does isNaN(" ") (string with spaces) equal false? | [
"",
"javascript",
"nan",
""
] |
After getting an answer from this thread, it would save me alot of retyping if any readers could refer to it: [link text](https://stackoverflow.com/questions/702448/timezone-functions-help)
I find that I need to update(within a mysql db) a timezone code, singularly (e.g 10+, 1-, etc) to olsen code (e.g "Europe/London", etc) according to what already exists within the user\_timezone column. What would be the easiest what to go about that?
Any ideas would be very appreciated. | Given that a timezone offset (e.g. UTC+2) may correspond to many entries in the Olson database (e.g. Europe/Sofia, Europe/Riga, Africa/Cairo, etc.) you have to choose beforehand the offset-to-Olson-code correspondence.
Create a table describing those correspondences and then use it to build you update statement. | Unfortunately you've no way of knowing which zone a user is in from the UTC offset. If you take a look at [Wikipedia's list of timezones](http://en.wikipedia.org/wiki/List_of_zoneinfo_time_zones), you'll notice that many zones share the same time offset, e.g. Europe/Sarajevo and Europe/Brussels | Large MySQL Update Query | [
"",
"php",
"mysql",
""
] |
I'm attempting my first google app engine project – a simple player stats database for a sports team I'm involved with. Given this model:
```
class Player(db.Model):
""" Represents a player in the club. """
first_name = db.StringProperty()
surname = db.StringProperty()
gender = db.StringProperty()
```
I want to make a basic web interface for creating and modifying players. My code structure looks something like this:
```
class PlayersPage(webapp.RequestHandler):
def get(self):
# Get all the current players, and store the list.
# We need to store the list so that we can update
# if necessary in post().
self.shown_players = list(Player.all())
# omitted: html-building using django template
```
This code produces a very basic HTML page consisting of a form and a table. The table has one row for each Player, looking like something like this:
```
<tr>
<td><input type=text name="first_name0" value="Test"></td>
<td><input type=text name="surname0" value="Guy"></td>
<td><select name="gender0">
<option value="Male" selected>Male</option>
<option value="Female" >Female</option>
</select></td>
</tr>
<!-- next row: first_name1, etc. -->
```
My idea is that I would store the Player instances that I used in self.shown\_players, so that I could later update Players if necessary in my `post()` method (of the same class) by doing:
```
def post(self):
# some code skipped
for i, player in enumerate(self.shown_players):
fn = self.request.get('first_name'+str(i)).strip()
sn = self.request.get('surname'+str(i)).strip()
gd = self.request.get('gender'+str(i)).strip()
if any([fn != player.first_name,
sn != player.surname,
gd != player.gender]):
player.first_name = fn
player.surname = sn
player.gender = gd
player.put()
```
However, this doesn't work because `self.shown_players` does not exist when the `post()` method is called. I guess the app engine creates a new instance of the class every time the page is accessed.
I experimented with the same idea but putting `shown_players` at the class or module level (and calling it `global`) but this didn't work for reasons that I cannot divine.
For example:
```
shown_players = []
class PlayersPage(webapp.RequestHandler):
def get(self):
# Get all the current players, and store the list.
# We need to store the list so that we can update
# if necessary in post().
global shown_players
shown_players[:] = list(Player.all())
```
`shown_players` appears to have the right value within `get()` because the HTML generates correctly, but it is empty within `post()`.
What should I do?
EDIT: Thanks, all. The answer ("Just retrieve the players again!") should have been obvious :-) Maybe I'll look at memcache one day, but I'm not expecting the player list to get beyond 30 in the near future.. | On each request you are working on a new instance of the same class. That's why you can't create a varable in `get()` and use its value in `post()`. What you could do is either retrieve the values again in your `post()`-method or store the data in the `memcache`.
Refer to the documentation of memcache here:
<http://code.google.com/intl/de-DE/appengine/docs/python/memcache/> | In your post method, just before the "for" clause, retrieve the players list from where it is stored:
```
def post(self):
# some code skipped
self.shown_players = Player.all().fetch()
for i, player in enumerate(self.shown_players):
...
``` | Updating data in google app engine | [
"",
"python",
"google-app-engine",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.