Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Perhaps someone can point me in the correct direction, because I'm completely stumped on this.
I have a function that simply prints out a LinkedList of classes:
```
LinkedList<Component> components = new LinkedList<Component>();
...
private void PrintComponentList()
{
Console.WriteLine("---Component List: " + components.Count + " entries---");
foreach (Component c in components)
{
Console.WriteLine(c);
}
Console.WriteLine("------");
}
```
The `Component` object actually has a custom `ToString()` call as such:
```
int Id;
...
public override String ToString()
{
return GetType() + ": " + Id;
}
```
This function typically works fine - however I've run into the issue that when it builds to about 30 or so entries in the list, the `PrintcomplentList` `foreach` statement comes back with an `InvalidOperationException: Collection was modified after the enumerator was instantiated.`
Now as you can see I'm not modifying the code within the for loop, and I haven't explicitly created any threads, although this is within an XNA environment (if it matters). It should be noted that the printout is frequent enough that the Console output is slowing down the program as a whole.
I'm completely stumped, has anyone else out there run into this? | I suspect the place to start looking will be at any places where you manipulate the list - i.e. insert/remove/re-assign items. My suspicion is that there will be a callback/even-handler somewhere that is getting fired asynchronously (perhaps as part of the XNA *paint* etc loops), and which is editing the list - essentially causing this problem as a race condition.
To check if this is the case, put some debug/trace output around the places that manipulate the list, and see if it ever (and in particular, just before the exception) runs the manipulation code at the same time as your console output:
```
private void SomeCallback()
{
Console.WriteLine("---Adding foo"); // temp investigation code; remove
components.AddLast(foo);
Console.WriteLine("---Added foo"); // temp investigation code; remove
}
```
Unfortunately, such things are often a pain to debug, as changing the code to investigate it often changes the problem (a [Heisenbug](http://en.wikipedia.org/wiki/Unusual_software_bug)).
One answer would be to synchronize access; i.e. in **all** the places that edit the list, use a `lock` around the complete operation:
```
LinkedList<Component> components = new LinkedList<Component>();
readonly object syncLock = new object();
...
private void PrintComponentList()
{
lock(syncLock)
{ // take lock before first use (.Count), covering the foreach
Console.WriteLine("---Component List: " + components.Count
+ " entries---");
foreach (Component c in components)
{
Console.WriteLine(c);
}
Console.WriteLine("------");
} // release lock
}
```
and in your callback (or whatever)
```
private void SomeCallback()
{
lock(syncLock)
{
components.AddLast(foo);
}
}
```
In particular, a "complete operation" might include:
* check the count **and** `foreach`/`for`
* check for existance **and** insert/remove
* etc
(i.e. not the individual/discrete operations - but units of work) | Instead of `foreach`, I use `while( collection.count >0)` then use `collection[i]`. | Strange "Collection was modified after the enumerator was instantiated" exception | [
"",
"c#",
"enumeration",
""
] |
I'm using Mercurial for development of quite a large C++ project which takes about 30 minutes to get built from the scratch(while incremental builds are very quick).
I'm usually trying to implement each new feature in the new branch(using "hg clone") and I may have several new features developed during the day and it's quickly getting very boring to wait for the new feature branch to get built.
Are there any recipes to somehow re-use object files from other already built branches?
P.S. in git there are named branches within the same repository which make re-usage of the existing object files possible for the build system, however I prefer the simpler Mercurial separate branches model... | My [Localbranch extension](https://www.mercurial-scm.org/wiki/LocalbranchExtension) was designed partly around this use case. It uses a single working directory, but I think it's simpler than git. It's essentially a mechanism for maintaining multiple repository clones under one working directory, where only one is active at a given time. | I suggest using [ccache](http://ccache.samba.org/ "ccache") as a way to speed up compilation of (mostly) the same code tree. The way it works is as following:
* You define a place to be used as the cache (and the maximum cache size) by using the `CCACHE_DIR` environment variable
* Your compiler should be set to `ccache ${CC}` or `ccache ${CXX}`
ccache takes the output of `${CC} -E` and the compilation flags and uses that as a base for its hash. As long as the compiler flags, source file and the headers are all unchanged, the object file will be taken from cache, saving valuable compilation time.
Note that this method speeds up compilation of any source file that eventually produces the same hash. If you share source files across projects, ccache will handle them as well.
If you already use `distcc` and wish to use it with ccache, set the `CCACHE_PREFIX` environment variable to `distcc`.
Using ccache sped up our source tree compilation around tenfold. | Avoiding unneccessry recompilations using "branchy" development model | [
"",
"c++",
"mercurial",
""
] |
I am writing a Scheme-like in interpreter. It seems natural that the Scheme-like interpreter ought to work well with any object that implements IEnumerable.
The interpreter does not allow for mutation - no functions with side effects are exposed.
Because IEnumerable is not cloneable, (see [here](https://stackoverflow.com/questions/807991/why-cant-ienumerators-be-cloned) ), I can't implement iteration over the list efficiently using car and cdr.
In order to allow any "higher order" stuff to be efficient then, I've had to implement some primitives as C# builtins for the interpreter.
So far I have implemented the following "primitives" as C# builtin functions:
1. filter
2. map (the full map, not just mapcar)
3. foldr
But I suspect, for example, that I could probably implement "filter" using a combination of map and foldr.
What is the minimal set of primitives I would need to expose as "builtins" such that I can implement any other functionality over IEnumerable instances without excess runtime or space costs, and without having to introduce mutation? | All the functions are already there for you in the System.Linq namespace.
1. filter = Where
2. map = Select
3. fold/reduce = Aggregate (foldr = Reverse then Aggregate)
You will find many more. Eg
SelectMany = map + map + flatten
GroupBy = partition
remq and friends can be done in terms of filter.
**Update**
These obviously only take 1 single list argument, unlike the normal Scheme definitions. | You don't strictly need `map` to be a primitive as you can define it in terms of `foldr`.
Example (in Haskell):
```
map f = foldr (\a b->f a:b) []
```
This is really `mapcar` not `map`, but full `map` is difficult to express in Haskell as `apply` is not available.
More complete example (in Scheme):
```
(define (mapcar f l)
(foldr (lambda (x t) (cons (f x) t)) ‛() l))
(define (heads ls) (mapcar car ls))
(define (tails ls) (mapcar cdr ls))
(define (any-null? ls) (foldr or? ﹟f (mapcar null? ls)))
(define (map f . ls)
(if (any-null? ls)
‛()
(cons (apply f (heads ls)) (apply map f (tails ls)))))
```
And if you don't have `car` and `cdr` there are other ways to define them, e.g. if you have closures & variables in your language:
```
(define (car a) (foldr (lambda (x y) x) ﹟f a))
(define (cdr a)
(let ((prev ‛())
(tmp #f))
(foldr (lambda (h t) (set! tmp (cons h t)) (set! prev t) tmp)
‛()
a)
prev))
``` | What's the minimal set of sequence "primitives" required for any sequence computations? | [
"",
"c#",
"functional-programming",
"scheme",
""
] |
I'm using a MS namespace but Visual Studio is telling me I don't have a reference to it. Is there a place you can go to and lookup namespaces?
Thanks | If you mean "to find which dll I need (per-type)": [MSDN](http://msdn.microsoft.com/en-us/library/ms229335.aspx)?
For example, [`CLSID`](http://msdn.microsoft.com/en-us/library/microsoft.aspnet.snapin.clsid.aspx)
> **Namespace:** Microsoft.Aspnet.Snapin
>
> **Assembly:** AspNetMMCExt (in AspNetMMCExt.dll) | You can normally find the MSDN page about a specific namespace by going to <http://msdn.microsoft.com/>*namespace*. So, for example, to find out about System.Web you could go to...
<http://msdn.microsoft.com/system.web>
That in itself doesn't help you. You'll need to click through from there to the specific types you're using, and it'll tell you (near the top) the name of the DLL that implements the type.
Remember that a namespace can contain types that are defined in more than one DLL. | c# Where can I lookup Microsoft Namespace names? | [
"",
"c#",
"namespaces",
""
] |
We have a particular Vista x64 machine that, when running our C# WinForms app, displays the following error:
> System.EntryPointNotFoundException:
> Unable to find an entry point named
> 'TaskDialogIndirect' in DLL
> 'ComCtl32'.
This same code works fine on other Vista machines. For some reason, this particular Vista machine always throws this exception.
How can we fix this? | I had problems with this and Naughter's free [XTaskDialog API](http://www.naughter.com/xtaskdialog.html), to get a fallback mechanism on Windows XP machines via emulation, rendering this dialog implementation much more useful. :)
In my case it was an activation context issue, as mentioned in this [blog entry](http://sharpmix.net/blog/2009/06/23/unable-to-find-an-entry-point-name-taskdialogindirect-in-dll-comctl32-dll/).
Or, quoted here, in case the blog post is lost in cyberspace some day (applies to Visual Studio):
1. Open your project properties in the Solution Explorer,
2. On the Security tab, check Enable ClickOnce Security Settings,
3. Now you can see appearing the app.manifest file in the Properties folder of your solution, open it,
4. Beneath the </trustInfo> tag, insert the code below.
5. If you try to build, there may be an error. To fix it, uncheck the Enable ClickOnce Security Settings.
The code to insert in step 4:
```
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls"
version="6.0.0.0" processorArchitecture="*"
publicKeyToken="6595b64144ccf1df" language="*" />
</dependentAssembly>
</dependency>
``` | I would suggest comparing the version of comctl32.dll on the working and non-working Vista machines -- and comparing their checksums even if they report the same version.
Other things to check:
* Is it possible that the non-working machine has a pre-release version of Vista?
* Is it possible that a non-Vista version of comctl32.dll has been copied onto the machine and is being picked up by the application? (The Depends utility that comes with Visual Studio may help here.)
* Is it possible that a virus or worm (or what not) has replaced the comctl32.dll?
It might also be worth reading this [article](http://msdn.microsoft.com/en-us/library/aa374153(VS.85).aspx) on activation contexts. | Unable to find an entry point named 'TaskDialogIndirect' in DLL 'ComCtl32' | [
"",
"c#",
"windows-vista",
"pinvoke",
""
] |
I need a stack structure that also allows the for the deleting of elements. I can't find anything like this in the .Net framework. Which structure provides the best basis for me to implement this? | I would use a LinkedList as it has methods for AddFirst (Push) and RemoveFirst (Pop). But then it also has a simple Remove method that can be used to remove in middle. | Maybe a `LinkedList<T>`? you'd have to wrap it yourself to treat it as a `Stack<T>`, though. Of course, you could just use `List<T>` - but you'd have to absorb the cost of deleting from the middle...
Something like:
```
using System;
using System.Collections.Generic;
class MyStack<T> {
private readonly LinkedList<T> list = new LinkedList<T>();
public void Push(T value) {
list.AddLast(value);
}
public int Count { get { return list.Count; } }
public T Pop() {
LinkedListNode<T> node = list.Last;
if(node == null) throw new InvalidOperationException();
list.RemoveLast();
return node.Value;
}
public bool Remove(T item) {
return list.Remove(item);
}
}
```
with whatever other methods / synchronization / etc you need. | C# Stack with deletable elements | [
"",
"c#",
".net",
"data-structures",
""
] |
I'm an ex Pascal guy, currently learning C#.
My question is the following:
Is the code below faster than making a switch?
```
int a = 5;
if (a == 1)
{
....
}
else if(a == 2)
{
....
}
else if(a == 3)
{
....
}
else if(a == 4)
{
....
}
else
....
```
And the switch:
```
int a = 5;
switch(a)
{
case 1:
...
break;
case 2:
...
break;
case 3:
...
break;
case 4:
...
break;
default:
...
break;
}
```
Which one is faster?
I'm asking, because my program has a similar structure (many, many "else if" statements).
Should I turn them into switches? | For just a few items, the difference is small. If you have many items you should definitely use a switch.
If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first. | Why do you care?
99.99% of the time, you shouldn't care.
These sorts of micro-optimizations are unlikely to affect the performance of your code.
Also, if you NEEDED to care, then you should be doing performance profiling on your code. In which case finding out the performance difference between a switch case and an if-else block would be trivial.
**Edit:** For clarity's sake: implement whichever design is clearer and more maintainable. Generally when faced with a huge switch-case or if-else block the solution is to use polymorphism. Find the behavior that's changing and encapsulate it. I've had to deal with huge, ugly switch case code like this before and generally it's not that difficult to simplify. But oh so satisfying. | Is "else if" faster than "switch() case"? | [
"",
"c#",
"performance",
"if-statement",
"switch-statement",
""
] |
Further to this question: [Algorithm for determining a file’s identity](https://stackoverflow.com/questions/456175/algorithm-for-determining-a-files-identity)
**Recap**: I'm looking for a cheap algorithm for determining a files identity which works the vast majority of the time.
I went ahead and implemented an algorithm that gives me a "*pretty unique*" hash per file.
The way my algorithm works is:
* For files smaller than a certain threshold I use the full files content for the identity hash.
* For files larger than the threshold I take random N samples of X size.
* I include the filesize in the hashed data. (meaning all files with different sizes result in a different hash)
Questions:
* What values should I choose for N and X (how many random samples should I take of which size?) I went with 4 samples of 8K each and am not able to stump the algorithm. I found that increasing the amount of samples quickly decreases the speed of the algorithm (cause seeks are pretty expensive)
* The maths one: how non-different do my files need to be for this algorithm to blow up. (2 different files with same length end up having the same hash)
* The optimization one: Are there any ways I can optimize my concrete implementation to improve throughput (I seem to be able to do about 100 files a second on my system).
* Does this implementation look sane? Can you think of any real world examples where this will fail. (My focus is on media files)
Relevant information:
[The algorithm I implemented](http://gist.github.com/101591)
Thanks for your help! | * Always include 1st and last block of file in hash.
This is because they're most likely to be different from file to file. If you consider BMP, it may have fairly standard header (like 800x600 image, 24bit, null rest), so you may want to overshoot the header a bit to get to the differentiating data. The problem is that headers vary wildly in size.
Last block is for fileformats that append data to original.
* Read in blocks of size that is native to the filesystem you use, or at least divisible by 512.
* Always read blocks at offset that is divisible by blocksize.
* If you get same has for same sized file, do the deep scan of it (hash all data) and memorize filepath to not scan it again.
Even then unless you're lucky you will misidentify some files as same (for example SQL Server database file and it's 1:1 backup copy after only a few insertions; except that SS does write a timestamp..) | I would avoid an solution like this. I practice it might be close to imposible that two media files have the same size and the same data at coresponding positions for compressed formats. But if you have to deal with uncompressed images or wave files, chances that small local changes are not detected grow .
So I think you should realy hash the whole file. While this seems expensive it might not be if you have access to all the files - for example if you build a file server or something like that. You could build the hash incrementaly.
If you see a new file with an unique file length, just store the file length. If another file with the same length is added, calculate the hashes of both files block by block until they differ. Store the file length, the hash and how many blocks of the file are included in the hash. Whenever you detect matching file lengths and hashes and you have not yet hashed the whole file, you extend the hash by adding more blocks.
Some thoughts about the performance. For small files, the chances of equal file length is quite high - there are not so many diffrent small file lengths. But it is not expensive to hash small files.
For larger files the chances of file lenght collisons goes down as there are more and more possible file lengths. For diffrent media files the chances are very good that they differ directly beyond the header so you will need to hash only a short part of the begining of the file.
Finally you will be sure to detect diffrent files (except for hash collisions) because you will hash the whole file if required.
**UPDATE**
For movies I would consider the file length practical unique, but files recoded to fit on a given medium probably render this idea void - (S)VCD movies will all be in a small range of file lenghs of about CD-ROM capacity.
But for movie files in general, I would just hash one block (maybe 512 Byte) from the middle of the file. Two different movies with the same image and sound at the same position? Practicaly imposible besides you manipulate files to fail this test. But you could easily generate files to fail all deterministic sampling strategies - so this should not really matter. | Algorithm for determining a file’s identity (Optimisation) | [
"",
"c#",
"optimization",
"identity",
""
] |
My script is generating a very long URL just like the one below and I wonder how this can be shorten with an algorithm or technique?
This is the long URL:
<http://example.com/script.php?param1=value1¶m2=value2¶m3=value3¶m4=value4¶m5=value5>
I want to shorten it to something like this:
<http://example.com/script.php?p=430x2920>
How can I do this with out caching the original link the database?
Thanks in advance. | You could always just use a single param with a delimiter and then split it back out in code.
<http://example.com/script.php?p=1x2x3x4x5>
with x or whatever you want that isn't part of the possible values as a delimeter. | Add static values to the `$_SESSION[]`. | How can I shorten the URL query paramters? | [
"",
"php",
"friendly-url",
""
] |
I'm parsing a source code file, and I want to remove all line comments (i.e. starting with "//") and multi-line comments (i.e. /*....*/). However, if the multi-line comment has at least one line-break in it (\n), I want the output to have exactly one line break instead.
For example, the code:
```
qwe /* 123
456
789 */ asd
```
should turn exactly into:
```
qwe
asd
```
and not "qweasd" or:
```
qwe
asd
```
What would be the best way to do so?
Thanks
---
EDIT:
Example code for testing:
```
comments_test = "hello // comment\n"+\
"line 2 /* a comment */\n"+\
"line 3 /* a comment*/ /*comment*/\n"+\
"line 4 /* a comment\n"+\
"continuation of a comment*/ line 5\n"+\
"/* comment */line 6\n"+\
"line 7 /*********\n"+\
"********************\n"+\
"**************/\n"+\
"line ?? /*********\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"********************\n"+\
"**************/\n"+\
"line ??"
```
Expected results:
```
hello
line 2
line 3
line 4
line 5
line 6
line 7
line ??
line ??
``` | ```
comment_re = re.compile(
r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
re.DOTALL | re.MULTILINE
)
def comment_replacer(match):
start,mid,end = match.group(1,2,3)
if mid is None:
# single line comment
return ''
elif start is not None or end is not None:
# multi line comment at start or end of a line
return ''
elif '\n' in mid:
# multi line comment with line break
return '\n'
else:
# multi line comment without line break
return ' '
def remove_comments(text):
return comment_re.sub(comment_replacer, text)
```
* `(^)?` will match if the comment starts at the beginning of a line, as long as the `MULTILINE`-flag is used.
* `[^\S\n]` will match any whitespace character except newline. We don't want to match line breaks if the comment starts on it's own line.
* `/\*(.*?)\*/` will match a multi-line comment and capture the content. Lazy matching, so we don't match two or more comments. `DOTALL`-flag makes `.` match newlines.
* `//[^\n]` will match a single-line comment. Can't use `.` because of the `DOTALL`-flag.
* `($)?` will match if the comment stops at the end of a line, as long as the `MULTILINE`-flag is used.
Examples:
```
>>> s = ("qwe /* 123\n"
"456\n"
"789 */ asd /* 123 */ zxc\n"
"rty // fgh\n")
>>> print '"' + '"\n"'.join(
... remove_comments(s).splitlines()
... ) + '"'
"qwe"
"asd zxc"
"rty"
>>> comments_test = ("hello // comment\n"
... "line 2 /* a comment */\n"
... "line 3 /* a comment*/ /*comment*/\n"
... "line 4 /* a comment\n"
... "continuation of a comment*/ line 5\n"
... "/* comment */line 6\n"
... "line 7 /*********\n"
... "********************\n"
... "**************/\n"
... "line ?? /*********\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "********************\n"
... "**************/\n")
>>> print '"' + '"\n"'.join(
... remove_comments(comments_test).splitlines()
... ) + '"'
"hello"
"line 2"
"line 3 "
"line 4"
"line 5"
"line 6"
"line 7"
"line ??"
"line ??"
```
**Edits:**
* Updated to new specification.
* Added another example. | The fact that you have to even ask this question, and that the solutions given are, shall we say, less than perfectly readable :-) should be a good indication that REs are not the real answer to this question.
You would be far better, from a readability viewpoint, to actually code this up as a relatively simple parser.
Too often, people try to use REs to be "clever" (I don't mean that in a disparaging way), thinking that a single line is elegant, but all they end up with is an unmaintainable morass of characters. I'd rather have a fully commented 20-line solution that I can understand in an instant. | Python regex question: stripping multi-line comments but maintaining a line break | [
"",
"python",
"regex",
"parsing",
"comments",
""
] |
I would like to play with a larger database to test my knowledge on SQL.
Is there a huge .sql out there that I can use to play with SQL queries? | You could try the classic [MySQL world database](http://downloads.mysql.com/docs/world.sql.gz).
The world.sql file is available for download here:
<http://dev.mysql.com/doc/index-other.html>
Just scroll down to **Example Databases** and you will find it. | This is an online database but you can try with the stackoverflow database:
<https://data.stackexchange.com/stackoverflow/query/new>
You also can download its dumps here:
<https://archive.org/download/stackexchange> | Sample database for exercise | [
"",
"sql",
"test-data",
"sample-data",
""
] |
I'm loading some fairly big data sets in to firefox (500 k or so) and drawing tables with them. Firefox is using up to 400 megs of memory. How can I tell if Firefox is leaking memory, or is just using a lot of memory just because it can?
Is there another browser which will use less memory if it doesn't need it? I get the feeling that firefox grabs a bunch of memory for itself and doesn't release it unless it has to. It may be apparent that my understanding of memory management in general is very superficial. | There is a setting you can set in firefox that forces it to free as much memory as it can on minimise:
1. On the website url toolbar type
about:config
2. A page full of words
will come up. right click anywhere
and choose New -> Boolean
3. For the
name input type
"config.trim\_on\_minimize" Select
True
4. Restart FireFox. | > **Memory Leak** - memory which is not released when it should be
If the memory Firefox is allocating to hold your data is released when you navigate away from your page, there is no memory leak. You can than argue if Firefox if using too much memory or not, but that is something beyond your scope.
You do have a leak on your hands if that memory is not released. In that case you should check if it is something you can handle in your JS code, or a firefox bug. If it's the latter, go ahead to the mozilla bugzilla, and open a ticket. | Am I experiencing a memory leak, or just high memory usage in Firefox? | [
"",
"javascript",
"memory-leaks",
""
] |
With Linq To Sql - what is the best way to update the value of one table in a database when a value changes in a different table?
For example in TableA, there is a column called DateModified. TableA has an association to TableB. Now I want to set the value of the DateModified field to the current date every time the record changes in tableA AND everytime a child record is created/updated/deleted in TableB.
How can this be achieved? | If the change was just in the one record, you can use either the `On*Changed` partial methods, or you can override `SubmitChanges` on the data-context, call `GetChangeSet`, and apply the changes just before they are updated. The latter (data-context) approach is useful for catching a broad spectrum of changes, where-as the `On*Changed` approach is useful for logic specific to individual properties.
However, in the case presented (non-homogeneous updates), I expect a database trigger may be more appropriate. | You could register a PropertyChanged event handler on the child entity in OnCreated (implemented in a partial class) and have that handler update the parent property. If you don't care about the already loaded classes getting the change, using a DB trigger as @Marc suggests would also be an option.
**EDIT**: If you need to catch deletes as well, you can implement the delete partial method for the data context to call the same handler method to update the parent of the entity being deleted. | Linq To Sql - Update a value when another value changes | [
"",
"c#",
".net",
"asp.net",
"linq",
"linq-to-sql",
""
] |
I would like to do something like this:
```
<x:out select="$productXML/product/sizes/size[<c:out value='${param.sizeIndex}'/>]" escapeXml="false"/>
```
but I think the only way to do it is like this:
```
<x:forEach var="size" begin="${param.sizeIndex}" end="${param.sizeIndex+1}" select="$productXML/product/sizes/*">
<x:out select="$size" escapeXml="false"/>
</x:forEach>
```
Is there a way to do it more like the way I want to? | Thanks to GClaramunt [user 98867] putting me on the right tack, I discovered the correct answer:
```
<x:out select="$productXML/product/sizes/size[$param:sizeIndex]" escapeXml="false"/>
``` | Not sure what are you trying to solve, but are you sure you need the `<c:out value='${param.sizeIndex}'/>` inside the '[]' ? JSTL should be processed all at the same time, and you should be able to write something like:
```
<x:out select="$productXML/product/sizes/size[param.sizeIndex]" escapeXml="false"/>
```
Or maybe using `<c:set var="sIdx" value="${param.sizeIndex}" />`
But I'm not totally familiar with JSTL XML tags to be 100% sure... | Avoid looping xml in jstl | [
"",
"java",
"xml",
"jsp",
"jstl",
""
] |
I love using an IDE, because I get some great productivity gains. However, I have a couple reasons to stop using a mouse with an IDE:
1. To code faster - It definitely slows down my coding when my typing is interrupted with all of the constant point and clicking.
2. To relieve pain - I've never had pain from the keyboard, but I get tendinitis from the mouse.
I've got my cheat sheet for my IDE printed out and now I'm ready.
* What's the best way get off the mouse?
* Are there any hurdles that I'm going to run into?
* Are there any tips for specific IDEs (Visual Studio, Eclipse, etc.) ? | Move it to the wrong side (eg if you are right handed then put it on the left of the keyboard). That way, you can still use it if necessary, but you should find you aren't using it unecessarily.
If changing sides isn't enough to confuse your brain, then moving it to a place where it is accessible but you have to think before reaching for it. As long as you can't reach for the mouse without thinking about it, then you will find that it is easier to use keyboard shortcuts instead. Essentially you want the mouse to be an option but the keyboard to be a better/easier/more convenient one!
As for pitfalls, well you may find that if you have to test any interfaces (web based or dektop) that you need to revert back to using the mouse. Also I find that if I have to work outside of the IDE, then it is just not as efficient to do without the mouse. Often we use WOrd for specifications and documentation, and trying to get away with using that without a mouse, is tricky (in my experience).
Another potential source of annoyance, is when switching between applications (Eclipse, VS, etc), you find that they often use different keyboard shortcuts, and so it can take a while to get back up to speed again, or you have to spend some time reconfiguring the shortcuts to be consistent. | Unplug it.
If your mouse is completely gone then you will be forced to learn how to live without it and therefore will become productive without it. | How can I stop using a mouse while programming in my IDE? | [
"",
"java",
".net",
"visual-studio",
"eclipse",
"ide",
""
] |
I have this xml-file:
```
<objects>
<object>
<value>test</value>
</object>
<object>
<value>foo</value>
</object>
<object>
<value>bar</value>
</object>
</objects>
```
Now, I want to query this xml, and retrieve all the object-elements where the text in the value-element = "foo"
Is there a easy way of doing this?
I have tried something like this:
```
var objects = from e in xml.Elements("value")
where e.Value.Equals("foo", StringComparison.OrdinalIgnoreCase)
select e.parent;
```
That does not work.. | I think you're looking for
```
xml.Descendants("value")
```
xml.Elements() just returns child elements... if xml is your root XDocument, it wouldn't return anything. | You should use *xml.Descendants* assuming you are querying from the document root. Also, I'd prefer using *string.Equals* over the *Equals* method called off the string returned by the *Value* property of the element (only as a matter of preference.) For example:
```
var objects = from e in xml.Descendants("value")
where string.Equals(e.Value,
"foo",
StringComparison.OrdinalIgnoreCase)
select e.Parent;
``` | LinqToXML: Getting elements with given value | [
"",
"c#",
"linq",
"linq-to-xml",
""
] |
Using c# regex I'm trying to match things in quotes which aren't also in brackets while also ignoring any white space:
```
"blah" - match
("blah") - no match
( "blah") - no match
( "blah") - no match
```
I've got (unescaped):
```
"(?<=[^(]\s")(.*?)"
```
which works with the first three but I can't work out how to deal with more than one space between the first bracket and the quote. Using a + after the s is the same result, using a \* means both the last two match. Any ideas? | This should work:
```
/(?<![^(\s])\s*"([^"]*)"\s*(?![\s)])/
```
* The first `(?<![^(\s])` asserts that there is no whitespace or left parenthesis before the string.
* Then `\s*` will match any number of whitespace characters.
* `("[^"]*")` will match a quoted string, and capture it's content.
* `\s*` will match any number of whitespace characters.
* Last, `(?![\s)])` will assert that there is no whitespace or right-parenthesis following.
Together they make sure that all the whitespace is matched by each `\s*`, and that they are not bordering a parenthesis. | In PCRE as I know it, lookbehinds have to be fixed-width. If that remains true in C#'s PCRE engine, then you're not going to be able to do it the way you're trying to. | negative look behind with unknown number of spaces | [
"",
"c#",
"regex",
""
] |
I have a column in my table that has values of type FLOAT. How can I get the average value of all items in this column? | ```
select avg( columnname) from table;
```
This will average all rows. To average a subset, use a `where` clause. To average for each group (of something) use a `group by` clause. | ```
select avg(col1) from table;
``` | SQLite - how to get average value? | [
"",
"sql",
"sqlite",
""
] |
> Parse error: syntax error, unexpected $end in blah/blah/blah.php line 1
This is the error that I receive, with this code
```
<?php
include("db.php");
if (isset($_POST['username']) &&
isset($_POST['password']) &&
isset($_POST['email']))
{
//Prevent SQL injections
$username = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
//Get MD5 hash of password
$password = md5($_POST['password']);
//Check to see if username exists
$sql = mysql_query("SELECT username FROM usersystem WHERE username = 'username'");
if (mysql_num_rows($s > 0))
{
die ("Username taken.");
}
mysql_query("INSERT INTO usersystem (username, password, email) VALUES ( '$username', '$password', '$email')")
or die (mysql_error()); echo "Account created.";
}
?>
```
I've already checked for unclosed brackets, that's not the problem. Also by troubleshooting with it, I've discovered that the include("db.php"); is causing the problem. When I comment it out, It loads the page just fine. However even when db.php is completely blank, just an empty .php file it still gives me the same error. I'm perplexed. Anyone have any ideas?
here is my db.php file, but honestly when I make db.php completely blank I get the same error. And I am saving it correctly.
```
<?php
session_start();
mysql_connect("localhost", "mydatabase", "mypassword");
mysql_select_db("ratherda_jetpackfandango");
function user_login ($username, $password)
{
//take the username and prevent SQL injections
//$username = mysql_real_escape_string($username);
//begin the query
$sql = mysql_query("SELECT * FROM user WHERE username = 'username' AND password = 'password' LIMIT 1");
//check to see how many rows were returned
$rows = mysql_num_rows($sql);
if ($rows<=0 )
{
echo "Incorrect username/password";
}
else
{
//have them logged in
$_SESSION['username'] = $username;
}
}
?>
``` | You have a [session\_start](https://www.php.net/function.session-start) in db.php thats not allowed there. It should be the first line in blah.php.
```
<?php
session_start();
require_once("db.php");
``` | Post your db.php file, the problem is obviously in there. Unexpected $end errors are usually a result of a missing curly brace, so check that file. | PHP: Can't find syntax error | [
"",
"php",
"mysql",
"parsing",
""
] |
Forget fancy shmancy web stuff. I'm looking for a good .NET CLI argument processing utility, prefer open source code. This is for quick and dirty utilities that need robust and friendly command line argument handling.
These are utilities with maybe a day of effort in them. Investing a few days writing good command line handling seems overkill ... but they really need it.
Features I like in command line handlers. I'd be thrilled with any open source project that had 2 or 3 of the following.
* A consistent syntax, [posix had a nice command line standard](http://www.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap12.html#tag_12_02), but not necessarily posix.
* Ability to provide short names for agruments. E.g. "msbuild /t" == "msbuild /target"
* It *supports* good command line parsing then gets out of the way. I want some that my code uses, not something that imposes a pattern on my code e.g. I don't want to have to respond to the presence of an arg with an event, that type of thing.
* Seperation of concerns is good enough that it's logic can be unit tested.
* Oh - is it two much to ask for it to read attributes off a class properties (as in .NET configuration classes)?
* I like the config file overrides in msbuild. I can set properties in a build file, but override on the command line.
* Built in "show usage". [WSF](http://msdn.microsoft.com/en-us/library/15x4407c.aspx) files (csript.exe) have this functionality. I'm not willing to write jscript to get the command line handling though.
* Not powershell. I can't find anyone in my company who can stand Powershell syntax.
PS If I don't find such a thing, I'll probably drop one on google code in the next few weeks
PPS If I could add tags, I'd tag this "pleasesearchtheinternetforme" | *Also from codePlex, the [CommandLine](http://commandline.codeplex.com/) project seems to meet your requirements. A Liberal application of copy/paste from the projects home page gives ...*
The Command Line Parser Library offers to CLR applications a simple programming interface for manipulating command line input. This library allows you to display an help screen with a good degree of customization. The API keeps on its shoulders everything boring to code.
The Command Parser Library supports:
* Short options (-s, for example)
+ Option+Value/No space: -sHello
+ Option+Space+Value: -s Hello
* Short options like switches; no value required
+ Option+Space+Option+....... -s -x -y -z
+ Option+Option+Option+...: -sxyz...
+ Option+Option+Space/Any Comb.: -sx -yz
* Long options (--long, for example)
+ Option+Equal+Value: --long=Hello
+ Option+Space+Value: --long Hello
* Composed options (its about values)
+ any 1;2;3;4 (separator is configurable)
Common features
Both accepts values with spaces: -s"Hello World!" --long "Hello CLR!" | You should check out Mono.Options (<http://www.ndesk.org/Options>) since it is a lot more cross-platform friendly and used extensively in Mono itself. | Robust and friendly command line tools for .NET? | [
"",
"c#",
".net",
"vb.net",
"command-line",
"mono",
""
] |
I want to use a win-form in C# and display its contents or the whole form in a panel used in another form.
Lets say i have a form A with a panel Panel\_of\_A
and a form B with a panel Panel\_of\_B
I want to display contents of Panel\_of\_A into Panel\_of\_B or you may say i want to use Panel\_of\_A in another form.
Or you may provide help for displaying a form say A into a panel on form B.
Hope i made u understand my thoughts... | I think a better way for doing this is to create a User Control which contains that panel and (re)use it on both forms.
Here is a [tutorial how to create User Controls on MSDN](http://msdn.microsoft.com/en-us/library/aa302342.aspx). | Create a user control that contains the logic you want to replicate, then incude the new user control in both places. | Can we use a panel of some winform from another winform in C#? | [
"",
"c#",
"winforms",
"panel",
""
] |
I have a PHP module written in C++, which relies on a C++ library (Boost Date\_Time) being installed.
Currently, in my config.m4 file I'm checking for the library as follows:
```
LIBNAME=boost_date_time
LIBSYMBOL=_ZN5boost9gregorian9bad_monthD0Ev
PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,,
[
AC_MSG_ERROR([lib $LIBNAME not found. Try: sudo apt-get install libboost-dev])
],[
-lstdc++ -ldl
])
```
Now, this works in my current environment, but I'm painfully aware this will probably break on a different version of the library or compiler.
How can I get automake to understand the non-mangled C++ symbol?
Edit:
I realise that checking on the mangled name is horrible, but is there not some way of checking for the symbol name as returned by "nm -C" (eg boost::gregorian::bad\_month etc).
I found some refence to the automake command AC\_LANG\_CPLUSPLUS(), but I'm not sure how to use it and whether it's applicable here. | You can check `AC_TRY_COMPILE` with something like that:
```
LIBNAME=boost_date_time
AC_MSG_CHECKING([for BOOST])
AC_TRY_COMPILE(
[
#include "boost/date_time/gregorian/greg_month.hpp"
],
[
boost::gregorian::bad_month* bm = new boost::gregorian::bad_month;
],
[
AC_MSG_RESULT(yes)
],
[
AC_MSG_ERROR([lib $LIBNAME not found. Try: sudo apt-get install libboost-dev])
])
```
This avoid the use of unmangled symbol. | Outside of the environment of a particular C++ compiler, there is no "non-mangled C++ symbol" - the mangling is done precisely to provide a unique name to external tools, such as linkers and librarians. | How do I check for an unmangled C++ symbol when building a PHP extension? | [
"",
"c++",
"automake",
"php-extension",
"name-mangling",
""
] |
Python's `getattr()` method is useful when you don't know the name of a certain attribute in advance.
This functionality would also come in handy in templates, but I've never figured out a way to do it. Is there a built-in tag or non-built-in tag that can perform dynamic attribute lookups? | I also had to write this code as a custom template tag recently. To handle all look-up scenarios, it first does a standard attribute look-up, then tries to do a dictionary look-up, then tries a **getitem** lookup (for lists to work), then follows standard Django template behavior when an object is not found.
(updated 2009-08-26 to now handle list index lookups as well)
```
# app/templatetags/getattribute.py
import re
from django import template
from django.conf import settings
numeric_test = re.compile("^\d+$")
register = template.Library()
def getattribute(value, arg):
"""Gets an attribute of an object dynamically from a string name"""
if hasattr(value, str(arg)):
return getattr(value, arg)
elif hasattr(value, 'has_key') and value.has_key(arg):
return value[arg]
elif numeric_test.match(str(arg)) and len(value) > int(arg):
return value[int(arg)]
else:
return settings.TEMPLATE_STRING_IF_INVALID
register.filter('getattribute', getattribute)
```
Template usage:
```
{% load getattribute %}
{{ object|getattribute:dynamic_string_var }}
``` | I don't think so. But it wouldn't be too hard to write a [custom template tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/) to return an attribute in the context dict. If you're simply trying to return a string, try something like this:
```
class GetAttrNode(template.Node):
def __init__(self, attr_name):
self.attr_name = attr_name
def render(self, context):
try:
return context[self.attr_name]
except:
# (better yet, return an exception here)
return ''
@register.tag
def get_attr(parser, token):
return GetAttrNode(token)
```
Note that it's probably just as easy to do this in your view instead of in the template, unless this is a condition that is repeated often in your data. | Performing a getattr() style lookup in a django template | [
"",
"python",
"django",
"django-templates",
""
] |
I'm writing an C# App (WinForm) with a ListBox having content added by the user. Now, I could have a ordinary button under the ListBox to remove items, but I would like to have the button right next to the content, thus being inside of the ListBox.
Like this:
* Content 1 | X
* Content 2 | X
* ...
* Content 5 | X
The problem is that I lack experience in .NET so I have no clue on how this would be possible with all the automated controls going on. I've googled it, but came up with no meaningful results.
Any hints, clues or snippets for achieving this are welcome! :) | So one could make a custom control but for my app it isn't really worth the trouble.
What I did was to create a DataGrid, made it resemble a ListView but with its own flare. I did this because the DataGrid already has a buttoncontrol built in to its cells.
Yes I know, kind of fugly "hack", but it works like a charm! :)
Props to Shay Erlichmen who led me into thinking outsite my ListBox. See what I did there? ;) | Instead of ListBox you can use ListView, ListView has the [ability to add custom column types](http://www.codeproject.com/KB/list/ListViewEmbeddedControls.aspx). | C# - Adding Button inside ListBox | [
"",
"c#",
".net",
"listbox",
""
] |
How can you remove a class name and replace it with a new one?
```
<style>
.red {background-color: #FF0000;}
.green{background-color: #00FF00;}
.blue {background-color: #0000FF;}
</style>
<body class="red">
<ul>
<li><a href="">red</a></li>
<li><a href="">green</a></li>
<li><a href="">blue</a></li>
</ul>
</body>
```
In this case when you click on red or green or blue, the body class name will change accordingly. Also it will make a cookie which will save the choice.
I tried the jQuery .addClass and it's working, but it's adding a class on top of the existing one. Also I can't manage to save the cookie. | Use:
```
$('.red').removeClass('red').addClass('blue');
```
[Here's the full working code](http://jsbin.com/ugufi):
```
$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
return false;
});
});
```
And now for the cookie part
```
$(function() {
$("a").click(function() {
var color = $(this).text();
$("body").removeClass().addClass(color);
createCookie("color",color);
return false;
});
if (readCookie("color") != null) {
$("body").removeClass().addClass(readCookie("color"));
}
else {
$("body").removeClass().addClass("red");
}
});
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else
var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ')
c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
```
[Working example here](http://jsbin.com/usucu). A thank you to [QuirksMode](http://www.quirksmode.org/js/cookies.html) for the pre-made cookie code (cookie-cutter cookie code?) | Without jQuery you can do this with a line as simple as:
```
document.getElementsByTagName("body")[0].className = "red";
```
This effectively removes the class assigned to the element and replace it with whatever you want.
For cookies, [PPK has a few simple methods to read/write/erase cookies](http://www.quirksmode.org/js/cookies.html).
```
createCookie("mySiteCookie", "red", 7); // Set the cookie to expire in 7 days.
readCookie("mySiteCookie"); // Should yield "red"
``` | How do I remove an existing class name and add a new one with jQuery and cookies? | [
"",
"javascript",
"jquery",
"css",
"cookies",
""
] |
The problem is pretty basic.
(I am puzzled why the search didn't find anything)
I have a rectangular "picture" that stores it's pixel color line
after line in a std::vector
I want to copy a rectangular region out of that picture.
How would I elegantly code this in c++?
My first try:
```
template <class T> std::vector<T> copyRectFromVector(const std::vector<T>& vec, std::size_t startx, std::size_t starty, std::size_t endx, std::size_t endy, std::size_t fieldWidth, std::size_t fieldHeight)
{
using namespace std;
vector<T> ret((endx-startx)*(endy-starty)+10); // 10: chickenfactor
// checks if the given parameters make sense:
if (vec.size() < fieldWidth*endy)
{
cerr << "Error: CopyRectFromVector: vector to small to contain rectangular region!" << std::endl;
return ret;
}
// do the copying line by line:
vector<T>::const_iterator vecIt = vec.begin();
vector<T>::forward_iterator retIt = ret.end();
vecIt += startx + (starty*fieldWidth);
for(int i=starty; i < endy; ++i)
{
std::copy(vecIt, vecIt + endx - startx, retIt);
}
return ret;
}
```
does not even compile.....
Addit: Clarification:
I know how to do this "by hand". It is not a problem as such. But I would love some c++ stl iterator magic that does the same, but faster and... more c++ stylish.
Addition: I give the algorithm the pictureDataVector, the width and height of the picture and a rectangle denoting the region that I want to copy out of the picture.
The return value should be a new vector with the contents of the rectangle.
Think of it as opening your favorite image editor, and copy a rectangular region out of that.
The Picture is stored as a long 1D array(vector) of pixelcolors. | Your question asks for a C++ way of copying a rectangular field of elements in some container. You have a fairly close example of doing so and will get more in the answers. Let's generalize, though:
You want an iterator that travels a rectangular range of elements over some range of elements. So, how about write a sort of adapter that sits on any container and provides this special iterator.
Gonna go broad strokes with the code here:
```
vector<pixels> my_picture;
point selTopLeft(10,10), selBotRight(40, 50);
int picWidth(640), picHeight(480);
rectangular_selection<vector<pixels> > selection1(my_picture.begin(),
my_picture.end(), picWidth, picHeight, selTopLeft, selBotRight);
// Now you can use stl algorithms on your rectangular range
vector<pixels> rect_copy = std::copy(selection1.begin(), selection1.end());
// or maybe you don't want to copy, you want
// to modify the selection in place
std::for_each (selection1.begin(), selection1.end(), invert_color);
```
I'm sure this is totally do-able, but I'm not comfortable coding stl-style template stuff off-the-cuff. If I have some time and you're interested, I may re-edit a rough-draft later, since this is an interesting concept.
See this [SO question's answer](https://stackoverflow.com/questions/757153/concatenating-c-iterator-ranges-into-a-const-vector-member-variable-at-construc) for inspiration. | ```
for (int r = startRow; r < endRow; r++)
for (int c = startCol; c < endCol; c++)
rect[r-startRow][c-startCol] = source[r*rowWidth+c];
``` | Howto elegantly extract a 2D rectangular region from a C++ vector | [
"",
"c++",
"templates",
"stl",
"boost",
"vector",
""
] |
Colleagues have been touting the wonders of maven and its magical dependency stuff but I'm finding that it fails at what I would consider the obvious use.
Suppose I have a root folder with a master POM.
Then underneath I have some projects, call them A and B
B requires A and so the POM in the B folder has the appropriate dependency entry in it
Now, back in the root folder, in a profile, I specify that I want to build B.
When I perform the usual mvn clean install, I get a failure because A was not built.
My friends tell me I have to specify both A and B in that main profile in the root.
But isn't the whole point of dependency management that maven sees B, goes to the B POM file where it sees the dependency on A and so it should go build A automatically. | A reason I can think of that your desired behaviour hasn't been implemented is as follows:
Suppose I'm working on both projects A and B. Currently A is broken. If dependency resolution happened as you would like, I would never be able to build B until A was fixed. So I either have to roll back my changes to A, or focus on fixing A first. Either way possibly not what I want to focus on right now.
Generally B wants to work with the "last good" version of A, rather than the latest. Using the dependencies from the repository means they at least compiled ok (and hopefully the unit tests were run too). | With the master POM:
### `~/scratch/pom.xml`
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>scratch</groupId>
<artifactId>scratch</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>nipple</module>
<module>cabbage</module>
</modules>
</project>
```
And the module POMs:
### `~/scratch/nipple/pom.xml`
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>scratch</artifactId>
<groupId>scratch</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>scratch</groupId>
<artifactId>nipple</artifactId>
<version>1.0-SNAPSHOT</version>
</project>
```
### `~/scratch/cabbage/pom.xml`
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>scratch</artifactId>
<groupId>scratch</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>scratch</groupId>
<artifactId>cabbage</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>scratch</groupId>
<artifactId>nipple</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
```
I can issue `mvn package` in the root directory after clearing out my local repository and end up with all the modules built. (Into empty-ish JARs, but built.)
Maven seems to look for dependencies either in the repository, or in the build in progress. It will not automatically traverse your project structure when you're only building a single module, because it's not required that you even have the parent project on your computer, much less one directory above the current module. (The parent-child relationship isn't even bijective.)
A reason why this is so might be because a directory layout where the location of modules would be predictable is in no way mandatory. It's even somewhat common and acceptable that the layout for the above example be like this:
```
projects
|
+--scratch
| |
| +--scratch-parent
| | |
| | +--pom.xml [The POM of scratch:scratch:1.0-SNAPSHOT]
| |
| +--nipple
| | |
| | +--pom.xml [The POM of scratch:mod1:1.0-SNAPSHOT]
| |
| +--cabbage
| | |
| | +--pom.xml [The POM of scratch:mod2:1.0-SNAPSHOT]
```
In this case, the `<modules>` section of the parent POM would be:
```
<modules>
<module>../nipple</module>
<module>../cabbage</module>
</modules>
```
Notice that there is nothing saying *which* artifact ID is in which module. It just serves to tell Maven that these are filesystem locations where to search for other artifacts related to this build. | Maven and dependent modules | [
"",
"java",
"maven-2",
"build-process",
""
] |
How do you insert data into a MySQL date or time column using PHP mysqli and bind\_param? | Like any other string
```
$stmt = $mysqli->prepare('insert into foo (dt) values (?)');
$dt = '2009-04-30 10:09:00';
$stmt->bind_param('s', $dt);
$stmt->execute();
``` | Timestamps in PHP are integers (the number of seconds from the UNIX epoch). An alternative to the above is to use an integer type date/time parameter, and the MySQL functions `FROM_UNIXTIME` and `UNIX_TIMESTAMP`
```
$stmt = $mysqli->prepare("INSERT INTO FOO (dateColumn) VALUES (FROM_UNIXTIME(?))");
$stmt->bind_param("i", $your_date_parameter);
$stmt->execute();
``` | Using Mysqli bind_param with date and time columns? | [
"",
"php",
"mysql",
"mysqli",
""
] |
This is probably really obvious and I'm being dense. In C# I can do this:
```
string = @"this is
some preformatted
text";
```
How do I do this in VB? | There isn't one.
In C# you have the ability to do something like this "This ends in a new line\n.", but in VB there's no concept of that, you have predefined variables that handle that for you like "This ends in a new line" & vbNewLine
Hence, there's no point in a string literal (@"something\n") because in VB it would be interpreted literally anyway.
The problem with VB .NET is that a statement is deemed terminated at the end of a line, so you can't do this
```
Dim _someString as String = "Look at me
I've wrapped my string
on multiple lines"
```
You're forced to terminate your string on every line and use an underscore to indicate you wish to continue your statement, which makes you do something like
```
Dim _someString as String = "Look at me " & vbNewLine &_
"*** add indentation here *** I've wrapped my string " & vbNewLine &_
vbTab & " on multiple lines" '<- alternate way to indent
``` | Like others said, there's no @ operator, so if you get into heavy string manipulation, use **String.Format**
IMHO, this
```
Dim text As String = String.Format("this is {0} some preformatted {0} text", Environment.Newline)
```
is more readable than this
```
Dim text As String = "this is" & Environment.NewLine _
& " some preformatted" & Environment.NewLine _
& " text"
``` | Preformatted text in VB - What is the C# @ equivalent in vb? | [
"",
"c#",
".net",
"vb.net",
""
] |
I was wondering, how is equality (==) established for STL iterators?
Is it a simple pointer comparison (and thus based on addresses) or something more fancy?
If I have two iterators from two different list objects and I compare them, will the result always be false?
What about if I compare a valid value with one that's out of range? Is that always false? | Iterator classes can define overloaded == operators, if they want. So the result depends on the implementation of `operator==`.
You're not really supposed to compare iterators from different containers. I think some debug STL implementations will signal a warning if you do this, which will help you catch cases of this erroneous usage in your code. | > **Daniel asked:**
> I was wondering, how is equality (==) established for STL iterators? Is it a simple pointer comparison (and thus based on addresses) or something more fancy?
It depends on implementation. Right now, on Visual C++ 2008, I see the following code (for the list iterator):
```
bool operator==(const _Myt_iter& _Right) const
{ // test for iterator equality
#if _HAS_ITERATOR_DEBUGGING
_Compat(_Right);
#else
_SCL_SECURE_TRAITS_VALIDATE(this->_Has_container() && this->_Same_container(_Right));
#endif /* _HAS_ITERATOR_DEBUGGING */
return (_Ptr == _Right._Ptr);
}
```
You'll see above that there is both code for verification of iterator validity, and `_Ptr` being a pointer to a list node.
So I guess there is both verification, and simple, raw pointer comparison.
> **Daniel asked:**
> If I have two iterators from two different list objects and I compare them, will the result always be false?
Until now, it appears the standard was somewhat unclear on the subject. Apparently, they will explicitly write that this kind of operation has undefined results:
Quoting: <http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#446>
> **The result of using any iterator operation** (24.2.1 [input.iterators], 24.2.2 [output.iterators], 24.2.3 [forward.iterators], 24.2.4 [bidirectional.iterators], 24.2.5 [random.access.iterators]) **that uses two iterator values as arguments** (footnote) **which were obtained from two different ranges** r1 and r2 (including their past-the-end values) which are not subranges of one common range **is undefined**, unless explicitly described otherwise.
>
> footnote) Among others these operations are ==, <, binary -, and copy assignment
So I guess it is evil to compare iterator from different containers...
^\_^
> **Daniel asked:**
> What about if I compare a valid value with one that's out of range? Is that always false?
Same as above. | How is STL iterator equality established? | [
"",
"c++",
"stl",
""
] |
I was wondering if you guys could help me.
Here are my .h:
```
Class Doctor {
const string name;
public:
Doctor();
Doctor(string name);
Doctor & Doctor::operator=(const Doctor &doc);
}
```
and my main:
```
int main(){
Doctor d1 = Doctor("peter");
Doctor d2 = Doctor();
d2 = d1;
}
```
I want to do the operator= function. Can anyone help me? Notice the const member on Doctor.
\*\*\*\*\*\*\*\*\*\*\*\*EDIT:\*\*\*\*\*\*\*\*\*
My main problem is that I want another class to have an attribute which is a Doctor like a Pacient has a Doctor. But I want to be able to change my Doctor. Like i am seeing doctor A but I want to see Doctor B. That would be done using a setDoctor function in my other class (Pacient). If it was me doing the code I would say something like this:
```
class Patient{
Doctor &d;
};
```
and then change the pointer. However I am using a base code made by one of the teachers and it has the class defined like:
```
class Patient{
Doctor d;
}
```
But I think this is impossible to do because with a setDoctor() in the Patient class I would either make a copy or alter the varable itself. The first doesn't make any difference and the second is impossible due to the const. Am I right? | You are almost there. Few noteworthy points:
* The name should not be `const` qualified. A `const` cannot be modified, which is exactly what we want in the assignment operator.
* The C++ keyword is `class` and not `Class` as your code has it (it'll give you compile errors)
* As Michael Burr notes: "It should be noted though that if the class simply contains other classes that already properly support assignment (as in this case with a simple string member), the implicit, compiler-generated operator=() will work just fine." Here, in your case, the only member `string` has a proper `op=`. So explicitly defining is redundant.
* Meeh's solution is almost there. The only thing it doesn't talk about is self-assignment. Read [FAQ 12](http://www.parashift.com/c++-faq-lite/assignment-operators.html).
* Assignment is one the Big Three member functions [FAQ 27.10](http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.10). Look it up. It says, requirement to implement either one of copy ctor, op= or the dtor usually implies that you'd need to implement the other two as well.
The corrected code sample should be something like this:
```
class Doctor {
string name;
public:
Doctor& operator=(Doctor const& o) {
if (&o != this) name = o.name;
return *this;
}
// ...
};
``` | The standard way to define the assignment constructor correctly so that it is exception safe is to define it in terms of the copy constructor.
```
class Doctor
{
public:
Doctor& operator=(Doctor const& rhs)
{
if (this != &rhs)
{
Doctor tmp(rhs); // Use copy constructor here
this->swap(tmp); // Now Swap
}
return *this;
}
void swap(Doctor& rhs) throws()
{
std::swap(.....); // swap each member variable.
}
};
```
By doing it like this makes it exception safe.
Note you just need to make the swap a no-throw method, this is relatively simple if you are using STL objects as they all define a no-throw swap just for this situation as does boost and all good libraries (so you should follow suite).
If this going wrong they will go wrong in using the copy constructor. At this point you have not modified your own object as you are copy constructing into a temporary. Thus you are providing good exception safety as your object is still un-changed. | Operator = Overload with Const Variable in C++ | [
"",
"c++",
"operators",
"operator-overloading",
"constants",
"conversion-operator",
""
] |
I'm working on a project where I need to know the amplitude of sound coming in from a microphone on a computer.
I'm currently using Python with the [Snack Sound Toolkit](http://www.speech.kth.se/snack/) and I can record audio coming in from the microphone, but I need to know how loud that audio is. I could save the recording to a file and use another toolkit to read in the amplitude at given points in time from the audio file, or try and get the amplitude while the audio is coming in (which could be more error prone).
Are there any libraries or sample code that can help me out with this? I've been looking and so far the Snack Sound Toolkit seems to be my best hope, yet there doesn't seem to be a way to get direct access to amplitude. | Looking at the Snack Sound Toolkit examples, there seems to be a dbPowerSpectrum function.
From the reference:
> dBPowerSpectrum ( )
>
> Computes the log FFT power spectrum of the sound (at the sample number given in the start option) and returns a list of dB values. See the section item for a description of the rest of the options. Optionally an ending point can be given, using the end option. In this case the result is the average of consecutive FFTs in the specified range. Their default spacing is taken from the fftlength but this can be changed using the skip option, which tells how many points to move the FFT window each step. Options:
EDIT: I am assuming when you say amplitude, you mean how "loud" the sound appears to a human, and not the time domain voltage(Which would probably be 0 throughout the entire length since the integral of sine waves is going to be 0. eg: 10 \* sin(t) is louder than 5 \* sin(t), but their average value over time is 0. (You do not want to send non-AC voltages to a speaker anyways)).
To get how loud the sound is, you will need to determine the amplitudes of each frequency component. This is done with a Fourier Transform (FFT), which breaks down the sound into it's frequency components. The dbPowerSpectrum function seems to give you a list of the magnitudes (forgive me if this differs from the exact definition of a power spectrum) of each frequency. To get the total volume, you can just sum the entire list (Which will be close, xept it still might be different from percieved loudness since the human ear has a frequency response itself). | I disagree completely with this "answer" from CookieOfFortune.
granted, the question is poorly phrased... but this answer is making things much more complex than necessary. I am assuming that by 'amplitude' you mean perceived loudness. as technically each sample in the (PCM) audio stream represents an amplitude of the signal at a given time-slice. to get a loudness representation try a simple RMS calculation:
[RMS](http://en.wikipedia.org/wiki/Root_mean_square)
|K< | Get the amplitude at a given time within a sound file? | [
"",
"python",
"audio",
"input",
"microphone",
"amplitude",
""
] |
How do I raise a number to a power?
```
2^1
2^2
2^3
```
etc... | pow() in the cmath library. More info [here](http://en.cppreference.com/w/cpp/numeric/math/pow).
Don't forget to put `#include<cmath>` at the top of the file. | `std::pow` in the `<cmath>` header has these overloads:
```
pow(float, float);
pow(float, int);
pow(double, double); // taken over from C
pow(double, int);
pow(long double, long double);
pow(long double, int);
```
Now you can't just do
```
pow(2, N)
```
with N being an int, because it doesn't know which of `float`, `double`, or `long double` version it should take, and you would get an ambiguity error. All three would need a conversion from int to floating point, and all three are equally costly!
Therefore, be sure to have the first argument typed so it matches one of those three perfectly. I usually use `double`
```
pow(2.0, N)
```
Some lawyer crap from me again. I've often fallen in this pitfall myself, so I'm going to warn you about it. | What is the C++ function to raise a number to a power? | [
"",
"c++",
"math",
"pow",
"exponentiation",
""
] |
im developing a cms.
the Table clients contains many fields and one of them is the image caption.
When the user uploads a file(image) the file is stored in a public folder.
The image caption field retrieves the final name of the file and stores it in the table.
The problem is when the user wants to update the information. If the user doesnt want to change the image, when he clicks "update", the image caption field is empty, so the path to the image becomes null and now he just shows(no image).
heres what ive been trying to do:
The HTML Form:
```
<p>
<label for="image_caption">Image Caption:</label>
<input name="image_caption" id="image_caption" type="text" class="formbox" size="60" disabled="disabled" value="<?php echo htmlentities($row['image_caption']); ?>" />
</p>
<p>
<label for="image">Insert image:</label>
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<input type="file" name="image" id="foto" value="<?php echo htmlentities($row['image_caption']); ?>"/>
</p>
<p>
<?php
if($row['image_caption']!= ""){
?>
<img src="../images/clientes/<?php echo $row['image_caption'];?>" width="194" height="145" title="Imagem cliente" class="floatright"/>
<?php
}else{
?>
<img src="../images/sem_imagem.gif" width="194" height="145" title="Imagem não disponível" class="floatright"/><br />
<?php
}
?>
</p>
<p>
<input type="submit" name="update" value="Update" />
<input name="cliente_id" type="hidden" value="<?php echo $row['codigo']; ?>" />
</p>
```
And now the upload PHP code(ive just inserted the code that i wanted to show u):
```
// This checks if the file input is empty, and if it is, insert the value from the table that was previously inserted
if(empty($_FILES['image']['name'])){
$image_caption = $row['image_caption'];
}else{
$image = str_replace(' ', '_', $_FILES['image']['name']);
// move the file to the upload folder and rename it
move_uploaded_file($_FILES['image']['tmp_name'],UPLOAD_DIR.$foto);
$image_caption = $image;
}
``` | I'm still not sure I understand, but can't you just pass the name of the original file as a hidden field? Then if nothing's uploaded, use that.
EDIT: Having just seen your comment, you already have the name of the original file, so changing your PHP to:
```
if(empty($_FILES['image']['name'])){
$image_caption = $_POST['image_caption'];
}else{
....(etc)
```
should work, no?
And, of course, if you're going to do something like that then you should perform some kind of sanitization on the posted variables to ensure there's no nastiness... | Do you fetch the info from the database after the form is submitted? I mean, does $row['nome\_foto'] actually contain the previous path?
Edit: Either way, it would be better to simply not update the path field in the database if no new path is supplied.
Also, you need to add some form of checks to the upload to make sure it is an image - right now I could upload a php script or a virus to the server if I wanted to. | How i can retrieve the path for the file that i upload? | [
"",
"php",
"mysql",
""
] |
Firebug is reporting a "return not in function" error with no location (well, line 1 of nothing). How can I track down the source of this error?
```
return not in function
[Break on this error] return(0)
javascript:return... (line 1)
```
I'm running FireBug 1.05 on FF 2.0.0.20 on Ubuntu.
I found a **solution** that works (for this configuration):
```
var link = document.createElement('a');
link.href='/';
if (childSummary.more) {
link.onclick = capture(function(id) { follow(id); }, childSummary.id);
} else {
link.onclick = capture(function(id) { show(id); }, childSummary.id);
}
link.appendChild(document.createTextNode(name));
div.appendChild(link);
[...]
function capture(fn, val) {
return function() { fn(val); return false; };
}
```
The code was in a loop in which the id was changing, necessitating the capture function.
Formerly the href was 'javascript: return 0' and the capture function wasn't returning false directly, instead using the result of the fn, and there was a path when it was returning the equivalent of true. The href was being evaluated causing the error.
Defining href as '#' or '' caused all the links to appear as already visited. Not defining href at all caused there to be no link highlighting. This seemed simplest. | I think the "javascript:return ..." is telling. I believe you're trying to return a value in the `href` attribute of an anchor, as below:
```
<a href="javascript: return false">Test</a>
```
The reason Firebug isn't telling you the location is because it's not in any JavaScript, but is rather in a one-liner in the DOM. | Javascript returns an error because the return statement is not inside a function. A possible cause for this is incorrect function definition, such as:
```
myFunc() { some code; return; }
```
where the correct code definition is:
```
function myFunc() { some code; return; }
``` | Return not in function | [
"",
"javascript",
"firebug",
""
] |
Is it possible to have a 'persistent' temp table in MS-SQL? What I mean is that I currently have a background task which generates a global temp table, which is used by a variety of other tasks (which is why I made it global). Unfortunately if the table becomes unused, it gets deleted by SQL automatically - this is gracefully handled by my system, since it just queues it up to be rebuilt again, but ideally I would like it just to be built once a day. So, ideally I could just set something like set some timeout parameter, like "If nothing touches this for 1 hour, then delete".
I really don't want it in my existing DB because it will cause loads more headaches related to managing the DB (fragmentation, log growth, etc), since it's effectively rollup data, only useful for a 24 hour period, and takes up more than one gigabyte of HD space.
Worst case my plan is to create another DB on the same drive as tempdb, call it something like PseudoTempDB, and just handle the dropping myself.
Any insights would be greatly appreciated! | I would go with your plan B, "create another DB on the same drive as tempdb, call it something like PseudoTempDB, and just handle the dropping myself." | If you create a table as tempdb.dbo.TempTable, it won't get dropped until:
a - SQL Server is restarted
b - You explicitly drop it
If you would like to have it always available, you could create that table in model, so that it will get copied to tempdb during the restart (but it will also be created on any new database you create afterwards, so you would have to delete manually) or use a startup stored procedure to have it created. There would be no way of persisting the data through restarts though. | Persistent temp tables in SQL? | [
"",
"sql",
"sql-server",
"tempdb",
""
] |
I'm trying to get a product's name and its number of sales from two separate tables.
My tables look something like this:
```
BOOK
Book_ID | Book_Title | Book_Author
SOLD
Transaction_ID | Book_ID | Customer_ID
```
I can get most of the results I want from the following query
```
SELECT b.Book_Title, COUNT(s.Book_ID) FROM Book b, Sold s
WHERE b.Book_ID = s.Book_ID
GROUP BY b.Book_Title;
```
However, this only displays products with at least one sale. I would like to display all products, simply showing a zero if no sales have occurred. I've been messing around with something like this:
```
SELECT b.Book_Title,
COUNT(CASE WHEN s.Book_ID IS NULL THEN 0 ELSE s.Book_ID END)
FROM Book b, Sold s WHERE b.Book_ID = s.Book_ID GROUP BY Book_Title;
```
But the `WHERE` clause is limiting the results to the ones with 1 or more sales.
Can anyone suggest a way around this? I am using Oracle 10g.
Thanks | use a left outer join:
```
SELECT b.Book_Title, COUNT(s.Book_ID)
FROM Book b left outer join Sold s on b.Book_ID = s.Book_ID
GROUP BY b.Book_Title;
``` | You can also use a correlated subquery in the `select` clause :
```
select b.book_title, (select count(*) from sold s where s.book_id=b.book_id) from book b
```
It doesn't need either `group by` or `outer join`s, which can be slow for very large number of rows. | SQL CASE STATEMENT in COUNT CLAUSE | [
"",
"sql",
"join",
"count",
"case",
""
] |
I have a class that I have to call one or two methods a lot of times after each other. The methods currently return `void`. I was thinking, would it be better to have it return `this`, so that the methods could be nested? or is that considerd very very very bad? or if bad, would it be better if it returned a new object of the same type? Or what do you think? As an example I have created three versions of an adder class:
```
// Regular
class Adder
{
public Adder() { Number = 0; }
public int Number { get; private set; }
public void Add(int i) { Number += i; }
public void Remove(int i) { Number -= i; }
}
// Returning this
class Adder
{
public Adder() { Number = 0; }
public int Number { get; private set; }
public Adder Add(int i) { Number += i; return this; }
public Adder Remove(int i) { Number -= i; return this; }
}
// Returning new
class Adder
{
public Adder() : this(0) { }
private Adder(int i) { Number = i; }
public int Number { get; private set; }
public Adder Add(int i) { return new Adder(Number + i); }
public Adder Remove(int i) { return new Adder(Number - i); }
}
```
The first one can be used this way:
```
var a = new Adder();
a.Add(4);
a.Remove(1);
a.Add(7);
a.Remove(3);
```
The other two can be used this way:
```
var a = new Adder()
.Add(4)
.Remove(1)
.Add(7)
.Remove(3);
```
Where the only difference is that `a` in the first case is the `new Adder()` while in the latter it is the result of the last method.
The first I find that quickly become... annoying to write over and over again. So I would like to use one of the other versions.
The third works kind of like many other methods, like many String methods and IEnumerable extension methods. I guess that has its positive side in that you can do things like `var a = new Adder(); var b = a.Add(5);` and then have one that was 0 and one that was 5. But at the same time, isn't it a bit expensive to create new objects all the time? And when will the first object die? When the first method returns kind of? Or?
Anyways, I like the one that returns `this` and think I will use that, but I am very curious to know what others think about this case. And what is considered best practice. | The 'return this' style is sometimes called a [fluent interface](http://en.wikipedia.org/wiki/Fluent_interface) and is a common practice. | I like "fluent syntax" and would take the second one. After all, you could still use it as the first, for people who feel uncomfortable with fluent syntax.
another idea to make an interface like the adders one easier to use:
```
public Adder Add(params int[] i) { /* ... */ }
public Adder Remove(params int[] i) { /* ... */ }
Adder adder = new Adder()
.Add(1, 2, 3)
.Remove(3, 4);
```
I always try to make short and easy-to-read interfaces, but many people like to write the code as complicated as possible. | C#: Returning 'this' for method nesting? | [
"",
"c#",
"methods",
"return-value",
"fluent-interface",
""
] |
In Ruby you can use string interpolation like so:
```
text = "This is visit number #{numVisits} to this website"
```
This bypasses the need for explicit concatenation.
I'm working with jQuery and have a bit like this:
```
$(document).ready(function(){
$("a.ajax").click(function(event){
$("#content").load("data.html this.getClass");
});
});
```
The behavior I want is "click on `<a class="ajax" id="schedule"></a>` and the `content` `div` on the current page is replaced by the `schedule` `div` from `data.html`. If I manually write in
```
load("data.html #test");
```
that works, but I want the script to load the DIV with the ID value of the anchor clicked. Any help would be swell!
Example Page: <http://www.mariahandalex.info/stack/> | You cannot embed javascript code inside a string, but you can concatenate a string to an object using '+' like so
```
$('#content').load('data.html #' + $(this).getClass());
```
About embedding code in a string, I don't think it has a name. Groovy calls those strings "[Gstring](http://groovy.codehaus.org/Strings+and+GString)"s, and ruby calls those '[Expression substitution in strings](http://docs.huihoo.com/ruby/ruby-man-1.4/syntax.html#string)'. I'm not sure it has a standard name. | This has changed.
As of 2015 there is now a better way:
<https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings>
Bringing to JS what many languages like Ruby and PHP have enjoyed already.
For example, in my jQuery driven page I use:
```
$('#myModalLabel').html(`Show GRAPH of : ${fundCode}-${funcCode}`);
```
Which safely renders in my updated Firefox and Chrome as:
> Show GRAPH of : AIP001-\_sma
Note the use of backticks surrounding the string param in .html(**....**) | String interpolation in JavaScript | [
"",
"javascript",
"jquery",
""
] |
I am looking at the .h file of a Wrapper class. And the class contains one private member:
```
T* dataPtr;
```
(where `T` is as in `template < class T >` defined at the top of the .h file)
The class provides two "\* overloading operator" methods:
```
T& operator*()
{
return *dataPtr;
}
const T& operator*() const
{
return *dataPtr;
}
```
Both simply return `*dataPtr`, but what does the notation "`*dataPtr`" actually return, in plain English? And how does it fit with the return type "`T&`"? | The return type T& states that you are returning a reference of an instance of a T object. dataPtr is a pointer, which you "dereference" (get the reference value/instance of a pointer) using \*. | dataPtr is a pointer to something.
The \* operator dereferences the pointer, so \*dataPtr is (or, instead of 'is', you can say 'refers to' or 'is a reference to') the pointee, i.e. the thing that dataPtr is pointing to.
T& means 'a reference to an object whose type is T' (not to be confused with T\* which means 'a pointer to an object whose type is T'). | Question About & operator in C++ | [
"",
"c++",
"pointers",
"wrapper",
""
] |
My application uses quite a lot of pictures that are downloaded from the internet and cached locally on the Android phone. I am wondering, what is the correct way to save those pictures. There are several ways I see, that are not fully satisfying.
Save them on SD Card in a public folder
* Uses up space that wont be freed on uninstall
* User can see pics in Gallery
* Needs a folder on the sdcard root (you can actually see it while browsing your phone)
Save them on SD Card in a non-public folder
* Uses up space that wont be freed on uninstall
* Secretly uses space on the SD Card
Save them inside the application
* Blows up application size far too much
What is the correct way of locally saving the images of my application to not distract the user and leave no garbage anywhere? | Your best solution is to use:
```
context.getCacheDir()
```
This directory is private to the application and will be deleted on uninstall, furthermore the system can delete from this directory for you if the device is running short of space.
Note though that the docs say:
> you should not rely on the system
> deleting these files for you; you
> should always have a reasonable
> maximum, such as 1 MB, for the amount
> of space you consume with cache files,
> and prune those files when exceeding
> that space
If you need a lot of space and would rather use the SD card you can call
```
getExternalCacheDir()
```
instead. These will also get removed on uninstall, but the system does not monitor the space available in external storage, so won't automatically delete these files if low on space. If using this option you should also check that external storage is available with
```
Environment.getExternalStorageState()
```
before attempting to write to it. | You can hide images from the MediaScanner if you [put it in a hidden dir](http://groups.google.com/group/android-discuss/browse_thread/thread/cc0e81735392df8f/5a60a54ae9749d72) (i.e., with a dot prefixed) such as `/sdcard/.donotscan/`.
Update: As [romainguy mentions on twitter](http://twitter.com/#!/romainguy/status/63828545704701952) this also works if you put a file named `.nomedia` into the dir. | Where to save pictures on Android? | [
"",
"java",
"android",
"media",
"image",
""
] |
Are there any frameworks for building squarified treemaps in C# 2.0 WinForms?
Something similar to this:

(from <http://www.codeproject.com/KB/recipes/treemaps.aspx>) | Microsoft Research put one together.
Don't know how easy it is use.
<http://research.microsoft.com/en-us/downloads/dda33e92-f0e8-4961-baaa-98160a006c27/default.aspx> | I know you asked about WinForms, but I'm sure someone will hit this page when searching for WPF tree maps. This currently seems to be the best WPF freebie out there, though I found a few minor issues with it, it's still pretty good:
<http://treemaps.codeplex.com/> | Visual Treemap in Winforms | [
"",
"c#",
"winforms",
"data-visualization",
"treemap",
""
] |
I have a dll "mytest.dll" that when loaded via `LoadLibrary()`, returns NULL (and 127 as the `GetLastError()`). If I use DependencyWalker on "mytest.dll", it reports that it should load correctly and that all DLLs are found correctly. Running the profiler option of DependencyWalker on the host exe gives me this relevant section in the log:
```
00:00:55.099: Loaded "mytest.DLL" at address 0x07860000 by thread 0xBBC. Successfully hooked module.
00:00:55.115: First chance exception 0xC0000139 (DLL Not Found) occurred in "NTDLL.DLL" at address 0x76E24285 by thread 0xBBC.
00:00:55.115: Unloaded "mytest.DLL" at address 0x07860000 by thread 0xBBC.
00:00:55.115: LoadLibraryW("mytest.dll") returned NULL by thread 0xBBC. Error: The specified procedure could not be found (127).
```
Is there a way to debug this to find out what the DLL Not Found message that NTDLL.DLL reports is trying to look for? Or should I be looking elsewhere for the source of the problem?
Note that loading this same "mytest.DLL" from another application seems to work correctly. | Could your application be trying to call a specific DLL function via GetProcAddress after the initial load (perhaps) which is not found? Is it a 32 or 64 bit application?
If it is loading correctly in another application as you suggest, then it probably has a correct entry point.
A quick [google search](http://www.google.com.au/search?hl=en&client=firefox-a&rls=org.mozilla%3Aen-GB%3Aofficial&q=0xC0000139+DLL+Not+Found&btnG=Search&meta=) suggests that the error code you are getting back is likely from a missing function name (or specific function's ordinal value) in the DLL. I'd suggest opening the DLL in something like [Exescope](http://hp.vector.co.jp/authors/VA003525/emysoft.htm) and inspect the exports list.
It might also explain why the DLL works with another application (perhaps the other application uses different exported functions in the DLL)? | Using [Process Monitor](http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) or [FileMon](http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx) from SysInternals might give you a clue as to whether myTest.dll is simply not where it's being looked for. | LoadLibrary fails: First chance exception 0xC0000139 (DLL Not Found) - How to debug? | [
"",
"c++",
"exception",
"dll",
"loadlibrary",
""
] |
Bellow is simplified version of the code I have:
```
public interface IControl<T>
{
T Value { get; }
}
public class BoolControl : IControl<bool>
{
public bool Value
{
get { return true; }
}
}
public class StringControl : IControl<string>
{
public string Value
{
get { return ""; }
}
}
public class ControlFactory
{
public IControl GetControl(string controlType)
{
switch (controlType)
{
case "Bool":
return new BoolControl();
case "String":
return new StringControl();
}
return null;
}
}
```
The problem is in GetControl method of ControlFactory class. Because it returns IControl and I have only IControl<T> that is a generic interface. I cannot provide T because in Bool case it's going to bool and in String case it's going to be string.
Any idea what I need to do to make it work? | Just derive `IControl<T>` from `IControl`.
```
public interface IControl<T> : IControl
{
T Value { get; }
}
```
**UPDATE**
If I missunterstood you, and you don't want a non-generic interface, you will have to make the method `GetControl()` generic, too.
```
public IControl<T> GetControl<T>()
{
if (typeof(T) == typeof(Boolean))
{
return new BoolControl(); // Will not compile.
}
else if (typeof(T) == typeof(String))
{
return new StringControl(); // Will not compile.
}
else
{
return null;
}
}
```
Now you have the problem that the new controls cannot be implicitly casted to `IControl<T>` and you would have to make this explicit.
```
public IControl<T> GetControl<T>()
{
if (typeof(T) == typeof(Boolean))
{
return new (IControl<T>)BoolControl();
}
else if (typeof(T) == typeof(String))
{
return (IControl<T>)new StringControl();
}
else
{
return null;
}
}
```
**UPDATE**
Changed the cast from `as IControl<T>` to `(IControl<T>)`. This is prefered because it will cause an exception if there is a bug while `as IControl<T>` silently returns `null`. | ```
public IControl<T> GetControl<T>()
{
switch (typeof(T).Name)
{
case "Bool":
return (IControl<T>) new BoolControl();
case "String":
return (IControl<T>) new StringControl();
}
return null;
}
```
Update; corrected a couple of errors in the code. Heres a call to get a class:
```
IControl<bool> boolControl = GetControl<bool>();
``` | Generic class factory problem | [
"",
"c#",
"oop",
""
] |
I have the following code to let the GUI respond to a change in the collection.
```
myObservableCollection.CollectionChanged += ((sender, e) => UpdateMyUI());
```
First of all is this a good way to do this?
Second: what's the code to unsubscribe from this event? Is it the same but with -= (and then the complete anonymous method again)? | If you need to unsubscribe from an event, you need an instanced reference. Unfortunately, that means you can't use that particular syntax. | First of all... yes its a good way of doing it, it's clean, small form and easy to read & understand... the caveat of course is "Unless you later want to unsubscribe".
I believe [Jon Skeet](https://stackoverflow.com/questions/183367/unsubscribe-anonymous-method-in-c/183380#183380) pointed out before that
"the specification explicitly doesn't guarantee the behaviour either way when it comes to equivalence of delegates created with anonymous methods."
So if you need to unsubscribe from the event at a later time, you'd be best to actually create a delegate instance so you can hang onto the reference for later.
```
var myDelegate = delegate(sender, e){UpdateMyUI()};
myObservableCollection.CollectionChanged += myDelegate;
myObservableCollection.CollectionChanged -= myDelegate;
``` | How to unsubscribe from an event which uses a lambda expression? | [
"",
"c#",
".net",
"c#-3.0",
"event-handling",
"lambda",
""
] |
I want to have a Singleton that will be auto instantiated on program start.
What I mean by "auto instantiated" is that the code in the Singleton should instantiate itself on program start without any calls or declarations by other code.
So I want something like the following to instantiate and write out "MySingleton Instantiated" on program start (without the main code doing anything)...
```
static class MySingleton
{
private static MySingleton self = new MySingleton();
protected MySingleton()
{
System.Console.WriteLine("MySingleton Instantiated");
}
}
```
except this doesn't work since C# will only initialize the static members of a class when needed, ie when they are accessed/etc.
So what do I do? can this be done?
I haven't done this personally with C++ (haven't been using C++ for a while) but I'm pretty sure it can be done in C++ but not sure about C#.
Any help is appreciated. Thanks.
---
What I'm actually wanting to do with this is...
There would be many of these singleton classes (and more can be added as time goes on), all of which would inherit from a common (abstract) parent class (aka. PClass).
The PClass would have a static member that is a collection of PClasses... and a constructor to add itself to the collection...
Then in theory all the singletons would automagically be added to the collection (since when they are instantiated the base PClass constructor is called and adds the new object to the collection)... then the collection can be used without knowing anything about what child (singleton) classes have been implemented, and new child (singleton) classes can be added any time without having to change any other code.
Unfortunately I can't get the children (singletons) to instantiate themselves... screwing up my little plan, resulting in this post.
Hope I explained that well enough.
---
PS. Yes I realize there are bad feelings around Singletons and their use... but they are useful sometimes, and even if Satan himself made Singletons I'd still like to know if my problem can be achieved in C#. Thanks kindly to you all. | The IoC approach mentioned by Chris is probably the best, but failing that the "best" solution I can think of is to do something funky with reflection and attributes along the lines of:
```
public class InitOnLoad : Attribute
{
public static void Initialise()
{
// get a list of types which are marked with the InitOnLoad attribute
var types =
from t in AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes())
where t.GetCustomAttributes(typeof(InitOnLoad), false).Count() > 0
select t;
// process each type to force initialise it
foreach (var type in types)
{
// try to find a static field which is of the same type as the declaring class
var field = type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic).Where(f => f.FieldType == type).FirstOrDefault();
// evaluate the static field if found
if (field != null) field.GetValue(null);
}
}
}
[InitOnLoad]
public class Foo
{
public static Foo x = new Foo();
private Foo()
{
Console.WriteLine("Foo is automatically initialised");
}
}
public class Bar
{
public static Bar x = new Bar();
private Bar()
{
Console.WriteLine("Bar is only initialised as required");
}
}
```
With a call to InitOnLoad.Initialise() added to your main method.
You could do away with the attribute, but this may cause unnecessary types to be initialized and needlessly consume memory (such as Bar in the above code).
It's also worth noting that this won't handle types contained in any assemblies which are loaded dynamically, unless you make another call to Initialise, but based on your question ("auto instantiated on program start") that doesn't sound like an issue for you. | While .NET modules can in theory (IIRC) react to module load etc, this isn't available via C#. In some frameworks (like ASP.NET) there are hooks you can use via configuration, such as hacking it via a handler or via global.asax.cs - however, for a regular C# app (console, winform etc) you would have to trigger it manually. For example, a static constructor on the class that hosts your `Main` entry point would get invoked.
So: what is the use-case here? When wouldn't the lazy loading approach be OK? | How To: Auto Instantiate Singleton in C# | [
"",
"c#",
"singleton",
""
] |
I have an entity that has a state table associated with it. The state table is managed by another process, and contains a list of objects that my business logic must process. I would like to get a new snapshot of the state table each time I reload the entity. How can I ensure that no part of Hibernate or its support libraries *ever* caches any of the values of this table? Basically, I want to get a new view of the collection *every* time I call getMyStateValues (). | Most of the point of Hibernate is to prevent that from happening and return a consistent view of an entity's state in the scope of a given transaction. So either reload the whole entity, in different transactions every time. Or, if you need to reload the state table during a business transaction, load only the state table by the parent entity's id in a separate Hibernate session. | You can create a method in your entity that queries the database and return the collection. getXYXReload(). It´s not a very nice design decision, thought. | How can I create a hibernate collection that will be re-read every time I request it? | [
"",
"java",
"hibernate",
"configuration",
"caching",
""
] |
I am writing a PHP application that will have the ability to edit settings through a web interface. I didn't mean for the user (and actually, it will only be **admins**) to be able to load the file up in a text editor, but rather, they make a change using a form, and that will change the settings file (and *do other things as well*).
At this stage in the development, settings are stored in a PHP file, for example:
```
define ('UPLOAD_DIR','uploads/');
define ('DISPLAY_NUM',true);
$names = array('a' => 'b','c'=>'d','e'=>'f');
```
However, parsing arrays (and they get more complicated (i.e multilevel nested) than the above), doesn't seem so fun. And because specific settings can be added and removed, reading the entire file, and then writing out all the settings again, doesn't seem fun either.
What are the advantages and disadvantages to using the following formats? (And any others that I missed out):
* Custom XML
* INI (able to use parse\_ini\_file)
(Using a database *is not* suitable due to the requirements for the project. I understand in many situations a database would be prefered, just not in this case.)
If you were unable to use a database, and had to store settings that could be edited using a web interface, what would you do?
(Note: This is a different question to [this one](https://stackoverflow.com/questions/798654/how-to-store-configurations-for-php-app-xml-or-ini-or-db), where settings can't be changed, it's PHP file all the way. And yes, the setup does currently write out a PHP file with the correct settings.) | OK, I didn't get any sort of answer I was looking for. Here's the sort of thing I was expecting.
**INI**
* Storing settings in an INI file might be appropriate for simple settings which you want the user to edit by hand.
* However, creating complex arrays is not easy, and would require some mental acrobatics to understand which heading is at which level of the array.
* Reserved words, which must not be used anywhere in the file, include: yes, no, true, and false, this might be problematic.
* Constants can be used in the file.
* No built in method of writing out INI files.
**XML**
* Can use the SimpleXML Extension, which "provides a very simple and easily usable toolset" to turn XML into an object that can then be processed using the normal methods.
* Allows the use of very complex arrays.
* Possible to edit by hand, if required.
* Can use external tools to verify the validity of the file.
* Many many XML processors available for PHP.
**YAML**
* <http://yaml.org/>
* <http://www.techyouruniverse.com/software/dont-use-yaml-for-php-use-parse%5Fini%5Ffile>
Remember: no database. Requires being able to use complex arrays. | If you're not committed to using XML, you may like to consider [YAML](http://yaml.org/xml.html). I've only used it with Ruby, but a quick [Google](http://www.google.co.uk/search?q=php+yaml&sourceid=navclient-ff&ie=UTF-8&rlz=1B3GGGL_enGB223GB223) suggests there are a few options for PHP support. TBF, the links there include some [arguments against](http://www.techyouruniverse.com/software/dont-use-yaml-for-php-use-parse_ini_file) using YAML with PHP, but YMMV. | Storing settings, to edit later, in PHP | [
"",
"php",
"xml",
"settings",
"ini",
""
] |
```
Array ( [kanye] => Array ( [0] => Kanya [1] => Janaye [2] => Kayne [3] => Kane [4] => Kaye ) [wst] => Array ( [0] => ST [1] => St [2] => st [3] => EST [4] => West ) )
Array
(
[0] => Kanya
[1] => Janaye
[2] => Kayne
[3] => Kane
[4] => Kaye
)
Array
(
[0] => ST
[1] => St
[2] => st
[3] => EST
[4] => West
)
```
I've got those two arrays inside one array. The top array holds them both, then below is each one individually. When I am displaying the individual arrays, how do I echo their name?
So the first would be kanye, then list the contents, etc.
Hope that makes sense. I know it will be a simple bit of code but it's stumping me. | You can use a [foreach](http://www.php.net/foreach) statement to get the key value pair of the array:
```
$outer_arr = array('kanye' => array('Kanya', 'Janaye', 'Kayne', 'Kane'));
foreach($outer_arr as $key => $val) {
print($key); // "kanye"
print_r($val); // Array ( [0] => Kanya [1] => Janaye [2] => Kayne [3] => Kane )
}
``` | If you just need to get the keys, you can use `array_keys`
```
$myArray = array(
"Kanye" => array("Kane", ...)
"West" => array("Wst", ...)
);
print_r(array_keys($myArray));
/*
array (
0 => Kanye
1 => West
)
*/
``` | Return PHP array name | [
"",
"php",
"arrays",
""
] |
I have two classes: Account and Operator. Account contains a list of Operators. Now, whenever an operator (in the list) receives a message I want to notify Account object to perform some business logic as well.
I think of three alternatives on how to achieve this:
1) Hold a reference within Operator to the container [Account] object and call methods directly. Not absolutely good because of circular references.
2) Use events. As far as I know there is no built-in event handling mechanism in Python. So, this one is a bit tricky to implement.
3) Don't send messages to Operators directly. Instead, operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.
I wonder which approach is the most advantageous from the architectural point of view. How do you usually handle this task?
It would be great if you could point out snippets in Python. | You're over-thinking this. Seriously. Python isn't C++; your concerns are non-issues in Python. Just write what makes sense in your problem domain.
" Not absolutely good because of circular references."
Why not? Circularity is of no relevance here at all. Bidirectional relationships are great things. Use them. Python garbage collects them just fine without any thinking on your part.
What possible problem do you have with mutual (birectional) relationships?
"...operate only Accounts, and within them, internally, handler operators. This one is a bit limiting because in this case I cannot pass around references to operators.
"
What? Your Operators are Python objects, pass all you want. All Python objects are (in effect) references, don't sweat it.
What possible problem do you have with manipulating Operator objects? | There is no "one-size-fits-all" solution for the Observer pattern. But usually, it's better to define an EventManager object where interested parties can register themselves for certain events and post these events whenever they happen. It simply creates less dependencies.
Note that you need to use a global EventManager instance, which can be problematic during testing or from a general OO point of view (it's a global variable). I strongly advise against passing the EventManager around all the time because that will clutter your code.
In my own code, the "key" for registering events is the class of the event. The EventManager uses a dictionary (event class -> list of observers) to know which event goes where. In the notification code, you can then use `dict.get(event.__class__, ())` to find your listeners. | Notifying container object: best practices | [
"",
"python",
"architecture",
"containers",
"notifications",
""
] |
I'd like to iterate over a std::map using BOOST\_FOREACH and edit the values. I can't quite get it.
```
typedef std::pair<int, int> IdSizePair_t;
std::map<int,int> mmap;
mmap[1] = 1;
mmap[2] = 2;
mmap[3] = 3;
BOOST_FOREACH( IdSizePair_t i, mmap )
i.second++;
// mmap should contain {2,3,4} here
```
Of course this doesn't change anything because I'm not iterating by reference. So I substitute this line instead (as per the example in the Boost docs):
```
BOOST_FOREACH( IdSizePair_t &i, mmap )
```
and I get the compiler error:
```
error C2440: 'initializing' :
cannot convert from 'std::pair<_Ty1,_Ty2>' to 'IdSizePair_t &'
with
[
_Ty1=const int,
_Ty2=int
]
```
Any suggestions? | The problem is with the first member of the pair, which should be *const*. Try this:
```
typedef std::map<int, int> map_t;
map_t mmap;
BOOST_FOREACH( map_t::value_type &i, mmap )
i.second++;
``` | This is an old thread, but there is a more convenient solution.
boost has the notion of 'range adapters' that perform a transformation on iterator ranges. There are specific range adapters for this exact use case (iterating over map keys or values): `boost::adaptors::map_values` and `boost::adaptors::map_keys`.
So you could iterate over map values like this:
```
BOOST_FOREACH(int& size, mmap | boost::adaptors::map_values)
{
++size;
}
```
More information [here](http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/introduction.html). | using BOOST_FOREACH with std::map | [
"",
"c++",
"boost",
"foreach",
"maps",
"std",
""
] |
I am planning to use P6Spy to intercept database statements within our architecture. However, I noticed on the P6Spy website that the last release of the software was back in 2003. Is there anything out there that is better or should I just stick with P6Spy? | We still use P6Spy with our Weblogic 8.1.5 with EJB2.0 and it works charms. I'm about to try and integrate it with Weblogic 10.3 and EJB3.0 | Some other tools and libraries that are similiar to P6Spy.
* [Craftsman Spy](http://zer0.free.fr/craftsman/spy.php) appears to overlap quite a bit with the feature set in log4jdbc. This library hasn't been updated in 2 years and depends on Jakarta Commons Logging.
* [JAMon](http://jamonapi.sourceforge.net/) (Java Application Monitor) is a comprehensive application monitor and monitoring API which includes JDBC/SQL monitoring as part of it's very large feature set.
* [JdbcProxy](http://sourceforge.net/projects/jdbcproxy/) The driver can also emulate another JDBC driver to test the application without a database.
* [LogDriver](http://rkbloom.net/logdriver/index.html) appears to be similiar to log4jdbc and the author has written a nice article on JDBC logging in general and his motivation and experience of writing LogDriver.
* yet another [JDBC logger](http://jdbclogger.sourceforge.net/)
* [log4jdbc-remix](http://code.google.com/p/log4jdbc-remix/) an experimental fork of log4jdbc with some interesting features.
* [jdbcdslog](http://code.google.com/p/jdbcdslog/) Another new jdbc wrapper with a lot of crossover with log4jdbc features.
* [SqlRecorder](https://github.com/gokulesh/SqlRecorder) A library that is a wrapper around a JDBC driver to record all executed queries to different locations like a file,console or any other remote server via plugins.
* [log4jdbc-log4j2](https://code.google.com/p/log4jdbc-log4j2/) Another fork of log4jdbc that includes the log4jdbc-remix fork and other features of it's own.
Source: <https://code.google.com/archive/p/log4jdbc/> | Anything better than P6Spy? | [
"",
"sql",
"database",
"p6spy",
""
] |
so, object initializers are all kinds of handy - especially if you're doing linq, where they're downright necessary - but I can't quite figure out this one:
```
public class Class1 {
public Class2 instance;
}
public class Class2 {
public Class1 parent;
}
```
using like this:
```
Class1 class1 = new Class1();
class1.instance = new Class2();
class1.parent = class1;
```
as an initializer:
```
Class1 class1 = new Class1() {
instance = new Class2() {
parent = class1
}
};
```
this doesn't work, class1 is supposedly an unassigned local variable. it gets even trickier in Linq when you are doing something like
```
select new Class1() { ...
```
it doesn't even have a name to refer to it by!
how do I get around this? can I simply not make nested references using object initializers? | > can I simply not make nested references using object initializers?
You are right - you cannot. There would be a cycle; A requires B for initialization but B requires A before. To be precise - you can of course make nested object initializers but not with circular dependencies.
But you can - and I would suggest you should if possible - work this around as follows.
```
public class A
{
public B Child
{
get { return this.child; }
set
{
if (this.child != value)
{
this.child = value;
this.child.Parent = this;
}
}
}
private B child = null;
}
public class B
{
public A Parent
{
get { return this.parent; }
set
{
if (this.parent != value)
{
this.parent = value;
this.parent.Child = this;
}
}
}
private A parent = null;
}
```
Building the relation inside the property has the benifit that you cannot get an inconsitent state if you forget one of the initialization statements. It is quite obvious that this is an suboptimal solution because you need two statements to get one thing done.
```
b.Parent = a;
a.Child = b;
```
With the logic in the properties you get the thing done with only one statement.
```
a.Child = b;
```
Or the other way round.
```
b.Parent = a;
```
And finally with object initializer syntax.
```
A a = new A { Child = new B() };
``` | I don't think there is anyway to get around this, when the application is instantiating the Class1 object it needs to have created the Class2 object first so that it knows where in memory the reference is located. You can see this if you try the following:
```
Class1 myClass1 = null;
myClass1 = new Class1()
{
instance = new Class2
{
parent = myClass1
}
};
```
This will compile and run, but the parent property of Class2 will be null since that is what the value was at the time the inner line of code was run, meaning that the inner most line was the first to be executed. | Nested use of C# Object Initializers | [
"",
"c#",
"c#-3.0",
""
] |
I keep getting empty files generated from running
```
$command = 'mysqldump --opt -h localhost -u username -p \'password\' dbname > \'backup 2009-04-15 09-57-13.sql\'';
command($command);
```
Anyone know what might be causing this? My password has strange characters in it, but works fine with connecting to the db.
I've ran `exec($command, $return)` and outputted the $return array and it is finding the command. I've also ran it with `mysqldump > file.sql` and the file contains
```
Usage: mysqldump [OPTIONS] database [tables]
OR mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR mysqldump [OPTIONS] --all-databases [OPTIONS]
For more options, use mysqldump --help
```
So it would seem like the command is working. | **Remove the space** between `-p` and the password. If it didn't work, try to remove the quotes from the password
from [MySQL documentation](http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_password):
> If you use the short option form (-p), you **cannot** have a space between the option and the password.
however, it is fine to have space with `-h` and `-u` options | I believe there are no spaces between -u and the actual username.
```
host: localhost user: peter password: pwd
```
would become:
```
-hlocalhost -upeter -ppwd
``` | Empty files generated from running `mysqldump` using PHP | [
"",
"php",
"mysql",
""
] |
Assume an HTML page:
```
<html>
<body>
.. html content (outside of our control) ..
.. javascript block ..
.. some more html content (outside of our control) ..
</body>
</html>
```
Assume further that the only part of the HTML page that we're able to control is a javascript block in the middle of the page.
Using that javascript block, how do I increase the total page height by 150 pixels by "padding" the bottom of the page?
If I could alter the HTML a simple solution would be:
```
<html>
<body>
.. html content (outside of our control) ..
.. javascript block ..
.. some more html content (outside of our control) ..
<div style="height: 150px; clear: both;"></div>
</body>
</html>
```
But how do I achieve this only by using the javascript block?
The ideal solution should be cross-browser compatible and 100 % inline (that is using no javascript library).
**Update #1:** The javascript block has access to the entire DOM of the page.
**Update #2:** The total length of the page (before altering the DOM) varies.
**Update #3:** Assume that no javascript library (such as the otherwise excellent jQuery) can be used. | Updated code:
```
var space = document.createElement('div');
space.style.height = "150px";
space.style.clear = "both";
document.getElementsByTagName("body")[0].appendChild(space);
``` | Can you generate DOM elements via javascript and simply add that div to the bottom?
I'd vote for cobbal If I had any rep.. heh. | How to increase the page height by X pixels by using only javascript | [
"",
"javascript",
"html",
"css",
"dom",
""
] |
I have objects representing folders and I'm wondering if they should be represented in the database.
On the one hand it seems like the easiest way would be to not represent folder objects and just store a path value for objects contained in a folder. Problems I see with this is that you can't persist an folder whose descendants do not contain any items, which isn't too big of a deal. Also I don't have a clear idea of how to load the folder hierarchy to display (such as in a TreeView) without loading everything into memory upfront, which would probably be a performance issue.
The alternative is to have a "Folder" table with references to its parent folder. This seems like it should work, but I'm unsure how to allow folders with the same name as long as they do not share a parent. Should that even be something the DB should be concerning itself with or is that something that I should just enforce in the the business logic? | The idea is something like this (self-referencing):
```
CREATE TABLE FileSystemObject (
ID int not null primary key identity,
Name varchar(100) not null,
ParentID int null references FileSystemObject(ID),
constraint uk_Path UNIQUE (Name, ParentID),
IsFolder bit not null
)
``` | Take a look at the ERD in the middle of this [page](http://www.dynamicalsoftware.com/cr/prod/guest/standard.html). Factoring out the hierarchy into a separate table permits you to support multiple taxonomies. | Storing folder hierarchy in relational database | [
"",
"sql",
"sql-server-ce",
"hierarchy",
"directory",
"relational",
""
] |
I am using prototype to load external js file (actually it is php file) dynamically.
Like this:
```
function UpdateJS(file)
{
var url = 'main_js.php?file='+file;
var myAjax = new Ajax.Request( url, {method: 'get', onComplete: showResponseHeader} );
}
function showResponseHeader (originalRequest)
{
$('jscode').innerHTML = originalRequest.responseText;
}
```
Container "jscode" is defined like this:
```
<script type="text/javascript" id="jscode"></script>
```
And it works!
But if some different file is called, all the functions from previous one are preserved. And I don't want that.
Anybody knows how to "unload" first js file when second one is called?
(I also tried using Ajax.Updater function but the result is the same.)
Update:
It turns out that there is bigger problem: it only loads if function "UpdateJS" is in window.onload that is why it doesn't load anything else after that.
So prototypes update it's maybe not such a good way for this... | There's a great tutorial on how to dynamically unload Javascript and CSS here:
<http://www.javascriptkit.com/javatutors/loadjavascriptcss2.shtml>
The below code is borrowed from the above link, it is a pure JS solution, not a Prototype JS one, but should do the trick:
```
function removejscssfile(filename, filetype){
var targetelement=(filetype=="js")? "script" : (filetype=="css")? "link" : "none" //determine element type to create nodelist from
var targetattr=(filetype=="js")? "src" : (filetype=="css")? "href" : "none" //determine corresponding attribute to test for
var allsuspects=document.getElementsByTagName(targetelement)
for (var i=allsuspects.length; i>=0; i--){ //search backwards within nodelist for matching elements to remove
if (allsuspects[i] && allsuspects[i].getAttribute(targetattr)!=null && allsuspects[i].getAttribute(targetattr).indexOf(filename)!=-1)
allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
}
}
removejscssfile("somescript.js", "js") //remove all occurences of "somescript.js" on page
removejscssfile("somestyle.css", "css") //remove all occurences "somestyle.css" on page
```
If you don't need the CSS removing functionality, I'm sure you can hack it away. | I don't think you can unload a set of properties defined within the scope of a file. A workaround would be to define the functions contained in each file in a central object that you scrap (or override) whenever you want to get rid of it. | Dynamically loading a js file using Prototype? | [
"",
"javascript",
"file",
"dynamic",
"prototypejs",
""
] |
In C++ how can I declare an array of strings? I tried to declare it as an array of `char` but that was not correct. | ```
#include <string>
std::string my_strings[100];
```
That is C++, using the STL. In C, you would do it like this:
```
char * my_strings[100];
```
This reads as "my strings is an array of 100 pointer to char", and the latter is how strings are represented in C. | I would rather recommend using a vector of strings in almost every case:
```
#include <string>
#include <vector>
std::vector<std::string> strings;
``` | How do I declare an array of strings in C++? | [
"",
"c++",
"string",
""
] |
I am working on database migration tool in java. The tool is copying database tables with their data's to the destination database. But I want it to work on different databases. Copy from mysql and create in derby etc. With JDBC, we can gather enough information about the table and its columns. But I am going to ask this, if I can recreate tables on java with sql free. I mean different databases have different data types and some times they differs at sql syntax. So can JDBC or any other library (can be open source) do this job at an easy and global way? | Apache's [DdlUtils](http://db.apache.org/ddlutils/) is done what I need. When I am searching about crossdb found it, and it is very useful yet powerful. It can generate a database from scratch, just with the parameters. Or it can grab existing database table definitions, also with index definitions. You can use delimiter if you want (it is a deadly important option for me to use Apache Derby). You can just print out these definitions or apply them directly to source database (I haven't tried the second one yet). It translates definitions for the selected database. But one big problem is there is no good tutorial about how to start using it. I searched through the packages to find a good place to start. Here is what i have achieved, a sample code to generate full database table create sql.
```
DerbyPlatform dp = new DerbyPlatform();
dp.setDelimitedIdentifierModeOn(true);
Database dbs = new Database();
DerbyModelReader dmr = new DerbyModelReader(dp);
Database test = dmr.getDatabase(conn, "MyDBTest");
DerbyBuilder db = new DerbyBuilder(dp);
String testSqlDerby = dp.getCreateTablesSql(test, true, true);
System.out.println(testSqlDerby);
System.out.println("\n\n\n\n");
MySql50Platform mp = new MySql50Platform();
mp.setDelimitedIdentifierModeOn(true);
MySqlBuilder mb = new MySqlBuilder(mp);
String testSqlMysql = mp.getCreateTablesSql(test, true, true);
System.out.println(testSqlMysql);
``` | I'm not aware of JDBC having a generic facility to do this. You probably have to make a utility library that generates the SQL for table creation.
Start with one that does ANSI SQL and test it on as many platforms as you intend to support. Remember, Java is still write-once, debug everywhere so you will need to test this on any platform you intend to support the system on. Subclass the generator if you have to make dialectic variations of the create statement for any of your platforms. | Database Migration | [
"",
"java",
"database",
"jdbc",
"migrate",
""
] |
I've just seen [this question](https://stackoverflow.com/questions/795377/what-if-any-is-the-resource-penalty-for-using-system-diagnostics-stopwatch), where one of the answers indicates that [System.Diagnostics.Stopwatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(loband).aspx) should only be used for diagnosing performance and not in production code.
In that case, what would be the best way to get precision timing in .NET? I'm currently in the early stages of building a very simple [MIDI](http://en.wikipedia.org/wiki/Musical_Instrument_Digital_Interface) sequencer using the MIDI-out functionality of [NAudio](http://www.codeplex.com/naudio). I'd like to be able to send MIDI messages out aligned to (say) 1/10s with as little jitter as possible. Is this feasible, or will things like context-switching ruin my day?
I currently have some code in a console app that continuously calls `Stopwatch` and calculates the jitter when generating a stream of 1/16th-notes at 150bpm. The jitter is very low in this situation. However, I'll be moving this off to another thread, so I don't know if that will remain the case. | If you don't mind P/Invoke, you can use QueryPerformanceCounter: <http://www.eggheadcafe.com/articles/20021111.asp> | You could also use the native streaming MIDI API. I don't think its in NAudio but you could look at the C# Midi Toolkit to see if that one supports it. Otherwise you have two examples of how to do native MIDI API P/Invoke and can roll your own... | Precision timing in .NET | [
"",
"c#",
".net",
"midi",
"timing",
"naudio",
""
] |
I was recently asked by a friend of mine who's just starting to play around with threading what the difference between using a secondary object purely for the purpose of locking or just locking the object you're referencing is. I had to admit that I had no idea, can anyone tell me? I will try and demonstrate with a couple of code snippets:
First method:
```
List<string> data = new List<string>();
object datalock = new object();
void main()
{
lock(datalock)
{
if (data.contains("SomeSearchString"))
{
//Do something with the data and then remove it
}
}
}
```
Second method:
```
List<string> data = new List<string>();
void main()
{
lock(data)
{
if (data.contains("SomeSearchString"))
{
//Do something with the data and then remove it
}
}
}
```
Is there a significant difference or is this down to personal coding style? If there is a significant difference, can anyone explain what it is?
I did come across another question [[Difference between lock(locker) and lock(variable\_which\_I\_am\_using)](https://stackoverflow.com/questions/230716/difference-between-locklocker-and-lockvariablewhichiamusing)] in which the answer implied that both of these are equivalent, but if that's the case, which would be the best to use and why?
I've seen a number of examples scattered around the net, I tend to use the first method as a matter of personal choice, but I wondered what the merits of using the second method would be. | The big difference is that with a secondary object **that only your code knows about** there is no risk of unexpected consequences (deadlocks, pulse/wait gotchas, etc) from *other* code (not yours) locking against the primary object (which is commonly available to other code).
IMO, perhaps the CLR team would have done better with an explicit `Lock` type - or maybe `Monitor` should have been non-static, etc. | The most important point has been covered by Marc, but I prefer the first pattern because it also opens up scope for having separate objects for read and write locks or any other level of granularity that may be useful for your specific use. | What is the difference between locking the specified object and locking a secondary object? | [
"",
"c#",
".net",
""
] |
I use an java application which generates a class dynamically. Via an ant script the source code will be produced for a give classname and a class template.
In the template for the class I need to know the name of even this class, to call a static method of the class.
Example. The class will be named "VersionInfo". Then in static main() of it I want to call the static method: VersionInfo.getId().
But I don't know the class-name.
Is there an equivalent to "this" for static contexts or some Utility-Class for such a purpose? | If you are creating the class via Ant then why not just generate a static method getClassName that returns the name of the class? | If your main method resides in the same class you just can call `getId()` in the main method. | How can a class access its own classname? | [
"",
"java",
""
] |
I'm trying to create a BMI calculator. This should allow people to use either metric or imperial measurements.
I realise that I could use hidden tags to solve my problem, but this has bugged me before so I thought I'd ask: I can use `$_POST['variableName']` to find the submitted variableName field-value; but...I don't know, or see, how to verify which form was *used* to submit the variables.
My code's below (though I'm not sure it's strictly relevant to the question):
```
<?php
$bmiSubmitted = $_POST['bmiSubmitted'];
if (isset($bmiSubmitted)) {
$height = $_POST['height'];
$weight = $_POST['weight'];
$bmi = floor($weight/($height*$height));
?>
<ul id="bmi">
<li>Weight (in kilograms) is: <span><?php echo "$weight"; ?></span></li>
<li>Height (in metres) is: <span><?php echo "$height"; ?></span></li>
<li>Body mass index (BMI) is: <span><?php echo "$bmi"; ?></span></li>
</ul>
<?php
}
else {
?>
<div id="formSelector">
<ul>
<li><a href="#metric">Metric</a></li>
<li><a href="#imperial">Imperial</a></li>
</ul>
<form name="met" id="metric" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">
<fieldset>
<label for="weight">Weight (<abbr title="Kilograms">kg</abbr>):</label>
<input type="text" name="weight" id="weight" />
<label for="height">Height (<abbr title="metres">m</abbr>):</label>
<input type="text" name="height" id="height" />
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>
<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>
<form name="imp" id="imperial" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="form/multipart">
<fieldset>
<label for="weight">Weight (<abbr title="Pounds">lbs</abbr>):</label>
<input type="text" name="weight" id="weight" />
<label for="height">Height (Inches):</label>
<input type="text" name="height" id="height" /
<input type="hidden" name="bmiSubmitted" id="bmiSubmitted" value="1" />
</fieldset>
<fieldset>
<input type="reset" id="reset" value="Clear" />
<input type="submit" id="submit" value="Submit" />
</fieldset>
</form>
<?php
}
?>
```
I verified that it worked (though without validation at the moment -I didn't want to crowd my question too much) with metric; I've added the form but not the processing for the imperial yet. | To identify the submitted form, you can use:
* A hidden input field.
* The name or value of the submit button.
The name of the form is not sent to the server as part of the [POST](https://en.wikipedia.org/wiki/POST_%28HTTP%29) data.
You can use code as follows:
```
<form name="myform" method="post" action="" enctype="multipart/form-data">
<input type="hidden" name="frmname" value=""/>
</form>
``` | You can do it like this:
```
<input type="text" name="myform[login]">
<input type="password" name="myform[password]">
```
Check the posted values
```
if (isset($_POST['myform'])) {
$values = $_POST['myform'];
// $login = $values['login'];
// ...
}
``` | How to access the form's 'name' variable from PHP | [
"",
"php",
"forms",
""
] |
I've been going deeper into C++ recently and my bugs seem to get complex.
I have a vector of objects, each object contains a vector of floats. I decided I needed to create a further flat array containing all the float values of all objects in one. It's a little more complex than that but the gist of the problem is that as I loop through my objects extracting the float values, at some point my vector of objects is changed, or corrupted in some strange way. (My read operations are all const functions)
Another example was with MPI. I was just getting started so I just wanted to run the exact same code on two different nodes with their own memory and with no data transfer happening, all very simple. To my surprise I got segmentation errors and after hours tracking, I found that one assignment of one variable was setting an entirely different variable to NULL.
So I am curious, how is it possible that read operations can affect my data structures. Similarly how can a seemingly unrelated operation affect another. I couldn't expect solutions to my problems with those brief descriptions but any advice will be greatly appreciated.
Update:
Here's a segment of the code, I didn't post originally because I am not sure how much can be extracted from it without understanding the whole system.
One thing I just found out though was that when I stopped assigning the value to my flat array and just cout'ed instead, the seg errors disappeared. So perhaps I am declaring my array wrong, but even if I was I'm not sure how it would affect the object vector.
```
void xlMasterSlaveGpuEA::FillFlatGenes() {
int stringLength = pop->GetGenome(0).GetLength();
for (int i=0;i<pop->GetPopSize();i++)
for (int j=0;j<stringLength;j++)
flatGenes[(i*stringLength)+j]<< pop->GetGenome(i).GetFloatGene(j);
}
float xlVectorGenome::GetFloatGene(unsigned int i) const {
return GetGene(i);
}
```
my flat array is a member function
```
float * flatFitness;
```
initailsed in the constructor like so:
```
flatFitness = new float(popSize);
```
Update 2:
I just want to point out that the two examples above are not related, the first one is not multi threaded. The second MPI example is technically, but MPI is distributed memory and I deliberately attempted the most simple implementation I could think of, which is both machines running code independently. There is however one extra detail, I put in a condtional saying
```
if node 1 then do bottom half of loop
if node 1 then do top half
```
Again the memory should be isolated, they should be working as if they know nothing about each other.. but removing this conditional and making both loops do all cubes, eliminates the error | This is not an array constructor:
```
float * flatFitness;
flatFitness = new float(popSize);
```
You're creating one float on the heap here, initialized with value `popSize`. If you want an array of floats you need to use brackets instead of parentheses:
```
float *flatFitness = new float[popSize];
```
This could easily be causing the problems you describe. Also, remember when you create arrays, you need to delete using `delete []` (eventually):
```
delete [] flatFitness;
```
If you just use `delete`, it might work, but the behavior is undefined.
If you want to avoid using array syntax altogether, why not use `std::vector`? You can create a vector of popSize elements like this:
```
#include <vector>
std::vector<float> flatFitness(popSize);
```
This will be freed automatically when it falls out of scope, so you don't have to worry about `new` or `delete`.
**Update (re: comment):** If you're already using `std::vectors` elsewhere in your code, take a look at `std::vector::swap()`. You may be able to avoid copying things altogether and just swap a couple vectors back and forth between buffering for CUDA and the processing you're doing here. | I suspect you have multi-threading or memory corruption issues you are not aware of. The behavior you describe isn't any sort of standard, by-design, desirable behavior. | C++: How is it possible that reading data can affect memory? | [
"",
"c++",
"mpi",
"corruption",
""
] |
I am trying to execute this but cant see any result:
```
<script>
function init() {
document.getElementById('welcome').innerHTML = "<font color=white>Logged As:"+ param + "</font>";
}
window.onload = init;
</script>
<body>
...........
<div class="span-24 bottom_header" id="welcome"></div>
...........
</body>
```
what is wrong here.......... | This self-contained example works perfectly for me in Firefox and IE7:
```
<html><head><script>
function init() {
document.getElementById('welcome').innerHTML = "<font color=white>Logged As: TEST</font>";
}
window.onload = init;
</script></head>
<body>
<div class="span-24 bottom_header" id="welcome"></div>
</body></html>
```
You are adding white-on-white text, remember... | Maybe because your background is white and you are setting white color to your font: `<font color=white>`. Try with black :-) | document.getElementById doesnt seem to work | [
"",
"javascript",
""
] |
I want to go through all the elements on a page using Javascript and see if they have a property set. Is there an easy way to do this, or do I have to use a recursive solution? | You can use:
```
var divs = document.getElementsByTagName("div");
for(var i = 0; i < divs.length; i++){
//do something to each div like
divs[i].innerHTML = "something new...";
}
``` | To find a property in one or more of all divs on a page:
```
var divs = document.getElementsByTagName("div"), i=divs.length;
while (i--) {
if (divs[i].getAttribute([yourProperty]) === 'yourValue'){
//do something
}
}
```
[**edit october 2022**] Very old answer. Today I would advise to use a css selector. For example:
```
const withStyle = document.querySelectorAll('[style]');
console.log(`Found ${withStyle.length} elements with style:\n${
[...withStyle]
.map(el =>`<${el.tagName}>: ${el.getAttribute('style')}`)
.join(`; `) }` );
```
```
<div style="color:#777">
<div style="color:red;background:#EEE">red</div>
<div>no color</div>
<div data-something>data-attribute</div>
<div style="color:green">green</div>
<span>Hello</span>
<h3 style="font-family:monospace">That's all folks</h3>
</div>
``` | Iterating through all the <div> tags on a page | [
"",
"javascript",
"html",
"recursion",
"iteration",
""
] |
For example I've often wanted to search stackoverflow with
```
SELECT whatever FROM questions WHERE
views * N + votes * M > answers AND NOT(answered) ORDER BY views;
```
or something like that.
*Is there any reasonable way to allow users to use SQL as a search/filter language?*
I see a few problems with it:
* Accessing/changing stuff (a carefully setup user account should fix that)
* SQL injection (given the previous the worst they should be able to do is get back junk and crash there session).
* DOS attacks with pathological queries
* What indexes do you give them?
*Edit:* I'd like to allow joins and what not as well. | **Accessing/changing stuff**
No problem, just run the query with a crippled user, with permissions only to select
**SQL injection**
Just sanitize the query
**DOS attacks**
Time-out the query and throttle the access by IP. I guess you can also throttle the CPU usage in some servers | If you do `SQLEncode` your users' input (and make sure to remove all `;` as well!), I see no huge safety flaw (other than that we're still handing nukes out to psychos...) in having three input boxes - one for table, one for columns and one for conditions. They won't be able to have strings in their conditions, but queries like your example should work. You will do the actual pasting together of the SQL statement, so you'll be in control of what is actually executed. If your setup is good enough you'll be safe.
BUT, I wouldn't for my life let my user enter SQL like that. If you want to really customize search options, give either a bunch of flags for the search field, or a bunch of form elements that can be combined at will.
Another option is to invent some kind of "markup language", sort of like Markdown (the framework SO uses for formatting all these questions and answers...), that you can translate to SQL. Then you can make sure that only "harmless" selects are performed, and you can protect user data etc.
In fact, if you ever implement this, you should see if you could run the commands from a separate account on the SQL server, which only has access to the very basic needs, and obviously only read access. | "Safely" allow users to search with SQL | [
"",
"sql",
"security",
"web-applications",
""
] |
I have binary files no larger than 20Mb in size that have a header section and then a data section containing sequences of uchars. I have Numpy, SciPy, etc. and each library has different ways of loading in the data. Any suggestions for the most efficient methods I should use? | [struct](http://docs.python.org/library/struct.html) should work for the header section, while numpy's [memmap](http://docs.scipy.org/doc/numpy/reference/generated/numpy.memmap.html#numpy.memmap) would be efficient for the data section if you are going to manipulate it in numpy anyways. There's no need to stress out about being inconsistent here. Both methods are compatible, just use the right tool for each job. | Use the [struct](http://docs.python.org/library/struct.html) module, or possibly a custom module written in C if performance is critical. | Most efficient way of loading formatted binary files in Python | [
"",
"python",
"input",
"binaryfiles",
""
] |
Let's say I have a set of vectors (readings from sensor 1, readings from sensor 2, readings from sensor 3 -- indexed first by timestamp and then by sensor id) that I'd like to correlate to a separate set of vectors (temperature, humidity, etc -- also all indexed first by timestamp and secondly by type).
What is the cleanest way in numpy to do this? It seems like it should be a rather simple function...
In other words, I'd like to see:
```
> a.shape
(365,20)
> b.shape
(365, 5)
> correlations = magic_correlation_function(a,b)
> correlations.shape
(20, 5)
```
Cheers,
/YGA
P.S. I've been asked to add an example.
Here's what I would like to see:
```
$ In [27]: x
$ Out[27]:
array([[ 0, 0, 0],
[-1, 0, -1],
[-2, 0, -2],
[-3, 0, -3],
[-4, 0.1, -4]])
$ In [28]: y
$ Out[28]:
array([[0, 0],
[1, 0],
[2, 0],
[3, 0],
[4, 0.1]])
$ In [28]: magical_correlation_function(x, y)
$ Out[28]:
array([[-1. , 0.70710678, 1. ]
[-0.70710678, 1. , 0.70710678]])
```
Ps2: whoops, mis-transcribed my example. Sorry all. Fixed now. | The simplest thing that I could find was using the scipy.stats package
```
In [8]: x
Out[8]:
array([[ 0. , 0. , 0. ],
[-1. , 0. , -1. ],
[-2. , 0. , -2. ],
[-3. , 0. , -3. ],
[-4. , 0.1, -4. ]])
In [9]: y
Out[9]:
array([[0. , 0. ],
[1. , 0. ],
[2. , 0. ],
[3. , 0. ],
[4. , 0.1]])
In [10]: import scipy.stats
In [27]: (scipy.stats.cov(y,x)
/(numpy.sqrt(scipy.stats.var(y,axis=0)[:,numpy.newaxis]))
/(numpy.sqrt(scipy.stats.var(x,axis=0))))
Out[27]:
array([[-1. , 0.70710678, -1. ],
[-0.70710678, 1. , -0.70710678]])
```
These aren't the numbers you got, but you've mixed up your rows. (Element [0,0] should be 1.)
A more complicated, but purely numpy solution is
```
In [40]: numpy.corrcoef(x.T,y.T)[numpy.arange(x.shape[1])[numpy.newaxis,:]
,numpy.arange(y.shape[1])[:,numpy.newaxis]]
Out[40]:
array([[-1. , 0.70710678, -1. ],
[-0.70710678, 1. , -0.70710678]])
```
This will be slower because it computes the correlation of each element in x with each other element in x, which you don't want. Also, the advanced indexing techniques used to get the subset of the array you desire can make your head hurt.
If you're going to use numpy intensely, get familiar with the rules on [broadcasting](http://www.scipy.org/EricsBroadcastingDoc) and [indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html). They will help you push as much down to the C-level as possible. | Will this do what you want?
```
correlations = dot(transpose(a), b)
```
Note: if you do this, you'll probably want to standardize or whiten `a` and `b` first, e.g. something equivalent to this:
```
a = sqrt((a - mean(a))/(var(a)))
b = sqrt((b - mean(b))/(var(b)))
``` | Correlate one set of vectors to another in numpy? | [
"",
"python",
"numpy",
""
] |
This is one of my first issues. Whenever I exit out the program, tcpClient.Connect() takes forever to close. I've tried a ton of things, and none of them seem to work.
Take a look at the CreateConnection() thread, if the client isn't connected yet... and I close the program, it takes forever to close. If it IS connected, it closes immediately. I know this can be done with some kind of timeout trick, but i've tried a few and none of them worked.
Please provide a code example if you can.
If you see anything else to help me improve this... by all means, go ahead. I'm trying to teach myself how to do this and I have no help, so don't let me go on doing something wrong if you see it!
```
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace RemoteClient
{
public partial class Form1 : Form
{
private int MyPort = 56789;
private IPAddress myIp = IPAddress.Parse("210.232.115.79");
private IPAddress serverIp = IPAddress.Parse("72.216.18.77"); // Master Server's IP Address
public static TcpClient masterServer = new TcpClient();
private StreamWriter responseWriter;
private StreamReader commandReader;
private Thread connectionThread;
private Thread commandsThread;
private bool RequestExitConnectionThread { get; set; }
private delegate void AddMessageDelegate(string message, int category);
private delegate void ConnectedDelegate();
private bool isConnected { get; set; }
public Form1()
{
InitializeComponent();
isConnected = false;
}
private void LogMessage(string message, int category)
{
if (category == 1)
{
ListViewItem item = new ListViewItem(message);
item.BackColor = Color.LightGreen;
item.UseItemStyleForSubItems = true;
Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
}
if (category == 2)
{
ListViewItem item = new ListViewItem(message);
item.BackColor = Color.Orange;
item.UseItemStyleForSubItems = true;
Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
}
if (category == 3)
{
ListViewItem item = new ListViewItem(message);
item.BackColor = Color.Yellow;
item.UseItemStyleForSubItems = true;
Log.Items.Add(item).SubItems.Add(DateTime.Now.ToString());
}
if (category == 0)
{
Log.Items.Add(message).SubItems.Add(DateTime.Now.ToString());
}
}
private void Connected()
{
LogMessage("Found and Accepted Master Server's connection. Waiting for reply...",1);
Status.Text = "Connected!";
Status.ForeColor = Color.Green;
commandsThread = new Thread(new ThreadStart(RecieveCommands));
sendClientInfo();
}
private void exitButton_Click(object sender, EventArgs e)
{
Disconnect();
exitButton.Enabled = false;
exitButton.Text = "Closing...";
if (connectionThread != null)
{
while (connectionThread.IsAlive)
{
Application.DoEvents();
}
}
this.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
Connect();
}
private void Disconnect()
{
RequestExitConnectionThread = true;
if (masterServer != null)
masterServer.Close();
if (connectionThread != null)
connectionThread.Abort();
LogMessage("Closing Client. Please wait while Program threads end.", 2);
}
private void Disconnected()
{
Status.Text = "Disconnected";
Status.ForeColor = Color.Red;
Connect();
}
private void Connect()
{
LogMessage("Attempting to connect to Master Server...", 1);
connectionThread = new Thread(new ThreadStart(CreateConnection));
connectionThread.Start();
}
private void CreateConnection()
{
int i = 1;
bool success = false;
while (!success)
{
try
{
using (masterServer = new TcpClient())
{
IAsyncResult result = masterServer.BeginConnect(serverIp, MyPort, null, null);
success = result.AsyncWaitHandle.WaitOne(1000, false);
}
if (success)
{
BeginInvoke(new ConnectedDelegate(this.Connected), new object[] {});
break;
}
else
{
Thread.Sleep(2000);
BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Connection Retry # " + i.ToString() + ". Master Server hasn't been started yet.", 3 });
}
}
catch
{
MessageBox.Show("Error!");
}
i++;
}
}
private void RecieveCommands()
{
MessageBox.Show("Hello!");
commandReader = new StreamReader(masterServer.GetStream());
string CommandResponse = commandReader.ReadLine();
string Command = null;
if (CommandResponse != null)
MessageBox.Show("Recieved Command that was NOT null!");
if (CommandResponse != null)
{
MessageBox.Show("Recieved null response!");
BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Disconnected From Master Server. Reason: Recieved Null response.", 1 });
Disconnected();
}
else if (CommandResponse.StartsWith("0"))
{
MessageBox.Show("Recieved 0 as a response!");
Command = CommandResponse.Substring(2).Trim();
isConnected = false;
BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Disconnected From Master Server. Reason: " + Command, 1 });
}
else if (CommandResponse.StartsWith("1"))
{
MessageBox.Show("Recieved 1 as a response!");
isConnected = true;
BeginInvoke(new AddMessageDelegate(LogMessage), new object[] { "Connected to Master Server Successfully.", 1 });
}
}
//************************** RESPONSE'S BELOW HERE ************************* \\
private void sendClientInfo()
{
responseWriter = new StreamWriter(masterServer.GetStream());
responseWriter.WriteLine(myIp.ToString());
responseWriter.Flush();
}
}
}
``` | Adding a check within your connection process to cancel it if the program is exiting should help.
Try adding this in `CreateConnection()` inside your `while(!success)` loop but before your `try` block:
```
if(RequestExitConnectionThread)
{
break;
}
```
Here's an example of an asynchronous BeginConnect() call:
```
myTcpClient.BeginConnect("localhost", 80, OnConnect, null);
```
OnConnect function:
```
public static void OnConnect(IAsyncResult ar)
{
// do your work
}
``` | Sorry, after testing it: NO, it does not use an async waithandle, it blocks the process :(
I prefer this solution, which also blocks the process but only by the period you specify, in this case 5 seconds:
```
using (TcpClient tcp = new TcpClient())
{
IAsyncResult ar = tcp.BeginConnect("127.0.0.1", 80, null, null);
System.Threading.WaitHandle wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
{
tcp.Close();
throw new TimeoutException();
}
tcp.EndConnect(ar);
}
finally
{
wh.Close();
}
}
```
From: <http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/2281199d-cd28-4b5c-95dc-5a888a6da30d>
The following example uses both async connection and async timeout control:
```
var tcp = new TcpClient();
var ar = tcp.BeginConnect(Ip, Port, null, null);
Task.Factory.StartNew(() =>
{
var wh = ar.AsyncWaitHandle;
try
{
if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))
{
// The logic to control when the connection timed out
tcp.Close();
throw new TimeoutException();
}
else
{
// The logic to control when the connection succeed.
tcp.EndConnect(ar);
}
}
finally
{
wh.Close();
}
});
``` | C# How do I stop a tcpClient.Connect() process when i'm ready for the program to end? It just sits there for like 10 seconds | [
"",
"c#",
"timeout",
"tcpclient",
""
] |
I'm looking for a 3D graphics library for a Java web app. Could use some recommendations - only open source, though.
Edit: I don't really care how the graphics are output - Javascript/applets/canvas/flash but I want to write the graphics logic in Java. | JMonkeyEngine is very good. | Have a look at the *The Lightweight Java Game Library*. It provided developers access to crossplatform libraries such as openGl. And can run in the browser.
* <http://lwjgl.org>
Here are a few demos:
* <http://lwjgl.org/applet/>
* <http://fabiensanglard.net/Prototyp/index.php>
* <http://www.cokeandcode.com/info/tut2d-4.html>
People are doing awesome projects with this library:
<http://lwjgl.org/projects.php> | What's the best 3D graphics library for Java web apps? | [
"",
"java",
"web-applications",
"graphics",
"3d",
""
] |
Our project is using many static libraries to build the application. How can we make sure we are using release version of libraries in release build of application?
We are making mistakes by taking debug library in release application build.
I am looking for an elegant way in which I can write a module in that we can check whether a particular library is release or debug and report it if not matching. Our application is written in C/C++. (Platform MSVC & GCC) | The normal approach is eithr to give the libraries different names or store them in different directories, such as Debug and Release. And if your build is correctly automated, I can't see how you can make mistakes. | Yes. You can check the `Characteristics` field of the `IMAGE_FILE_HEADER` structure of the file. If the library is a release build, then bit 0x0200 (`DEBUG_STRIPPED`) will be set; on a debug build, it will be clear.
You can find technical information on the PE Format used by Windows EXEs and DLLs, to see how to retrieve that structure, in various places on the 'net (such as [here](http://www.csn.ul.ie/~caolan/publink/winresdump/winresdump/doc/pefile.html)). | How to identify if a library is DEBUG or RELEASE build? | [
"",
"c++",
""
] |
Im trying to build a little site using XML instead of a database.
I would like to build a next and prev button which will work relative to the content I have displayed.
I found the php function next() and prev() as well as current() but I do not know how to set the pointer to a specific position to be able to navigate relative to the current page.
```
$list=array('page1','page2','page3')
```
eg if im displaying contents of page2 how could I tell php i am at $list[1] so that next($list) shows page3?
Thanks in advance | If your array is always indexed consistently (eg. 'page1' is always at index '0'), it's fairly simple:
```
$List = array('page1', 'page2', 'page3', 'page4', 'page5');
$CurrentPage = 3; // 'page4'
while (key($List) !== $CurrentPage) next($List); // Advance until there's a match
```
I personally don't rely on automatic indexing because there's always a chance that the automatic index might change. You should consider explicitly defining the keys:
```
$List = array(
'1' => 'page1',
'2' => 'page2',
'3' => 'page3',
);
```
**EDIT:** If you want to test the values of the array (instead of the keys), use [`current()`](http://php.net/current):
```
while (current($List) !== $CurrentPage) next($List);
``` | Using the functions below, you can get the *next* and *previous* **values** of the array.
If current **value** is not valid or it is the **last** (**first** *- for prev*) **value** in the array, then:
* the function **getNextVal(...)** returns the first **element value*** the function **getPrevVal(...)** returns the last **element value**
The functions are cyclic.
```
function getNextVal(&$array, $curr_val)
{
$next = 0;
reset($array);
do
{
$tmp_val = current($array);
$res = next($array);
} while ( ($tmp_val != $curr_val) && $res );
if( $res )
{
$next = current($array);
}
return $next;
}
function getPrevVal(&$array, $curr_val)
{
end($array);
$prev = current($array);
do
{
$tmp_val = current($array);
$res = prev($array);
} while ( ($tmp_val != $curr_val) && $res );
if( $res )
{
$prev = current($array);
}
return $prev;
}
``` | How to set an Arrays internal pointer to a specific position? PHP/XML | [
"",
"php",
"xml",
"arrays",
""
] |
I'm learning C++ and I'm still confused about this. What are the implications of return a value as constant, reference and constant reference in C++ ? For example:
```
const int exampleOne();
int& exampleTwo();
const int& exampleThree();
``` | Here's the lowdown on all your cases:
**• Return by reference**: The function call can be used as the left hand side of an assignment. e.g. using operator overloading, if you have operator[] overloaded, you can say something like
```
a[i] = 7;
```
(when returning by reference you need to ensure that the object you return is available after the return: you should not return a reference to a local or a temporary)
**• Return as constant value**: Prevents the function from being used on the left side of an assignment expression. Consider the overloaded operator+. One could write something like:
```
a + b = c; // This isn't right
```
Having the return type of operator+ as "const SomeType" allows the return by value and at the same time prevents the expression from being used on the left side of an assignment.
Return as constant value also allows one to prevent typos like these:
```
if (someFunction() = 2)
```
when you meant
```
if (someFunction() == 2)
```
If someFunction() is declared as
```
const int someFunction()
```
then the if() typo above would be caught by the compiler.
**• Return as constant reference**: This function call cannot appear on the left hand side of an assignment, and you want to avoid making a copy (returning by value). E.g. let's say we have a class Student and we'd like to provide an accessor id() to get the ID of the student:
```
class Student
{
std::string id_;
public:
const std::string& id() const;
};
const std::string& Student::id()
{
return id_;
}
```
Consider the id() accessor. This should be declared const to guarantee that the id() member function will not modify the state of the object. Now, consider the return type. If the return type were string& then one could write something like:
```
Student s;
s.id() = "newId";
```
which isn't what we want.
We could have returned by value, but in this case returning by reference is more efficient. Making the return type a const string& additionally prevents the id from being modified. | The basic thing to understand is that returning by value will create a new copy of your object. Returning by reference will return a reference to an existing object. NOTE: Just like pointers, you CAN have dangling references. So, don't create an object in a function and return a reference to the object -- it will be destroyed when the function returns, and it will return a dangling reference.
**Return by value:**
* When you have POD (Plain Old Data)
* When you want to return a copy of an object
**Return by reference:**
* When you have a performance reason to avoid a copy of the object you are returning, and you understand the lifetime of the object
* When you must return a particular instance of an object, and you understand the lifetime of the object
Const / Constant references help you enforce the contracts of your code, and help your users' compilers find usage errors. They do not affect performance. | Which are the implications of return a value as constant, reference and constant reference in C++? | [
"",
"c++",
"return-value",
""
] |
This query is taking long time when endDate is null (i think that its about case statement, before case statement it was fast)
```
SELECT *
FROM HastaKurumlari
WHERE CONVERT(SMALLDATETIME,'21-05-2009',103)
BETWEEN startDate
AND (CASE WHEN endDate IS NULL THEN GETDATE() ELSE endDate END)
```
What should i use, when endDate is null to make it faster ? | Here's the query without CONVERT or CASE:
```
SELECT *
FROM HastaKurumlari
WHERE '21-05-2009' between startDate and IsNull(endDate,getdate())
```
To make sure Sql Server doens't evaluate getdate() for every row, you could cache it, although I'm pretty sure Sql Server is smart enough by default:
```
declare @now datetime
set @now = getdate()
SELECT *
FROM HastaKurumlari
WHERE '21-05-2009' between startDate and IsNull(endDate,@now)
```
Posting the query plan could help explain why the query is slow:
```
SET SHOWPLAN_TEXT ON
go
SELECT *
FROM HastaKurumlari
WHERE CONVERT(SMALLDATETIME,'21-05-2009',103)
BETWEEN startDate
AND (CASE WHEN endDate IS NULL THEN GETDATE() ELSE endDate END)
``` | You could try the [coalesce](http://doc.ddart.net/mssql/sql70/ca-co_8.htm) function:
```
select *
from HastaKurumlari
where convert(smalldatetime, '21-05-2009', 103)
between startDate and coalesce(endDate, getdate());
```
The only way to be certain is to try any alternatives and view the execution plan generated for each query. | How to make faster this statement : "paramDate Between startDate and NULL"? | [
"",
"sql",
"sql-server",
"t-sql",
"between",
""
] |
Basically when user resizes my application's window I want application to be same size when application is re-opened again.
At first I though of handling SizeChanged event and save Height and Width, but I think there must be easier solution.
Pretty simple problem, but I can not find easy solution to it. | Save the values in the user.config file.
You'll need to create the value in the settings file - it should be in the Properties folder. Create five values:
* `Top` of type `double`
* `Left` of type `double`
* `Height` of type `double`
* `Width` of type `double`
* `Maximized` of type `bool` - to hold whether the window is maximized or not. If you want to store more information then a different type or structure will be needed.
Initialise the first two to 0 and the second two to the default size of your application, and the last one to false.
Create a Window\_OnSourceInitialized event handler and add the following:
```
this.Top = Properties.Settings.Default.Top;
this.Left = Properties.Settings.Default.Left;
this.Height = Properties.Settings.Default.Height;
this.Width = Properties.Settings.Default.Width;
// Very quick and dirty - but it does the job
if (Properties.Settings.Default.Maximized)
{
WindowState = WindowState.Maximized;
}
```
**NOTE:** The set window placement needs to go in the on source initialised event of the window not the constructor, otherwise if you have the window maximised on a second monitor, it will always restart maximised on the primary monitor and you won't be able to access it.
Create a Window\_Closing event handler and add the following:
```
if (WindowState == WindowState.Maximized)
{
// Use the RestoreBounds as the current values will be 0, 0 and the size of the screen
Properties.Settings.Default.Top = RestoreBounds.Top;
Properties.Settings.Default.Left = RestoreBounds.Left;
Properties.Settings.Default.Height = RestoreBounds.Height;
Properties.Settings.Default.Width = RestoreBounds.Width;
Properties.Settings.Default.Maximized = true;
}
else
{
Properties.Settings.Default.Top = this.Top;
Properties.Settings.Default.Left = this.Left;
Properties.Settings.Default.Height = this.Height;
Properties.Settings.Default.Width = this.Width;
Properties.Settings.Default.Maximized = false;
}
Properties.Settings.Default.Save();
```
This will fail if the user makes the display area smaller - either by disconnecting a screen or changing the screen resolution - while the application is closed so you should add a check that the desired location and size is still valid before applying the values. | Actually you don't need to use code-behind to do that (except for saving the settings). You can use a custom markup extension to bind the window size and position to the settings like this :
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication1"
Title="Window1"
Height="{my:SettingBinding Height}"
Width="{my:SettingBinding Width}"
Left="{my:SettingBinding Left}"
Top="{my:SettingBinding Top}">
```
You can find the code for this markup extension here :
<http://www.thomaslevesque.com/2008/11/18/wpf-binding-to-application-settings-using-a-markup-extension/> | .NET WPF Remember window size between sessions | [
"",
"c#",
".net",
"wpf",
"windows",
""
] |
I have two questions:
1) Why is my code adding a carriage return at the beggining of the selected\_line string?
2) Do you think the algorithm I'm using to return a random line from the file is good enough and won't cause any problems?
A sample file is:
```
line
number one
#
line number two
```
My code:
```
int main()
{
srand(time(0));
ifstream read("myfile.dat");
string line;
string selected_line;
int nlines = 0;
while(getline(read, line, '#')) {
if((rand() % ++nlines) == 0)
selected_line = line;
}
// this is adding a \n at the beginning of the string
cout << selected_line << endl;
}
```
**EDIT:** OK, what some of you suggested makes a lot of sense. The string is probably being read as "\nmystring". So I guess my question now is, how would i remove the first \n from the string? | What you probably want is something like this:
```
std::vector<std::string> allParagraphs;
std::string currentParagraph;
while (std::getline(read, line)) {
if (line == "#") { // modify this condition, if needed
// paragraph ended, store to vector
allParagraphs.push_back(currentParagraph);
currentParagraph = "";
else {
// paragraph continues...
if (!currentParagraph.empty()) {
currentParagraph += "\n";
}
currentParagraph += line;
}
}
// store the last paragraph, as well
// (in case it was not terminated by #)
if (!currentParagraph.empty()) {
allParagraphs.push_back(currentParagraph);
}
// this is not extremely random, but will get you started
size_t selectedIndex = rand() % allParagraphs.size();
std::string selectedParagraph = allParagraphs[selectedIndex];
```
For better randomness, you could opt for this instead:
```
size_t selectedIndex
= rand() / (double) (RAND_MAX + 1) * allParagraphs.size();
```
This is because the least significant bits returned by `rand()` tend to behave not so randomly at all. | Because you don't specify `\n` as a delimeter. | C++ adding a carriage return at beginning of string when reading file | [
"",
"c++",
"random",
"fstream",
""
] |
I am working off this example.
<http://www.drury.net.nz/2005/04/15/specifying-a-sort-parameter-for-a-tsql-stored-procedure/>
```
CREATE PROCEDURE getEmployees ( @ColumnName varchar(100) )
AS
SELECT
EmployeeID,
FirstName,
LastName,
SSN,
Salary
FROM
Employees
ORDER BY
CASE
WHEN @ColumnName=’LastName’ THEN LastName
WHEN @ColumnName=’Salary’ THEN CONVERT(varchar(50), Salary)
WHEN @ColumnName=’SSN’ THEN SSN
END
```
The case statement works, but what if I have the following parameters: @SortColumn, @SortDirection.
The @SortColumn could be any column of any type and it seems to use the case statement you have to convert the values to the same type. I suppose I can make them all VARCHAR and just make sure values like DateTime are put in the proper order to sort as I want.
But what if I have the @SortDirection parameter set as ASC or DESC as a VARCHAR value? How can I adjust the query to do change the sort direction? | If you don't want to use dynamic SQL then you can do it like this by having case statements that lead to non filtered parts of the where clause; it wont be quick though. You also need to be careful that the types in your case sections match up.
```
SELECT
*
FROM
dbo.Contacts
ORDER BY
CASE @Sort
WHEN 1 THEN Surname
WHEN 2 THEN Forename
WHEN 3 THEN Telephone_Number
ELSE ''
END ASC
,
CASE @Sort
WHEN 4 THEN Personnel_Ref
WHEN 5 THEN timesheet_number
WHEN 6 THEN Telephone_Number
ELSE ''
END DESC
``` | (I don't have enough of a reputation to comment apparently, so I'm replying here)
In reply to:
> Do you know how I could avoid using sp\_executesql? I have heard that if you use
> that then it cannot cache the query plan. – Brennan Apr 28 at 0:16
Actually, in most cases, sp\_executesql allows the query plan to be cached the same as a stored procedure.
The trick is to use parameterized dynamic sql, like so:
```
exec sp_executesql N'select from MyTable where myId = @id', N'@id int', @id;
```
This way, you are running the same query, just substituting in the @id, just like with a stored procedure. With dynamic sql, the query plan is cached based on the string value of the query (the first param to sp\_executesql).
The only question I would ask, is why do you have to sort this in the database? I feel like you should be sorting this later on...
However, since the sort expression and direction can NOT be parameterized (they must be concatenated right in to the query string), you will get a separate query plan cached for every sort expression and direction. This probably isn't a big deal.
**EDIT:**
Here's a link explaining how [dynamic SQL query plans are cached](http://blog.namwarrizvi.com/?p=145). | How can I run a query to sort by a column and asc/desc using parameters? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
```
private static readonly string dataProvider = ConfigurationManager.AppSettings.Get("Provider");
private static readonly DbProviderFactory factory = DbProviderFactories.GetFactory(dataProvider);
private static readonly string connectionString = ConfigurationManager.ConnectionStrings[dataProvider].ConnectionString;
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql)
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
connection.Open();
return command.ExecuteNonQuery();
}
}
}
```
I need help in re-writing this so that it'll work with stored procedures. (Pass in sproc name and params)
Does anyone have any idea how i should go about doing this?
Edit: The area I'm having problems with is trying to figure out ways to fill in params.
Thanks | You already need parameters independent of whether you're implementing stored procedures.
Right now, your code could be called with a query like `SELECT * FROM Table WHERE ID = @ID`, in which case, you already need to pass a `Dictionary<string,object> params`. Have your code fill in the Parameters collection of the command you already have, and test that, before worrying about stored procedures.
Once that works, you should simply create an overload that accepts a bool that says this is a stored procedure, then use it to set the CommandType property of the command.
---
**Edit: Here's How I Would Refactor It**
*Step 1: Generalize Update*
There's nothing special about the Update method that prevents it being used for other non-query operations, aside from the name. So:
```
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql)
{
return NonQuery(sql);
}
public static int NonQuery(string sql)
{
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
connection.Open();
return command.ExecuteNonQuery();
}
}
}
```
*Step 2: What About Parameters?*
Your current code couldn't even handle UPDATE queries that used parameters, so let's start fixing that. First, make sure it still works if no parameters are specified:
```
public static int NonQuery(string sql)
{
Dictionary<string, object> parameters = null;
if (parameters == null)
{
parameters = new Dictionary<string, object>();
}
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
foreach (KeyValuePair<string, object> p in parameters)
{
var parameter = command.CreateParameter();
parameter.ParameterName = p.Key;
parameter.Value = p.Value;
command.Parameters.Add(parameter);
}
connection.Open();
return command.ExecuteNonQuery();
}
}
}
```
Once that works, promote *parameters* to be a parameter. This doesn't affect any existing callers of `Update`:
```
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql)
{
return NonQuery(sql, null);
}
public static int NonQuery(string sql, Dictionary<string, object> parameters)
```
At this point, test NonQuery with a parameterized query. Once that works, create an overload of Update that accepts the parameters:
```
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql)
{
return NonQuery(sql, null);
}
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <param name="parameters">Name/value dictionary of parameters</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql, Dictionary<string, object> parameters)
{
return NonQuery(sql, parameters);
}
```
*Step 3: Take Stored Procedures Into Account*
There's little difference in terms of how stored procedures would be handled. What you've already got is implicitly as follows:
```
using (DbCommand command = factory.CreateCommand())
{
command.Connection = connection;
command.CommandText = sql;
command.CommandType = CommandType.Text;
```
So take the CommandType.Text and promote it to be a parameter in an overload:
```
public static int NonQuery(string sql, Dictionary<string, object> parameters)
{
return NonQuery(sql, CommandType.Text, parameters);
}
public static int NonQuery(string sql, CommandType commandType, Dictionary<string, object> parameters)
```
Finally, if you like, update `Update`:
```
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <param name="parameters">Name/value dictionary of parameters</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql, Dictionary<string, object> parameters)
{
return Update(sql, CommandType.Text, parameters);
}
/// <summary>
/// Executes Update statements in the database.
/// </summary>
/// <param name="sql">Sql statement.</param>
/// <param name="commandType">CommandType.Text or CommandType.StoredProcedure</param>
/// <param name="parameters">Name/value dictionary of parameters</param>
/// <returns>Number of rows affected.</returns>
public static int Update(string sql, CommandType commandType, Dictionary<string, object> parameters)
{
return NonQuery(sql, parameters);
}
```
Of course, as a final exercise for the reader, you might replace all your Update calls with calls to NonQuery and get rid of Update entirely.
---
Of course, this simple technique doesn't handle output parameters, or situations where it's necessary to specify the DbType of the parameter. For that, you'd need to accept a ParameterCollection of some kind. | You could add 3 parameters :
1. `string SchemaName` -- store the name of the database schema
2. `string StoredProcName` -- store the name of the stored procedure
3. `List<Parameter>` -- list of your stored procedure parameters | Refactoring DAL Code to Support Stored Procedures | [
"",
"c#",
"refactoring",
"data-access-layer",
""
] |
I've been programming Ruby pretty extensively for the past four years or so, and I'm extremely comfortable with the language. For no particular reason, I've decided to learn some Python this week. Is there a specific book, tutorial, or reference that would be well-suited to someone coming from a nearly-identical language, or should I just "Dive into Python"?
Thanks! | A safe bet is to just dive into python (skim through some tutorials that explain the syntax), and then get coding. The best way to learn any new language is to write code, [lots of it](http://projecteuler.net/index.php?section=problems). Your experience in Ruby will make it easy to pick up python's dynamic concepts (which might be harder to get used to for say a Java programmer).
Try a [python tutorial](http://docs.python.org/tutorial/) or [book on learning python](http://www.diveintopython.org/). | I started learning from the [python tutorial](http://docs.python.org/tutorial/). It is well written and easy to follow. Then I started to solve problems in [python challenge](http://www.pythonchallenge.com/). It was a really fun way to start :) | What's the quickest way for a Ruby programmer to pick up Python? | [
"",
"python",
"ruby",
""
] |
Is there an easy way to wrap a "Preferences Panel" thing around the `Settings.settings` file (or any other settings file)?
Basically I have a bunch of strings stored in `Settings.settings`, and want to have a form where the user can edit these..
I could add a bunch of TextBoxes, and have a button that does `Properties.blah = this.blahInput.Text; Properties.Save();` for each, but this feels like reinventing the wheel..
*Edit:* The PropertyGrid control (as suggested by [bassfriend's](https://stackoverflow.com/questions/846144/visual-c-settings-editor-within-application/846163#846163)) seems perfect, but I cannot work out how to bind the property grid's SelectedObject to `Properties.Settings.Default` - When I try I get the following error:
```
Cannot implicitly convert type 'MyProject.Properties.Settings' to 'object[]'
``` | Maybe you want to take a look at the [PropertyGrid Control](http://msdn.microsoft.com/en-us/library/system.windows.forms.propertygrid.aspx). | I had no problem:
```
propertyGrid1.SelectedObject = Properties.Settings.Default;
```
I did have to change the visibility to Public in the Settings Designer. | Visual C# "Settings Editor" within application? | [
"",
"c#",
".net",
"settings",
""
] |
I have a jsp page which should load a popup using ajax. The content of the page is determined by form filled by user.
Something like this:
javascript:
```
ajax('getPage.action', 'content_id', 'form_id');
```
foo.jsp:
```
<div id="content_id"></div>
<form id="form_id">
...
</form>
```
java/spring:
```
@RequestMapping("getPage.action")
MyController extends AbstractCommandController {
RealDto dto = (RealDto)command;
...
return new ModelAndView("foo", data);
}
```
The most difficult part for me is how to send the form data easily as an ajax call. Can I use jQuery here? The form changes dynamically so it would be quite bothersome to list all the fields of the form.
Would it help to use Springs XT (which I never have)? | Yes, you can use [serialize](http://docs.jquery.com/Ajax/serialize) to trivially convert the form to send the data.
```
$("#form1").submit(function() {
$.get("/desiredURL", $("#form1").serialize(), function(response) {
// send response data to a popup
}
}
```
You can use [get](http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype) or [post](http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype) to send the data.
For the popup I like [facebox](https://github.com/defunkt/facebox), but there's loads of choices. | [jQuery form plug-in](http://malsup.com/jquery/form) can help you easily transform a regular form to an Ajax one. You only need a single line of code:
```
$("#myform").ajaxForm(
{beforeSubmit: validate, success: showPopup} );
``` | Loading a popup using ajax | [
"",
"java",
"jquery",
"spring",
"xt",
""
] |
I'm generating a MJpeg Stream and trying to stream it to VLC and play it there.
The code:
```
public void SendMultiPartData(String contentType, Func<byte[]> getData)
{
MemoryStream mem = null;
response.StatusCode = 200;
for ( byte[] buffer = getData(); buffer != null && buffer.Length > 0; buffer = getData())
{
response.ContentType = "multipart/x-mixed-replace; boundary=--testboundary";
ASCIIEncoding ae = new ASCIIEncoding();
byte[] boundary = ae.GetBytes("\r\n--testboundary\r\nContent-Type: " + contentType + "\r\nContent-Length:" + buffer.Length + "\r\n\r\n");
mem = new MemoryStream(boundary);
mem.WriteTo(response.OutputStream);
mem = new MemoryStream(buffer);
mem.WriteTo(response.OutputStream);
response.OutputStream.Flush();
}
mem.Close();
listener.Close();
}
```
If I try to open the stream with firefox, there's no problem at all, although with VLC it doesn't work (VLC seems to keep reading but never shows the video)
I've been sniffing VLC-to-VLC streaming and they seems to use as HTTP header "application/octet-stream" instead of multipart/x-mixed-replace
Any ideas ?
Tks in advance,
Jose | Jose,
I had exactly same problem. Firefox plays my stream but VLC doesnt. I went thru so many ways to figure this out including debugging VLC source code, and got no where.
btw My (REST) URL looks like <http://server:port/livevideo/xyz>
Then, I thought I should try <http://server:port/livevideo/xyz.mjpeg>
And guess what, VLC started to play video!
I think VLC might need a little hint more than content type to figure out it is a mjpeg stream.
Hope this helps.
Cindy | Have you tried this:
```
Response.Buffer = false;
Response.BufferOutput = false;
```
Or some variation of those? | Mjpeg VLC and HTTP Streaming | [
"",
"c#",
"http",
"streaming",
"vlc",
"mjpeg",
""
] |
So I've been brushing up on my Java skills as of late and have found a few bits of functionality that I didn't know about previously. Static and Instance Initializers are two such techniques.
My question is when would one use an initializer instead of including the code in a constructor? I've thought of a couple obvious possibilities:
* static/instance initializers can be used to set the value of "final" static/instance variables whereas a constructor cannot
* static initializers can be used to set the value of any static variables in a class, which should be more efficient than having an "if (someStaticVar == null) // do stuff" block of code at the start of each constructor
Both of these cases assume that the code required to set these variables is more complex than simply "var = value", as otherwise there wouldn't seem to be any reason to use an initializer instead of simply setting the value when declaring the variable.
However, while these aren't trivial gains (especially the ability to set a final variable), it does seem that there are a rather limited number of situations in which an initializer should be used.
One can certainly use an initializer for a lot of what is done in a constructor, but I don't really see the reason to do so. Even if all constructors for a class share a large amount of code, the use of a private initialize() function seems to make more sense to me than using an initializer because it doesn't lock you into having that code run when writing a new constructor.
Am I missing something? Are there a number of other situations in which an initializer should be used? Or is it really just a rather limited tool to be used in very specific situations? | Static initializers are useful as cletus mentioned and I use them in the same manner. If you have a static variable that is to be initialized when the class is loaded, then a static initializer is the way to go, especially as it allows you to do a complex initialization and still have the static variable be `final`. This is a big win.
I find "if (someStaticVar == null) // do stuff" to be messy and error prone. If it is initialized statically and declared `final`, then you avoid the possibility of it being `null`.
However, I'm confused when you say:
> static/instance initializers can be used to set the value of "final"
> static/instance variables whereas a constructor cannot
I assume you are saying both:
* static initializers can be used to set the value of "final" static variables whereas a constructor cannot
* instance initializers can be used to set the value of "final" instance variables whereas a constructor cannot
and you are correct on the first point, wrong on the second. You can, for example, do this:
```
class MyClass {
private final int counter;
public MyClass(final int counter) {
this.counter = counter;
}
}
```
Also, when a lot of code is shared between constructors, one of the best ways to handle this is to chain constructors, providing the default values. This makes is pretty clear what is being done:
```
class MyClass {
private final int counter;
public MyClass() {
this(0);
}
public MyClass(final int counter) {
this.counter = counter;
}
}
``` | Anonymous inner classes can't have a constructor (as they're anonymous), so they're a pretty natural fit for instance initializers. | Use of Initializers vs Constructors in Java | [
"",
"java",
"constructor",
"initializer",
"static-initializer",
"initialization-block",
""
] |
I just wondered, how to hide special
```
__.*__
```
methods in python\*? Especially I am using an interactive python interpreter with tab-completion, and I would like to display only the methods my modules expose ...
thanks,
/ myyn /
\*(at least from the user, who uses a python shell)
---
it looks like this now:
```
h[2] >>> Q.
Q.ALL( Q.__delattr__( Q.__getattribute__(
Q.__package__ Q.__sizeof__( Q.find_values(
Q.json
Q.DEFAULT_CONDITION( Q.__dict__ Q.__hash__(
Q.__reduce__( Q.__str__( Q.get_loops_total_platform(
Q.jsonlib
Q.SUCCESSFUL( Q.__doc__ Q.__init__(
Q.__reduce_ex__( Q.__subclasshook__( Q.get_platforms(
Q.memoize(
Q.__all__ Q.__file__ Q.__name__
Q.__repr__( Q.cached_open( Q.get_snippets(
Q.__class__( Q.__format__( Q.__new__(
Q.__setattr__( Q.find_results( Q.get_subjects(
h[2] >>> Q.
```
and I wish it looked like:
```
h[2] >>> Q.
Q.ALL( Q.find_values( Q.json
Q.DEFAULT_CONDITION( Q.get_loops_total_platform(
Q.jsonlib Q.SUCCESSFUL( Q.get_platforms(
Q.memoize( Q.cached_open( Q.get_snippets(
Q.find_results( Q.get_subjects(
h[2] >>> Q.
``` | Well, you could create a subclass of `rlcompleter.Completer`, override
the methods in question, and install that into `readline`.
```
import rlcompleter
import readline
class MyCompleter(rlcompleter.Completer):
def global_matches(self, text):
....
def attr_matches(self, text):
....
import readline
readline.set_completer(MyCompleter().complete)
```
These code snippets allow case-insensitive tab completion:
<http://www.nabble.com/Re%3A-Tab-completion-question-p22905952.html> | I think you should look for a way to get that particular environment/interpreter to stop displaying the "private" methods when you press TAB. I don't think there is a way to "hide" methods from Python itself, that would be very weird. | How to hide __methods__ in python? | [
"",
"python",
"hide",
"magic-methods",
"facade",
""
] |
I have a class (A web control) that has a property of type IEnumerable and would like to work with the parameter using LINQ.
Is there any way to cast / convert / invoke via reflection to IEnumerable<T> not knowing the type at compile time?
```
Method void (IEnumerable source)
{
var enumerator = source.GetEnumerator();
if (enumerator.MoveNext())
{
var type = enumerator.Current.GetType();
Method2<type>(source); // this doesn't work! I know!
}
}
void Method2<T>(IEnumerable<T> source) {}
``` | Does your `Method2` really care what type it gets? If not, you could just call `Cast<object>()`:
```
void Method (IEnumerable source)
{
Method2(source.Cast<object>());
}
```
If you definitely need to get the right type, you'll need to use reflection.
Something like:
```
MethodInfo method = typeof(MyType).GetMethod("Method2");
MethodInfo generic = method.MakeGenericMethod(type);
generic.Invoke(this, new object[] {source});
```
It's not ideal though... in particular, if source isn't *exactly* an `IEnumerable<type>` then the invocation will fail. For instance, if the first element happens to be a string, but source is a `List<object>`, you'll have problems. | You probably want to refactor your code to use `IEnumerable.Cast<T>`
Use it like this:
```
IEnumerable mySet = GetData();
var query = from x in mySet.Cast<int>()
where x > 2
select x;
``` | Convert / Cast IEnumerable to IEnumerable<T> | [
"",
"c#",
"linq",
""
] |
I have an Orders table (simplified)
```
OrderId,
SalesPersonId,
SaleAmount,
CurrencyId,
...
```
I am attempting to create a report on this table, I'm hoping for something like:
```
SalesPersonId TotalCAD TotalUSD
1 12,345.00 6,789.00
2 7,890.00 1,234.00
```
I'd prefer not to do a self join (perhaps I'm optimizing prematurely, but this seems inefficient) IE:
```
SELECT SalesPersonId, SUM(OrdersCAD.SaleAmount), SUM(OrderUSD.SaleAmount)
FROM Orders
LEFT JOIN Orders AS OrdersCAD ON Orders.OrderID AND Orders.CurrencyID = 1
LEFT JOIN Orders AS OrdersUSD ON Orders.OrderID AND Orders.CurrencyID = 2
```
But I cannot think of another way to do this, any ideas? | Use a CASE block:
```
SELECT
SalesPersonId,
SUM(
CASE CurrencyID
WHEN 1 THEN SaleAmount
ELSE 0
END
) AS TotalCAD,
SUM(
CASE CurrencyID
WHEN 2 THEN SaleAmount
ELSE 0
END
) AS TotalUSD
FROM Orders
GROUP BY SalesPersonId
``` | Try This:
```
SELECT SalesPersonId,
SUM(CASE WHEN CurrencyID = 1 THEN SaleAmount ELSE 0 END) as CAD,
SUM(CASE WHEN CurrencyID = 2 THEN SaleAmount ELSE 0 END) as USD
FROM ORDERS
``` | Sum different row in column based on second column value | [
"",
"sql",
"sql-server",
""
] |
I'm trying to open MS Word 2003 document in java, search for a specified String and replace it with a new String. I use APACHE POI to do that. My code is like the following one:
```
public void searchAndReplace(String inputFilename, String outputFilename,
HashMap<String, String> replacements) {
File outputFile = null;
File inputFile = null;
FileInputStream fileIStream = null;
FileOutputStream fileOStream = null;
BufferedInputStream bufIStream = null;
BufferedOutputStream bufOStream = null;
POIFSFileSystem fileSystem = null;
HWPFDocument document = null;
Range docRange = null;
Paragraph paragraph = null;
CharacterRun charRun = null;
Set<String> keySet = null;
Iterator<String> keySetIterator = null;
int numParagraphs = 0;
int numCharRuns = 0;
String text = null;
String key = null;
String value = null;
try {
// Create an instance of the POIFSFileSystem class and
// attach it to the Word document using an InputStream.
inputFile = new File(inputFilename);
fileIStream = new FileInputStream(inputFile);
bufIStream = new BufferedInputStream(fileIStream);
fileSystem = new POIFSFileSystem(bufIStream);
document = new HWPFDocument(fileSystem);
docRange = document.getRange();
numParagraphs = docRange.numParagraphs();
keySet = replacements.keySet();
for (int i = 0; i < numParagraphs; i++) {
paragraph = docRange.getParagraph(i);
text = paragraph.text();
numCharRuns = paragraph.numCharacterRuns();
for (int j = 0; j < numCharRuns; j++) {
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
System.out.println("Character Run text: " + text);
keySetIterator = keySet.iterator();
while (keySetIterator.hasNext()) {
key = keySetIterator.next();
if (text.contains(key)) {
value = replacements.get(key);
charRun.replaceText(key, value);
docRange = document.getRange();
paragraph = docRange.getParagraph(i);
charRun = paragraph.getCharacterRun(j);
text = charRun.text();
}
}
}
}
bufIStream.close();
bufIStream = null;
outputFile = new File(outputFilename);
fileOStream = new FileOutputStream(outputFile);
bufOStream = new BufferedOutputStream(fileOStream);
document.write(bufOStream);
} catch (Exception ex) {
System.out.println("Caught an: " + ex.getClass().getName());
System.out.println("Message: " + ex.getMessage());
System.out.println("Stacktrace follows.............");
ex.printStackTrace(System.out);
}
}
```
I call this function with following arguments:
```
HashMap<String, String> replacements = new HashMap<String, String>();
replacements.put("AAA", "BBB");
searchAndReplace("C:/Test.doc", "C:/Test1.doc", replacements);
```
When the Test.doc file contains a simple line like this : "**AAA EEE**", it works successfully, but when i use a complicated file it will read the content successfully and generate the Test1.doc file but when I try to open it, it will give me the following error:
**Word unable to read this document. It may be corrupt.
Try one or more of the following:
\* Open and repair the file.
\* Open the file with Text Recovery converter.
(C:\Test1.doc)**
Please tell me what to do, because I'm a beginner in POI and I have not found a good tutorial for it. | You could try [OpenOffice API](http://weblogs.java.net/blog/tchangu/archive/2005/12/open_office_jav_1.html), but there arent many resources out there to tell you how to use it. | First of all you should be closing your document.
Besides that, what I suggest doing is resaving your original Word document as a Word XML document, then changing the extension manually from .XML to .doc . Then look at the XML of the actual document you're working with and trace the content to make sure you're not accidentally editing hexadecimal values (AAA and EEE could be hex values in other fields).
Without seeing the actual Word document it's hard to say what's going on.
There is not much documentation about POI at all, especially for Word document unfortunately. | Open Microsoft Word in Java | [
"",
"java",
"apache",
"ms-word",
"apache-poi",
""
] |
I have a asp.net 3.5 application hosted on IIS 7.0. I'm looking for a comprehensive system to monitor traffic, down to page level minimum. Does .net have any specific tools or is it better to write my own, or what systems/software is freely available to use
Thanks | Use **[Google Analytics](http://www.google.com/analytics)**. Its a small piece of Javascript code that is inserted before the tag. Its based on Urchin analytics tracking software which Google bought. They've been doing this for a long long time.
As long as your site is referenced using a fully qualified domain name, Google Analytics can track what you need. It's got lots of flexibility with the filter mechanism as well (let's you rewrite URLs based on query string parameters, etc.)
LOTS of functionality and well thought out as well as a pretty good API if you need to do tracking on things other than clicks. | If you have access to the IIS logs, you can use a log analyzer to interpret the data. An example is the free AWStats analyzer:
<http://awstats.sourceforge.net/>
An alternative (and one I recommend) is Google Analytics (<http://www.google.com/analytics>). This relies on you embedding a small chunk of Javascript in each page you want tracking, then Google does the grunt work for you, presenting the results in an attractive Flash-rich site.
I'd suggest trying both and seeing which suits your needs. I'd definitely recommend against rolling your own system, as the above solutions are very mature and capable. Best of luck! | What is recommended for monitoring traffic to my asp.net application | [
"",
"c#",
"asp.net",
"iis",
"web-applications",
""
] |
I can't really think of the best way to phrase this question, so I'll just give an example. Suppose I have a table that is created like this:
```
CREATE VIEW People
AS
SELECT
id, --int
name, --varchar(20)
birthdate --datetime
FROM SomeTable
```
If I wanted to change this from a view to a physical table, is there any way to create a table with the same layout?
In other words, I want to take that view and create a table like this:
```
CREATE TABLE People(
id int,
name varchar(20),
birtdate datetime
)
```
...but without having to manually write that query out.
This is of course a contrived example. The view has a lot of fields with a lot of different data types, so it would be difficult to do by hand. | How about
```
SELECT * INTO MyNewTable FROM MyView
```
AND if you don't want the content, just the structure
```
SELECT * INTO MyNewTable FROM MyView WHERE 1 = 2
``` | ```
SELECT *
INTO People_Table
FROM People_View
``` | Is there any way to create a table with the same layout as a view in SQL Server 2005? | [
"",
"sql",
"sql-server-2005",
"view",
""
] |
I am stuck figuring out a working SQL Query for the fallowing:
I need to generate a Fire Register report (how many people are still inside the building) based on an Access database that records login/logout events along with some metadata.
The Access DB looks like this:
```
+----+---------------------+---------+---------+------+
| id | date | action | success | user |
+----+---------------------+---------+---------+------+
| 1 | 2009-04-28 02:00:00 | login | 1 | Nick |
| 2 | 2009-04-28 03:00:00 | logout | 1 | Nick |
| 3 | 2009-04-28 04:00:00 | login | 1 | Nick |
| 4 | 2009-04-28 04:00:00 | logout | 1 | Nick |
| 5 | 2009-04-28 04:00:00 | login | 1 | Nick |
| 6 | 2009-04-28 07:00:00 | login | 1 | John |
| 7 | 2009-04-28 07:30:00 | login | 1 | Sue |
| 8 | 2009-04-28 08:00:00 | logout | 1 | John |
+----+---------------------+---------+---------+------+
```
During the day there can be multiple login/logout actions.
When administrator runs the report, it's only limited for current day and needs to list all users where the last known action for this user is `login` and success=1, meaning that this person is currently in the building.
On the data above, **Nick** and **Sue** must be pointed out as still being inside the building. | Another approach to the problem:
```
SELECT
T1.user
FROM
Some_Table T1
LEFT OUTER JOIN Some_Table T2 ON
T2.user = T1.user AND
T2.success = 1 AND
T2.date > T1.date
WHERE
T1.success = 1 AND
T1.action = 'login' AND
T2.id IS NULL
```
This assumes that you only care about successful actions. Also, if a user has two actions on the same EXACT date AND time then it might not act as expected. | This assumes the ID's are always incremented by a positive number and are unique.
```
SELECT LogTable.*
FROM LogTable
INNER JOIN (Select User, Max(ID) AS LastID
FROM LogTable
GROUP BY LogTable.User
) as LastLog
ON LogTable.User = LastLog.User
AND LogTable.ID = LastLog.LastID
WHERE LogTable.success = 1 AND LogTable.action = 'login';
```
Based on assumption, you don't have to worry about a datetime not being unique.
Hope people are not in the habit of holding the door open for others who don't log in. | Generate a Fire Register report | [
"",
"sql",
"database",
"ms-access",
""
] |
I'm trying to write a simple Python script that will copy a index.tpl to index.html in all of the subdirectories (with a few exceptions).
I'm getting bogged down by trying to get the list of subdirectories. | I did some **speed testing** on various functions to return the *full path* to all current subdirectories.
tl;dr:
**Always use `scandir`:**
`list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]`
Bonus: With `scandir` you can also simply only get folder names by using `f.name` instead of `f.path`.
This (as well as all other functions below) will not use *natural sorting*. This means results will be sorted like this: 1, 10, 2. To get natural sorting (1, 2, 10), please have a look at <https://stackoverflow.com/a/48030307/2441026>
---
**Results**:
`scandir` is: 3x faster than `walk`, 32x faster than `listdir` (with filter), 35x faster than `Pathlib` and 36x faster than `listdir` and 37x (!) faster than `glob`.
```
Scandir: 0.977
Walk: 3.011
Listdir (filter): 31.288
Pathlib: 34.075
Listdir: 35.501
Glob: 36.277
```
Tested with W7x64, Python 3.8.1. Folder with 440 subfolders.
In case you wonder if `listdir` could be speed up by not doing os.path.join() twice, yes, but the difference is basically nonexistent.
Code:
```
import os
import pathlib
import timeit
import glob
path = r"<example_path>"
def a():
list_subfolders_with_paths = [f.path for f in os.scandir(path) if f.is_dir()]
# print(len(list_subfolders_with_paths))
def b():
list_subfolders_with_paths = [os.path.join(path, f) for f in os.listdir(path) if os.path.isdir(os.path.join(path, f))]
# print(len(list_subfolders_with_paths))
def c():
list_subfolders_with_paths = []
for root, dirs, files in os.walk(path):
for dir in dirs:
list_subfolders_with_paths.append( os.path.join(root, dir) )
break
# print(len(list_subfolders_with_paths))
def d():
list_subfolders_with_paths = glob.glob(path + '/*/')
# print(len(list_subfolders_with_paths))
def e():
list_subfolders_with_paths = list(filter(os.path.isdir, [os.path.join(path, f) for f in os.listdir(path)]))
# print(len(list(list_subfolders_with_paths)))
def f():
p = pathlib.Path(path)
list_subfolders_with_paths = [x for x in p.iterdir() if x.is_dir()]
# print(len(list_subfolders_with_paths))
print(f"Scandir: {timeit.timeit(a, number=1000):.3f}")
print(f"Listdir: {timeit.timeit(b, number=1000):.3f}")
print(f"Walk: {timeit.timeit(c, number=1000):.3f}")
print(f"Glob: {timeit.timeit(d, number=1000):.3f}")
print(f"Listdir (filter): {timeit.timeit(e, number=1000):.3f}")
print(f"Pathlib: {timeit.timeit(f, number=1000):.3f}")
``` | ```
import os
def get_immediate_subdirectories(a_dir):
return [name for name in os.listdir(a_dir)
if os.path.isdir(os.path.join(a_dir, name))]
``` | How to get all of the immediate subdirectories in Python | [
"",
"python",
"file",
""
] |
I'm trying to read an object from a XML file using XMLDecoder.
The construction seems to be OK, but when I call the readObject() method i get null instead of the object I expected.
The file exists and the created BufferedInputStream reads the file correctly.
This code works OK on the original Vista laptop it was written on, but fails on my Win Xp machine.
```
try {
XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
new FileInputStream("Params.xml")));
Params = (Parameters)decoder.readObject();
decoder.close();
} catch (FileNotFoundException e) {
System.out.println(e.toString());
}
``` | Is the same version of Java being used on the Vista and XP boxes?
Also check the version of Java used to create the xml originally.
Another test would be to encode an object on the XP box and try and read it back. | If it fails on your XP machine, but works on your Vista machine, then that sounds like some environment problem.
As it involves XML, I wonder if there's a character encoding issue and your Vista/XP environments have different encoding properties set. If this is the case then the XMLDecoder may not be able to parse the XML properly.
Check your system property `file.encoding` on both installations. It would be interesting to see if they're different. Does your .xml file specify the character encoding ? | XMLDecoder.readObject() returns null | [
"",
"java",
"xml",
""
] |
I've got a table with measurement data in SQL Server 2005, one value per person and year, if available. My TSQL code fetches these values in a loop and processes them:
```
...
SET @val = (SELECT measurement FROM tbl_data WHERE persid = @curpersid AND yr = @curyear)
...
```
Now, for a certain person and year, the table can contain (i) a valid measurement, (ii) a NULL value or (iii) no corresponding row at all.
How do I differentiate between these cases efficiently? Both (ii) and (iii) will result in @val being NULL, so with the current code, they can't be differentiated...
Thanks a bunch for any hints, wwwald | Well, it's a bit of a hack, but:
```
SET @val = -99999 -- or some other value that will never occur in the table
SELECT @val = measurement FROM tbl_data WHERE persid = @curpersid AND yr = @curyear
```
Now, if @val is still -9999 then there was no row, or null if the measurement was null. | If you can use a value that measurement can never take, COALESCE() can used.
```
SET @val = (SELECT COALESCE(measurement, someValueThatDoesNotOccur) FROM tbl_data WHERE persid = @curpersid AND yr = @curyear)
```
No row: @val == null
measurement was NULL: @val equals somevalue
else a vlaid measurement | Differentiate empty from NULL query results | [
"",
"sql",
"sql-server",
"database",
"t-sql",
""
] |
I am using GridLayout in my SWT GUI app. I have the following GridData defined for each grid cell. The grid cell itself is just a label.
```
GridData gridData = new GridData();
gridData.horizontalAlignment = GridData.FILL;
gridData.grabExcessHorizontalSpace = true;
gridData.grabExcessVerticalSpace = true;
gridData.heightHint = 25;
gridData.widthHint = 25;
gridData.verticalAlignment = GridData.VERTICAL_ALIGN_CENTER;
gridData.verticalIndent = 10;
```
And I create each lable element like this -
```
Label l = new Label(shell, SWT.BORDER);
l.setAlignment(SWT.CENTER);
l.setText("some text");
l.setLayoutData( gridData );
```
Now My problem is in spite of using verticalAlignment property, verticalIndent property and setAlignment on the label itself, I am not able to get the text align vertically centered with respect to the grid cell area ( 25 x 25 ). I think I am missing something. How can I achieve the vertically centered alignment in a grid cell ? | There is no setVerticalAlignment() on a Label and if you set the height, using the heightHint in the LayoutData, that becomes the size of the control and effectively stopping you from setting it in the middle. A workaround would be to put the Label into a composite with the size you want and then center the control. E.g.
```
Composite labelCell = new Composite(shell, SWT.BORDER);
GridData gridData = new GridData();
gridData.heightHint = 250;
gridData.widthHint = 250;
labelCell.setLayoutData(gridData);
labelCell.setLayout(new GridLayout());
Label l = new Label(labelCell , SWT.NONE);
l.setText("some text");
l.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, true, true));
``` | CLabel? Why don't you use it?
```
CLabel cl = new CLabel(shell, SWT.CENTER);
cl.setBounds(0, 0, 100, 100);
cl.setText("Custom Label!!!");
```
Even, you can use leftMargin, rightMargin, topMargin, bottomMargin.
( I'm sorry for after 3 years later ) | SWT layout problem - padding for labels possible? | [
"",
"java",
"user-interface",
"swt",
""
] |
Background: I've got a bunch of strings that I'm getting from a database, and I want to return them. Traditionally, it would be something like this:
```
public List<string> GetStuff(string connectionString)
{
List<string> categoryList = new List<string>();
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
string commandText = "GetStuff";
using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
categoryList.Add(sqlDataReader["myImportantColumn"].ToString());
}
}
}
return categoryList;
}
```
But then I figure the consumer is going to want to iterate through the items and doesn't care about much else, and I'd like to not box myself in to a List, per se, so if I return an IEnumerable everything is good/flexible. So I was thinking I could use a "yield return" type design to handle this...something like this:
```
public IEnumerable<string> GetStuff(string connectionString)
{
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
string commandText = "GetStuff";
using (SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection))
{
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlConnection.Open();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
while (sqlDataReader.Read())
{
yield return sqlDataReader["myImportantColumn"].ToString();
}
}
}
}
```
But now that I'm reading a bit more about yield (on sites like this...msdn didn't seem to mention this), it's apparently a lazy evaluator, that keeps the state of the populator around, in anticipation of someone asking for the next value, and then only running it until it returns the next value.
This seems fine in most cases, but with a DB call, this sounds a bit dicey. As a somewhat contrived example, if someone asks for an IEnumerable from that I'm populating from a DB call, gets through half of it, and then gets stuck in a loop...as far as I can see my DB connection is going to stay open forever.
Sounds like asking for trouble in some cases if the iterator doesn't finish...am I missing something? | It's a balancing act: do you want to force all the data into memory immediately so you can free up the connection, or do you want to benefit from streaming the data, at the cost of tying up the connection for all that time?
The way I look at it, that decision should potentially be up to the caller, who knows more about what they want to do. If you write the code using an iterator block, the caller can *very* easily turned that streaming form into a fully-buffered form:
```
List<string> stuff = new List<string>(GetStuff(connectionString));
```
If, on the other hand, you do the buffering yourself, there's no way the caller can go back to a streaming model.
So I'd probably use the streaming model and say *explicitly* in the documentation what it does, and advise the caller to decide appropriately. You might even want to provide a helper method to basically call the streamed version and convert it into a list.
Of course, if you don't trust your callers to make the appropriate decision, and you have good reason to believe that they'll never really want to stream the data (e.g. it's never going to return much anyway) then go for the list approach. Either way, document it - it could very well affect how the return value is used.
Another option for dealing with large amounts of data is to use batches, of course - that's thinking somewhat away from the original question, but it's a different approach to consider in the situation where streaming would normally be attractive. | You're not always unsafe with the IEnumerable. If you leave the framework call `GetEnumerator` (which is what most of the people will do), then you're safe. Basically, you're as safe as the carefullness of the code using your method:
```
class Program
{
static void Main(string[] args)
{
// safe
var firstOnly = GetList().First();
// safe
foreach (var item in GetList())
{
if(item == "2")
break;
}
// safe
using (var enumerator = GetList().GetEnumerator())
{
for (int i = 0; i < 2; i++)
{
enumerator.MoveNext();
}
}
// unsafe
var enumerator2 = GetList().GetEnumerator();
for (int i = 0; i < 2; i++)
{
enumerator2.MoveNext();
}
}
static IEnumerable<string> GetList()
{
using (new Test())
{
yield return "1";
yield return "2";
yield return "3";
}
}
}
class Test : IDisposable
{
public void Dispose()
{
Console.WriteLine("dispose called");
}
}
```
Whether you can affort to leave the database connection open or not depends on your architecture as well. If the caller participates in an transaction (and your connection is auto enlisted), then the connection will be kept open by the framework anyway.
Another advantage of `yield` is (when using a server-side cursor), your code doesn't have to read all data (example: 1,000 items) from the database, if your consumer wants to get out of the loop earlier (example: after the 10th item). This can speed up querying data. Especially in an Oracle environment, where server-side cursors are the common way to retrieve data. | C# IEnumerator/yield structure potentially bad? | [
"",
"c#",
".net",
"database",
"resources",
"yield",
""
] |
**[ edit ]**
For the record, here's the problem portion of the query, which is now working:
```
SELECT
m.groupNum,
t.ea,
( t.ea - ( t.ea * m.margin )) AS estCost,
(( t.ea - ( t.ea * m.margin )) * t.quantity ) AS salesSub,
((( t.ea - ( t.ea * m.margin )) * t.quantity ) /
(
SELECT SUM(( t2.ea - ( t2.ea * m.margin )) * t2.quantity )
FROM temp as t2
INNER JOIN masters as m2
ON t2.mod = m2.mod
WHERE m2.groupNum = m.groupNum
)
) AS salesPercent
etc...
```
**[ end edit ]**
I think I need a query that can recursively update itself based on the total of a column's values after inserting values on all the rest of the records for a given (groupNum) range.
I already have the estCost and salesSub fields. Now I need to do calculations on the **salesPercent** field, which involves knowing the total amount of all salesSub records in a given set (groupNum).
```
salesPercent =
( salesSub / [the sum total of all salesSub amounts for each groupNum] )
```
*(snip)*
```
SELECT
m.id,
t.priceEach,
( t.priceEach - ( t.priceEach * m.margin )) AS estCost,
(( t.priceEach - ( t.priceEach * m.margin )) * t.quantity ) AS salesSub
-- is it possible to perform calculation on salesPercent here?
INTO output
FROM financeMasters AS m
INNER JOIN temp AS t .......
```
*(end snip)*
I have this...
```
------
output
---------------------------------------------------------------
id | groupNum | priceEach | estCost | salesSub | salesPercent |
---------------------------------------------------------------
1 | apple | 150.00 | 90.00 | 90.00 |
2 | apple | 100.00 | 60.00 | 60.00 |
3 | apple | 50.00 | 30.00 | 30.00 |
```
but how can I calculate salesPercent on the salesSub total (in this case 180.00) before knowing the total? | You'll probably have to use a subselect to do the math on each row, there's no way to "go back" and change previous rows.
Something like this:
```
SELECT
m.id,
t.priceEach,
( t.priceEach - ( t.priceEach * m.margin )) AS estCost,
(( t.priceEach - ( t.priceEach * m.margin )) * t.quantity ) AS salesSub,
((( t.priceEach - ( t.priceEach * m.margin )) * t.quantity )
/ (SELECT SUM(( t2.priceEach - ( t2.priceEach * m.margin )) * t2.quantity )
FROM financeMasters AS m2
INNER JOIN temp AS t2 .....
WHERE m2.groupNum = m.groupNum))
AS salesPercent
INTO output
FROM financeMasters AS m
INNER JOIN temp AS t .......
```
Yes, it's pretty ugly. I had to leave out some details due to not knowing how you were doing the join, and also I'm not sure which table that groupNum is coming from, you didn't show that anywhere. | Like Chad Birch said, a subselect is probably your best bet. You could make it less ugly by storing the subselect in a separate query. | Access DB do line item calculation on total of a column before knowing the total | [
"",
"sql",
"database",
"ms-access",
""
] |
I need to open a URL in a new browser process. I need to be notified when that browser process quits. The code I'm currently using is the following:
```
Process browser = new Process();
browser.EnableRaisingEvents = true;
browser.StartInfo.Arguments = url;
browser.StartInfo.FileName = "iexplore";
browser.Exited += new EventHandler(browser_Exited);
browser.Start();
```
Clearly, this won't due because the "FileName" is fixed to iexplore, not the user's default web browser. How do I figure out what the user's default web browser is?
I'm running on Vista->forward. Though XP would be nice to support if possible.
A bit more context: I've created a very small stand-alone web server that serves some files off a local disk. At the end of starting up the server I want to start the browser. Once the user is done and closes the browser I'd like to quit the web server. The above code works perfectly, other than using only IE.
Thanks in advance! | Ok. I now have working C# code to do what I want. This will return the "command line" you should run to load the current default browser:
```
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Linq;
using System.Text;
namespace testDefaultBrowser
{
public enum ASSOCIATIONLEVEL
{
AL_MACHINE,
AL_EFFECTIVE,
AL_USER,
};
public enum ASSOCIATIONTYPE
{
AT_FILEEXTENSION,
AT_URLPROTOCOL,
AT_STARTMENUCLIENT,
AT_MIMETYPE,
};
[Guid("4e530b0a-e611-4c77-a3ac-9031d022281b"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IApplicationAssociationRegistration
{
void QueryCurrentDefault([In, MarshalAs(UnmanagedType.LPWStr)] string pszQuery,
[In, MarshalAs(UnmanagedType.I4)] ASSOCIATIONTYPE atQueryType,
[In, MarshalAs(UnmanagedType.I4)] ASSOCIATIONLEVEL alQueryLevel,
[Out, MarshalAs(UnmanagedType.LPWStr)] out string ppszAssociation);
void QueryAppIsDefault(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszQuery,
[In] ASSOCIATIONTYPE atQueryType,
[In] ASSOCIATIONLEVEL alQueryLevel,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName,
[Out] out bool pfDefault);
void QueryAppIsDefaultAll(
[In] ASSOCIATIONLEVEL alQueryLevel,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName,
[Out] out bool pfDefault);
void SetAppAsDefault(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName,
[In, MarshalAs(UnmanagedType.LPWStr)] string pszSet,
[In] ASSOCIATIONTYPE atSetType);
void SetAppAsDefaultAll(
[In, MarshalAs(UnmanagedType.LPWStr)] string pszAppRegistryName);
void ClearUserAssociations();
}
[ComImport, Guid("591209c7-767b-42b2-9fba-44ee4615f2c7")]//
class ApplicationAssociationRegistration
{
}
class Program
{
static void Main(string[] args)
{
IApplicationAssociationRegistration reg =
(IApplicationAssociationRegistration) new ApplicationAssociationRegistration();
string progID;
reg.QueryCurrentDefault(".txt",
ASSOCIATIONTYPE.AT_FILEEXTENSION,
ASSOCIATIONLEVEL.AL_EFFECTIVE,
out progID);
Console.WriteLine(progID);
reg.QueryCurrentDefault("http",
ASSOCIATIONTYPE.AT_URLPROTOCOL,
ASSOCIATIONLEVEL.AL_EFFECTIVE,
out progID);
Console.WriteLine(progID);
}
}
}
```
Whew! Thanks everyone for help in pushing me towards the right answer! | If you pass a path of the known file type to the (file) explorer application, it will '*do the right thing*', e.g.
```
Process.Start("explorer.exe", @"\\path.to\filename.pdf");
```
and open the file in the PDF reader.
But if you try the same thing with a URL, e.g.
```
Process.Start("explorer.exe", @"http://www.stackoverflow.com/");
```
it fires up IE (which isn't the default browser on my machine).
I know doesn't answer the question, but I thought it was an interesting sidenote. | Open a URL in a new browser process | [
"",
"c#",
"windows",
"system",
"shellexecute",
""
] |
Take an example `login()` function within a `class Account`.
```
class Account {
/* Class variables */
public function login() {
if(isset($_POST['username']) && isset($_POST['password']))
return $this->_formLogin();
else if(isset($_SESSION['accountId']))
return $this->_sessionLogin();
else if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
return $this->_cookieLogin();
else return false;
}
private function _formLogin() {
//perform login actions using $_POST data
}
/* All that other stuff */
}
```
Try for this moment to ignore any concerns about unseen methods for data sanitizing, password salting, and such. Concentrating strictly on `login()`, is this global access bad juju? I avoid using PHP super globals within classes normally, but I can't think of a good reason not to do it in this situation.
I can understand why you wouldn't want magic-in-the-background occuring with globals interacting across classes, but these globals are built into PHP, aren't modified by the class, and are only used by this class.
It would result in this at the beginning of pages you needed a user logged in on:
```
$user = new Account($whatever, $objects, $we, $depend, $on);
if($user->login()) {
//Do this stuff when logged in
}
```
instead of this on every page, the logic of which may need to be changed later:
```
$user = new Account($whatever, $objects, $we, $depend, $on);
if(isset($_POST['username']) && isset($_POST['password']))
$user->formLogin($_POST['username'], $_POST['password']);
else if(isset($_SESSION['accountId']))
$user->sessionLogin($_SESSION['accountId']);
else if(isset($_COOKIE['username']) && isset($_COOKIE['password']))
$user->cookieLogin($_COOKIE['username'], $_COOKIE['password']);
if($user->isLoggedIn() {
//Do this stuff when logged in
}
```
And while I'm aware that creating a function outside of the class to handle that is an option, wouldn't that be just as bad as obfuscating globals in a class? | I wouldn't say there is a straight yes or no answer to this one. What the idea (with all superglobals `$_GET` `$_POST` `$_SESSION`) is that you are asking for data that sits in your entire application, and not local to the scope you are asking for.
What can happen with these superglobals is that what if they change somewhere for whatever reason just before or (god forbid) during the execution of your function. That can turn out to be a very annoying bug to reproduce.
So I would say it is bad form. | To answer my own question, I'd say yes, it's fine to access super globals, provided you aren't modifying them to be accessed across multiple classes. There's no magic going on in the background - you're just reading the state, and super globals are how PHP provides that to you.
However, you should never, ever, ever modify a global within a class and access it somewhere else. That's when you make unit testing impossible. | Do you consider it bad form in PHP to access super globals within class methods? | [
"",
"php",
"oop",
"authentication",
"session",
"superglobals",
""
] |
Let's suppose that have a stream of text (or Reader in Java) that I'd like to check for a particular string. The stream of text might be very large so as soon as the search string is found I'd like to return true and also try to avoid storing the entire input in memory.
Naively, I might try to do something like this (in Java):
```
public boolean streamContainsString(Reader reader, String searchString) throws IOException {
char[] buffer = new char[1024];
int numCharsRead;
while((numCharsRead = reader.read(buffer)) > 0) {
if ((new String(buffer, 0, numCharsRead)).indexOf(searchString) >= 0)
return true;
}
return false;
}
```
Of course this fails to detect the given search string if it occurs on the boundary of the 1k buffer:
Search text: "stackoverflow"
Stream buffer 1: "abc.........stack"
Stream buffer 2: "overflow.......xyz"
How can I modify this code so that it correctly finds the given search string across the boundary of the buffer but without loading the entire stream into memory?
**Edit:** Note when searching a stream for a string, we're trying to **minimise the number of reads from the stream** (to avoid latency in a network/disk) and to **keep memory usage constant** regardless of the amount of data in the stream. Actual efficiency of the [string matching algorithm](http://en.wikipedia.org/wiki/String_searching_algorithm) is secondary but obviously, it would be nice to find a solution that used one of the more efficient of those algorithms. | I did a few changes to the Knuth Morris Pratt algorithm for partial searches. Since the actual comparison position is always less or equal than the next one there is no need for extra memory. The code with a Makefile is also available on [github](https://github.com/databigbang/stream-oriented-knuth-morris-pratt) and it is written in Haxe to target multiple programming languages at once, including Java.
I also wrote a related article: [searching for substrings in streams: a slight modification of the Knuth-Morris-Pratt algorithm in Haxe](http://blog.databigbang.com/searching-for-substrings-in-streams-a-slight-modification-of-the-knuth-morris-pratt-algorithm-in-haxe/). The article mentions the [Jakarta RegExp](http://jakarta.apache.org/regexp/), now retired and resting in the Apache Attic. The Jakarta Regexp library “[match](http://jakarta.apache.org/regexp/apidocs/org/apache/regexp/RE.html#match%28org.apache.regexp.CharacterIterator,%20int%29)” method in the RE class uses a CharacterIterator as a parameter.
```
class StreamOrientedKnuthMorrisPratt {
var m: Int;
var i: Int;
var ss:
var table: Array<Int>;
public function new(ss: String) {
this.ss = ss;
this.buildTable(this.ss);
}
public function begin() : Void {
this.m = 0;
this.i = 0;
}
public function partialSearch(s: String) : Int {
var offset = this.m + this.i;
while(this.m + this.i - offset < s.length) {
if(this.ss.substr(this.i, 1) == s.substr(this.m + this.i - offset,1)) {
if(this.i == this.ss.length - 1) {
return this.m;
}
this.i += 1;
} else {
this.m += this.i - this.table[this.i];
if(this.table[this.i] > -1)
this.i = this.table[this.i];
else
this.i = 0;
}
}
return -1;
}
private function buildTable(ss: String) : Void {
var pos = 2;
var cnd = 0;
this.table = new Array<Int>();
if(ss.length > 2)
this.table.insert(ss.length, 0);
else
this.table.insert(2, 0);
this.table[0] = -1;
this.table[1] = 0;
while(pos < ss.length) {
if(ss.substr(pos-1,1) == ss.substr(cnd, 1))
{
cnd += 1;
this.table[pos] = cnd;
pos += 1;
} else if(cnd > 0) {
cnd = this.table[cnd];
} else {
this.table[pos] = 0;
pos += 1;
}
}
}
public static function main() {
var KMP = new StreamOrientedKnuthMorrisPratt("aa");
KMP.begin();
trace(KMP.partialSearch("ccaabb"));
KMP.begin();
trace(KMP.partialSearch("ccarbb"));
trace(KMP.partialSearch("fgaabb"));
}
}
``` | There are three good solutions here:
1. If you want something that is easy and reasonably fast, go with no buffer, and instead implement a simple nondeterminstic finite-state machine. Your state will be a list of indices into the string you are searching, and your logic looks something like this (pseudocode):
```
String needle;
n = needle.length();
for every input character c do
add index 0 to the list
for every index i in the list do
if c == needle[i] then
if i + 1 == n then
return true
else
replace i in the list with i + 1
end
else
remove i from the list
end
end
end
```
This will find the string if it exists and you will never need a
buffer.
2. Slightly more work but also faster: do an NFA-to-DFA conversion that figures out in advance what lists of indices are possible, and assign each one to a small integer. (If you read about string search on Wikipedia, this is called the *powerset construction*.) Then you have a single state and you make a state-to-state transition on each incoming character. The NFA you want is just the DFA for the string preceded with a state that nondeterministically either drops a character or tries to consume the current character. You'll want an explicit error state as well.
3. If you want something faster, create a buffer whose size is at least twice `n`, and user Boyer-Moore to compile a state machine from `needle`. You'll have a lot of extra hassle because Boyer-Moore is not trivial to implement (although you'll find code online) and because you'll have to arrange to slide the string through the buffer. You'll have to build or find a *circular* buffer that can 'slide' without copying; otherwise you're likely to give back any performance gains you might get from Boyer-Moore. | Efficient way to search a stream for a string | [
"",
"java",
"algorithm",
"string",
"search",
"stream",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.