Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I would like to create a `String.replaceAll()` method in JavaScript and think using a regex would be the most terse way to do it. However, I can't figure out how to pass a variable into a regex. I can do this already which will replace all the instances of `"B"` with `"A"`. ``` "ABABAB".replace(/B/g, "A"); ``` But I want to do something like this: ``` String.prototype.replaceAll = function(replaceThis, withThis) { this.replace(/replaceThis/g, withThis); }; ``` But obviously, this will only replace the text `"replaceThis"`...so how do I pass this variable into my regex string?
Instead of using the `/regex\d/g` syntax, you can construct a new [RegExp](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Regular_Expressions) object: ``` var replace = "regex\\d"; var re = new RegExp(replace,"g"); ``` You can dynamically create regex objects this way. Then you will do: ``` "mystring1".replace(re, "newstring"); ```
As Eric Wendelin mentioned, you can do something like this: ``` str1 = "pattern" var re = new RegExp(str1, "g"); "pattern matching .".replace(re, "regex"); ``` This yields `"regex matching ."`. However, it will fail if str1 is `"."`. You'd expect the result to be `"pattern matching regex"`, replacing the period with `"regex"`, but it'll turn out to be... ``` regexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregexregex ``` This is because, although `"."` is a String, in the RegExp constructor it's still interpreted as a regular expression, meaning any non-line-break character, meaning every character in the string. For this purpose, the following function may be useful: ``` RegExp.quote = function(str) { return str.replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); }; ``` Then you can do: ``` str1 = "." var re = new RegExp(RegExp.quote(str1), "g"); "pattern matching .".replace(re, "regex"); ``` yielding `"pattern matching regex"`.
How do you use a variable in a regular expression?
[ "", "javascript", "regex", "" ]
How can I draw a filled rectangle in an applet with half opacity/transparency?
What API are you using? If you use Graphics from Java2D, when you create Color objects, you can add transparency to them as an alpha between 0 and 1. [Here's an old article on Java2D](http://java.sun.com/products/jfc/tsc/articles/swing2d/index.html) that has some examples
Yup. ``` void foo(Graphics g) { g.setColor(new Color(.3f, .4f, .5f, .6f); g.fillRect(50, 50, 100, 100); } ```
How can I draw a filled rectangle in an applet with half opacity?
[ "", "java", "applet", "" ]
I have a big image that has to go in the background. Say the image is a square. Now when someone does a mouseover on any of the square's corners, the image should change to the green version of the image. Actually the background image is going to remain, but I have to somehow overlay the green image slice over the background image. So I have a file called 'background.png' and then 'corner1.png', corner2.png etc. How can I implement this? Do I have to know the exact number of pixels to place the image in the corner properly?
``` <div class="image"> <div class="top left" onmouseover="javascript: cornerHover();" /> <div class="top right" onmouseover="javascript: cornerHover();" /> <div class="bottom left" onmouseover="javascript: cornerHover();" /> <div class="bottom right" onmouseover="javascript: cornerHover();" /> </div> <style> div.image {background: url() top left no-repeat; div.image > div { position: absolute; width: 10px; height: 10px; } div.image > div[class=top] { top: 0; } div.image > div[class=bottom] { bottom: 0; } div.image > div[class=left] { left: 0; } div.image > div[class=right] { right: 0; } /* if corners need to have a different background */ div.image > div[class=top][class=left] { background: url(); } div.image > div[class=top][class=right] { background: url(); } div.image > div[class=bottom][class=left] { background: url(); } div.image > div[class=bottom][class=right] { background: url(); } </style> ``` Might require some fine-tuning
It should be possible for you to use CSS to place the corner images overlaid into each of the corners of your background image. You shouldn't need to know the size of those corner images to place them, just use alignment parameters, The mouse-over actions would then be associated with those invisible image objects.
Image with rollovers
[ "", "javascript", "css", "image", "" ]
I'm passing some numeric arguments while creating a process (in VC++) I'm stuck at converting LPTSTR to int. Thanks in advance.
A LPTSTR is just a Long Pointer to a char or wide-char string. Use `_ttoi` or `_tstoi` for a character-width-agnostic way of doing the conversion. Also see * [How do you convert a C++ string to an int?](https://stackoverflow.com/questions/200090/how-do-you-convert-a-c-string-to-an-int) * <http://msdn.microsoft.com/en-us/library/hc25t012(VS.71).aspx>
Gack! What exactly are you trying to do? Is your problem on the parent process side (which calls `CreateProcess()` ) or on the child process side? There are several ways of communicating parameters from a parent process to a child process created by the [`CreateProcess()`](http://msdn.microsoft.com/en-us/library/ms682425.aspx) function. If you can encode those parameters as a reasonably-sized string, then passing them through command-line parameters (the `lpCommandLine` parameter of CreateProcess) is probably the most straightforward & portable, with environment variables 2nd. If you have a data structure you can't encode in a reasonably-sized string (either because it's a large amount of memory, or it's not easily serialized), then you need to resort to some method of interprocess communication. A file or a block of shared memory are two ways of doing this. In either case you need to come up with an agreed-upon location for the child to find this (a filepath in the case of a file, or the name of the shared memory block), and then pass this string as a command-line parameter or environment variable. If you're trying to parse the `lpCommandLine` parameter within the child process, then it's what other people have suggested.
LPTSTR to int (c++)
[ "", "c++", "casting", "lptstr", "" ]
I have a name in a database, lets say its "DFectuoso" and some legacy system stored DFectuoso\_randomnameofafile.doc. Now I want to find all the filed "DFectuoso" owns and display links to them in a PHP page. What would be the way to start on this?
I'd try with [`glob()`](http://php.net/glob) in combination with [`readfile()`](http://php.net/readfile). Off the top of my head: ``` $findname = 'DFectuoso'; foreach (glob('/path/to/somewhere/'.$findname.'*') as $file) { provide_a_link_to($file); } ``` and just pass the file with `readfile()`. Remember, if you are using `$_GET` to pass the chosen file to the user, sanitize and validate the permissions first. Don't do just `readfile($_GET['chosenFile']);` or you'll get in trouble!
A good way is using [glob()](http://php.net/glob). ``` $files = glob("PATH_TO_FILES/DFectuoso_*.doc"); echo "<ul>\n"; foreach($files as $f) echo '<li><a href="'.$f.'">'.$f."</a></li>\n"; echo "</ul>\n"; ```
regex or something to find a file in php
[ "", "php", "regex", "file", "" ]
Python is pretty clean, and I can code neat apps quickly. But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run? Also, I dislike how python has no enums. If I were to write code that needs a lot of enums and types, should I be doing it in C++? It feels like I can do it quicker in C++.
**"I don't find the error at compile but at run time"** Correct. True for all non-compiled interpreted languages. **"I need to change and run the script again"** Also correct. True for all non-compiled interpreted languages. **"Is there a way to have it break and let me modify and run?"** What? If it's a run-time error, the script breaks, you fix it and run again. If it's not a proper error, but a logic problem of some kind, then the program finishes, but doesn't work correctly. No language can anticipate what you hoped for and break for you. Or perhaps you mean something else. **"...code that needs a lot of enums"** You'll need to provide examples of code that needs a lot of enums. I've been writing Python for years, and have no use for enums. Indeed, I've been writing C++ with no use for enums either. You'll have to provide code that needs a lot of enums as a specific example. Perhaps in another question along the lines of "What's a Pythonic replacement for all these enums." It's usually polymorphic class definitions, but without an example, it's hard to be sure.
With interpreted languages you have a lot of freedom. Freedom isn't free here either. While the interpreter won't torture you into dotting every i and crossing every T before it deems your code worthy of a run, it also won't try to statically analyze your code for all those problems. So you have a few choices. 1) {Pyflakes, pychecker, pylint} will do static analysis on your code. That settles the syntax issue mostly. 2) Test-driven development with nosetests or the like will help you. If you make a code change that breaks your existing code, the tests will fail and you will know about it. This is actually better than static analysis and can be as fast. If you test-first, then you will have all your code checked at *test* runtime instead of program runtime. Note that with 1 & 2 in place you are a bit better off than if you had just a static-typing compiler on your side. Even so, it will not create a proof of correctness. It is possible that your tests may miss some plumbing you need for the app to actually run. If that happens, you fix it by writing more tests usually. But you still need to fire up the app and bang on it to see what tests you should have written and didn't.
python coding speed and cleanest
[ "", "python", "" ]
Is it me or are there no standard trim functions in the c or c++ library? is there any single function that acts as a trim? If not can anyone tell me Why trim is not part of the standard library? (i know trim is in boost) My trim code is ``` std::string trim(const std::string &str) { size_t s = str.find_first_not_of(" \n\r\t"); size_t e = str.find_last_not_of (" \n\r\t"); if(( string::npos == s) || ( string::npos == e)) return ""; else return str.substr(s, e-s+1); } ``` test: cout << trim(" \n\r\r\n \r\n text here\nwith return \n\r\r\n \r\n "); -edit- i mostly wanted to know why it wasnt in the standard library, BobbyShaftoe answer is great. [trim is not part of the standard c/c++ library?](https://stackoverflow.com/questions/479080/trim-is-not-part-of-the-standard-c-c-library#479091)
The reason trim() isn't in the standard library is that when the last standard was made, they had to strike a balance between formalizing current behavior (adding nothing new, just stabilizing what already existed), and adding new functionality. In general, they preferred not to add a feature unless it either 1) would be impossible otherwise, or 2) there were significant drawbacks to using third-party libraries instead. Making too many changes would * break compatibility with existing code (which may have defined its own trim() * Add more work for compiler writers (who already had a huge amount of work ahead of them) * Make the language more complex to learn and use. With trim(), there are no major interoperability issues. As long as your third-party trim() implementation takes a string and returns a string, we don't really care where it's defined. So it's not really *necessary* In the standard library. It can be easily supplied by other libraries. By contrast, something like the string class or vector, are classes that the standard library must supply, because if you use a custom string class, only string operations from that library will work. With a standard library string, third-party libraries can target this common string definition, and everyone wins. When the last standard came out, Herb Sutter wrote a post describing this very well [here](http://www.gotw.ca/publications/mill01.htm) Of course, it would be nice to have a trim() function, but they had bigger fish to fry. They had to standardize all the basics first. I don't think C++0x will add a trim function, but it will add a lot of other convenience utilities that back in '98 were considered "unnecessary" or too specialized.
No, you have to write it yourself or use some other library like Boost and so forth. In C++, you could do: ``` #include <string> const std::string whiteSpaces( " \f\n\r\t\v" ); void trimRight( std::string& str, const std::string& trimChars = whiteSpaces ) { std::string::size_type pos = str.find_last_not_of( trimChars ); str.erase( pos + 1 ); } void trimLeft( std::string& str, const std::string& trimChars = whiteSpaces ) { std::string::size_type pos = str.find_first_not_of( trimChars ); str.erase( 0, pos ); } void trim( std::string& str, const std::string& trimChars = whiteSpaces ) { trimRight( str, trimChars ); trimLeft( str, trimChars ); } ```
trim is not part of the standard c/c++ library?
[ "", "c++", "trim", "standard-library", "" ]
Currently, i have basic C++ and PHP skills. But, i want to switch to C# and ASP ( for the web part ). Why ? you will ask. Because i have the opportunity to learn pretty easily C# ( including OOP-ed ) to a pretty advanced level. And because i read that ASP is very similar to C#, i'm thinking to learn it. So, there are many stuff that can't be done in C# ? What kind of stuff ? The same question for ASP.
Limitations of C# (and, by association, .NET): * Not really a systems level language - not generally good for writing drivers etc. (Having said which, there are interesting projects like [Cosmos](http://www.gocosmos.org/index.en.aspx).) * Limited support of platforms other than Windows. [Mono](http://mono-project.org) does a good job, but it's still not at parity with .NET itself (compared with, say, Java which has simultaneous releases on multiple platforms). * Only options for running as an unmanaged language are third-party ones - ngen will "pre-JIT" your code, but it's still running under the .NET framework. Really C# was designed to be running in a VM, with garbage collection. * Some people don't like the lack of deterministic destruction, which means the C++ RAII technique doesn't work. (Instead, you rely on the GC for memory management and the `IDisposable` interface for non-memory resources. The `using` statement makes this easier, but it's not a perfect solution.) * The language is somewhat at the whim of Microsoft. If MS decided to abandon it, I think it wouldn't progress any further and would quickly lose support for new development. Having said that, I don't expect MS to abandon it any time soon. * Until C# 4 comes out, it doesn't have much support for late binding. You can do it with reflection, but it's somewhat painful. Even with C# 4, it will still be a fundamentally static language, but with ways of working dynamically where it really helps. * Currently there's not much support for immutability. In particular, C# 3 introduced a few new features (automatic properties, collection initializers, object initializers) which make it easier to write mutable types - but no corresponding features are available for immutable types. Named and optional parameters in C# 4 should help on this front, but more support would be welcome. C# 3 made it easier to code in a functional style, but this really requires immutability. * For desktop app development, you basically have a choice between WinForms and WPF (Windows Presentation foundation). The latter is newer and much better designed IMO, but in both cases you may well see a slight difference in "snappiness" between a managed application and a well-written Win32 app. This is particularly true at start-up, while the framework is loading and lots of UI code is being JITted etc. Personally I don't think it's much of a barrier, but...
Another consideration, on top of what the other respondents are saying, is that hosting .NET apps is generally more expensive than hosting PHP apps, because of the various MS license costs. This may or may not be an issue for you.
Am i limited with C# and ASP?
[ "", "c#", "asp.net", "" ]
If I have a solution with 10 projects. When I click "Clean Solution" does that just clean out the bin/debug in the main startup projects solution or the bin/debug in every projects directory?
It cleans every project contained in the solution, for the currently selected configuration (e.g. Debug, Release, etc).
To add to other answers, if you want a right click app, you can find the source code of clean source plus [here](http://www.codinghorror.com/blog/archives/000368.html). *This application does one thing. It adds an explorer shell menu to folders that when selected will recursively delete the contents of the bin, obj and setup folders. If you have a .NET project that you wish to share with someone, this is useful to remove the unnecessary stuff from the folder before you zip it up and send it off.*
Visual Studio 2005 Clean Solution
[ "", "c#", "visual-studio", "visual-studio-2005", "" ]
I recently had cause to work with some Visual Studio C++ projects with the usual Debug and Release configurations, but also 'Release All' and 'Debug All', which I had never seen before. It turns out the author of the projects has a single ALL.cpp which #includes all other .cpp files. The \*All configurations just build this one ALL.cpp file. It is of course excluded from the regular configurations, and regular configurations don't build ALL.cpp I just wondered if this was a common practice? What benefits does it bring? (My first reaction was that it smelled bad.) What kinds of pitfalls are you likely to encounter with this? One I can think of is if you have anonymous namespaces in your .cpps, they're no longer 'private' to that cpp but now visible in other cpps as well? All the projects build DLLs, so having data in anonymous namespaces wouldn't be a good idea, right? But functions would be OK?
It's referred to by some (and google-able) as a "Unity Build". It links insanely fast and compiles reasonably quickly as well. It's great for builds you don't need to iterate on, like a release build from a central server, but it isn't necessarily for incremental building. And it's a PITA to maintain. EDIT: here's the first google link for more info: <http://buffered.io/posts/the-magic-of-unity-builds/> The thing that makes it fast is that the compiler only needs to read in everything once, compile out, then link, rather than doing that for every .cpp file. Bruce Dawson has a much better write up about this on his blog: <http://randomascii.wordpress.com/2014/03/22/make-vc-compiles-fast-through-parallel-compilation/>
Unity builds improved build speeds for three main reasons. The first reason is that all of the shared header files only need to be parsed once. Many C++ projects have a lot of header files that are included by most or all CPP files and the redundant parsing of these is the main cost of compilation, especially if you have many short source files. Precompiled header files can help with this cost, but usually there are a lot of header files which are not precompiled. The next main reason that unity builds improve build speeds is because the compiler is invoked fewer times. There is some startup cost with invoking the compiler. Finally, the reduction in redundant header parsing means a reduction in redundant code-gen for inlined functions, so the total size of object files is smaller, which makes linking faster. Unity builds can also give better code-gen. Unity builds are *NOT* faster because of reduced disk I/O. I have profiled many builds with xperf and I know what I'm talking about. If you have sufficient memory then the OS disk cache will avoid the redundant I/O - subsequent reads of a header will come from the OS disk cache. If you don't have enough memory then unity builds could even make build times worse by causing the compiler's memory footprint to exceed available memory and get paged out. Disk I/O is expensive, which is why all operating systems aggressively cache data in order to avoid redundant disk I/O.
#include all .cpp files into a single compilation unit?
[ "", "c++", "visual-studio", "build", "" ]
I have a `List<T>` that I want to search not for a given item but for an item satisfying a given condition. Given an item in the list I can test which of 4 conditions is true: * the desired item must be to the left * the desired item must be to the right * this is the desired item * the desired can't be in the list A quick glance at the list functions was not encouraging so I'm wondering if anyone knows off a function I can use? Edit: this is a local temp list so I known that it will be sorted correctly Edit: BinarySearch looks almost right but in my case I don't have an item to compare with. I'd use Jon Skeet's solution and ignore one arg, but I'm not sure that I can count on it always being the same arg.
**New edit:** I'll leave the extra binary searches below, as they'll be useful for others, and here's a final option which is I think what you actually want. Your delegate should return a positive number if the item it's looking for is "less than" the one specified, a negative number if it's "greater than" the one specified, and 0 if it's just right. ``` public static int BinarySearchForMatch<T>(this IList<T> list, Func<T,int> comparer) { int min = 0; int max = list.Count-1; while (min <= max) { int mid = (min + max) / 2; int comparison = comparer(list[mid]); if (comparison == 0) { return mid; } if (comparison < 0) { min = mid+1; } else { max = mid-1; } } return ~min; } ``` **Old edit:** I'll leave the original answer below, but here are two other options. The first takes a projection from the source data to a key type, and specifies the key to find. The comparison itself is just done in the default way for that key type: ``` public static int BinarySearchBy<TSource,TKey>(this IList<TSource> list, Func<TSource,TKey> projection, TKey key) { int min = 0; int max = list.Count-1; while (min <= max) { int mid = (min + max) / 2; TKey midKey = projection(list[mid]); int comparison = Comparer<TKey>.Default.Compare(midKey, key); if (comparison == 0) { return mid; } if (comparison < 0) { min = mid+1; } else { max = mid-1; } } return ~min; } ``` The second takes a Func instead, to compare an item from the list with the key we're looking for. The code is almost exactly the same, of course - it's just the comparison which changes: ``` public static int BinarySearchBy<TSource,TKey>(this IList<TSource> list, Func<TSource,TKey,int> comparer, TKey key) { int min = 0; int max = list.Count-1; while (min <= max) { int mid = (min + max) / 2; int comparison = comparer(list[mid], key); if (comparison == 0) { return mid; } if (comparison < 0) { min = mid+1; } else { max = mid-1; } } return ~min; } ``` These are both untested, but do at least compile :) **Original answer:** You can use `List<T>.BinarySearch` with an `IComparer<T>`. You don't have to write your own implementation of `IComparer<T>` - I've got on in [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) which builds an `IComparer<T>` from a `Comparison<T>` delegate. That only spots the first three conditions, but the binary search will work out the last one from the rest. In fact, the code is so short I might as well paste it here (sans comments, admittedly). ``` public sealed class ComparisonComparer<T> : IComparer<T> { readonly Comparison<T> comparison; public ComparisonComparer(Comparison<T> comparison) { if (comparison == null) { throw new ArgumentNullException("comparison"); } this.comparison = comparison; } public int Compare(T x, T y) { return comparison(x, y); } } ``` So you might do something like: ``` var comparer = new ComparisonComparer<Person>((p1, p2) => p1.ID.CompareTo(p2.ID)); int index = list.BinarySearch(employee, comparer); ``` MiscUtil also has a `ProjectionComparer` you might be interested in - you just specify a projection, just like in `OrderBy` with LINQ - but it really depends on your use case.
Are you sure of those conditions? Normally that works if the list is sorted, in which case perhaps you want to use a [`SortedList<TKey, TValue>`](http://msdn.microsoft.com/en-us/library/ms132319.aspx) in the first place. Either way, assuming C# 3.0 or later you probably want the `.Where()` method. Write in your condition as a Lambda and let the framework do the search. It should use a search technique appropriate to the collection.
Binary search of a C# list using delegate condition
[ "", "c#", "search", "list", "" ]
I need to union two sets of XElements into a single, unique set of elements. Using the `.Union()` extension method, I just get a "union all" instead of a union. Am I missing something? ``` var elements = xDocument.Descendants(w + "sdt") .Union(otherDocument.Descendants(w + "sdt") .Select(sdt => new XElement( sdt.Element(w + "sdtPr") .Element(w + "tag") .Attribute(w + "val").Value, GetTextFromContentControl(sdt).Trim()) ) ); ```
Your first impulse was almost correct.:) As per **David B**, if you do not tell LINQ exactly how you define equality and then give it a bunch of XElements, it will compare them by reference. Fortunately, you can tell it to use different criteria by specifying an `IEqualityComparer‹XElement›` (basically, an object that has an Equals method that returns true iff two XElements are equal according to your definition and false otherwise and a `GetHashCode` method that takes an `XElement` and returns a hash code based on your equality criteria). For example: ``` var elements = xDocument.Descendants(w + "sdt") .Union(otherDocument.Descendants(w + "sdt", new XElementComparer()) .RestOfYourCode ``` ... Somewhere else in your project ``` public class XElementComparer : IEqualityComparer‹XElement› { public bool Equals(XElement x, XElement y) { return ‹X and Y are equal according to your standards›; } public int GetHashCode(XElement obj) { return ‹hash code based on whatever parameters you used to determine Equals. For example, if you determine equality based on the ID attribute, return the hash code of the ID attribute.›; } } ``` Note: I do not have the framework at home, so the exact code is not tested and the IEqualityComparer code is from [here](http://community.sgdotnet.org/forums/t/11567.aspx) (scroll down to second post).
It's really hard to troubleshoot your "left join" observation without seeing what it is you are using to come to that conclusion. Here's my shot in the dark. ``` XDocument doc1 = XDocument.Parse(@"<XML><A/><C/></XML>"); XDocument doc2 = XDocument.Parse(@"<XML><B/><C/></XML>"); // var query1 = doc1.Descendants().Union(doc2.Descendants()); Console.WriteLine(query1.Count()); foreach (XElement e in query1) Console.WriteLine("--{0}",e.Name); 6 --XML --A --C --XML --B --C // var query2 = doc1.Descendants().Concat(doc2.Descendants()) .GroupBy(x => x.Name) .Select(g => g.First()); Console.WriteLine(query2.Count()); foreach (XElement e in query2) Console.WriteLine("--{0}", e.Name); 4 --XML --A --C --B ``` In linq to objects (which is what linq to xml really is), Union against reference types uses reference equality to test for duplicates. XElement is a reference type.
Union with LINQ to XML
[ "", "c#", "linq", "linq-to-xml", "union", "openxml-sdk", "" ]
*I was having trouble parsing some dodgy HTML with BeautifulSoup. Turns out that the HTMLParser used in newer versions is less tolerant than the SGMLParser used previously.* --- Does BeautifulSoup have some kind of debug mode? I'm trying to figure out how to stop it borking on some nasty HTML I'm loading from a crabby website: ``` <HTML> <HEAD> <TITLE>Title</TITLE> <HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> </HEAD> <BODY> ... ... </BODY> </HTML> ``` BeautifulSoup gives up after the `<HTTP-EQUIV...>` tag ``` In [1]: print BeautifulSoup(c).prettify() <html> <head> <title> Title </title> </head> </html> ``` The problem is clearly the HTTP-EQUIV tag, which is really a *very* malformed `<META HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE">` tag. Evidently, I need to specify this as self-closing, but no matter what I specify I can't fix it: ``` In [2]: print BeautifulSoup(c,selfClosingTags=['http-equiv', 'http-equiv="pragma"']).prettify() <html> <head> <title> Title </title> </head> </html> ``` Is there a verbose debug mode in which BeautifulSoup will tell me what it is doing, so I can figure out what it is treating as the tag name in this case?
Your problem must be something else; it works fine for me: ``` In [1]: import BeautifulSoup In [2]: c = """<HTML> ...: <HEAD> ...: <TITLE>Title</TITLE> ...: <HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> ...: </HEAD> ...: <BODY> ...: ... ...: ... ...: </BODY> ...: </HTML> ...: """ In [3]: print BeautifulSoup.BeautifulSoup(c).prettify() <html> <head> <title> Title </title> <http-equiv> </http-equiv> </head> <body> ... ... </body> </html> In [4]: ``` This is Python 2.5.2 with BeautifulSoup 3.0.7a — maybe it's different in older/newer versions? This is exactly the kind of soup BeautifulSoup handles so beautifully, so I doubt it's been changed at some point… Is there something else to the structure that you haven't mentioned in the problem?
[Having problems with Beautiful Soup 3.1.0?](http://www.crummy.com/software/BeautifulSoup/3.1-problems.html) recommends to use [html5lib](http://code.google.com/p/html5lib/)'s parser as one of workarounds. ``` #!/usr/bin/env python from html5lib import HTMLParser, treebuilders parser = HTMLParser(tree=treebuilders.getTreeBuilder("beautifulsoup")) c = """<HTML> <HEAD> <TITLE>Title</TITLE> <HTTP-EQUIV="PRAGMA" CONTENT="NO-CACHE"> </HEAD> <BODY> ... ... </BODY> </HTML>""" soup = parser.parse(c) print soup.prettify() ``` Output: ``` <html> <head> <title> Title </title> </head> <body> <http-equiv="pragma" content="NO-CACHE"> ... ... </http-equiv="pragma"> </body> </html> ``` The output shows that html5lib hasn't fixed the problem in this case though.
BeautifulSoup 3.1 parser breaks far too easily
[ "", "python", "html", "parsing", "beautifulsoup", "" ]
I am writing a Python utility that needs to parse a large, regularly-updated CSV file I don't control. The utility must run on a server with only Python 2.4 available. The CSV file does not quote field values at all, but the [Python 2.4 version of the csv library](http://www.python.org/doc/2.4.3/lib/csv-fmt-params.html#csv-fmt-params) does not seem to give me any way to turn off quoting, it just allows me to set the quote character (`dialect.quotechar = '"'` or whatever). If I try setting the quote character to `None` or the empty string, I get an error. I can sort of work around this by setting `dialect.quotechar` to some "rare" character, but this is brittle, as there is no ASCII character I can absolutely guarantee will not show up in field values (except the delimiter, but if I set `dialect.quotechar = dialect.delimiter`, things go predictably haywire). In [Python 2.5 and later](http://docs.python.org/library/csv.html), if I set `dialect.quoting` to `csv.QUOTE_NONE`, the CSV reader respects that and does not interpret any character as a quote character. Is there any way to duplicate this behavior in Python 2.4? **UPDATE**: Thanks Triptych and Mark Roddy for helping to narrow the problem down. Here's a simplest-case demonstration: ``` >>> import csv >>> import StringIO >>> data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ >>> reader = csv.reader(StringIO.StringIO(data)) >>> for i in reader: print i ... [] Traceback (most recent call last): File "<stdin>", line 1, in ? _csv.Error: newline inside string ``` The problem only occurs when there's a single double-quote character in the *final* column of a row. Unfortunately, this situation exists in my dataset. I've accepted Tanj's solution: manually assign a nonprinting character (`"\x07"` or `BEL`) as the quotechar. This is hacky, but it works, and I haven't yet seen another solution that does. Here's a demo of the solution in action: ``` >>> import csv >>> import StringIO >>> class MyDialect(csv.Dialect): ... quotechar = '\x07' ... delimiter = ',' ... lineterminator = '\n' ... doublequote = False ... skipinitialspace = False ... quoting = csv.QUOTE_NONE ... escapechar = '\\' ... >>> dialect = MyDialect() >>> data = """ ... 1,2,3,4,"5 ... 1,2,3,4,5 ... """ >>> reader = csv.reader(StringIO.StringIO(data), dialect=dialect) >>> for i in reader: print i ... [] ['1', '2', '3', '4', '"5'] ['1', '2', '3', '4', '5'] ``` In Python 2.5+ setting quoting to csv.QUOTE\_NONE would be sufficient, and the value of `quotechar` would then be irrelevant. (I'm actually getting my initial dialect via a `csv.Sniffer` and then overriding the quotechar value, not by subclassing `csv.Dialect`, but I don't want that to be a distraction from the real issue; the above two sessions demonstrate that `Sniffer` isn't the problem.)
I don't know if python would like/allow it but could you use a non-printable ascii code such as BEL or BS (backspace) These I would think to be extremely rare.
I tried a few examples using Python 2.4.3, and it seemed to be smart enough to detect that the fields were unquoted. I know you've already accepted a (slightly hacky) answer, but have you tried just leaving the `reader.dialect.quotechar` value alone? What happens if you do? Any chance we could get example input?
How can I disable quoting in the Python 2.4 CSV reader?
[ "", "python", "csv", "" ]
So i have this method: ``` internal K GetValue<T, K>(T source, string col) where T : IBaseObject { string table = GetObjectTableName(source.GetType()); DataTable dt = _mbx.Tables[table]; DataRow[] rows = dt.Select("ID = " + source.ID); if (rows.Length == 0) return K; return (K) rows[0][col]; } ``` I want to be able to return a null, or some kind of empty value, if no rows are found. What's the correct syntax to do this?
You could return default(K), and that means you will return null if K is a reference type, or 0 for int, '\0' for char, and so on... Then you can easily verify if that was returned: ``` if (object.Equals(resultValue, default(K))) { //... } ```
You have to use the class generic constraint on the K type parameter (because classes - as opposed to structs - are nullable) ``` internal K GetValue<T, K>(T source, string col) where K : class where T : IBaseObject { // ... return null; } ```
Returning null value from generic method
[ "", "c#", ".net", "generics", "" ]
I have a listview with two columns and I'm using a context menu to allow users to remove selected rows. To remove the selected rows, I've tried with the following code but it doesn't work: ``` private void toolStripMenuItem1_Click(object sender, EventArgs e) { listView1.SelectedItems.Clear(); } ``` I suspect this is because the listview has two columns, but I can't figure out a solution to remove selected rows. Removing all rows works with: `listView1.Items.Clear();`.
The latest example of BeefTurkey looks correct, but he should decrement the variable `i` after removing a selected item: ``` for (int i = 0; i < listView1.Items.Count; i++ ) { if (listView1.Items[i].Selected) { listView1.Items[i].Remove(); i--; } } ``` The index of items larger as `i` is decremented by 1 after the removal. So you should reposition `i` to match the next not tested item.
``` while (listBox1.SelectedItems.Count > 0) { listBox1.Items.Remove(listBox1.SelectedItem); } ```
Remove selected rows from multi-column listView
[ "", "c#", "winforms", "listview", "" ]
I'm using log4net to log write log message to a rolling log file. Now I would also redirect all trace messages from `System.Diagnostics.Trace` to that log file. How can I configure that? I tried to find anything about that in the log4net documentation, but without success. Is it possible at all? The reason I want to do that is because I am interested in the Trace messages of a 3rd party library. ``` <log4net> <appender name="R1" type="log4net.Appender.RollingFileAppender"> <file value="C:\Logs\MyService.log" /> <appendToFile value="true" /> <rollingStyle value="Date" /> <maxSizeRollBackups value="10" /> <datePattern value="yyyyMMdd" /> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /> </layout> </appender> </log4net> ```
According to Rune's suggestion I implemented a basic TraceListener which output to log4net: ``` public class Log4netTraceListener : System.Diagnostics.TraceListener { private readonly log4net.ILog _log; public Log4netTraceListener() { _log = log4net.LogManager.GetLogger("System.Diagnostics.Redirection"); } public Log4netTraceListener(log4net.ILog log) { _log = log; } public override void Write(string message) { if (_log != null) { _log.Debug(message); } } public override void WriteLine(string message) { if (_log != null) { _log.Debug(message); } } } ```
I don't know if log4net supports this, but you could implement your own trace listener that did this. The TraceListener doesn't have too many method that needs to be implemented and all you would do is to forward the values to log4net so this should be easy to do. To add a custom trace listener you would either modify your app.config/web.config or you would add it in code using `Trace.Listeners.Add(new Log4NetTraceListener());`
How to log Trace messages with log4net?
[ "", "c#", ".net", "log4net", "" ]
I've set up an AJAX page refresh with **setInterval**. From time to time, the server is so slow that a new request is initiated before the previous one has completed. How can I prevent that?
Use a timeout value that is shorter than your refresh interval. When the request times out, it will call the error handler so you'll need to differentiate between time out errors and other types of errors in the handler. ``` $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", timeout: 5000, /* ms or 5s */ success: function(msg){ alert( "Data Saved: " + msg ); } }); ``` [Docs](http://docs.jquery.com/Ajax/jQuery.ajax#options) at jquery.com. Example above from same source, but with added timeout value.
What I can tell you is, use a flag in your code. Like (not what I actually recommend just a simple example) ``` var isWorking = false; function doRequest(){ if(isWorking) return; isWorking = true; $.ajax({ ..., success: workWithResponse }); } function workWithResponse(){ /* doAnythingelse */ isWorking = false; } setInterval(doRequest,1000); ``` Something like that, its primitive but you will avoid race conditions. Regards.
jQuery: delay interval of ajax function till previous run is completed
[ "", "javascript", "jquery", "ajax", "setinterval", "" ]
I have a .net library dll that acts like a functional library. There are a bunch of static types along with static methods. There is some initialization code that I need to run to set up the library ready for use. When the assembly gets loaded is there a way to ensure that a particular method is run? Something like AppDomain.AssemblyLoad but called automatically from the assembly itself. I was thinking that maybe there is something like an AssemblyAttribute that could be used? At the moment I have this initialization code in a static constructor but as this is a library with many entry points there is no guarantee that this particular type will be used. Thanks!
Why do you need all the data to be loaded before *any* of it is used, rather than just when the first type which needs it is used? I don't believe there's any way of forcing a method to be run on assembly load, from within the assembly. You could put a static constructor in *every* type, but frankly I think it just makes more sense to have a single type representing that data and providing access to it - and put a static constructor on that type alone. (If you've got separate bits of data which can be used independently, perhaps create separate types for them.)
Yes there is - sort of. Use the excellent little utility by by Einar Egilsson, [InjectModuleInitializer](https://github.com/einaregilsson/InjectModuleInitializer). Run this executable as a post build step to create a small .cctor function (the module initializer function) that calls a static void function of yours that takes no parameters. It would be nice if compiler gave us the ability to create .cctor(), luckily we rarely need this capability. This is not a complete DllMain replacement, however. The CLR only calls this .cctor function prior to any methods called in your assembly, not upon assembly load. So, if you need something to happen upon assembly load, you need to have the loading code call a method directly or use the hack I detailed <https://stackoverflow.com/a/9745422/240845>
Initialize library on Assembly load
[ "", "c#", ".net", "assemblies", "" ]
I am trying to automate some upload/download tasks from an ftp web server. When I connect to the server through client, or through Firefox even, in order to get to my directory, I have to specify a path like this: ``` ftp://ftpserver.com/../AB00000/incoming/files ``` If I try to access this: ``` ftp://ftpserver.com/AB00000/incoming/files ``` The server throws an error that the directory does not exist. So, the problem: I am trying to create an FTPWebRequest with the first ftp address, but it always parses out the "/../" part and then my server says the path doesn't exist. I've tried these: ``` Uri target = new Uri("ftp://ftpserver.com/../AB00000/incoming/files"); FtpWebRequest request = (FtpWebRequest)WebReqeuest.Create(target); ``` and ``` string target = "ftp://ftpserver.com/../AB00000/incoming/files"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target); ``` In the first bit, the path is already incorrect when the Uri object is instantiated, in the second bit, it's after the WebRequest.Create method. Any ideas what's going on? EDIT: Additionally, since I posted this, I have tried creating the URI with the no parse option. I have also tried something like this: ``` string ftpserver = "ftp://ftpserver.com/../"; string path = "12345/01/01/file.toupload"; Uri = new Uri(ftpserver, path, true); ``` And it always parses out the root part ("/../").
Try escaping the .. with something like: ``` Uri target = new Uri("ftp://ftpserver.com/%2E%2E/AB00000/incoming/files"); ``` That works according to this [blog](http://blogs.msdn.com/mariya/default.aspx) which I found in this [discussion](http://social.msdn.microsoft.com/Forums/en-US/netfxnetcom/thread/76d3a3a2-48b6-4753-988e-dfd845f582e9/).
Not really sure about it, but it may be for security reasons, since allowing "/../" URIs would potentially let people navigate freely on any server's file system. Also, the official [URI RFC](http://www.ietf.org/rfc/rfc2396.txt) states that when resolving an URI one of the steps performed is actually the removal of "/../" segments, so it's not a problem in the C# library but it's regular URI behavior.
Why doesn't FTPWebRequest, or WebRequest in general accept a /../ path?
[ "", "c#", "ftpwebrequest", "" ]
Is there any way i can access the page object from within the global.asax Application\_EndRequest function ? I'm trying to set the text of a label at the end of the request but accessing the page is proving to be more difficult than I thought. here is what i have that's currently NOT working: ``` protected void Application_BeginRequest(Object sender, EventArgs e) { Context.Items.Add("Request_Start_Time", DateTime.Now); } protected void Application_EndRequest(Object sender, EventArgs e) { TimeSpan tsDuration = DateTime.Now.Subtract((DateTime)Context.Items["Request_Start_Time"]); System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page; if (page != null) { Label label = page.FindControl("lblProcessingTime") as Label; if (label != null) { label.Text = String.Format("Request Processing Time: {0}", tsDuration.ToString()); } } } ``` page is always null here. Thanks in advance.
It's probably best just to create a BasePage class from which all your pages should inherit. Then you can put the code within the Unload event of the page and there will be no issue.
You cannot do this in Application\_Start and Application\_End. From MSDN: The Application\_Start and Application\_End methods are special methods that do not represent HttpApplication events. ASP.NET calls them once for the lifetime of the application domain, not for each HttpApplication instance. <http://msdn.microsoft.com/en-us/library/ms178473.aspx>
Asp.Net Global.asax access to the current requested Page object
[ "", "c#", "asp.net", "global-asax", "" ]
Language used: C# Theory: I want to create a file with the flag `FileOptions.DeleteOnClose` in a temporary folder. The file is successfully created and I write dato onto it, the next step is to launch the application associated with the file `Process.Start(...)` and allow the user to inspect the document, finally I close my handle and as soon as other process close the handle to the temporary file, the file is deleted by operating system. My problem is that other processes cannot open the file, even for reading, despite if I add `FileShare.ReadWrite | FileShare.Delete` to the sharing mode. Any suggestions?
The other processes need to specify `FileShare.Delete` when they open the `DeleteOnClose` file From the [MSDN CreateFile](http://msdn.microsoft.com/en-us/library/aa363858.aspx) docs: > "`FILE_FLAG_DELETE_ON_CLOSE`... Subsequent open requests for the file fail, unless the `FILE_SHARE_DELETE` share mode is specified."
Check this: You need to make sure that **all** processes are opening the file with FileShare.ReadWrite and FileShare.Delete. Even if the creator opens with share-readwrite, if a second program tries to open with share-read, the second program is basically saying no-one else can write. But the first program already has that power so the second open fails.
Delete on close files
[ "", "c#", "file", "filesystems", "temporary-files", "" ]
I'm trying to determine at runtime what the SqlDbType of a sql server table column is. is there a class that can do that in System.Data.SqlClient or should I do the mapping myself? I can get a string representation back from ``` SELECT DATA_TYPE, CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_CATALOG = '{0}' AND TABLE_SCHEMA = '{1}' AND TABLE_NAME = '{2}' AND COLUMN_NAME = '{3}' ``` EDIT: I can't use SMO as I have no control over the executing machine so I can't guarantee it will be installed. (Sorry for not making that clear rp). EDIT: In answer to Joel, I'm trying to make a function that I can call that will return me a SqlDBType when passed a SqlConnection, a table name, and a column name.
In SQL Server you can use the FMTONLY option. It allows you to run a query without getting any data, just returning the columns. ``` SqlCommand cmd = connection.CreateCommand(); cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF"; SqlDataReader reader = cmd.ExecuteReader(); SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"]; ```
You can use enum System.Data.CommandBehavior as paramter for method SqlCommand.ExecuteReader(System.Data.CommandBehavior.KeyInfo): ``` SqlCommand cmd = connection.CreateCommand(); cmd.CommandText = "select column from table"; SqlDataReader reader = cmd.ExecuteReader(System.Data.CommandBehavior.KeyInfo); SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0]["ProviderType"]; ``` This example looks like the example with using sql: SET FMTONLY ON; SET FMTONLY OFF. But you haven't to use SET FMTONLY. And in this case you don't receive data from the table. You receive only metadata.
How do I get the SqlDbType of a column in a table using ADO.NET?
[ "", "c#", ".net", "sql-server", "ado.net", "" ]
I am using an LdapContext in java to query an LDAP server (I think the server is Sun server version 5.2). I use the LdapContext.search(String name, String filter, SearchControls cons) method for the regular querys, but I don't know how to run a query equivalent to sql's "select count(\*)". Any idea? Performance is important so I don't want to just run a regular query and count the results.
I do not believe there is an equivalent to the "select count(\*)" function in SQL. I think you will have to retrieve the results of your query into some data structure, and count the number of nodes in there. To my knowledge there is nothing in the LDAP command set that allows this, therefore if you happened to find such a feature in an LDAP server you would have to test to see if it worked anywhere else, if you cared about cross server compatibility.
Have you tried the Context.list(String name) method? I don't know about the performance and you can't apply filters.
LdapContext, how to do select count(*)
[ "", "java", "ldap", "" ]
Seems like every C# static analyzer wants to complain when it sees a public field. But why? Surely there are cases where a public (or internal) *field* is enough, and there is no point in having a property with its `get_` and `set_` methods? What if I know for sure that I won't be redefining the field or adding to it (side effects are bad, right?) - shouldn't a simple field suffice?
Because it breaks encapsulation -- this is why most people use accessors heavily. However, if you think it's the right solution for your task, ignore it (meaning the strict encapsulation complaints) and do what's right for your project. Don't let the OO nazis tell you otherwise.
It's really about future-proofing your code. When you say (emphasis mine): > **What if I know for sure** that I won't > be redefining the field or adding to > it (side effects are bad, right?) - > shouldn't a simple field suffice? That's an absolute statement, and as we know (as well as most static analyzers), there are only two absolutes in life. It's just trying to protect you from that. If it is an issue, you should be able to tell the analyzer to ignore it (through attributes that are dependent on the analysis tool you are using).
Why won't anyone accept public fields in C#?
[ "", "c#", "properties", "field", "public", "" ]
Does anyone know why `java.lang.Number` does not implement `Comparable`? This means that you cannot sort `Number`s with `Collections.sort` which seems to me a little strange. **Post discussion update:** Thanks for all the helpful responses. I ended up doing [some more research about this topic](http://radioeiffel.blogspot.com/2009/02/what-java-can-sort-numbers.html). The simplest explanation for why java.lang.Number does not implement Comparable is rooted in mutability concerns. For a bit of review, `java.lang.Number` is the abstract super-type of `AtomicInteger`, `AtomicLong`, `BigDecimal`, `BigInteger`, `Byte`, `Double`, `Float`, `Integer`, `Long` and `Short`. On that list, `AtomicInteger` and `AtomicLong` to do not implement `Comparable`. Digging around, I discovered that it is not a good practice to implement `Comparable` on mutable types because the objects can change during or after comparison rendering the result of the comparison useless. Both `AtomicLong` and `AtomicInteger` are mutable. The API designers had the forethought to not have `Number` implement `Comparable` because it would have constrained implementation of future subtypes. Indeed, `AtomicLong` and `AtomicInteger` were added in Java 1.5 long after `java.lang.Number` was initially implemented. Apart from mutability, there are probably other considerations here too. A `compareTo` implementation in `Number` would have to promote all numeric values to `BigDecimal` because it is capable of accommodating all the `Number` sub-types. The implication of that promotion in terms of mathematics and performance is a bit unclear to me, but my intuition finds that solution kludgy.
It's worth mentioning that the following expression: ``` new Long(10).equals(new Integer(10)) ``` is always `false`, which tends to trip everyone up at some point or another. So not only can you not compare arbitrary `Number`s but you can't even determine if they're equal or not. Also, with the real primitive types (`float`, `double`), determining if two values are equal is tricky and has to be done within an acceptable margin of error. Try code like: ``` double d1 = 1.0d; double d2 = 0.0d; for (int i=0; i<10; i++) { d2 += 0.1d; } System.out.println(d2 - d1); ``` and you'll be left with some small difference. So back to the issue of making `Number` `Comparable`. How would you implement it? Using something like `doubleValue()` wouldn't do it reliably. Remember the `Number` subtypes are: * `Byte`; * `Short`; * `Integer`; * `Long`; * `AtomicInteger`; * `AtomicLong`; * `Float`; * `Double`; * `BigInteger`; and * `BigDecimal`. Could you code a reliable `compareTo()` method that doesn't devolve into a series of if instanceof statements? `Number` instances only have six methods available to them: * `byteValue()`; * `shortValue()`; * `intValue()`; * `longValue()`; * `floatValue()`; and * `doubleValue()`. So I guess Sun made the (reasonable) decision that `Number`s were only `Comparable` to instances of themselves.
For the answer, see Java bugparade [bug 4414323](https://bugs.java.com/bugdatabase/view_bug?bug_id=4414323). You can also find a discussion from [comp.lang.java.programmer](http://coding.derkeiler.com/Archive/Java/comp.lang.java.programmer/2007-07/msg02451.html) To quote from the Sun response to the bug report from 2001: > All "numbers" are not comparable; > comparable assumes a total ordering of > numbers is possible. This is not even > true of floating-point numbers; NaN > (not a number) is neither less than, > greater than, nor equal to any > floating-point value, even itself. > {Float, Double}.compare impose a total > ordering different from the ordering > of the floating-point "<" and "=" > operators. Additionally, as currently > implemented, the subclasses of Number > are only comparable to other instances > of the same class. There are other > cases, like complex numbers, where no > standard total ordering exists, > although one could be defined. In > short, whether or not a subclass of > Number is comparable should be left as > a decision for that subclass.
Why doesn't java.lang.Number implement Comparable?
[ "", "java", "sorting", "comparable", "" ]
i have a class whose equality is based on 2 fields such that if either one is equal then the objects of this type are considered equal. how can i write a hashCode() function for such an equals() so that the general contract of hashCode being equal when equals returns true is preserved? ``` public class MyClass { int id; String name; public boolean equals(Object o) { if (!(o instanceof MyClass)) return false; MyClass other = (MyClass) o; if (other.id == this.id || other.name == this.name) return true; return false; } } ``` how do i write a hashCode() function for this class? and i want to avoid the trivial case here of returning a constant like so: ``` public int hashCode() { return 1; } ```
I don't think a nontrivial hashcode exists. Also, your `equals()` violates the general contract as [stated in the API](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)) --- it is **not transitive**: `(1,2)` equals `(1,3)` `(4,3)` equals `(1,3)` But `(4,3)` is **not equal** to `(1,2)`. --- For the sake of completeness, I present to you the [Skeet](https://stackoverflow.com/questions/479105/hashcode-method-when-equals-is-based-on-multiple-independent-fields#479128)-[Niko](https://stackoverflow.com/questions/479105/hashcode-method-when-equals-is-based-on-multiple-independent-fields#479163) proof =) *Claim*: **The hashcode must be the trivial constant function.** *Proof*: Let `(a,b)` and `(c,d)` be two objects with distinct hashcodes, i.e. `h(a,b) ≠ h(c,d)`. Consider the object `(a,d)`. By the OP's definition, `(a,d)` is equal to `(a,b)`, and `(a,d)` is equal to `(c,d)`. It follows from the [hashcode contract](http://java.sun.com/javase/6/docs/api/java/lang/Object.html#hashCode()) that `h(a,d) = h(a,b) = h(c,d)`; a contradiction.
Ok, in your scenario, ignoring the API requirements for a second, there is no non-constant hash function Imagine there were a hashfunction which has different values for (a,b), (a,c), b!=c, then hash(a,b) != hash(a,c), eventhough (a,b) = (a,c). Similarly, (b,a) and (c,a) must emit the same hashCode. Let's call our hash-function h. We find: h(x,y) = h(x,w) = h(v,w) forall x,y,v,w. Hence, the only hashFunction that does what you want is constant.
hashCode() method when equals() is based on multiple independent fields
[ "", "java", "equals", "hashcode", "" ]
I want a way to be able to schedule callbacks, I want to be able register lots of different callbacks at various times to a "Scheduler"-object. Something like this. ``` public class Foo { public void Bar() { Scheduler s = new Scheduler(); s.Schedule(() => Debug.WriteLine("Hello in an hour!"), DateTime.Now.AddHours(1)); s.Schedule(() => Debug.WriteLine("Hello a week later!"), DateTime.Now.AddDays(7)); } } ``` The best way I can come up with for implementing the Scheduler is to have a timer running inside at a given interval and each time the interval has elapsed I check the registered callbacks and see if it's time to call them, if so I do. This is quite simple but has the drawback that you only get the "resolution" of the timer. Let's say the timer is set to tick once a second and you register a callback to be called in half a second it still may not be called for a whole second. Is there a better way to solve this?
This is a good approach. You should dynamically set the timer to go off as soon as the next event is going to occur. You do this by putting jobs in a priority queue. After all, in any case you are **always limited to the resolution** the system can provide, but you should code so that it be the **only** limiting factor.
A good way to do it is to vary the duration of your timer: tell it to go off when (but not before) your first/next scheduled event is due. `<`*Standard disclaimer about Windows not being a real-time operating system, so its timers must always all be a little inaccurate*`>`
Schedule delegate calls
[ "", "c#", ".net", "scheduling", "" ]
I have a image in the shape of a Circle. The circle is broken into 3 equal parts. I have an image with the entire circle. I have 3 other images, each only a piece of the circle but in the color green. I have to do the following: 1. Display the original circle image. 2. Have a 3 buttons on the screen, each button is linked to the 3 parts of the circle. When clicked, it overlays the green image over the circle. So if you clicked all 3 buttons, the entire circle would be green. If you only clicked the 1st button, only that section of the circle would be green. How can I implement this? Is it possible to overlay 2 images at once? Do I have to play with x and y positioning here? (the green image sections currently, if you place them over the original image, will lineup exactly with the original circle image.
Here's a solution shown in straight JavaScript and also jQuery. The straight JavaScript uses the DOM0 onclick handlers of the buttons which is OK because they're only triggering one event. The onload handler for the window is more of a problem: you can only have one per document. The [jQuery](http://jquery.com/) solution is much shorter as you can see, but you'll have to include the jQuery library. The `$( function(){} )` takes the place of the window onload handler but you can have as many as you like. The images sector1.gif, sector2.gif and sector3.gif are transparent apart from the bits of the circle that are visible for them. You could use .png too but that wouldn't work in ie6 without some tweakery. ``` <!-- the markup --> <div id="circle"> <div id="sector1"></div> <div id="sector2"></div> <div id="sector3"></div> </div> <input type="button" id="button1" value="Sector 1"> <input type="button" id="button2" value="Sector 2"> <input type="button" id="button3" value="Sector 3"> ``` \_ ``` /* the style */ #circle{ width: 100px; height 100px; position: relative; background: url( images/circle.gif ); } #sector1, #sector1, #sector1 { width: 100px; height 100px; top: 0; left: 0; position: absolute; display: none; } #sector1 { background: url( images/sector1.gif ); } #sector2 { background: url( images/sector2.gif ); } #sector2 { background: url( images/sector3.gif ); } ``` \_ ``` //basic javascript solution window.onload = function() { // get references to the buttons var b1 = document.getElementById( 'button1' ); var b2 = document.getElementById( 'button2' ); var b3 = document.getElementById( 'button3' ); // get references to the sectors var s1 = document.getElementById( 'button1' ); var s2 = document.getElementById( 'button2' ); var s3 = document.getElementById( 'button3' ); // add onclick events to the buttons which display the sectors b1.onclick = function() { s1.style.display = 'block'; } b2.onclick = function() { s2.style.display = 'block'; } b3.onclick = function() { s3.style.display = 'block'; } } //jQuery solution $(function() { $('#button1').click( function() { $('#sector1').show() } ); $('#button2').click( function() { $('#sector2').show() } ); $('#button3').click( function() { $('#sector3').show() } ); }); ```
The 3 images with partial circles should be transparent for the parts that are not green. Then all 4 images can be overlayed always, and the buttons can change the stacking order. The ones "displayed" will go on top of the solid circle and the others will go beneath it.
Circle image overlays
[ "", "javascript", "css", "" ]
I've been writing tools in Maya for years using MEL and Python. I'd consider myself an expert in custom window/gui design in Maya except for one area; modifying existing panels and editors. Typically, I'm building tools that need totally custom UIs, so its customary for me to build them from scratch. However, recently I've found myself wanting to add some additional functionality to the layer editor in Maya. I've seen tutorials that explain how to do this, but now that I want to do it, I can't find any. Links to tutorials or a brief code snippet to get me started would be great. I just need to know how to find the layer editor/panel and, say, add a button or text field to it.
Have you tried searching ui item names in MEL files under maya installation directory? It should be one of the MEL scripts included, and from there you can just modify it.
The easy way can modify existing Maya code and put it in you user/script. You can use whatIs to get the script name. Say for eg: ``` whatIs "layerEditor"; ``` Result is `./scripts/others/layerEditor.mel //` .But now you can use wrapping instance with PyQt also.
How to modify existing panels in Maya using MEL or Python?
[ "", "python", "user-interface", "maya", "panels", "mel", "" ]
If the locks make sure only one thread accesses the locked data at a time, then what controls access to the locking functions? I thought that [boost::mutex::scoped\_lock](http://www.boost.org/doc/libs/1_37_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.mutex) should be at the beginning of each of my functions so the local variables don't get modified unexpectedly by another thread, is that correct? What if two threads are trying to acquire the lock at very close times? Won't the lock's local variables used internally be corrupted by the other thread? My question is not boost-specific but I'll probably be using that unless you recommend another.
You're right, when implementing locks you need some way of guaranteeing that two processes don't get the lock at the same time. To do this, you need to use an atomic instruction - one that's guaranteed to complete without interruption. One such instruction is [test-and-set](http://en.wikipedia.org/wiki/Test-and-set), an operation that will get the state of a boolean variable, set it to true, and return the previously retrieved state. What this does is this allows you to write code that continually tests to see if it can get the lock. Assume x is a shared variable between threads: ``` while(testandset(x)); // ... // critical section // this code can only be executed by once thread at a time // ... x = 0; // set x to 0, allow another process into critical section ``` Since the other threads continually test the lock until they're let into the critical section, this is a very inefficient way of guaranteeing mutual exclusion. However, using this simple concept, you can build more complicated control structures like semaphores that are much more efficient (because the processes aren't looping, they're sleeping)
You only need to have exclusive access to shared data. Unless they're static or on the heap, local variables inside functions will have different instances for different threads and there is no need to worry. But shared data (stuff accessed via pointers, for example) should be locked first. As for how locks work, they're carefully designed to prevent race conditions and often have hardware level support to guarantee atomicity. IE, there are some machine language constructs guaranteed to be atomic. Semaphores (and mutexes) may be implemented via these.
Why do locks work?
[ "", "c++", "multithreading", "boost", "locking", "mutex", "" ]
``` public class ExampleClass { public static void main(String[] args) { // TODO Auto-generated method stub Horse hr1 = new Horse(); Horse hr2 = new Horse(); Horse hr3 = new Horse(); Horse hr4 = new Horse(); Set hrSet = new HashSet(); hrSet.add(hr1); hrSet.add(hr2); hrSet.add(hr3); hrSet.add(hr4); Horse hr; String hor = "sher_pkg.Horse"; callHorse(hrSet,hor); } public static void callHorse(Set xSet,String clsName){ try { Class hrt = Class.forName(clsName); Iterator hritr = xSet.iterator(); while(hritr.hasNext()){ exam(hrt.cast(hritr.next())); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void exam(Object obj){ //I want to use exam(Horse hrr) System.out.println(obj); } } ``` Here the argument for the exam function is an `Object`. But I want to have the argument be `Horse`... so what changes must be done in "`exam(hrt.cast(hritr.next()))`" method call? I don't want to explicitly use the class name `Horse` in `callHorse()`... So what am I supposed to do? Thanks
Note: Code with sequences of "`if (x instanceof MyClass)` usually indicates that you are not using polymorphism enough. Code can usually be refactored to get rid of the need to test this. But I'll ignore this for the sake of answering the question asked. You can do what you are trying to do, but not without some code changes. Method overloading cannot do what you need because in Java, method overloading is decided at compile time. Thus, if you have two methods in a class where both methods have the same name, same return type, but different parameter types, then any code invoking this overloaded method must make explicit which one will be invoked. Your current code does this with the types it provides due to the use of explicit casts but the fully dynamic version does not. If method overloading were decided at runtime, then your code would do what you want. But because it is decided at compile time, your code does not compile. To solve your problem, you can use generics, or you can restructure your code. First I'll introduce a test harness that shows a very simplified version of what you're starting with: ``` public class Test { public void test(Object obj) { if (obj instanceof Horse) { Horse c = (Horse) obj; noise(c); } if (obj instanceof Cow) { Cow c = (Cow) obj; noise(c); } } public void noise(Horse h) { System.out.println("Neigh"); } public void noise(Cow c) { System.out.println("Moo"); } public static void main(String[] args) { Object o1 = new Horse(); Object o2 = new Cow(); Test tester = new Test(); tester.test(o1); tester.test(o2); } } class Horse {} class Cow {} ``` This code runs and does what you would expect. It prints "Neigh" followed by "Moo". You are trying to replace ``` if (obj instanceof Horse) { Horse c = (Horse) obj; noise(c); } ``` with ``` if (obj instanceof Horse) { handleNoise(obj, Horse.class); } ``` and then adding the method to handle it (simplified): ``` void handleNoise(Object obj, Class clazz) { noise(clazz.cast(obj)); } ``` and as I said before, this doesn't work the overloading of `noise` is decided at compile time. The compiler sees that you are casting, but does not know at compile time what the type is. So it cannot pick an overloading and compilation fails. The best way to solve this is by using polymorphism, because polymorphism is decided at runtime. That is, have all of those classes implement some interface and then move the code in question into the individual classes. Here is an example that does this: ``` public class Test { public void test(Animal obj) { obj.noise(); } public static void main(String[] args) { Animal o1 = new Horse(); Animal o2 = new Cow(); Test tester = new Test(); tester.test(o1); tester.test(o2); } } interface Animal { void noise(); } class Horse implements Animal { public void noise() { System.out.println("Neigh"); } } class Cow implements Animal { public void noise() { System.out.println("Moo"); } } ``` Notice how much simpler the test method is! If you can have each item implement an interface that handles what you call stringProp below, then you can simplify part way: ``` if (obj instanceof Cust) { loopOverSet(c.getCustPhonSet()); } else if (obj instanceof Name) { loopOverSet(c.getCustNameSet()); } // and so on for the rest... ``` and then add the method: ``` void loopOVerSet(Set cxSet) { if (cxSet != null && cxSet.size() > 0) { Iterator cxSetIterator = cxSet.iterator(); while (cxSetIterator.hasNext()) { ((StringProp)cxSetIterator.next()).stringProp(); } } } ``` This assumes that the previously-overloaded methods `stringProp` have been moved into the individual classes `CustPhone` and `CustName` and so on and that these classes all implement some interface which I've called `StringProp` where this interface defines the method `stringProp()`. Since this code is using *overriding* instead of *overloading* it will be decided at runtime.
You might want to take a look at generics. ``` public static void callHorse(Set<Horse> xSet) { Iterator<Horse> hritr = xSet.iterator(); while (hritr.hasNext()) { exam(hritr.next()); } } public static void exam(Horse obj) { //I want to use exam(Horse hrr) System.out.println(obj); } ``` Of course in your example you could always just cast the objects. Why you don’t want to do that is beyond me.
Casting to Unknown Type When Class Name as a String
[ "", "java", "reflection", "casting", "" ]
[SharpNEAT](http://sharpneat.sourceforge.net/index.htm) is a [NeuroEvolution of Augmenting Topologies](http://en.wikipedia.org/wiki/NeuroEvolution_of_Augmented_Topologies) (NEAT) library in C#. The whole thing sounds pretty exciting but I can't find a damn sample/tutorial anywhere! Any help appreciated!
I just wrote a tutorial for SharpNEAT 2: <http://www.nashcoding.com/?p=90> There are going to be at least two more follow-ups, covering co-evolution and HyperNEAT, but part 1 is enough to handle most experiments.
I haven't tried SharpNEAT, but I have played with a few of the java variants. I don't really know of any tutorials out there, most of them are just the way-too-simple XOR function. Is there a specific question/problem you are trying to solve? Perhaps we could brainstorm a solution (to be fair I'm also relatively new at NEAT tho, but perhaps two minds are better than one? :-))
Any good SharpNEAT tutorial?
[ "", "c#", "neural-network", "neat", "" ]
Slightly strange question, but hopefully someone can help. In essence, if the time was 12pm the the elapsed percentage would be 50%, 6am would be 25% and 16pm would be 75%. Given the current time, how could you work out the amount of day that already passed?
Assuming you can get the current time of day, it'd be pretty easy to calculate the percentage of the day elapsed. ``` percentage = (hours / 24 + minutes / (60 * 24)) * 100 ```
24hours are 100% so 24/currentTime = result 100 / result = % ;)
Work out the percentage of the day that has elapsed
[ "", "php", "datetime", "date", "time", "" ]
I'm making a template that is relying on a lot on a tabbed interface and in order to make it a bit more intuitive, I want to make sure that a user can click anywhere in the tab in order to activate it, instead of having to click the text inside the tab. In order to achive this, I'm currently doing this: ``` <div class="tab" onclick="javascript:window.location='http://example.com';"> tab text </div> ``` for all the tabs I create. Does anyone have a more efficient way of doing this that they'd like to share with me/the community?
It would be more accessible if you did this: ``` <div class="tab"> <a href="..." style="display: block;">tab text</a> </div> ``` Setting the `<a>` to `block` lets it fill the width, and you can give it height, padding etc. just like a `<div>`. You could even do away with the `<div>` entirely. ``` <a href="..." class="tab" style="display: block;">tab text</a> ``` Of course, you'd add `display: block;` to `.tab {}` but you get the idea.
It's better in terms of semantics and compatibility to modify the <a> tag with CSS to do this, you could try something like this: ``` a.tab { display:block; } ``` And then also set other relevant attributes like the width/height, background color, etc for that. Then instead your HTML looks like this: ``` <a class="tab" href="http://example.com">tab text</a> ```
Making an entire tab clickable
[ "", "javascript", "html", "css", "" ]
OK, *[info break](https://sourceware.org/gdb/onlinedocs/gdb/Set-Breaks.html)* lists the breakpoints, but not in a format that would work well with reusing them using the --command [as in this question](https://stackoverflow.com/questions/500967/gdb-breakpoints). Does GDB have a method for dumping them into a file acceptable for input again? Sometimes in a debugging session, it is necessary to restart GDB after building up a set of breakpoints for testing. The .gdbinit file has the same problem as --command. The *info break* command does not list commands, but rather a table for human consumption. To elaborate, here is a sample from *info break*: ``` (gdb) info break Num Type Disp Enb Address What 1 breakpoint keep y 0x08048517 <foo::bar(void)+7> ```
As of GDB 7.2 (2011-08-23) you can now use the *[save breakpoints](https://sourceware.org/gdb/onlinedocs/gdb/Save-Breakpoints.html)* command. ``` save breakpoints <filename> Save all current breakpoint definitions to a file suitable for use in a later debugging session. To read the saved breakpoint definitions, use the `source' command. ``` Use [`source <filename>`](https://sourceware.org/gdb/onlinedocs/gdb/Command-Files.html) to restore the saved breakpoints from the file.
***This answer is outdated. GDB now supports saving directly. See [this answer](https://stackoverflow.com/a/3984156/331858).*** You can use logging: ``` (gdb) b main Breakpoint 1 at 0x8049329 (gdb) info break Num Type Disp Enb Address What 1 breakpoint keep y 0x08049329 <main+16> (gdb) set logging file breaks.txt (gdb) set logging on Copying output to breaks.txt. (gdb) info break Num Type Disp Enb Address What 1 breakpoint keep y 0x08049329 <main+16> (gdb) q ``` The file breaks.txt now contains: ``` Num Type Disp Enb Address What 1 breakpoint keep y 0x08049329 <main+16> ``` Writing an AWK script that transforms that into a format useful for the `.gdbinit` or a `--command` file is easy. Or you may even make the script emit separate `--eval-command`'s to the GDB command line... Adding this small macro to [.gdbinit](https://sourceware.org/gdb/onlinedocs/gdb/gdbinit-man.html) will help you do it: ``` # Call with dump_breaks file.txt define dump_breaks set logging file $arg0 set logging redirect on set logging on info breakpoints set logging off set logging redirect off end ```
Getting GDB to save a list of breakpoints
[ "", "c++", "c", "debugging", "gdb", "breakpoints", "" ]
Here's what I'd like to do: I've got a line of text in an HTML page. I'd like to have that piece of text start at a given color, cycle though the spectrum, wait a second or two, and then repeat. I'd like to do this in javascript if possible (something like flash isn't totally out of the question, but would be some major scope creep of this project.) I know enough JS to know this is possible, but that's about it. Can anyone point me in the right direction? And yes, this is a real client request. I'm just glad they didn't also ask for the blink tag. ;)
After browsing some of the "fading" examples, we ended up going with jQuery's .animate() function and [this color animation plugin](http://plugins.jquery.com/project/color). Works spectacularly.
If you want to cycle through the spectrum, using the HSB color model is your best bet. Related questions: * [Color scaling function](https://stackoverflow.com/questions/168838/color-scaling-function) * [Generate colors between red and green for a power meter?](https://stackoverflow.com/questions/340209/generate-color-for-a-power-meter-red-to-green)
Is there a good way to do color cycling in javascript?
[ "", "javascript", "animation", "colors", "" ]
My HTML has ``` cell = document.createElement("td"); cell.appendChild(document.createTextNode(contents)); cell.setAttribute('width', '100'); ``` The following syntax is not working. ``` cell.appendChild(document.createElement('br')).appendChild(document.createTextNode("Another text")); ``` And after the contents of the cell, I have a line break followed by another text in small letters in same cell. How can I do it?
It looks like you are trying to chain your method calls... Sorry! No chaining for native elements. If you want chaining then try [jQuery](http://jquery.com), otherwise try: ``` var cell = document.createElement("td"); cell.appendChild(document.createTextNode(contents)); cell.setAttribute('width', '100'); // To make some text smaller you'll need it in a different element like a span var span = document.createElement('span'); span.className = 'your-class-for-small-text'; span.appendChild(document.createTextNode("Another text")); cell.appendChild(document.createElement('br')); cell.appendChild(span); ``` You'll have to add some css to style that span to have smaller text: ``` <style type="text/css"> .your-class-for-small-text { font-size: 12px; } </style> ``` Or you could just modify the style of that element instead of using the className: ``` var cell = document.createElement("td"); cell.appendChild(document.createTextNode(contents)); cell.setAttribute('width', '100'); // To make some text smaller you'll need it in a different element like a span var span = document.createElement('span'); span.style.fontSize = '12px'; span.appendChild(document.createTextNode("Another text")); cell.appendChild(document.createElement('br')); cell.appendChild(span); ```
First of all, you are appending a text node to a BR tag which has no children. Try to split your line in two calls instead: ``` cell.appendChild(document.createElement('br')); cell.appendChild(document.createTextNode("Another text")); ```
JavaScript DOM code is not working
[ "", "javascript", "html", "dom", "" ]
This is a follow up to my [earlier question](https://stackoverflow.com/questions/490792/error-1053-while-trying-to-restart-stop-tomcat-5-0-30-installed-as-a-windows-ser). Tomcat 5.0.28 had a bug where the Servlet's destroy() method was not being invoked by the container on a shutdown. This is fixed in Tomcat 5.0.30, but if the Servlet's destroy() method had a System.exit(), it would result in the Tomcat windows service throwing the Error 1053 and refusing to shutdown gracefully (see above link for more details on this error) Anybody has any idea on whether: * Calling System.exit() inside a Servlet's destroy() method to forcefully kill any non-daemon threads is a good idea? * Why does Tomcat 5.0.30 and (later versions including Tomcat 6.x.x) fail to shutdown properly if there's a System.exit() in the destroy() method of the Servlet.
You're asking two questions: **Question 1: Is calling System.exit() inside a Servlet's destroy() method to forcefully kill any non-daemon threads a good idea?** Calling System.exit() inside ANY servlet-related method is always 100% incorrect. Your code is not the only code running in the JVM - **even if you are the only servlet running** (the servlet container has resources it will need to cleanup when the JVM really exits.) The correct way to handle this case is to clean up your threads in the destroy() method. This means starting them in a way that lets you gently stop them in a correct way. Here is an example (where MyThread is one of your threads, and extends ServletManagedThread): ``` public class MyServlet extends HttpServlet { private List<ServletManagedThread> threads = new ArrayList<ServletManagedThread>(); // lots of irrelevant stuff left out for brevity public void init() { ServletManagedThread t = new MyThread(); threads.add(t); t.start(); } public void destroy() { for(ServletManagedThread thread : threads) { thread.stopExecuting(); } } } public abstract class ServletManagedThread extends Thread { private boolean keepGoing = true; protected abstract void doSomeStuff(); protected abstract void probablySleepForABit(); protected abstract void cleanup(); public void stopExecuting() { keepRunning = false; } public void run() { while(keepGoing) { doSomeStuff(); probablySleepForABit(); } this.cleanup(); } } ``` It's also worth noting that there are thread/concurrency libraries out there that can help with this - but if you really do have a handful of threads that are started at servlet initialization and should run until the servlet is destroyed, this is probably all you need. **Question 2: Why does Tomcat 5.0.30 and (later versions including Tomcat 6.x.x) fail to shutdown properly if there's a System.exit() in the destroy() method of the Servlet?** Without more analysis, it's hard to know for certain. [Microsoft says](http://support.microsoft.com/kb/839174) that Error 1053 occurs when Windows asks a service to shutdown, but the request times out. That would make it seem like something happened internally to Tomcat that got it into a really bad state. I would certainly suspect that your call to `System.exit(`) could be the culprit. Tomcat (specifically, Catalina) does register a shutdown hook with the VM (`see org.apache.catalina.startup.Catalina.start()`, at least in 5.0.30). That shutdown hook would get called by the JVM when you call `System.exit()`. The shutdown hook delegates to the running services, so each service could potentially be required to do alot of work. If the shutdown hooks (`triggered by your System.exit()`) fail to execute (they deadlock or something like that,) then it is very easy to understand why the Error 1053 occurs, given the documentation of the `Runtime.exit(int)` method (which is called from `System.exit()`): > If this method is invoked after the > virtual machine has begun its shutdown > sequence then if shutdown hooks are > being run this method will block > indefinitely. If shutdown hooks have > already been run and on-exit > finalization has been enabled then > this method halts the virtual machine > with the given status code if the > status is nonzero; otherwise, it > blocks indefinitely. This "indefinite blocking" behavior would definitely cause an Error 1053. If you want a more complete answer than this, you can [download the source](http://archive.apache.org/dist/tomcat/tomcat-5/v5.0.30/src/jakarta-tomcat-5.0.30-src.zip) and debug it yourself. But, I would be willing to bet that if you properly handle your thread management issue (as outlined above,) your problems will go away. In short, leave the System.exit() call to Tomcat - that's not your job.
> Calling System.exit() inside a Servlet's destroy() method to forcefully kill any non-daemon threads is a good idea? It is absolutely not a good idea - it is a horrible idea. The `destroy()` method is called when the servlet is taken out of service, which can happen for any number of reasons: the servlet/webapp has been stopped, the webapp is being undeployed, the webapp is being restarted etc. `System.exit()` shuts down **the entire JVM**! Why would you want to forcibly shutdown the entire server simply because one servlet is being unloaded? > Why does Tomcat 5.0.30 and (later versions including Tomcat 6.x.x) fail to shutdown properly if there's a System.exit() in the destroy() method of the Servlet. Probably to prevent such dangerous behavior like this. You shouldn't write code that assumes that your code/application is the only thing running on the server.
Calling System.exit() in Servlet's destroy() method
[ "", "java", "tomcat", "servlets", "windows-services", "" ]
We have a user table, every user has an unique email and username. We try to do this within our code but we want to be sure users are never inserted (or updated) in the database with the same username of email. I've added a `BEFORE INSERT` Trigger which prevents the insertion of duplicate users. ``` CREATE TRIGGER [dbo].[BeforeUpdateUser] ON [dbo].[Users] INSTEAD OF INSERT AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; DECLARE @Email nvarchar(MAX) DECLARE @UserName nvarchar(MAX) DECLARE @UserId int DECLARE @DoInsert bit SET @DoInsert = 1 SELECT @Email = Email, @UserName = UserName FROM INSERTED SELECT @UserId = UserId FROM Users WHERE Email = @Email IF (@UserId IS NOT NULL) BEGIN SET @DoInsert = 0 END SELECT @UserId = UserId FROM Users WHERE UserName = @UserName IF (@UserId IS NOT NULL) BEGIN SET @DoInsert = 0 END IF (@DoInsert = 1) BEGIN INSERT INTO Users SELECT FirstName, LastName, Email, Password, UserName, LanguageId, Data, IsDeleted FROM INSERTED END ELSE BEGIN DECLARE @ErrorMessage nvarchar(MAX) SET @ErrorMessage = 'The username and emailadress of a user must be unique!' RAISERROR 50001 @ErrorMessage END END ``` But for the Update trigger I have no Idea how to do this. I've found this example with google: <http://www.devarticles.com/c/a/SQL-Server/Using-Triggers-In-MS-SQL-Server/2/> But I don't know if it applies when you update multiple columns at once. **EDIT:** I've tried to add a unique constraint on these columns but it doesn't work: ``` Msg 1919, Level 16, State 1, Line 1 Column 'Email' in table 'Users' is of a type that is invalid for use as a key column in an index. ```
You can add a unique contraint on the table, this will raise an error if you try and insert or update and create duplicates ``` ALTER TABLE [Users] ADD CONSTRAINT [IX_UniqueUserEmail] UNIQUE NONCLUSTERED ( [Email] ASC ) ALTER TABLE [Users] ADD CONSTRAINT [IX_UniqueUserName] UNIQUE NONCLUSTERED ( [UserName] ASC ) ``` EDIT: Ok, i've just read your comments to another post and seen that you're using NVARCHAR(MAX) as your data type. Is there a reason why you might want more than 4000 characters for an email address or username? This is where your problem lies. If you reduce this to NVARCHAR(250) or thereabouts then you can use a unique index.
Sounds like a lot of work instead of just using one or more unique indexes. Is there a reason you haven't gone the index route?
Adding a constraint to prevent duplicates in SQL Update Trigger
[ "", "sql", "triggers", "sql-update", "sql-insert", "" ]
I am posting a very simple form using a method I have used frequently in the past. It may be easier to show my code rather than type a lengthy explanation. Here's the HTML: ``` <% Html.BeginForm("CreateMarketingType", "ListMaintenance"); %> <div id="ListMaintenanceContainer"> <table> <tr> <th>Marketing Type Id</th> <th>Marketing Type Name</th> </tr> <%foreach (MarketingType marketingType in ViewData.Model.MarketingTypes) %> <%{ %> <tr> <td><%= marketingType.MarketingTypeId.ToString() %></td> <td><%= marketingType.MarketingTypeName %></td> </tr> <%} %> </table> <div> <fieldset id="fsSaveNewMarketingType"> <legend>Add New Marketing Type</legend> <label for="txtNewMarketingTypeName">New Marketing Type Name:</label> <input type="text" id="txtNewMarketingTypeName" /> <input type="submit" value="Save" id="CreateMarketingType" /> </fieldset> </div> </div> <% Html.EndForm();%> ``` And here's the controller code: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult CreateMarketingType(FormCollection form) { string newMarketingTypeName = Request.Form["txtNewMarketingTypeName"].ToString(); MarketingType newMarketingType = new MarketingType() { MarketingTypeName = newMarketingTypeName }; _marketingTypeRepository.AddNewMarketingType(newMarketingType); return View("ListMaintenance", GetModel()); } ``` The submit button posts the form, and the method is invoked, but the form object defined in my parameter is empty. I have also tried Request.Form and I get the same result. Am I missing something here?
None of your inputs have a name attribute. No name = not in the FormCollection.
I had this issue and then realised I had disabled all the INPUT controls before I submitted the form (as a UX feature).
FormCollection Empty on Form Post in ASP.NET-MVC
[ "", "c#", "asp.net", "asp.net-mvc", "" ]
How would you model the references and citations to publications (articles, books, chapters, etc...)? A publication can be an article, book or a chapter and it has many references to other publications and other publications refer to it (call these citations) I need to be able to list the relationships among the publications: The references in a publication and the citations from other publications to this publication My initial understanding is that this would be a polymorphic relationship to handle the different types of publications and that it would require a bidirectionalself join. My stab at it ``` Publication belongs_to :writing, :polymorphic =>true has_and_belongs_to_many :references :class_name => "Publication" :join_table => 'reference_citation' :foreign_key => 'reference_id' :foreign_key => 'citation_id' Book, Chapter, Article all have: has_many :publications :as =>writing ``` I find this a bit confusing so any suggestions that would help clarify it would be great. Even object and field naming suggestions. [I asked a less clear version of this question [here](https://stackoverflow.com/questions/499934/how-would-you-model-articles-with-references-and-citations-in-rails-activerecord).] I also probably need to use has many through because I will need the ability to destroy the relationship
Here's a solution using a self-referential relationship using single table inheritance. Use these commands to create the app: ``` $ rails myproject $ cd myproject $ script/generate model publication type:string name:string $ script/generate model citation publication_id:integer reference_id:integer ``` The setup the relationships this way: ``` class Publication < ActiveRecord::Base has_many :citations has_many :cited_publications, :through => :citations, :source => :reference has_many :references, :foreign_key => "reference_id", :class_name => "Citation" has_many :refered_publications, :through => :references, :source => :publication end class Citation < ActiveRecord::Base belongs_to :publication belongs_to :reference, :class_name => "Publication" end class Article < Publication end class Book < Publication end class Chapter < Publication end ``` Now we can create the DB and try it out from the console: ``` $ rake db:migrate $ script/console Loading development environment (Rails 2.2.2) >> a = Article.create!(:name => "Article") => #<Article id: 1, ...> >> b = Book.create!(:name => "Book") => #<Book id: 2, ...> >> a.citations.create(:reference => b) => #<Citation id: 1, publication_id: 1, reference_id: 2, created_at: "2009-02-15 14:13:15", updated_at: "2009-02-15 14:13:15"> >> a.citations => [#<Citation id: 1, ...>] >> a.references => [] >> b.citations => [] >> b.references => [#<Citation id: 1, publication_id: 1, reference_id: 2, created_at: "2009-02-15 14:13:15", updated_at: "2009-02-15 14:13:15">] >> a.cited_publications => [#<Book id: 2, type: "Book", name: "Book", created_at: "2009-02-15 14:11:00", updated_at: "2009-02-15 14:11:00">] >> a.refered_publications => [] >> b.cited_publications => [] >> b.refered_publications => [#<Article id: 1, type: "Article", name: "Article", created_at: "2009-02-15 14:10:51", updated_at: "2009-02-15 14:10:51">] ```
Here's a solution that doesn't use Single Table Inheritance for the publications. That means that there are articles, books and chapters tables, instead of one publications table. Here are the commands to run to create the app: ``` $ rails myproject $ cd myproject $ script/generate model book name:string $ script/generate model chapter name:string $ script/generate model article name:string $ script/generate model citation publication_type:string publication_id:integer reference_type:string reference_id:integer ``` Create this file in `lib/acts_as_publication.rb`: ``` module ActsAsPublication def self.included(base) base.extend(ClassMethods) end module ClassMethods def acts_as_publication has_many :citations, :as => :publication has_many :references, :as => :reference, :class_name => "Citation" end end end ``` Create this file in `config/initializers/acts_as_publication.rb`: ``` ActiveRecord::Base.send(:include, ActsAsPublication) ``` Then call that in each model, Article, Book and Chapter, like this: ``` class Article < ActiveRecord::Base acts_as_publication end ``` Then add these relationships in `app/models/citation.rb`: ``` class Citation < ActiveRecord::Base belongs_to :publication, :polymorphic => true belongs_to :reference, :polymorphic => true end ``` Now we can create the DB and try it out from the console: ``` $ rake db:migrate $ script/console Loading development environment (Rails 2.2.2) >> a = Article.create!(:name => "a") => #<Article id: 1, ...> >> b = Article.create!(:name => "b") => #<Article id: 2, ...> >> Citation.create!(:publication => a, :reference => b) => #<Citation id: 1, publication_type: "Article", publication_id: 1, reference_type: "Article", reference_id: 2, created_at: "2009-02-15 13:14:27", updated_at: "2009-02-15 13:14:27"> >> a.citations => [#<Citation id: 1, ...>] >> a.references => [] >> b.citations => [] >> b.references => [#<Citation id: 1, ...>] >> Book.create!(:name => "foo") => #<Book id: 1, name: "foo", created_at: "2009-02-15 13:18:23", updated_at: "2009-02-15 13:18:23"> >> a.citations.create(:reference => Book.first) => #<Citation id: 2, publication_type: "Article", publication_id: 1, reference_type: "Book", reference_id: 1, created_at: "2009-02-15 13:18:52", updated_at: "2009-02-15 13:18:52"> >> Book.first.references => [#<Citation id: 2, ...>] >> a.citations => [#<Citation id: 1, publication_type: "Article", publication_id: 1, reference_type: "Article", reference_id: 2, created_at: "2009-02-15 13:14:27", updated_at: "2009-02-15 13:14:27">, #<Citation id: 2, publication_type: "Article", publication_id: 1, reference_type: "Book", reference_id: 1, created_at: "2009-02-15 13:18:52", updated_at: "2009-02-15 13:18:52">] ```
Tricky active record relationships - polymorphic bi-directional self-referential
[ "", "sql", "ruby-on-rails", "activerecord", "" ]
I'm studying ICT. One of my courses is C# and another is Physics. Our Physics teacher used Visual Studio to animate some movements gave us some of the code he used to do it. He told us to look it up. Here's something I don't recognize: ``` public static Vector operator + (Vector v1, Vector v2) { return new Vector(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z); } ``` That is supposed to be a constructor, but I've never seen anything like it before. I don't know what it's called, so I don't know what to google for. Can someone enlighten me please?
It's not a constructor. It's an operator method for the '+' operator. It defines what happens when you do somethig like the following:- ``` var Vector v1 = new Vector(1,2,3); var Vector v2 = new Vector(1,2,3); var Vector v3 = v1 + v2; ```
That is called "operator overloading". It is not a constructor but returns a new Vector. See: [Operator Overloading](http://msdn.microsoft.com/en-us/library/aa288467(VS.71).aspx)
Specific form of Constructor in C#
[ "", "c#", "visual-studio", "constructor", "" ]
In other answers at Stackoverflow it's been suggested that Weka is good, but there are others ([Classifier4j](http://classifier4j.sourceforge.net/), [jBNC](http://jbnc.sourceforge.net/), [Naiban](http://www.tempeststrings.com/naiban/)). Does anyone have actual experience with these?
Weka is awesome, but [Classifier4J](http://classifier4j.sourceforge.net/) is probably closer to what you want, since it's more aimed at text recognition.
You could also have a look at the still very new [Apache Mahout](http://cwiki.apache.org/MAHOUT/index.html#index-Classification) project.
What's the best open-source Java Bayesian spam filter library?
[ "", "java", "machine-learning", "spam-prevention", "classification", "bayesian", "" ]
Is it a good practice to bootstrap your PHP application. I found two ways to bootstrap my PHP application. Need some suggestions which is a better way. **First.** Define a constant for the folder structures ``` $controllerPath = 'controller'; define('CONTROLLER', str_replace('\\', '/', realpath($controllerPath)).'/'); //usage require_once CONTROLLER . 'somecontroller.php'; ``` **Second** Using ini\_set set the include path to the application root ``` $rootPath = $_SERVER['DOCUMENT_ROOT']; $includePath = ini_get('include_path'); ini_set('include_path', '.'.PATH_SEPARATOR.$rootPath.PATH_SEPARATOR.$includePath); //usage require_once 'controller/somecontroller.php'; ``` Please tell me which is a better way. **In case of a high-load application which would be the best method ??**
Use ini\_set to set it to the directory -above- your application. That why you can use the literal strings in your require statements. In addition, it makes it easier to use reuse code ``` require 'coolapp/class/Model.php' require 'coolapp/display/Router.php' require 'spinoff/display/JsView.php' // etc ``` Its similar to the idea in java of having fully qualified imports of `com.whatever.app.more`, or how in python all of an apps imports should be absolute with respect to that app. Re: **High load application** Unless you are loading many thousand files, the time it takes to include files probably isn't a bottle neck. But, if it was the case you have a couple options. One is APC, which caches the results of `include` in memory. Another is to load everything from a single file, similar to how javascript files are concatenated into one for better performance (coincidentally, APC has a function that gives you this information). APC is really easy to setup and is completely transparent, for a boost of [~50% better performance](http://www.whitewashing.de/blog/articles/73).
Better use absolute paths than letting PHP find the file in one of the given include paths. So I tend for the first way using a constant that holds the absolute path to the application root.
PHP Bootstrapping better method?
[ "", "php", "bootstrapping", "" ]
Eclipse is giving me a warning of the following form: > Type safety: Unchecked cast from Object to HashMap This is from a call to an API that I have no control over which returns Object: ``` HashMap<String, String> getItems(javax.servlet.http.HttpSession session) { HashMap<String, String> theHash = (HashMap<String, String>)session.getAttribute("attributeKey"); return theHash; } ``` I'd like to avoid Eclipse warnings, if possible, since theoretically they indicate at least a potential code problem. I haven't found a good way to eliminate this one yet, though. I can extract the single line involved out to a method by itself and add `@SuppressWarnings("unchecked")` to that method, thus limiting the impact of having a block of code where I ignore warnings. Any better options? I don't want to turn these warnings off in Eclipse. Before I came to the code, it was simpler, but still provoked warnings: ``` HashMap getItems(javax.servlet.http.HttpSession session) { HashMap theHash = (HashMap)session.getAttribute("attributeKey"); return theHash; } ``` Problem was elsewhere when you tried to use the hash you'd get warnings: ``` HashMap items = getItems(session); items.put("this", "that"); Type safety: The method put(Object, Object) belongs to the raw type HashMap. References to generic type HashMap<K,V> should be parameterized. ```
Wow; I think I figured out the answer to my own question. I'm just not sure it's worth it! :) The problem is the cast isn't checked. So, you have to check it yourself. You can't just check a parameterized type with instanceof, because the parameterized type information is unavailable at runtime, having been erased at compile time. But, you can perform a check on each and every item in the hash, with instanceof, and in doing so, you can construct a new hash that is type-safe. And you won't provoke any warnings. Thanks to mmyers and Esko Luontola, I've parameterized the code I originally wrote here, so it can be wrapped up in a utility class somewhere and used for any parameterized HashMap. If you want to understand it better and aren't very familiar with generics, I encourage viewing the edit history of this answer. ``` public static <K, V> HashMap<K, V> castHash(HashMap input, Class<K> keyClass, Class<V> valueClass) { HashMap<K, V> output = new HashMap<K, V>(); if (input == null) return output; for (Object key: input.keySet().toArray()) { if ((key == null) || (keyClass.isAssignableFrom(key.getClass()))) { Object value = input.get(key); if ((value == null) || (valueClass.isAssignableFrom(value.getClass()))) { K k = keyClass.cast(key); V v = valueClass.cast(value); output.put(k, v); } else { throw new AssertionError( "Cannot cast to HashMap<"+ keyClass.getSimpleName() +", "+ valueClass.getSimpleName() +">" +", value "+ value +" is not a "+ valueClass.getSimpleName() ); } } else { throw new AssertionError( "Cannot cast to HashMap<"+ keyClass.getSimpleName() +", "+ valueClass.getSimpleName() +">" +", key "+ key +" is not a " + keyClass.getSimpleName() ); } } return output; } ``` That's a lot of work, possibly for very little reward... I'm not sure if I'll use it or not. I'd appreciate any comments as to whether people think it's worth it or not. Also, I'd appreciate improvement suggestions: is there something better I can do besides throw AssertionErrors? Is there something better I could throw? Should I make it a checked Exception?
The obvious answer, of course, is not to do the unchecked cast. If it's absolutely necessary, then at least try to limit the scope of the `@SuppressWarnings` annotation. According to its [Javadocs](http://java.sun.com/javase/6/docs/api/java/lang/SuppressWarnings.html), it can go on local variables; this way, it doesn't even affect the entire method. Example: ``` @SuppressWarnings("unchecked") Map<String, String> myMap = (Map<String, String>) deserializeMap(); ``` There is no way to determine whether the `Map` really should have the generic parameters `<String, String>`. You must know beforehand what the parameters should be (or you'll find out when you get a `ClassCastException`). This is why the code generates a warning, because the compiler can't possibly know whether is safe.
How do I address unchecked cast warnings?
[ "", "java", "generics", "warnings", "" ]
Been doing mostly Java and smattering of .NET for last five years and haven't written any significant C or C++ during that time. So have been away from that scene for a while. If I want to write a C or C++ program today that does some multi-threading and is source code portable across Windows, Mac OS X, and Linux/Unix - is PThread a good choice? The C or C++ code won't be doing any GUI, so won't need to worry with any of that. For the Windows platform, I don't want to bring a lot of Unix baggage, though, in terms of unix emulation runtime libraries. Would prefer a PThread API for Windows that is a thin-as-possible wrapper over existing Windows threading APIs. **ADDENDUM EDIT:** > Am leaning toward going with > boost:thread - I also want to be able > to use C++ try/catch exception > handling too. And even though my > program will be rather minimal and not > particularly OOPish, I like to > encapsulate using class and namespace > - as opposed to C disembodied functions.
Well, pthreads is the old posix standard for writing threaded programs. Its the lowest level threading routines, so its a good choice for cross-platform threading. However, there are alternatives: * [boost::thread](http://www.ddj.com/cpp/184401518) - an STL style threading library * Intel's [Thread Building Blocks](http://www.threadingbuildingblocks.org/) * [OpenMP](http://openmp.org/wp/) - both these are a higher-level way of writing threaded apps without needing to do any threading calls. As the latter are all fully supported on all platforms, (pthreads requires a bit of compiler settings as its only part of Windows posix subsystem, unless you want to use [Pthreads-w32](http://sourceware.org/pthreads-win32/)), then perhaps the latter ones are a better choice. boost::threads are more like a threading library, the other 2 are high-level ways of achieving parallelism without needing to code 'threads', they allow you to write loops that run concurrently automatically (subject to common-sense conditions) Boost::thread is not a C compatible library though. **edit**: cross-platform abilities of the above: > [Intel TBB is cross-platform](http://www.intel.com/cd/software/products/asmo-na/eng/threading/294797.htm#sysreq) (Windows\*, > Linux\*, and Mac OS\* X), supports > 32-bit and 64-bit applications and > works with Intel, Microsoft and GNU > compilers. OpenMP depends on the compiler you want to use, but GCC and/or Intel [compilers have supported](http://openmp.org/wp/openmp-compilers/) OpenMP Windows, Linux and MacOS.
If you need your code to be truly portable then it may be best to stay away from the various libraries that scatter the internet. At some point you'll find a platform they don't support and will then have to create your own branch. This is also not a hard problem to solve and can be a good exercise for creating cross-platform code. I'd suggest you create a class, e.g. CThread, that has separate .cpp implementations for each platform and a pure-virtual execute() function that is called after your thread is constructed/run. That allows all of your thread-creation and sleep/shutdown/priority code to be implemented using the most appropriate API for the platform. You may also need a header (e.g. ThreadTypes.h) that contains defines/typedefs for each platform. E.g. ``` // ThreadTypes.h #if defined(PLATFORM_WIN) || defined(PLATFORM_XBOX) typedef DWORD ThreadID #elif defined(PLATFORM_PS3) // etc etc #endif ``` This is how I have written all my cross-platform threading code for platforms such as PC/PS2/PS3/360/Wii. It is also a good pattern to follow for things like mutex's and semaphores, which if you have threads you're certain to need at some point :)
Is PThread a good choice for multi-platorm C/C++ multi-threading program?
[ "", "c++", "c", "multithreading", "pthreads", "portability", "" ]
According to this: <http://www.codeplex.com/IronPython/Wiki/View.aspx?title=IP20VsCPy25Perf&referringTitle=IronPython%20Performance> IronPython (Python for .Net) is faster than regular Python (cPython) on the same machine. Why is this? I would think compiled C code would always be faster than the equivalent CLI bytecode.
Python code doesn't get compiled to C, Python itself is written in C and interprets Python bytecode. CIL gets compiled to machine code, which is why you see better performance when using IronPython.
You're right, C is a lot faster. That's why in those results CPython is twice as fast when it comes to dictionaries, which are almost pure C. On the other hand, Python code is not compiled, it's interpreted. Function calls in CPython are terribly slow. But on the other hand: ``` TryRaiseExcept: +4478.9% ``` Now, there's where IronPython get is horribly wrong. And then, there is this PyPy project, with one of the objectives being Just-In-Time compiler. There is even subset of Python, called RPython (Reduced Python) which can be statically compiled. Which of course is a **lot** faster.
Why is IronPython faster than the Official Python Interpreter
[ "", "python", "performance", "ironpython", "" ]
I have a program that I would like to run on just one CPU so it doesn't take up too much system resources. The problem is, it makes a call into an external DLL that automatically uses all available CPU cores. I do not have the source code to the external DLL. How can I limit the DLL to only using one CPU? EDIT: Thanks for the help, here is the code I used to limit to one CPU (Windows): ``` // Limit the process to only 1 thread so we don't chew up system resources HANDLE ProcessHandle = GetCurrentProcess(); DWORD ProcessAffinityMask; DWORD SystemAffinityMask; if(GetProcessAffinityMask(ProcessHandle,&ProcessAffinityMask,&SystemAffinityMask) && SystemAffinityMask != 0) { // Limit to 1 thread by masking all but 1 bit of the system affinity mask DWORD NewProcessAffinityMask = ((SystemAffinityMask-1) ^ SystemAffinityMask) & SystemAffinityMask; SetProcessAffinityMask(ProcessHandle,NewProcessAffinityMask); } ``` EDIT: Turns out Brannon's approach of setting process priority works even better for what I want, which is to keep the process from chewing up resources. Here's that code (Windows): ``` // Make the process low priority so we don't chew up system resources HANDLE ProcessHandle = GetCurrentProcess(); SetPriorityClass(ProcessHandle,BELOW_NORMAL_PRIORITY_CLASS); ```
Setting processor affinity is the wrong approach. Let the OS handle scheduling. If the machine is sitting idle, you want to use as much processor as you can. Otherwise you're doing less work for no reason. If the machine is busy, then you want to make use of "free" cycles and not adversely affect other processes. Windows has this functionality built-in. The proper solution for this is to set the base priority of the process. See <http://msdn.microsoft.com/en-us/library/ms686219(VS.85).aspx> for details on `SetPriorityClass()`. If you want to test this without writing any code, use Task Manager to change the priority of your process.
You could set the CPU affinity of your program. Try the [SetProcessAffinityMask](http://msdn.microsoft.com/en-us/library/ms686223(VS.85).aspx) function on Windows or [sched\_setaffinity](http://www.kernel.org/doc/man-pages/online/pages/man2/sched_setaffinity.2.html) on Linux.
How do I limit an external DLL to one CPU?
[ "", "c++", "multithreading", "dll", "external-dependencies", "" ]
How does one go about attaching a bunch of code to an `onkeydown` event, but keep entering text into a `textarea` fast and crisp? Anything more than a couple of IF statements seems to slow it down quite considerably. **EDIT**: I should add (can't believe I forgot!) that this doesn't affect desktop browsers. It's mainly an issue with iPhone Safari. Other mobile browsers might be affected as well, but we're focusing on iPhone Safari since it executes JS the best (AFAIK)
Considering your edit regarding this being focused on iPhone access... The iPhone really just doesn't have that much power to it. You'll be better off just using **`onchange`** or **`onblur`** instead of **`onkeydown`**. --- --- An alternative to Dave's answer is waiting for the user to pause (e.g. for 5 seconds): ``` var textarea = document.getElementById('textarea'); function checkTextArea() { if (textarea.value /* ... */) { /* ... */ } } textarea.keyDownTimeout = null; textarea.onkeydown = function () { if (textarea.keyDownTimeout) clearTimeout(textarea.keyDownTimeout); textarea.keyDownTimeout = setTimeout(checkTextArea, 5000); }; ``` This should set the timer with the first keydown, stopping and recreating the timer for each successive keydown. Finally calling 5 seconds after the user stops typing. Also, note the lack of parenthesis after `checkTextArea`. This will give `setTimeout` the function's reference vs. its `return`. --- You can also set this up in a function to make it easier to use for multiple elements: ``` function setPauseTimer(element, timeout, callback) { var timer = null; element.onkeydown = function () { if (timer) clearTimeout(timer); timer = setTimeout(function(){ callback(element); }, timeout); }; } function checkTextArea(textarea) { /* moved from global to argument */ if (textarea.value /* ... */) { /* ... */ } } setPauseTimer(document.getElementById('textarea'), 5000, checkTextArea); ```
Maybe you could post "a bunch of code" and we could discuss whether there's some refactoring there (before complexifying it with a timer). It seems like you might be jumping to secondary optimizations first.
Textarea lags after registering `keydown` events using Javascript
[ "", "javascript", "html", "events", "textarea", "keydown", "" ]
I need to process a large file, around 400K lines and 200 M. But sometimes I have to process from bottom up. How can I use iterator (yield return) here? Basically I don't like to load everything in memory. I know it is more efficient to use iterator in .NET.
Reading text files backwards is really tricky unless you're using a fixed-size encoding (e.g. ASCII). When you've got variable-size encoding (such as UTF-8) you will keep having to check whether you're in the middle of a character or not when you fetch data. There's nothing built into the framework, and I suspect you'd have to do separate hard coding for each variable-width encoding. EDIT: This has been *somewhat* tested - but that's not to say it doesn't still have some subtle bugs around. It uses StreamUtil from MiscUtil, but I've included just the necessary (new) method from there at the bottom. Oh, and it needs refactoring - there's one pretty hefty method, as you'll see: ``` using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace MiscUtil.IO { /// <summary> /// Takes an encoding (defaulting to UTF-8) and a function which produces a seekable stream /// (or a filename for convenience) and yields lines from the end of the stream backwards. /// Only single byte encodings, and UTF-8 and Unicode, are supported. The stream /// returned by the function must be seekable. /// </summary> public sealed class ReverseLineReader : IEnumerable<string> { /// <summary> /// Buffer size to use by default. Classes with internal access can specify /// a different buffer size - this is useful for testing. /// </summary> private const int DefaultBufferSize = 4096; /// <summary> /// Means of creating a Stream to read from. /// </summary> private readonly Func<Stream> streamSource; /// <summary> /// Encoding to use when converting bytes to text /// </summary> private readonly Encoding encoding; /// <summary> /// Size of buffer (in bytes) to read each time we read from the /// stream. This must be at least as big as the maximum number of /// bytes for a single character. /// </summary> private readonly int bufferSize; /// <summary> /// Function which, when given a position within a file and a byte, states whether /// or not the byte represents the start of a character. /// </summary> private Func<long,byte,bool> characterStartDetector; /// <summary> /// Creates a LineReader from a stream source. The delegate is only /// called when the enumerator is fetched. UTF-8 is used to decode /// the stream into text. /// </summary> /// <param name="streamSource">Data source</param> public ReverseLineReader(Func<Stream> streamSource) : this(streamSource, Encoding.UTF8) { } /// <summary> /// Creates a LineReader from a filename. The file is only opened /// (or even checked for existence) when the enumerator is fetched. /// UTF8 is used to decode the file into text. /// </summary> /// <param name="filename">File to read from</param> public ReverseLineReader(string filename) : this(filename, Encoding.UTF8) { } /// <summary> /// Creates a LineReader from a filename. The file is only opened /// (or even checked for existence) when the enumerator is fetched. /// </summary> /// <param name="filename">File to read from</param> /// <param name="encoding">Encoding to use to decode the file into text</param> public ReverseLineReader(string filename, Encoding encoding) : this(() => File.OpenRead(filename), encoding) { } /// <summary> /// Creates a LineReader from a stream source. The delegate is only /// called when the enumerator is fetched. /// </summary> /// <param name="streamSource">Data source</param> /// <param name="encoding">Encoding to use to decode the stream into text</param> public ReverseLineReader(Func<Stream> streamSource, Encoding encoding) : this(streamSource, encoding, DefaultBufferSize) { } internal ReverseLineReader(Func<Stream> streamSource, Encoding encoding, int bufferSize) { this.streamSource = streamSource; this.encoding = encoding; this.bufferSize = bufferSize; if (encoding.IsSingleByte) { // For a single byte encoding, every byte is the start (and end) of a character characterStartDetector = (pos, data) => true; } else if (encoding is UnicodeEncoding) { // For UTF-16, even-numbered positions are the start of a character. // TODO: This assumes no surrogate pairs. More work required // to handle that. characterStartDetector = (pos, data) => (pos & 1) == 0; } else if (encoding is UTF8Encoding) { // For UTF-8, bytes with the top bit clear or the second bit set are the start of a character // See http://www.cl.cam.ac.uk/~mgk25/unicode.html characterStartDetector = (pos, data) => (data & 0x80) == 0 || (data & 0x40) != 0; } else { throw new ArgumentException("Only single byte, UTF-8 and Unicode encodings are permitted"); } } /// <summary> /// Returns the enumerator reading strings backwards. If this method discovers that /// the returned stream is either unreadable or unseekable, a NotSupportedException is thrown. /// </summary> public IEnumerator<string> GetEnumerator() { Stream stream = streamSource(); if (!stream.CanSeek) { stream.Dispose(); throw new NotSupportedException("Unable to seek within stream"); } if (!stream.CanRead) { stream.Dispose(); throw new NotSupportedException("Unable to read within stream"); } return GetEnumeratorImpl(stream); } private IEnumerator<string> GetEnumeratorImpl(Stream stream) { try { long position = stream.Length; if (encoding is UnicodeEncoding && (position & 1) != 0) { throw new InvalidDataException("UTF-16 encoding provided, but stream has odd length."); } // Allow up to two bytes for data from the start of the previous // read which didn't quite make it as full characters byte[] buffer = new byte[bufferSize + 2]; char[] charBuffer = new char[encoding.GetMaxCharCount(buffer.Length)]; int leftOverData = 0; String previousEnd = null; // TextReader doesn't return an empty string if there's line break at the end // of the data. Therefore we don't return an empty string if it's our *first* // return. bool firstYield = true; // A line-feed at the start of the previous buffer means we need to swallow // the carriage-return at the end of this buffer - hence this needs declaring // way up here! bool swallowCarriageReturn = false; while (position > 0) { int bytesToRead = Math.Min(position > int.MaxValue ? bufferSize : (int)position, bufferSize); position -= bytesToRead; stream.Position = position; StreamUtil.ReadExactly(stream, buffer, bytesToRead); // If we haven't read a full buffer, but we had bytes left // over from before, copy them to the end of the buffer if (leftOverData > 0 && bytesToRead != bufferSize) { // Buffer.BlockCopy doesn't document its behaviour with respect // to overlapping data: we *might* just have read 7 bytes instead of // 8, and have two bytes to copy... Array.Copy(buffer, bufferSize, buffer, bytesToRead, leftOverData); } // We've now *effectively* read this much data. bytesToRead += leftOverData; int firstCharPosition = 0; while (!characterStartDetector(position + firstCharPosition, buffer[firstCharPosition])) { firstCharPosition++; // Bad UTF-8 sequences could trigger this. For UTF-8 we should always // see a valid character start in every 3 bytes, and if this is the start of the file // so we've done a short read, we should have the character start // somewhere in the usable buffer. if (firstCharPosition == 3 || firstCharPosition == bytesToRead) { throw new InvalidDataException("Invalid UTF-8 data"); } } leftOverData = firstCharPosition; int charsRead = encoding.GetChars(buffer, firstCharPosition, bytesToRead - firstCharPosition, charBuffer, 0); int endExclusive = charsRead; for (int i = charsRead - 1; i >= 0; i--) { char lookingAt = charBuffer[i]; if (swallowCarriageReturn) { swallowCarriageReturn = false; if (lookingAt == '\r') { endExclusive--; continue; } } // Anything non-line-breaking, just keep looking backwards if (lookingAt != '\n' && lookingAt != '\r') { continue; } // End of CRLF? Swallow the preceding CR if (lookingAt == '\n') { swallowCarriageReturn = true; } int start = i + 1; string bufferContents = new string(charBuffer, start, endExclusive - start); endExclusive = i; string stringToYield = previousEnd == null ? bufferContents : bufferContents + previousEnd; if (!firstYield || stringToYield.Length != 0) { yield return stringToYield; } firstYield = false; previousEnd = null; } previousEnd = endExclusive == 0 ? null : (new string(charBuffer, 0, endExclusive) + previousEnd); // If we didn't decode the start of the array, put it at the end for next time if (leftOverData != 0) { Buffer.BlockCopy(buffer, 0, buffer, bufferSize, leftOverData); } } if (leftOverData != 0) { // At the start of the final buffer, we had the end of another character. throw new InvalidDataException("Invalid UTF-8 data at start of stream"); } if (firstYield && string.IsNullOrEmpty(previousEnd)) { yield break; } yield return previousEnd ?? ""; } finally { stream.Dispose(); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } } // StreamUtil.cs: public static class StreamUtil { public static void ReadExactly(Stream input, byte[] buffer, int bytesToRead) { int index = 0; while (index < bytesToRead) { int read = input.Read(buffer, index, bytesToRead - index); if (read == 0) { throw new EndOfStreamException (String.Format("End of stream reached with {0} byte{1} left to read.", bytesToRead - index, bytesToRead - index == 1 ? "s" : "")); } index += read; } } } ``` Feedback very welcome. This was fun :)
> Attention: this approach doesn't work (explained in EDIT) You could use File.ReadLines to get lines iterator ``` foreach (var line in File.ReadLines(@"C:\temp\ReverseRead.txt").Reverse()) { if (noNeedToReadFurther) break; // process line here Console.WriteLine(line); } ``` EDIT: After reading [applejacks01](https://stackoverflow.com/users/4223489/applejacks01)'s comment, I run some tests and it does *look like* `.Reverse()` actually loads whole file. I used `File.ReadLines()` to print **first line** of a 40MB file - memory usage of console app was **5MB**. Then, used `File.ReadLines().Reverse()` to print **last line** of same file - memory usage was **95MB**. > **Conclusion** > > Whatever `Reverse()' is doing, **it is not a good choice** for reading bottom of a big file.
How to read a text file reversely with iterator in C#
[ "", "c#", ".net", "" ]
How I can deallocate resources when the process gets killed by, for example, the Task Manager? Is there a way to call a function before the process gets closed?
There really is nothing you can do if your process is killed. By definition, killing a process is just that - killing it. The process does not get an opportunity to run any code. This is very much "by design". Imagine that you could register a routine that was called when your process was killed by the user (or by another process). What would it do? All the other threads in your process would be in an indeterminate state, How would you synchronize with them? Remember, the idea is that the process needs to be killed. The other scenario is even tougher: your code is benign and trying to do the right thing - e.g. clean up and be a good system citizen. Some code isn't. Imagine what a boon to a malware author it would be if the OS allowed code to be run for a process that was being killed. It would be bad enough for malicious processes that were running with standard user privileges, and completely awful for any running with administrative privileges. Critical finalizes and structured exception handling will not solve this fundamental issue. ON the upside, the OS will free all the resources it knows about when your process is killed, namely memory and kernel objects. Those will not leak. But explorer doesn't know about your process so it cannot clean up for it. One way to solve this would be to have a monitoring process that keeps track of your other processes state and cleans up for it. You could do this with a simple process, or with a service. You might also consider some kind of shell extension that had its own thread that did the same thing.
There is no way to execute arbitrary code upon termination within a process which is about to be killed by a call to `TerminateProcess`, such as by Task Manager, or another process utility such as TSKILL or TASKKILL. Neither critical finalizers, nor ordinary finalizers, nor try/finally blocks, and certainly not mere objects which implement `IDisposable` can cause code to be executed in this scenario. Even DLL detach events will not be invoked from a process termination via `TerminateProcess`. The best you can do is to use a watchdog process which monitors your original process and executes relevant code when the original process is terminated.
Deallocate resources on process termination
[ "", "c#", ".net", "process", "kill-process", "" ]
So i just received a connection string to a Cube in our one of our SQL databases. I'm supposed to create a report that can be emailed to 30 something people off of this data. I would much rather write a stored procedure and just let SSRS send it out whenever its supposed to. The problem is that the database is extremely complex and I'm not sure I can match everything up and get the correct information. Is there anyway that I can write a store procedure that will look at the information in a cube? I'm not sure if this matters but the database and the cube are on the same SQL server. Any information about cubes would be helpful. I know that they to some pre-calculations based on what they will probably be used the most for. Thanks
[Try OpenQuery and/or OpenRowset and pass through the MDX](http://sqlblogcasts.com/blogs/drjohn/archive/2008/09/27/mdx-and-sql-combining-relational-and-multi-dimensional-data-into-one-query-result-set.aspx)
You can make your report use a regular stored procedure but that stored procedure still has to run an MDX query that goes against the cube (via OLEDB). I am not sure what report you are using; specifically whether it is a Local or Server based report but SQL Server's server based reports do have an MDX generator which hides the MDX syntax from beginners and is adequate for populating straightforward Table (Tablix in SSRS 2008) and Matrix based reports. For more complex reporting, it helps learning the MDX syntax. If you are using Local reports (runs on the app server as opposed to the reporting server) you have to know the MDX syntax because you will have to use this MDX query to query the Analysis Services Cube via an OLEDB provider on your middleware component. One more thing, cubes are best utilized when you need to drill down and/or drill through from summary down to detailed information. They are best used for slicing and dicing data (measures) with dimension information. The matrix control is the best tool to view data in a cube with the data cell itself representing a measure and the column(s) and header(s) for this cell representing a measure. The matrix will then "transform" the data automatically depending on which dimension you choose.
SQL - Query Cubes
[ "", "sql", "stored-procedures", "reporting-services", "cubes", "" ]
I have an HTML string representing an element: `'<li>text</li>'`. I'd like to append it to an element in the DOM (a `ul` in my case). How can I do this with Prototype or with DOM methods? (I know i could do this easily in jQuery, but unfortunately we're not using jQuery.)
**Note:** most current browsers support HTML `<template>` elements, which provide a more reliable way of turning creating elements from strings. See [Mark Amery's answer below for details](https://stackoverflow.com/a/35385518/1709587). **For older browsers, and node/jsdom**: (which doesn't yet support `<template>` elements at the time of writing), use the following method. It's the same thing the libraries use to do to get DOM elements from an HTML string ([with some extra work for IE](https://stackoverflow.com/questions/1848588/why-does-html-work-and-not-innerhtml-or-appendchild/1849100#1849100) to work around bugs with its implementation of `innerHTML`): ``` function createElementFromHTML(htmlString) { var div = document.createElement('div'); div.innerHTML = htmlString.trim(); // Change this to div.childNodes to support multiple top-level nodes. return div.firstChild; } ``` Note that unlike HTML templates this *won't* work for some elements that cannot legally be children of a `<div>`, such as `<td>`s. If you're already using a library, I would recommend you stick to the library-approved method of creating elements from HTML strings: * Prototype has this feature built-into its [`update()` method](http://prototypejs.org/doc/latest/dom/Element/update/). * jQuery has it implemented in its [`jQuery(html)`](https://api.jquery.com/jQuery/#jQuery2) and [`jQuery.parseHTML`](https://api.jquery.com/jQuery.parseHTML/) methods.
HTML 5 introduced the `<template>` element which can be used for this purpose (as now described in the [WhatWG spec](https://html.spec.whatwg.org/multipage/scripting.html#the-template-element) and [MDN docs](https://developer.mozilla.org/en/docs/Web/HTML/Element/template)). A `<template>` element is used to declare fragments of HTML that can be utilized in scripts. The element is represented in the DOM as a [`HTMLTemplateElement`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement) which has a [`.content`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLTemplateElement/content) property of [`DocumentFragment`](https://developer.mozilla.org/en/docs/Web/API/DocumentFragment) type, to provide access to the template's contents. This means that you can convert an HTML string to DOM elements by setting the [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) of a `<template>` element, and then reaching into the `template`'s `.content` property. Examples: ``` /** * @param {String} HTML representing a single element. * @param {Boolean} flag representing whether or not to trim input whitespace, defaults to true. * @return {Element | HTMLCollection | null} */ function fromHTML(html, trim = true) { // Process the HTML string. html = trim ? html.trim() : html; if (!html) return null; // Then set up a new template element. const template = document.createElement('template'); template.innerHTML = html; const result = template.content.children; // Then return either an HTMLElement or HTMLCollection, // based on whether the input HTML had one or more roots. if (result.length === 1) return result[0]; return result; } // Example 1: add a div to the page const div = fromHTML('<div><span>nested</span> <span>stuff</span></div>'); document.body.append(div); // Example 2: add a bunch of rows to an on-page table const rows = fromHTML('<tr><td>foo</td></tr><tr><td>bar</td></tr>'); table.append(...rows); // Example 3: add a single extra row to the same on-page table const td = fromHTML('<td>baz</td>'); const row = document.createElement(`tr`); row.append(td); table.append(row); ``` ``` table { background: #EEE; padding: 0.25em; } table td { border: 1px solid grey; padding: 0 0.5em; } ``` ``` <table id="table"></table> ``` Note that similar approaches that [use a different container element such as a `div`](https://stackoverflow.com/a/494348/1709587) don't quite work. HTML has restrictions on what element types are allowed to exist inside which other element types; for instance, you can't put a `td` as a direct child of a `div`. This causes these elements to vanish if you try to set the `innerHTML` of a `div` to contain them. Since `<template>`s have no such restrictions on their content, this shortcoming doesn't apply when using a template. This approach was previously not always possible due to IE not having support for `<template>`, but Microsoft fully killed off the Internet Explorer family of browsers in June of 2022, [with Windows updates pushed out to even prevent folks from (re)installing it](https://techcommunity.microsoft.com/t5/windows-it-pro-blog/internet-explorer-11-desktop-app-retirement-faq/ba-p/2366549), so except in the rare few cases where you find yourself writing web content for dead browsers, this approach will work for you.
Creating a new DOM element from an HTML string using built-in DOM methods or Prototype
[ "", "javascript", "dom", "prototypejs", "" ]
First of all, I am a complete Java NOOB. I want to handle multiple button presses with one function, and do certain things depending on which button was clicked. I am using Netbeans, and I added an event with a binding function. That function is sent an ActionEvent by default. How do I get the object that was clicked in order to trigger the binding function from within that function so I know which functionality to pursue?
The object that sent the event is the event source so evt.getSource() will get you that. However, it would be far better to have separate handlers for separate events.
Call the `getSource()` method of the ActionEvent. For example: ``` public void actionPerformed(ActionEvent e) { Object source = e.getSource(); // 'source' now contains the object clicked on. } ```
Java - Handle multiple events with one function?
[ "", "java", "user-interface", "binding", "event-handling", "events", "" ]
I am developing a multilingual site and was wondering what is the best way to store the language chosen by the user? Either via QueryString or should it be in Session..or any other options?
I think it very much depends on how your application handles (desires to handle) the user languages. If your users have to log on to your site, then you probably have an account settings page somewhere with an appropriate user profile object or something similar behind. In such a case I guess you would save these settings on the DB, and when the user comes back to your site you get the user-information somehow (i.e. from a cookie), you load your user-profile object from the DB. The information would be kept in a session since I think that would be most suited in this case. If your users don't have to login, so you basically cannot directly identify them, I would store the language settings in a cookie. This gives your user the value that he will always find the site in his preferred language when he comes back later (given that he doesn't delete the cookies and the cookie's lifetime is long enough). As a third possibility you could just identify the users language according to his default browser settings (just as "regex" mentioned above). As I said, it really depends on your application's needs. What you have to keep in mind though is that * objects stored in the session are kept on the server-side, using server memory. So don't keep useless things there in memory if you don't need them. However the session object is suited for storing data related to a user's visit and configurations. * Data stored in cookies, or the Viewstate object are send back and forth between the client browser and web server. So this causes additional traffic and may decrease the performance. Bye
Another consideration not mentioned in any of the other answers, is Search Engine Friendliness. If you use a different url for each language like ``` http://{en|cy}.example.com/subdir/ or http://example.com/{en|cy}/subdir) ``` then search engines can index your site in multiple languages.
Storing Language in URL or Session or other
[ "", "c#", "asp.net", "internationalization", "multilingual", "" ]
I have a ``` List<InputField> ``` but I need a ``` List<IDataField> ``` Is there a way to cast this in c#? Or use Linq to get same result? I have two classes that implement the same interface: ``` interface IDataField { } class InputField : IDataField { } class PurchaseField : IDataField { } ``` This List comes from a Linq-to-Sql query: ``` List<InputField> list = (from i .... select i).ToList(); ```
Both .OfType<T> and .Cast<T> will return a list of T, but the meaning of the two methods is different. list.OfType() **filters** the original list and returns all items which are of type T, and skips the ones that are not of that type. list.Cast() **casts** all items in the original list to type T, and throws an exception for items which cannot be cast to that type. In your case both would give the same result, but using .Cast() would communicate your intent a lot more clearly, so I would recommend using that. ``` List<InputField> list = (from i .... select i).Cast<IDataField>().ToList(); ```
``` List<InputField> raw = (from i .... select i).ToList(); List<IDataField> result = raw.OfType<IDataField>().ToList(); ```
How do I cast a List<T> effectively?
[ "", "c#", "linq-to-sql", "" ]
Does there exist a cheat sheet for data structure like TreeMap, SortedMap, HashSet etc and under what circumstances which one to use. Are there good articles you recommend
The [Collections Tutorial](http://java.sun.com/docs/books/tutorial/collections/TOC.html) is a good resource.
Read a good [book](https://rads.stackoverflow.com/amzn/click/com/0201775786)! Datastructures are abstract and not bound to Java. Maybe this [website](http://nist.gov/dads/) is also worth looking at.
Data structures in JDK, under what scenario which one to use?
[ "", "java", "data-structures", "" ]
First of all, I must say that I am quite new to the API java.util.concurrent, so maybe what I am doing is completely wrong. What do I want to do? I have a Java application that basically runs 2 separate processing (called *myFirstProcess*, *mySecondProcess*), but these processing must be run at the same time. So, I tried to do that: ``` public void startMyApplication() { ExecutorService executor = Executors.newFixedThreadPool(2); FutureTask<Object> futureOne = new FutureTask<Object>(myFirstProcess); FutureTask<Object> futureTwo = new FutureTask<Object>(mySecondProcess); executor.execute(futureOne); executor.execute(futureTwo); while (!(futureOne.isDone() && futureTwo.isDone())) { try { // I wait until both processes are finished. Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } logger.info("Processing finished"); executor.shutdown(); // Do some processing on results ... } ``` *myFirstProcess* and *mySecondProcess* are classes that implements `Callable<Object>`, and where all their processing is made in the call() method. It is working quite well but I am not sure that it is the correct way to do that. Is a good way to do what I want? If not, can you give me some hints to enhance my code (and still keep it as simple as possible).
You'd be better off using the `get()` method. ``` futureOne.get(); futureTwo.get(); ``` Both of which wait for notification from the thread that it finished processing, this saves you the busy-wait-with-timer you are now using which is not efficient nor elegant. As a bonus, you have the API `get(long timeout, TimeUnit unit)` which allows you to define a maximum time for the thread to sleep and wait for a response, and otherwise continues running. See the [Java API](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Future.html#get()) for more info.
The uses of `FutureTask` above are tolerable, but definitely not idiomatic. You're actually wrapping an *extra* `FutureTask` around the one you submitted to the `ExecutorService`. Your `FutureTask` is treated as a `Runnable` by the `ExecutorService`. Internally, it wraps your `FutureTask`-as-`Runnable` in a new `FutureTask` and returns it to you as a `Future<?>`. Instead, you should submit your `Callable<Object>` instances to a [`CompletionService`](http://java.sun.com/javase/7/docs/api/java/util/concurrent/CompletionService.html). You drop two `Callable`s in via `submit(Callable<V>)`, then turn around and call `CompletionService#take()` twice (once for each submitted `Callable`). Those calls will block until one and then the other submitted tasks are complete. Given that you already have an `Executor` in hand, construct a new [`ExecutorCompletionService`](http://java.sun.com/javase/7/docs/api/java/util/concurrent/ExecutorCompletionService.html) around it and drop your tasks in there. Don't spin and sleep waiting; `CompletionService#take()` will block until either one of your tasks are complete (either finished running or canceled) or the thread waiting on `take()` is interrupted.
Is it a good way to use java.util.concurrent.FutureTask?
[ "", "java", "multithreading", "concurrency", "futuretask", "" ]
I have a series of divs in a pattern of header/body, where a click on the header will show the body in question. This all happens with .click initialized on page ready... Rather than doing this (which works fine, but is a pain): ``` $('#show_fold_ping').click(function(){ ShowArea('#fold_ping') }); $('#show_fold_http').click(function(){ ShowArea('#fold_http') }); $('#show_fold_smtp').click(function(){ ShowArea('#fold_smtp') }); $('#show_fold_pop3').click(function(){ ShowArea('#fold_pop3') }); ... ``` I am trying to do this: ``` var Areas = ['ping','http', 'smtp', 'pop3']; for( var i in Areas ){ Area = '#show_fold_'+Areas[i]; $(Area).click(function(){ alert(Area); /* ShowArea(Area); */ }); } ``` The problem I'm having is that ALL of them seem to be initialized to the last one. IE: If pop3 is the last one, a click on #show\_fold\_[any] will alert '#show\_fold\_pop3'. This seems like it should be really simple. Am I missing something obvious, or is there an issue with passing a string to jQuery that I don't know about? **Edit:** Hey, these are all great. I have read up a bit on closures and self-invoking functions, and (kindasorta) get it. So far, I have this, but the click doesn't seem to be binding correctly. Area will alert with the correct value, but no click bind. Am I still having scope issues with Area, or am I just totally off mark? ``` $(function(){ Areas = ['ping','http', 'smtp', 'pop3', 'imap', 'ftp', 'dns', 'tcp', 'database', 'seo']; for( var i = 0; i < Areas.length; i++ ){ (function (Area) { alert(Area); $("#show_fold_"+Area).click(function(){ alert('x'); }); })(Areas[i]); } }); ```
Yes, I have run into this problem all too often. `Area` is a global variable since it does not have `var` before it. Also, don't use a for...in construct. But you might still run into a similar problem. God knows how many scripts I've debugged because of a similar bug. Doing the following guarantees proper scoping: ``` var Areas = ['ping','http', 'smtp', 'pop3']; for( var i = 0; i < Areas.length; i++ ){ (function(area) { $(area).click(function(){ alert(area); /* ShowArea(area); */ }); })(Areas[i]); } ```
It's a JavaScript thing; it's not jQuery related. What you're doing is creating a closure, but you're not understanding properly how they work. You might want to read up on <http://blog.morrisjohns.com/javascript_closures_for_dummies>, especially Examples 5, 6, and 7.
jQuery: Set click from array loop
[ "", "javascript", "jquery", "" ]
I'm building a little app using Java and Swing in NetBeans. Using NetBeans design window, I created a JFrame with a JPanel inside. Now I want to dynamically add some jTextFields to the JPanel. I wrote something like that: ``` Vector textFieldsVector = new Vector(); JTextField tf; int i = 0; while (i < 3) { tf = new JTextField(); textFieldVector.add(tf); myPanel.add(tf); //myPanel is the JPanel where I want to put the JTextFields i++; } myPanel.validate(); myPanel.repaint(); ``` But nothing happens: when I run the app, the JFrame shows with the JPanel inside, but the JTextFields don't. I'm a total newbie in writing graphical Java apps, so I'm surely missing something very simple, but I can't see what.
In the Netbeans GUI, set the layout manager to something like GridLayout or FlowLayout (just for testing). You can do this by going to the GUI editor, clicking on your panel, and then right-clicking and selecting a layout. Once you've changed to a different layout, go to the properties and alter the layout properties. For the GridLayout, you want to make sure you have 3 grid cells. Instead of myPanel.validate(), try myPanel.revalidate(). The more canonical way to do this is to create a custom JPanel (without using the GUI editor) that sets its own layout manager, populates itself with components, etc. Then, in the Netbeans GUI editor, drag-and-drop that custom JPanel into the gui editor. Matisse is certainly capable of handling the runtime-modification of Swing components, but that's not the normal way to use it.
It's been a while since I've done some Swing but I think you'll need to recall pack() to tell the frame to relayout its components EDIT: Yep, I knew it had been too long since I did Swing. I've knocked up the following code which works as expected though and adds the textfields... ``` JFrame frame = new JFrame("My Frame"); frame.setSize(640, 480); JPanel panel = new JPanel(); panel.add(new JLabel("Hello")); frame.add(panel); frame.setLayout(new GridLayout()); frame.pack(); frame.setVisible(true); Vector textFieldVector = new Vector(); JTextField tf; int i = 0; while (i < 3) { tf = new JTextField(); textFieldVector.add(tf); panel.add(tf); //myPanel is the JPanel where I want to put the JTextFields i++; } panel.validate(); panel.repaint(); ```
Adding JTextField to a JPanel and showing them
[ "", "java", "swing", "jpanel", "jtextfield", "" ]
How come unserialize isn't restoring my array? See code below.. ``` // prints a:1:{s:8:"txn_type";s:32:"recurring_payment_profile_cancel";} echo $item['response']; // prints nothing print_r(unserialize($item['response'])); ``` I understand why the print\_r($response) gives me nothing \*\* edit - I noticed this Notice: unserialize() [function.unserialize]: Error at offset 6 of 2797 bytes in /home/reitinve/public\_html/action/doc.php on line 13 What does that mean?
Is it possible `$item['response']` contains some whitespace before or after it? Check `strlen($item['response'])` gives you 61. Edit: It seems to work with whitespace at the end, but whitespace at the start will make it fail to unserialize. Edit: that error message means either you have a LOT of whitespace (almost 2kb of it), or `$item['response']` is being changed between the `echo` and the `unserialize`
works for me just fine. are you sure that `$item['response']` is a string? yeah, seems like leading whitespaces. and on your dev server php never should give you 'nothing'. it should be configured to produce all errors, warnings and notices. also you can use <http://php.net/var_dump> instead of print\_r as it give you more information.
PHP unserialize problem
[ "", "php", "serialization", "" ]
In PHP, what's the best way to track an objects state, to tell whether or not it has been modified? I have a repository object that creates new entities, they are then read/modified by other components and eventually given back to the repository. If the object has changed I want the repository to save the data back to the persistent storage (DB). I can think of four options: 1. Use an internal boolean property called $\_modified, which every setter updates when modifications are made (tedious if there are a lot of setters). 2. Some horrible ugly hack using serialize() and comparing the strings (I'm sure this is a *very* bad idea, but I thought I'd add it for completeness) 3. Something like the above but with a hash of the objects properties (not sure if it would work with objects that contain other objects) 4. Taking clones of the objects as they come out of the repo and comparing what comes in (more complicated than it sounds, because how do you know which clone to compare the object to?) or... 5. Some other clever trick I'm not aware of? Thanks, Jack
Option 1 - using a boolean flag - is the best way. In terms of performance, as well as general usability and portability. All the other options incur excessive overhead which is simply not needed in this case.
You might want to look into the [Unit of Work](http://martinfowler.com/eaaCatalog/unitOfWork.html) pattern, as this is much the problem which it is designed to tackle. As objects are changed, they register themselves, or are passively registered, with the UoW, which is responsible for keeping track of which objects have been changed, and for figuring out what needs to be saved back to the database at the end of play.
Tracking an objects state
[ "", "php", "oop", "" ]
If you were writing the next 3d graphics intensive application in C# (like a 3d modelling and animation software), which one would be a better choice? If we consider C# as platform independent, then OpenGL seems tempting, but what about the performance, etc? Since the used language is C#, the performance is pretty crucial to consider. Edit: You can also consider SlimDX and TAO, OpenTK, csGL, etc too.
Performance in managed code, with respect to the graphics subsystem, is not bad. SlimDX pays a slightly penalty over completely native code on each call into DirectX, but it is by no means severe. The actual penalty depends on the call -- a call into DrawPrimitive will be vastly more expensive overall than a call to SetRenderState, so percentage-wise you end up losing a lot more on the SetRenderState calls. SlimDX incorporates a tuned math library that generally performs very well, although you have to be a bit careful with it. Profiling, even with a junker tool like NProf, highlights this stuff very quickly so it's not difficult to fix. Overall, if we consider generic, *completely optimal* C++ and C# code doing rendering via D3D, the C# version is probably within 10-15% of the C++ version. That's hard to achieve though; consider how much time you're saving by working in C# which you can apply to higher level graphics optimizations that you probably simply wouldn't have time for if you had to build the entire thing in C++. And even if you managed to get that extra 10% in C++, it'd promptly shrink to 5% within a few months, when a new round of hardware tears through your application code faster than ever. I know what I'd pick -- which is why I wrote SlimDX to begin with. OpenTK is subject to similar performance characteristics, with the caveat that their math library is rather slow in places. This is an implementation bug that I've discussed with them, and will hopefully be fixed before too long.
I'd recommend OpenGL for the following reasons :- 1. Cross Platform - OpenGLES being of particular relevance these days for Mobile platforms 2. The OpenGL shading language implementation is inherently superior to DirectX shaders. 3. OpenGL is somewhat easier to learn as it's possible to set up basic renders with very few lines of code 4. Philosophically OpenGL was designed as a general purpose rendering engine, whereas DirectX was always games orientated, so OpenGL would seem a better fit for your question. 5. OpenGL is stable technology that has been around for some time and will continue to be so. DirectX is more dependent on the whim of Microsoft and could be deprecated in an instant if MS felt like it. That said, the requirements of your system and your personal preferences could tip it either way as both approaches are solid implementations. On the downside OpenGL is very much a state machine and can be tricky to fit into OO, although it's certainly not impossible. EDIT: Added to clarify my comment on the OpenGL shader model being inherently superior to DirectX. This is because DirectX shaders are compiled with the program at development time against a generic GPU model, whereas OpenGL shaders are held as source code and compiled by the OpenGL driver at run time. Consequently theoretically it's possible for the driver writer to take advantage of specific (or updated when running an old program) features of the GPU and create compiled code that can run faster than DirectX shaders. It's a small point, but potentially quite an important one.
DirectX or OpenGL
[ "", "c#", ".net", "opengl", "directx", "" ]
Using extension syntax I'm trying to create a left-join using LINQ on two lists that I have. The following is from the Microsoft help but I've modified it to show that the pets list has no elements. What I'm ending up with is a list of 0 elements. I assume that this is because an inner-join is taking place. What I want to end up with is a list of 3 elements (the 3 Person objects) with null data filled in for the missing elements. i.e. a Left-Join. Is this possible? ``` Person magnus = new Person { Name = "Hedlund, Magnus" }; Person terry = new Person { Name = "Adams, Terry" }; Person charlotte = new Person { Name = "Weiss, Charlotte" }; //Pet barley = new Pet { Name = "Barley", Owner = terry }; //Pet boots = new Pet { Name = "Boots", Owner = terry }; //Pet whiskers = new Pet { Name = "Whiskers", Owner = charlotte }; //Pet daisy = new Pet { Name = "Daisy", Owner = magnus }; List<Person> people = new List<Person> { magnus, terry, charlotte }; //List<Pet> pets = new List<Pet> { barley, boots, whiskers, daisy }; List<Pet> pets = new List<Pet>(); // Create a list of Person-Pet pairs where // each element is an anonymous type that contains a // Pet's name and the name of the Person that owns the Pet. var query = people.Join(pets, person => person, pet => pet.Owner, (person, pet) => new { OwnerName = person.Name, Pet = pet.Name }).ToList(); ```
I think if you want to use extension methods you need to use the [GroupJoin](http://msdn.microsoft.com/en-us/library/bb534805.aspx) ``` var query = people.GroupJoin(pets, person => person, pet => pet.Owner, (person, petCollection) => new { OwnerName = person.Name, Pet = PetCollection.Select( p => p.Name ) .DefaultIfEmpty() } ).ToList(); ``` You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship. I think it's a little easier with the LINQ Query syntax ``` var query = (from person in context.People join pet in context.Pets on person equals pet.Owner into tempPets from pets in tempPets.DefaultIfEmpty() select new { OwnerName = person.Name, Pet = pets.Name }) .ToList(); ```
You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said: ``` Person magnus = new Person { Name = "Hedlund, Magnus" }; Person terry = new Person { Name = "Adams, Terry" }; Person charlotte = new Person { Name = "Weiss, Charlotte" }; Pet barley = new Pet { Name = "Barley", Owner = terry }; List<Person> people = new List<Person> { magnus, terry, charlotte }; List<Pet> pets = new List<Pet>{barley}; var results = from person in people join pet in pets on person.Name equals pet.Owner.Name into ownedPets from ownedPet in ownedPets.DefaultIfEmpty(new Pet()) orderby person.Name select new { OwnerName = person.Name, ownedPet.Name }; foreach (var item in results) { Console.WriteLine( String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) ); } ``` Outputs: ``` Adams, Terry has Barley Hedlund, Magnus has Weiss, Charlotte has ```
LINQ Inner-Join vs Left-Join
[ "", "c#", ".net", "linq", "left-join", "" ]
I have large batches of XHTML files that are manually updated. During the review phase of the updates I would like to programmatically check the well-formedness of the files. I am currently using a **XmlReader**, but the time required on an average CPU is much longer than I expected. The XHTML files range in size from 4KB to 40KB and verifying takes several seconds per file. Checking is essential but I would like to keep the time as short as possible as the check is performed while files are being read into the next process step. Is there a faster way of doing a simple XML well-formedness check? Maybe using external XML libraries? --- I can confirm that validating "regular" XML based content is lightning fast using the XmlReader, and as suggested the problem seems to be related to the fact that the XHTML DTD is read each time a file is validated. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` Note that in addition to the DTD, corresponding .ent files (xhtml-lat1.ent, xhtml-symbol.ent, xhtml-special.ent) are also downloaded. Since ignoring the DTD completely is not really an option for XHTML as the well-formedness is closely linked to allowed HTML entities (e.g., a &nbsp; will promptly introduce validation errors when we ignore the DTD). --- The problem was solved by using a **custom XmlResolver** as suggested, in combination with local (embedded) copies of both the DTD and entity files. I will post the solution here once I cleaned up the code
I would expect that `XmlReader` with `while(reader.Read)() {}` would be the fastest *managed* approach. It certainly shouldn't take **seconds** to read 40KB... what is the input approach you are using? Do you perhaps have some external (schema etc) entities to resolve? If so, you might be able to write a custom `XmlResolver` (set via `XmlReaderSettings`) that uses locally cached schemas rather than a remote fetch... The following does ~300KB virtually instantly: ``` using(MemoryStream ms = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.CloseOutput = false; using (XmlWriter writer = XmlWriter.Create(ms, settings)) { writer.WriteStartElement("xml"); for (int i = 0; i < 15000; i++) { writer.WriteElementString("value", i.ToString()); } writer.WriteEndElement(); } Console.WriteLine(ms.Length + " bytes"); ms.Position = 0; int nodes = 0; Stopwatch watch = Stopwatch.StartNew(); using (XmlReader reader = XmlReader.Create(ms)) { while (reader.Read()) { nodes++; } } watch.Stop(); Console.WriteLine("{0} nodes in {1}ms", nodes, watch.ElapsedMilliseconds); } ```
Create an `XmlReader` object by passing in an `XmlReaderSettings` object that has the `ConformanceLevel.Document`. This will validate well-formedness. This [MSDN article](https://learn.microsoft.com/en-us/dotnet/api/system.xml.xmlreadersettings.conformancelevel) should explain the details.
What is the fastest way to programmatically check the well-formedness of XML files in C#?
[ "", "c#", "xml", "well-formed", "" ]
Assume I have two data tables and a linking table as such: ``` A B A_B_Link ----- ----- ----- ID ID A_ID Name Name B_ID ``` 2 Questions: 1. I would like to write a query so that I have all of A's columns and a count of how many B's are linked to A, what is the best way to do this? 2. Is there a way to have a query return a row with all of the columns from A and a column containing *all* of linked names from B (maybe separated by some delimiter?) Note that **the query must return distinct rows from A**, so a simple left outer join is not going to work here...I'm guessing I'll need nested select statements?
For your first question: ``` SELECT A.ID, A.Name, COUNT(ab.B_ID) AS bcount FROM A LEFT JOIN A_B_Link ab ON (ab.A_ID = A.ID) GROUP BY A.ID, A.Name; ``` This outputs one row per row of A, with the count of matching B's. Note that you must list all columns of A in the GROUP BY statement; there's no way to use a wildcard here. An alternate solution is to use a correlated subquery, as @Ray Booysen shows: ``` SELECT A.*, (SELECT COUNT(*) FROM A_B_Link WHERE A_B_Link.A_ID = A.A_ID) AS bcount FROM A; ``` This works, but correlated subqueries aren't very good for performance. For your second question, you need something like MySQL's `GROUP_CONCAT()` aggregate function. In MySQL, you can get a comma-separated list of `B.Name` per row of A like this: ``` SELECT A.*, GROUP_CONCAT(B.Name) AS bname_list FROM A LEFT OUTER JOIN A_B_Link ab ON (A.ID = ab.A_ID) LEFT OUTER JOIN B ON (ab.B_ID = B.ID) GROUP BY A.ID; ``` There's no easy equivalent in Microsoft SQL Server. Check here for another question on SO about this: "[Simulating group\_concat MySQL function in MS SQL Server 2005?](https://stackoverflow.com/questions/451415/simulating-groupconcat-mysql-function-in-ms-sql-server-2005)" Or Google for '[microsoft SQL server "group\_concat"](http://www.google.com/search?q=microsoft+sql+server+%22group_concat%22)' for a variety of other solutions.
For #1 ``` SELECT A.*, (SELECT COUNT(*) FROM A_B_Link WHERE A_B_Link.A_ID = AOuter.A_ID) FROM A as AOuter ```
How do I get a count of items in one column that match items in another column?
[ "", "sql", "sql-server", "t-sql", "" ]
I am doing something like this in python ``` class MyThread ( threading.Thread ): def run (s): try: s.wantQuit = 0 while(not s.wantQuit): button = raw_input() if button == "q": s.wantQuit=1 except KeyboardInterrupt: s.wantQuit = 1 myThread = MyThread () myThread.start() a=5 while not myThread.wantQuit: print "hey" if (a == 0): break; a = a-1; time.sleep(1) #""" sys.exit() ``` What happens is my app locks up for 5 seconds printing "hey" (5 times) THEN i get the raw\_input dialog. How can i have the dialog show up so i can quit anytime instead of when my loop runs out?
You mean the while loop runs before the thread? Well, you can't predict this unless you synchronize it. No one guarantees you that the thread will run before or after that while loop. But if it's being blocked for 5 seconds that's akward - the thread should have been pre-empted by then. Also, since you're first use of wantToQuit is in the run() method, no one assures you that the thread has been started when you're checking for it's wantToQuit attribute in `while not myThread.wantToQuit` .
The behaviour here is not what you described. Look at those sample outputs I got: 1st: pressing `q<ENTER>` as fast as possible: ``` hey q ``` 2nd: wait a bit before pressing `q<ENTER>`: ``` hey hey hey q ``` 3rd: Don't touch the keyboard: ``` hey hey hey hey hey hey # Application locks because main thread is over but # there are other threads running. add myThread.wantQuit = 1 # to prevent that if you want ```
input and thread problem, python
[ "", "python", "multithreading", "" ]
I have this query: ``` SELECT page.id, revision.title, revision.number FROM page INNER JOIN revision ON page.id = revision.pageId ``` Which will return something like: ``` "1" "Page Version A" "1" "1" "Page Version B" "2" "1" "Page Version C" "3" ``` Now I only want to return one row for each page, with the data from the latest (highest numbered) revision. If I do: ``` SELECT page.id, revision.title, revision.number FROM page INNER JOIN revision ON page.id = revision.pageId GROUP BY page.id ``` I get: ``` "1" "Page Version A" "1" ``` But I want: ``` "1" "Page Version C" "3" ``` Any ideas? Thanks.
Add a WHERE clause similar to WHERE revision.number = (select max(number) from revision r where r.pageId = page.id)
If you just want to select a single record you could use the MySQL 'LIMIT' keyword (similar to MSSQL 'TOP') eg: ``` SELECT page.id, revision.title, revision.number FROM page INNER JOIN revision ON page.id = revision.pageId ORDER BY revision.number DESC LIMIT 0, 1 ``` This will order all of your results, then select the top result.
Simple SQL problem (MySQL)
[ "", "sql", "mysql", "" ]
Is there a particular reason why a generic `ICloneable<T>` does not exist? It would be much more comfortable, if I would not need to cast it everytime I clone something.
ICloneable is considered a bad API now, since it does not specify whether the result is a deep or a shallow copy. I think this is why they do not improve this interface. You can probably do a typed cloning extension method, but I think it would require a different name since extension methods have less priority than original ones.
In addition to Andrey's reply (which I agree with, +1) - when `ICloneable` *is* done, you can also choose explicit implementation to make the public `Clone()` return a typed object: ``` public Foo Clone() { /* your code */ } object ICloneable.Clone() {return Clone();} ``` Of course there is a second issue with a generic `ICloneable<T>` - inheritance. If I have: ``` public class Foo {} public class Bar : Foo {} ``` And I implemented `ICloneable<T>`, then do I implement `ICloneable<Foo>`? `ICloneable<Bar>`? You quickly start implementing a lot of identical interfaces... Compare to a cast... and is it really so bad?
Why no ICloneable<T>?
[ "", "c#", ".net", "icloneable", "" ]
Is there any way in which I can clean a database in SQl Server 2005 by dropping all the tables and deleting stored procedures, triggers, constraints and all the dependencies in one SQL statement? **REASON FOR REQUEST:** I want to have a DB script for cleaning up an existing DB which is not in use rather than creating new ones, especially when you have to put in a request to your DB admin and wait for a while to get it done!
this script cleans all views, SPS, functions PKs, FKs and tables. ``` /* Drop all non-system stored procs */ DECLARE @name VARCHAR(128) DECLARE @SQL VARCHAR(254) SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name]) WHILE @name is not null BEGIN SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']' EXEC (@SQL) PRINT 'Dropped Procedure: ' + @name SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name]) END GO /* Drop all views */ DECLARE @name VARCHAR(128) DECLARE @SQL VARCHAR(254) SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name]) WHILE @name IS NOT NULL BEGIN SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']' EXEC (@SQL) PRINT 'Dropped View: ' + @name SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name]) END GO /* Drop all functions */ DECLARE @name VARCHAR(128) DECLARE @SQL VARCHAR(254) SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name]) WHILE @name IS NOT NULL BEGIN SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']' EXEC (@SQL) PRINT 'Dropped Function: ' + @name SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name]) END GO /* Drop all Foreign Key constraints */ DECLARE @name VARCHAR(128) DECLARE @constraint VARCHAR(254) DECLARE @SQL VARCHAR(254) SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME) WHILE @name is not null BEGIN SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) WHILE @constraint IS NOT NULL BEGIN SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']' EXEC (@SQL) PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) END SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME) END GO /* Drop all Primary Key constraints */ DECLARE @name VARCHAR(128) DECLARE @constraint VARCHAR(254) DECLARE @SQL VARCHAR(254) SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME) WHILE @name IS NOT NULL BEGIN SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) WHILE @constraint is not null BEGIN SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']' EXEC (@SQL) PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME) END SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME) END GO /* Drop all tables */ DECLARE @name VARCHAR(128) DECLARE @SQL VARCHAR(254) SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name]) WHILE @name IS NOT NULL BEGIN SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']' EXEC (@SQL) PRINT 'Dropped Table: ' + @name SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name]) END GO ```
I'm using this script by Adam Anderson, updated to support objects in other schemas than dbo. ``` declare @n char(1) set @n = char(10) declare @stmt nvarchar(max) -- procedures select @stmt = isnull( @stmt + @n, '' ) + 'drop procedure [' + schema_name(schema_id) + '].[' + name + ']' from sys.procedures -- check constraints select @stmt = isnull( @stmt + @n, '' ) + 'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']' from sys.check_constraints -- functions select @stmt = isnull( @stmt + @n, '' ) + 'drop function [' + schema_name(schema_id) + '].[' + name + ']' from sys.objects where type in ( 'FN', 'IF', 'TF' ) -- views select @stmt = isnull( @stmt + @n, '' ) + 'drop view [' + schema_name(schema_id) + '].[' + name + ']' from sys.views -- foreign keys select @stmt = isnull( @stmt + @n, '' ) + 'alter table [' + schema_name(schema_id) + '].[' + object_name( parent_object_id ) + '] drop constraint [' + name + ']' from sys.foreign_keys -- tables select @stmt = isnull( @stmt + @n, '' ) + 'drop table [' + schema_name(schema_id) + '].[' + name + ']' from sys.tables -- user defined types select @stmt = isnull( @stmt + @n, '' ) + 'drop type [' + schema_name(schema_id) + '].[' + name + ']' from sys.types where is_user_defined = 1 exec sp_executesql @stmt ``` [Source: an Adam Anderson blog post](https://web.archive.org/web/20120308203046/http://blog.falafel.com/Blogs/AdamAnderson/09-01-06/T-SQL_Drop_All_Objects_in_a_SQL_Server_Database.aspx)
Drop all the tables, stored procedures, triggers, constraints and all the dependencies in one sql statement
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I have runtime dependencies on some external jars that I would like to "rejar" into a single jar. These external dependencies are stored in an external\_jars directory, and I'd like to be able to not have to list them all (i.e., not to need to change my build scripts if my dependencies change). Any thoughts? Google gave me a good answer on how to do this - if you don't mind listing out each jar as a dependency: <http://markmail.org/message/zijbwm46maxzzoo5> Roughly, I want something along the lines of the following, which would combine all jars in the lib directory into out.jar (with some sane overwrite rules). ``` jar -combine -out out.jar -in lib/*.jar ```
Just use `zipgroupfileset` with the Ant [Zip task](http://ant.apache.org/manual/Tasks/zip.html) ``` <zip destfile="out.jar"> <zipgroupfileset dir="lib" includes="*.jar"/> </zip> ``` This will flatten all included jar libraries' content.
Vladimir's answer is a correct one, but I feel that what he suggests implies repacking all jars in a one big out.jar, which is then feeded to Ant Jar task as a single `<zipfileset>` or something like that. This two-step approach is unnecessary. I'm not sure whether this is connected with Ant version, but I have Ant 1.7.1, and its `<jar>` task understands `<zipgroupfileset>`, which allows to feed all contents of third party jars' directly. ``` <jar destfile="MyApplication.jar"> <zipgroupfileset dir="lib" includes="*.jar" /> <!-- other options --> <manifest> <attribute name="Main-Class" value="Main.MainClass" /> </manifest> </jar> ```
Clean way to combine multiple jars? Preferably using Ant
[ "", "java", "ant", "jar", "" ]
Hey, I am so close to fininshing my guess a number game, very simple in PHP, but for some reason I am stuck. I am storing the variable in a hidden form, but obviously each time the page is sent it resets the number so you can never get the right one. Any ideas? My code is below. ``` <?php // generate a random number for user to guess $number = rand(1,100); if($_POST["guess"]){ // grab the user input guess $guess = $_POST['guess']; $numbe = $_POST['number']; if ($guess < $number){ echo "Guess Higher"; }elseif($guess > $number){ echo "Guess Lower"; }elseif($guess == $number){ echo "You got it!"; } echo "<br />Random Number:".$number."<br />"; echo $guess; } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Guess A Number</title> </head> <body> <form action="<?=$_SERVER['PHP_SELF'] ?>" method="post" name="guess-a-number"> <label for="guess">Guess A Number:</label><br/ > <input type="text" name="guess" /> <input name="number" type="hidden" value="<?= $number ?>" /> <input name="submit" type="submit" /> </form> </body> </html> ```
Change: ``` // generate a random number for user to guess $number = rand(1,100); ``` To: ``` if(isset($_POST['number'])) { $number = $_POST['number']; } else { $number = rand(1,100); } ```
Is it because of this typo? ``` $numbe = $_POST['number']; //numbe -> number ```
Problems with guess a number game
[ "", "php", "" ]
What is a Vanilla JS or jQuery solution that will select all of the contents of a textbox when the textbox receives focus?
``` $(document).ready(function() { $("input:text").focus(function() { $(this).select(); } ); }); ```
``` <input type="text" onfocus="this.select();" onmouseup="return false;" value="test" /> ```
Select all contents of textbox when it receives focus (Vanilla JS or jQuery)
[ "", "javascript", "jquery", "user-interface", "" ]
I have a series of ranges with start dates and end dates. I want to check to see if a date is within that range. Date.before() and Date.after() seem to be a little awkward to use. What I really need is something like this pseudocode: ``` boolean isWithinRange(Date testDate) { return testDate >= startDate && testDate <= endDate; } ``` Not sure if it's relevant, but the dates I'm pulling from the database have timestamps.
``` boolean isWithinRange(Date testDate) { return !(testDate.before(startDate) || testDate.after(endDate)); } ``` Doesn't seem that awkward to me. Note that I wrote it that way instead of ``` return testDate.after(startDate) && testDate.before(endDate); ``` so it would work even if testDate was exactly equal to one of the end cases.
# tl;dr ``` ZoneId z = ZoneId.of( "America/Montreal" ); // A date only has meaning within a specific time zone. At any given moment, the date varies around the globe by zone. LocalDate ld = givenJavaUtilDate.toInstant() // Convert from legacy class `Date` to modern class `Instant` using new methods added to old classes. .atZone( z ) // Adjust into the time zone in order to determine date. .toLocalDate(); // Extract date-only value. LocalDate today = LocalDate.now( z ); // Get today’s date for specific time zone. LocalDate kwanzaaStart = today.withMonth( Month.DECEMBER ).withDayOfMonth( 26 ); // Kwanzaa starts on Boxing Day, day after Christmas. LocalDate kwanzaaStop = kwanzaaStart.plusWeeks( 1 ); // Kwanzaa lasts one week. Boolean isDateInKwanzaaThisYear = ( ( ! today.isBefore( kwanzaaStart ) ) // Short way to say "is equal to or is after". && today.isBefore( kwanzaaStop ) // Half-Open span of time, beginning inclusive, ending is *exclusive*. ) ``` # Half-Open Date-time work commonly employs the "Half-Open" approach to defining a span of time. The beginning is *inclusive* while the ending is *exclusive*. So a week starting on a Monday runs up to, but does not include, the following Monday. # java.time Java 8 and later comes with the [`java.time`](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework built-in. Supplants the old troublesome classes including `java.util.Date/.Calendar` and `SimpleDateFormat`. Inspired by the successful Joda-Time library. Defined by JSR 310. Extended by the ThreeTen-Extra project. An [`Instant`](https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) is a moment on the timeline in [UTC](https://en.m.wikipedia.org/wiki/Coordinated_Universal_Time) with nanosecond resolution. ## `Instant` Convert your `java.util.Date` objects to Instant objects. ``` Instant start = myJUDateStart.toInstant(); Instant stop = … ``` If getting `java.sql.Timestamp` objects through JDBC from a database, [convert to java.time.Instant](https://docs.oracle.com/javase/8/docs/api/java/sql/Timestamp.html#toInstant--) in a similar way. A `java.sql.Timestamp` is already in UTC so no need to worry about time zones. ``` Instant start = mySqlTimestamp.toInstant() ; Instant stop = … ``` Get the current moment for comparison. ``` Instant now = Instant.now(); ``` Compare using the methods isBefore, isAfter, and equals. ``` Boolean containsNow = ( ! now.isBefore( start ) ) && ( now.isBefore( stop ) ) ; ``` ## `LocalDate` Perhaps you want to work with only the date, not the time-of-day. The `LocalDate` class represents a date-only value, without time-of-day and without time zone. ``` LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ; LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ; ``` To get the current date, specify a time zone. At any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal. ``` LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) ); ``` We can use the `isEqual`, `isBefore`, and `isAfter` methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is *inclusive* while the ending is *exclusive*. ``` Boolean containsToday = ( ! today.isBefore( start ) ) && ( today.isBefore( stop ) ) ; ``` ## `Interval` If you chose to add the [ThreeTen-Extra](https://www.threeten.org/threeten-extra/) library to your project, you could use the [`Interval`](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/Interval.html) class to define a span of time. That class offers methods to test if the interval [contains](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/Interval.html#contains(java.time.Instant)), [abuts](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/Interval.html#abuts(org.threeten.extra.Interval)), [encloses](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/Interval.html#encloses(org.threeten.extra.Interval)), or [overlaps](https://www.threeten.org/threeten-extra/apidocs/org.threeten.extra/org/threeten/extra/Interval.html#overlaps(org.threeten.extra.Interval)) other date-times/intervals. The `Interval` class works on `Instant` objects. The [`Instant`](http://docs.oracle.com/javase/8/docs/api/java/time/Instant.html) class represents a moment on the timeline in [UTC](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) with a resolution of [nanoseconds](https://en.wikipedia.org/wiki/Nanosecond) (up to nine (9) digits of a decimal fraction). We can adjust the `LocalDate` into a specific moment, the first moment of the day, by specifying a time zone to get a `ZonedDateTime`. From there we can get back to UTC by extracting a `Instant`. ``` ZoneId z = ZoneId.of( "America/Montreal" ); Interval interval = Interval.of( start.atStartOfDay( z ).toInstant() , stop.atStartOfDay( z ).toInstant() ); Instant now = Instant.now(); Boolean containsNow = interval.contains( now ); ``` --- # About java.time The [java.time](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) framework is built into Java 8 and later. These classes supplant the troublesome old [legacy](https://en.wikipedia.org/wiki/Legacy_system) date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/8/docs/api/java/util/Date.html), [`Calendar`](https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html), & [`SimpleDateFormat`](http://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html). The [Joda-Time](http://www.joda.org/joda-time/) project, now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advises migration to the [`java.time`](http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html) classes. To learn more, see the [Oracle Tutorial](http://docs.oracle.com/javase/tutorial/datetime/TOC.html). And search Stack Overflow for many examples and explanations. Specification is [JSR 310](https://jcp.org/en/jsr/detail?id=310). Where to obtain the `java.time` classes? * [**Java SE 8**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8) and [**SE 9**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_9) and later * Built-in. * Part of the standard Java API with a bundled implementation. * Java 9 adds some minor features and fixes. * [**Java SE 6**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_6) and [**SE 7**](https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7) * Much of the `java.time` functionality is back-ported to Java 6 & 7 in [***ThreeTen-Backport***](http://www.threeten.org/threetenbp/). * [**Android**](https://en.wikipedia.org/wiki/Android_(operating_system)) * The [*ThreeTenABP*](https://github.com/JakeWharton/ThreeTenABP) project adapts ***ThreeTen-Backport*** (mentioned above) for Android specifically. * See [*How to use…*](https://stackoverflow.com/q/38922754/642706). The [ThreeTen-Extra](http://www.threeten.org/threeten-extra/) project extends `java.time` with additional classes. This project is a proving ground for possible future additions to `java.time`. You may find some useful classes here such as [`Interval`](https://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html), [`YearWeek`](http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearWeek.html), [`YearQuarter`](https://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/YearQuarter.html), and [more](http://www.threeten.org/threeten-extra/apidocs/index.html).
How do I check if a date is within a certain range?
[ "", "java", "date", "" ]
I am looking for the simplest way to disable a whole HTML element (typically a `<div>`). With "disable" I mean a way to prevent the user to click on any of the elements contained into the element. For instance, if you have a form into the disabled element, the form elements won't catch the focus. I've tried with a method that traverses the DOM and disables each element it finds. It works but it seems too complex and I'm looking for a simpler method, something like `$("#mydiv").disable()` I would like to prevent the user to fire other events like onmouseover, etc. and even avoid the user to select and modify elements using the keyboard. Maybe some kind of semitransparent overlay covering the whole element to be disabled could do the trick. Is that possible with jQuery or do you know an easy way to implement it with plain JS ?
The [jQuery plugin BlockUI](http://malsup.com/jquery/block/) is a great way to achieve this.
Something along the lines of : ``` $("#mydiv").find("input").attr('disabled','disabled'); ``` Which basically finds all `input` elements in the myDiv element, and disables them.
Disable HTML element in the client side (javascript)
[ "", "javascript", "jquery", "html", "" ]
Imagine a situation, I have PC with two lan cards, one is connected to internet another is connected to local network, how can I detect IP which is connected to internet with C# ?
Try this: ``` static IPAddress getInternetIPAddress() { try { IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName()); IPAddress gateway = IPAddress.Parse(getInternetGateway()); return findMatch(addresses, gateway); } catch (FormatException e) { return null; } } static string getInternetGateway() { using (Process tracert = new Process()) { ProcessStartInfo startInfo = tracert.StartInfo; startInfo.FileName = "tracert.exe"; startInfo.Arguments = "-h 1 208.77.188.166"; // www.example.com startInfo.UseShellExecute = false; startInfo.RedirectStandardOutput = true; tracert.Start(); using (StreamReader reader = tracert.StandardOutput) { string line = ""; for (int i = 0; i < 9; ++i) line = reader.ReadLine(); line = line.Trim(); return line.Substring(line.LastIndexOf(' ') + 1); } } } static IPAddress findMatch(IPAddress[] addresses, IPAddress gateway) { byte[] gatewayBytes = gateway.GetAddressBytes(); foreach (IPAddress ip in addresses) { byte[] ipBytes = ip.GetAddressBytes(); if (ipBytes[0] == gatewayBytes[0] && ipBytes[1] == gatewayBytes[1] && ipBytes[2] == gatewayBytes[2]) { return ip; } } return null; } ``` Note that this implementation of `findMatch()` relies on class C matching. If you want to support class B matching, just omit the check for `ipBytes[2] == gatewayBytes[2]`. **Edit History:** * Updated to use `www.example.com`. * Updated to include `getInternetIPAddress()`, to show how to use the other methods. * Updated to catch `FormatException` if `getInternetGateway()` failed to parse the gateway IP. (This can happen if the gateway router is configured such that it doesn't respond to [traceroute](http://en.wikipedia.org/wiki/Traceroute) requests.) * Cited Brian Rasmussen's comment. * Updated to use the IP for www.example.com, so that it works even when the DNS server is down.
I suggest this simple code since `tracert` is not always effective and whatsmyip.com is not specially designed for that purpose : ``` private void GetIP() { WebClient wc = new WebClient(); string strIP = wc.DownloadString("http://checkip.dyndns.org"); strIP = (new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b")).Match(strIP).Value; wc.Dispose(); return strIP; } ```
How to get *internet* IP?
[ "", "c#", "networking", "" ]
I'm working on a grid system which has a number of very powerful computers. These can be used to execute python functions very quickly. My users have a number of python functions which take a long time to calculate on workstations, ideally they would like to be able to call some functions on a remote powerful server, but have it appear to be running locally. Python has an old function called "apply" - it's mostly useless these days now that python supports the extended-call syntax (e.g. \*\*arguments), however I need to implement something that works a bit like this: ``` rapply = Rapply( server_hostname ) # Set up a connection result = rapply( fn, args, kwargs ) # Remotely call the function assert result == fn( *args, **kwargs ) #Just as a test, verify that it has the expected value. ``` Rapply should be a class which can be used to remotely execute some arbitrary code (`fn` could be literally anything) on a remote server. It will send back the result which the `rapply` function will return. The "result" should have the same value as if I had called the function locally. Now let's suppose that `fn` is a user-provided function I need some way of sending it over the wire to the execution server. If I could guarantee that fn was always something simple it could could just be a string containing python source code... but what if it were not so simple? What if `fn` might have local dependencies: It could be a simple function which uses a class defined in a different module, is there a way of encapsulating `fn` and everything that `fn` requires which is not standard-library? An ideal solution would not require the users of this system to have much knowledge about python development. They simply want to write their function and call it. Just to clarify, I'm not interested in discussing what kind of network protocol might be used to implement the communication between the client & server. My problem is how to encapsulate a function and its dependencies as a single object which can be serialized and remotely executed. I'm also not interested in the security implications of running arbitrary code on remote servers - let's just say that this system is intended purely for research and it is within a heavily firewalled environment.
Take a look at [PyRO](https://pyro5.readthedocs.io/en/stable/) (Python Remote objects) It has the ability to set up services on all the computers in your cluster, and invoke them directly, or indirectly through a name server and a publish-subscribe mechanism.
It sounds like you want to do the following. * Define a shared filesystem space. * Put ALL your python source in this shared filesystem space. * Define simple agents or servers that will "execfile" a block of code. * Your client then contacts the agent (REST protocol with POST methods works well for this) with the block of code. The agent saves the block of code and does an `execfile` on that block of code. Since all agents share a common filesystem, they all have the same Python library structure. We do with with a simple WSGI application we call "batch server". We have RESTful protocol for creating and checking on remote requests.
Execute arbitrary python code remotely - can it be done?
[ "", "python", "grid", "" ]
I am using the format ToString("0,0") to display a number like ``` 5000 as 5,000 ``` but if the number is 0 - 9, it displays 01, 02, 03, etc. Does anyone know the correct syntax so it does not display the leading 0? Thanks, XaiSoft
``` ToString("#,0") ``` Also, [this](http://acodingfool.typepad.com/blog/dotnet-string-formatting-cheat-sheet.html) may help you further
What you are looking for is the string formatter "N0". Example: ``` int x = 10000; int y = 5; Console.WriteLine(x.ToString("N0")); Console.WriteLine(y.ToString("N0")); ``` Prints: ``` 10,000 5 ``` More information [here](http://msdn.microsoft.com/en-us/library/0c899ak8(vs.71).aspx).
How to display 1 instead of 01 in ToString();
[ "", "c#", "formatting", "string", "" ]
Let's say I have two tables, "Parent" and "Child". Parent-to-Child is a many:many relationship, implemented through a standard cross-referencing table. I want to find all records of Parent that are referenced by ALL members of a given set of Child using SQL (in particular MS SQL Server's T-SQL; 2005 syntax is acceptable). For example let's say I have: * List item * Parent Alice * Parent Bob * Child Charlie references Alice, Bob * Child David references Alice * Child Eve references Bob My goals are: * If I have Children Charlie, I want the result set to include Alice and Bob * If I have Children Charlie and David, I want the result set to include Alice and **NOT** Bob. * If I have Children Charlie, David, and Eve, I want the result set to include nobody.
Relying on a numerical trick (where the number of parent-child links = the number of children, that parent is linked to all children): ``` SELECT Parent.ParentID, COUNT(*) FROM Parent INNER JOIN ChildParent ON ChildParent.ParentID = Parent.ParentID INNER JOIN Child ON ChildParent.ChildID = Child.ChildID WHERE <ChildFilterCriteria> GROUP BY Parent.ParentID HAVING COUNT(*) = ( SELECT COUNT(Child.ChildID) FROM Child WHERE <ChildFilterCriteria> ) ```
( I guess where you said "Child Eve references Eve" you meant "Child Eve references Bob", right?) I think I've got it... looks ugly... the secret is the double negation... that is, everyone for which it's true,, is the same as not anyone for which is false... (ok, I have troubles with my english, but I guess you understand what I mean) ``` select * from parent parent_id name --------------------------------------- -------------------------------------------------- 1 alice 2 bob select * from child child_id name --------------------------------------- -------------------------------------------------- 1 charlie 2 david 3 eve select * from parent_child parent_id child_id --------------------------------------- --------------------------------------- 1 1 2 1 1 2 2 3 select * from parent p where not exists( select * from child c where c.child_id in ( 1, 2, 3 ) and not exists( select * from parent_child pc where pc.child_id = c.child_id and pc.parent_id = p.parent_id ) ) --when child list = ( 1 ) parent_id name --------------------------------------- -------------------------------------------------- 1 alice 2 bob --when child list = ( 1, 2 ) parent_id name --------------------------------------- -------------------------------------------------- 1 alice --when child list = ( 1, 2, 3 ) parent_id name --------------------------------------- -------------------------------------------------- ``` well, I hope it helps...
Select Parent Record With All Children in SQL
[ "", "sql", "sql-server", "sql-server-2005", "t-sql", "" ]
I am making an application that does some custom image processing. The program will be driven by a simple menu in the console. The user will input the filename of an image, and that image will be displayed using openGL in a window. When the user selects some processing to be done to the image, the processing is done, and the openGL window should redraw the image. My problem is that my image is never drawn to the window, instead the window is always black. I think it may have to do with the way I am organizing the threads in my program. The main execution thread handles the menu input/output and the image processing and makes calls to the Display method, while a second thread runs the openGL mainloop. Here is my main code: ``` #include <iostream> #include <GL/glut.h> #include "ImageProcessor.h" #include "BitmapImage.h" using namespace std; DWORD WINAPI openglThread( LPVOID param ); void InitGL(); void Reshape( GLint newWidth, GLint newHeight ); void Display( void ); BitmapImage* b; ImageProcessor ip; int main( int argc, char *argv[] ) { DWORD threadID; b = new BitmapImage(); CreateThread( 0, 0, openglThread, NULL, 0, &threadID ); while( true ) { char choice; string path = "TestImages\\"; string filename; cout << "Enter filename: "; cin >> filename; path += filename; b = new BitmapImage( path ); Display(); cout << "1) Invert" << endl; cout << "2) Line Thin" << endl; cout << "Enter choice: "; cin >> choice; if( choice == '1' ) { ip.InvertColour( *b ); } else { ip.LineThinning( *b ); } Display(); } return 0; } void InitGL() { int argc = 1; char* argv[1]; argv[0] = new char[20]; strcpy( argv[0], "main" ); glutInit( &argc, argv ); glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowPosition( 0, 0 ); glutInitWindowSize( 800, 600 ); glutCreateWindow( "ICIP Program - Character recognition using line thinning, Hilbert curve, and wavelet approximation" ); glutDisplayFunc( Display ); glutReshapeFunc( Reshape ); glClearColor(0.0,0.0,0.0,1.0); glEnable(GL_DEPTH_TEST); } void Reshape( GLint newWidth, GLint newHeight ) { /* Reset viewport and projection parameters */ glViewport( 0, 0, newWidth, newHeight ); } void Display( void ) { glClear (GL_COLOR_BUFFER_BIT); // Clear display window. b->Draw(); glutSwapBuffers(); } DWORD WINAPI openglThread( LPVOID param ) { InitGL(); glutMainLoop(); return 0; } ``` Here is my draw method for BitmapImage: ``` void BitmapImage::Draw() { cout << "Drawing" << endl; if( _loaded ) { glBegin( GL_POINTS ); for( unsigned int i = 0; i < _height * _width; i++ ) { glColor3f( _bitmap_image[i*3] / 255.0, _bitmap_image[i*3+1] / 255.0, _bitmap_image[i*3+2] / 255.0 ); // invert the y-axis while drawing glVertex2i( i % _width, _height - (i / _width) ); } glEnd(); } } ``` Any ideas as to the problem? Edit: The problem was technically solved by starting a glutTimer from the openglThread which calls glutPostRedisplay() every 500ms. This is OK for now, but I would prefer a solution in which I only have to redisplay every time I make changes to the bitmap (to save on processing time) and one in which I don't have to run another thread (the timer is another thread im assuming). This is mainly because the main processing thread is going to be doing a lot of intensive work and I would like to dedicate most of the resources to this thread rather than anything else.
I've had this problem before - it's pretty annoying. The problem is that all of your OpenGL calls must be done in the thread where you started the OpenGL context. So when you want your main (input) thread to change something in the OpenGL thread, you need to somehow signal to the thread that it needs to do stuff (set a flag or something). Note: I don't know what your `BitmapImage` loading function (here, your constructor) does, but it probably has some OpenGL calls in it. The above applies to that too! So you'll need to signal to the other thread to create a `BitmapImage` for you, or at least to do the OpenGL-related part of creating the bitmap.
A few points: * Generally, if you're going the multithreaded route, it's preferable if your main thread is your GUI thread i.e. it does minimal tasks keeping the GUI responsive. In your case, I would recommend moving the intensive image processing tasks into a thread and doing the OpenGL rendering in your main thread. * For drawing your image, you're using vertices instead of a textured quad. Unless you have a very good reason, it's **much** faster to use a single textured quad (the processed image being the texture). Check out [glTexImage2D](http://opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/teximage2d.html) and [glTexSubImage2D](http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/texsubimage2d.html). * Rendering at a framerate of 2fps (500ms, as you mentioned) will have negligible impact on resources if you're using an OpenGL implementation that is accelerated, which is almost guaranteed on any modern system, and if you use a textured quad instead of a vertex per pixel.
Console menu updating OpenGL window
[ "", "c++", "multithreading", "opengl", "console", "" ]
Is there any reason why JQuery would not work when used in an ASPX page? We have been trying to get working a simple call like this: ``` $(document).ready(function() { alert("This is SPARTA!!!!!!!!!"); }); ``` An the alert box is never shown. I've had some experience with JS and ASP.Net before with buttons and I know that I have to return false after the JS like: ``` <input type=button value="Button 1" onclick='button_1_onclick();return false;'> ``` Is there a similar thing to be done? Edited: I have ran Firebug in the debugger mode and the JS is never ran, all the libs are present in the page. The only thing I can think of is that the ready event is not triggered or something similar.
ASP.NET and JQuery play really nicely together (and also with ASP.NET AJAX library too), I have used all of them together on a recent ASP.NET 3.5 web application. There are some [oddities to be aware of](http://encosia.com/2008/09/28/avoid-this-tricky-conflict-between-aspnet-ajax-and-jquery/), but on the whole work well together. Firstly, you need to ensure that you have a script tag with src of your jQuery file- ``` <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> ``` I have usually done this by adding a ScriptReference to the ScriptManager, but either way works. Then put your jQuery code after the script tag - ``` $(function() { alert("This is SPARTA!!!!!!!!!"); }); ``` If your jQuery file is in a folder and you have some kind of authentication set up on your site, then you need to ensure that the folder is accessible on the pages where you are using jQuery, by modifying the web.config (much like you need to do with images and css). I've been tripped up by this before. You can check in firebug to see if the jQuery code is accessible (i.e. visible) by expanding the relevant script node; if you see some kind of HTTP error, then it could be due to the script not being accessible. As others have already said, there could be conflicts with other JavaScript libraries. You can still use the $ shorthand if also using libraries by using the following pattern ``` (function($) { $(function() { alert("This is SPARTA!!!!!!!!!"); }); })(jQuery); ``` This means that $ within the scope of the outer function is shorthand for jQuery object.
Are you using another library at the same time? The $ may have been re-assigned, try this: ``` jQuery(document).ready(function() { alert("This is SPARTA!!!!!!!!!"); }); ```
How to get JQuery and ASP.Net work together?
[ "", "asp.net", "javascript", "jquery", "" ]
I have written a basic Windows Form app in C# that has an embedded web browser control. I am navigating to a page to view a camera's feed. The application works fine on Windows XP, but not on Vista. On Vista, I get a AccessViolationException. This seems to be related to Data Execution Prevention. The article at <http://jtstroup.net/CommentView,guid,3fa30293-a3a4-4a1c-a612-058e751ad151.aspx> has a couple solutions. The fix at the bottom of the page, editbin.exe /NXCOMPAT:NO YourProgram.exe from a Visual Studio Command Prompt works just fine. However, what I'd like is to use the post build event method, by adding the following as suggested: REM Mark project as DEP Noncompliant call "$(DevEnvDir)....\VC\bin\vcvars32.bat" call "$(DevEnvDir)....\VC\bin\editbin.exe" /NXCOMPAT:NO "$(TargetPath)" However, this doesn't work when I try to run the program through the debugger (i.e. I get the same exception). Any ideas?
According to [this article](http://blogs.msdn.com/gauravb/archive/2008/09/23/disable-dep-on-applications.aspx): > Because It was observed in a Setup > project with Visual Studio 2008 that > the Add Project Output source path > Points to c:\App\OBJ\*.exePost Build > Event would update c:\app\BIN\*.exe > and not the OBJ. > > Manually add the build in setup and > deployment Project Create New Setup > Project | Add File | select Build EXE > which is under Bin Folder
Turn off the Visual Studio Hosting Process, or alternatively mark the hosting process (yourapp.vshost.exe) as DEP noncompliant?
AccessViolationException with a webbrowser in a windows form
[ "", "c#", "winforms", "webbrowser-control", "data-execution-prevention", "" ]
How to order Controls at runtime in ASP.NET for instance I have three text boxes in my web page in the following order * textbox1 * textbox2 * textbox3 I want the order of these controls to be changed depending on the user preferences * textbox3 * textbox2 * textbox1 that is just an example, any idea?
Finally I have found a solution and I will explain it in detail create a "panel control" and called it "myPanel" and put in this all controls you want to resort ``` <asp:Panel ID="myPanel" runat="server"> <asp:Panel ID="dock1" runat="server">this is first module</asp:Panel> <asp:Panel ID="dock2" runat="server">this is second module</asp:Panel> <asp:Panel ID="dock3" runat="server">this is third module</asp:Panel> </asp:Panel> ``` the output will be the following this is first module this is second module this is third module so what should I do to change their order, lets see I have created more three panels to act like a containers for the docks my code will be like this ``` <asp:Panel ID="myPanel" runat="server"> <asp:Panel ID="container1" runat="server"></asp:Panel> <asp:Panel ID="container2" runat="server"></asp:Panel> <asp:Panel ID="container3" runat="server"></asp:Panel> <asp:Panel ID="dock1" runat="server">this is first module</asp:Panel> <asp:Panel ID="dock2" runat="server">this is second module</asp:Panel> <asp:Panel ID="dock3" runat="server">this is third module</asp:Panel> </asp:Panel> ``` in the code behind I have something like this this will remove dock1 control from mypanel and put it in container3 ``` Control myCtrl1 = myPanel.FindControl("dock1"); Control containerCtrl1 = myPanel.FindControl("container3"); myCtrl1.Visible = true; myPanel.Controls.Remove(myCtrl1); containerCtrl1 .Controls.Add(myCtrl1); ``` and you can manage these thing depending on user preferences from a database or a cookies best regards
The jQuery UI framework can do that for you. Check out this [demo](http://ui.jquery.com/demos/sortable/) and the [docs](http://docs.jquery.com/UI/Sortables/sortable) for the same.
How to sort controls at runtime in ASP.NET
[ "", "c#", "asp.net", "vb.net", "controls", "runtime", "" ]
I need to perform case-insensitive queries on `username` by default when using the Django Auth framework. I tried fixing the issue by writing a custom subclass of `Queryset` and overriding the `_filter_or_exclude` method and then using that subclass in a custom manager for the User model- ``` from django.db.models import Manager from django.db.models.query import QuerySet from django.contrib.auth.models import UserManager class MyQuerySet(QuerySet): def _filter_or_exclude(self, negate, *args, **kwargs): if 'username' in kwargs: kwargs['username__iexact'] = kwargs['username'] del kwargs['username'] return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) class MyUserManager(UserManager): def get_query_set(self): return MyQuerySet(self.model) User.objects = MyUserManager() ``` But this approach didn't work and I am getting an weird error when I try doing `User.objects.get(username='Foo')`. Any help would be appreciated. **Update**: I am including the exact error that I am getting. ``` /usr/lib/python2.5/site-packages/django/db/models/query.py in get(self, *args, **kwargs) 295 keyword arguments. 296 """ --> 297 clone = self.filter(*args, **kwargs) 298 num = len(clone) 299 if num == 1: /usr/lib/python2.5/site-packages/django/db/models/query.py in filter(self, *args, **kwargs) 481 set. 482 """ --> 483 return self._filter_or_exclude(False, *args, **kwargs) 484 485 def exclude(self, *args, **kwargs): /home/ghoseb/src/git/ocricket.git/ocricket/user/models.py in _filter_or_exclude(self, negate, *args, **kwargs) 38 kwargs['username__iexact'] = kwargs['username'] 39 del kwargs['username'] ---> 40 return super(MyQuerySet, self)._filter_or_exclude(negate, *args, **kwargs) 41 42 class MyUserManager(UserManager): /usr/lib/python2.5/site-packages/django/db/models/query.py in _filter_or_exclude(self, negate, *args, **kwargs) 499 clone.query.add_q(~Q(*args, **kwargs)) 500 else: --> 501 clone.query.add_q(Q(*args, **kwargs)) 502 return clone 503 /usr/lib/python2.5/django/db/models/sql/query.py in add_q(self, q_object, used_aliases) /usr/lib/python2.5/django/db/models/sql/query.py in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras) /usr/lib/python2.5/django/db/models/sql/query.py in get_meta(self) <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute '_meta' ``` **Update**: By the way, I just wanted to mention that when I copy the logic inside my `_filter_or_exclude` method into the actual `QuerySet` class, it works flawlessly.
Managers can't be added to classes with simple attribute assignment (`User.objects = MyManager()`). Look at the ModelBase metaclass (db/models/base.py) to see what all is done for you behind the scenes when you subclass Model. You should be able to make it work with `User.add_to_class('objects', MyManager())`. Alternatively, you could make a [proxy subclass](http://docs.djangoproject.com/en/dev/topics/db/models/#proxy-models) of User and add the manager there.
You don't want to mess with internal features of Django classes. That way lies trouble with every upgrade in the future. If you want to change the way people authenticate, write a custom authentication backend. Here are two recipes. <http://www.davidcramer.net/code/224/logging-in-with-email-addresses-in-django.html> <http://www.djangosnippets.org/snippets/577/> Both of these us email instead of username. It's not hard to use case-insensitive query instead of an email query.
Django: Perform case-insensitive lookups by default
[ "", "python", "django", "django-models", "django-orm", "" ]
I am working on both parts of a data layer. I get to create the procs, and the business object layer that will consume the procs. Is there a best practice for determining where a delete should occur? Here's the scenario. I have a table Book with foreign key to a child table Pages. If I delete the book, I also want to delete the pages. If the deletion of a page fails, I want the whole book to stay (transaction). Should the delete occur in managed code (by creating a transaction, deleting all child objects and finally the book), or in the proc (again in a transaction)? Or does it matter?
I would say it depends where you store your "logic" for the data. 1) If your stored procedures are mostly "dumb" ones with simple Inserts/Update/Delete. I would put the deletes in the data layer object where you would have more complex code. 2)IF you have written many complex stored procedure, where you need to check biz rules. Keep the logic all in the SPs and keep the data layer simple. Really it where you want the complexity to lie. Don't put too many rules in both the objects and the SPs, or else maintenance will be a bitch.
well there are 3 ways for this: 1. do it in the app with TransactionScope 2. do it in the proc 3. create a cascade delete on the PK-FK relationship. depending on what your DAL looks like you'll have to make a choice. if it's a ORM then go with 1. else go with 3.
Should I delete child objects from the client, or via a stored proc
[ "", ".net", "sql", "" ]
I have an HTML textbox that contains some SQL code that I need executed. I am able to retrieve the actual code from the textbox but I am not sure how to go about executing the code. Any simple and elegant ways using c# 3.5?
**DON'T EXECUTE CODE FROM A TEXTBOX** unless you really trust what is being entered. If you do, use this: ``` SqlConnection con = new SqlConnection("Your connection string"); con.Open(); SqlCommand cmd = new SqlCommand(TexdtBox1.Text, con); cmd.ExecuteNonQuery(); con.Close() ``` Note that this will not return anything, jsut run the query. If you want to return data, you need a SqlDataAdaptor or SqlDataReader.
![alt text](https://imgs.xkcd.com/comics/exploits_of_a_mom.png)
How do I run SQL code using c# 3.5?
[ "", "c#", "" ]
This might be quite a strange question since usually people bind only complex types to a gridview. But I need to bind a List of Int (the same is for strings). Usually, as the property to bind one uses the name of the property of the object, but when using a Int or a String, the value is exactly the object itself, not a property. What is the "name" to get the value of the object? I tried "Value", "" (empty), "this", "item" but no luck. I'm referring to a gridview in a web form. **Update** There's a related Stack Overflow question, *[How to bind a List to a GridView](https://stackoverflow.com/questions/5720349/how-to-bind-a-listdatetime-to-a-gridview)*.
`<BoundField DataField="!" />` may do the trick (since `BoundField.ThisExpression` equals "!").
``` <asp:TemplateField> <ItemTemplate> <%# Container.DataItem.ToString() %> </ItemTemplate> </asp:TemplateField> ```
How to bind a List<Int> to a gridview?
[ "", "c#", "asp.net", "list", "gridview", "" ]
I have a set of some classes which are all capable of being constructored with an argument being an instance of a particular interface. Since they all can be constructed by this same object (and the process during which this construction happens is largely the same in all cases), I figured perhaps templating would work. Basically, I want to do something like this: ``` public static void dostuff<T, U> (List<T> items) { foreach (T item in items) { func(new U(item).SpecialMember); } } ``` Of course, that won't compile since `U` is templated and thus lacks `SpecialMember` as well as the `T` constructor. Basically, any given implementation of the inteface `T` has certain features. `U` is an implementation of `T which has an additional feature that is needed *and* which can be constructed from an any instance of`U`. Advice?
Unfortunately while constraints will get you *some* of the way there, there's no way to specify that a type has a constructor which takes certain argument: the only constructor you can require is a parameterless one. Personally I'd like to see that change using an idea of ["static interfaces"](http://msmvps.com/blogs/jon_skeet/archive/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces.aspx) (only usable for type constraints) but for the moment the best you'll get is a type factory or reflection - or possibly a parameterless constructor *and* an "Init" method in the interface. None of these are nice options, frankly.
You can add [constraints](http://msdn.microsoft.com/en-us/library/d5x73970(VS.80).aspx) to the generic parameters which will allow you to access SpecialMember for example: ``` public class SpecialObjFactory<T,U> where T : ISpecialMethod where u : new() { } ```
C# Templates and special constructors
[ "", "c#", "generics", "oop", "templates", "" ]
I read [This article](http://jacobcarpenter.wordpress.com/2008/01/02/c-abuse-of-the-day-functional-library-implemented-with-lambdas/) and i found it interesting. To sum it up for those who don't want to read the entire post. The author implements a higher order function named Curry like this (refactored by me without his internal class): ``` public static Func<T1, Func<T2, TResult>> Curry<T1, T2, TResult>(this Func<T1, T2, TResult> fn) { Func<Func<T1, T2, TResult>, Func<T1, Func<T2, TResult>>> curry = f => x => y => f(x, y); return curry(fn); } ``` That gives us the ability to take an expression like F(x, y) eg. ``` Func<int, int, int> add = (x, y) => x + y; ``` and call it in the F.Curry()(x)(y) manner; This part i understood and i find it cool in a geeky way. What i fail to wrap my head around is the practical usecases for this approach. When and where this technique is necessary and what can be gained from it? Thanks in advance. Edited: After the initial 3 responses i understand that the gain would be that in some cases when we create a new function from the curried some parameters are not re evalued. I made this little test in C# (keep in mind that i'm only interested in the C# implementation and not the curry theory in general): ``` public static void Main(string[] args) { Func<Int, Int, string> concat = (a, b) => a.ToString() + b.ToString(); Func<Int, Func<Int, string>> concatCurry = concat.Curry(); Func<Int, string> curryConcatWith100 = (a) => concatCurry(100)(a); Console.WriteLine(curryConcatWith100(509)); Console.WriteLine(curryConcatWith100(609)); } public struct Int { public int Value {get; set;} public override string ToString() { return Value.ToString(); } public static implicit operator Int(int value) { return new Int { Value = value }; } } ``` On the 2 consecutive calls to curryConcatWith100 the ToString() evaluation for the value 100 is called twice (once for each call) so i dont see any gain in evaluation here. Am i missing something ?
Its easier to first consider fn(x,y,z). This could by curried using fn(x,y) giving you a function that only takes one parameter, the z. Whatever needs to be done with x and y alone can be done and stored by a closure that the returned function holds on to. Now you call the returned function several times with various values for z without having to recompute the part the required x and y. **Edit:** There are effectively two reasons to curry. ## Parameter reduction As Cameron says to convert a function that takes say 2 parameters into a function that only takes 1. The result of calling this curried function with a parameter is the same as calling the original with the 2 parameters. With Lambdas present in C# this has limited value since these can provide this effect anyway. Although it you are use C# 2 then the Curry function in your question has much greater value. ## Staging computation The other reason to curry is as I stated earlier. To allow complex/expensive operations to be staged and re-used several times when the final parameter(s) are supplied to the curried function. This type of currying isn't truely possible in C#, it really takes a functional language that can natively curry any of its functions to acheive. ## Conclusion Parameter reduction via the Curry you mention is useful in C# 2 but is considerably de-valued in C# 3 due to Lambdas.
Currying is used to transform a function with x parameters to a function with y parameters, so it can be passed to another function that needs a function with y parameters. For example, `Enumerable.Select(this IEnumerable<T> source, Func<TSource, bool> selector)` takes a function with 1 parameter. `Math.Round(double, int)` is a function that has 2 parameters. You could use currying to "store" the `Round` function as data, and then pass that curried function to the `Select` like so ``` Func<double, int, double> roundFunc = (n, p) => Math.Round(n, p); Func<double, double> roundToTwoPlaces = roundFunc.Curry()(2); var roundedResults = numberList.Select(roundToTwoPlaces); ``` The problem here is that there's also anonymous delegates, which make currying redundant. In fact anonymous delegates *are* a form of currying. ``` Func<double, double> roundToTwoPlaces = n => Math.Round(n, 2); var roundedResults = numberList.Select(roundToTwoPlaces); ``` Or even just ``` var roundedResults = numberList.Select(n => Math.Round(n, 2)); ``` Currying was a way of solving a particular problem given the syntax of certain functional languages. With anonymous delegates and the lambda operator the syntax in .NET is alot simpler.
C# lambda - curry usecases
[ "", "c#", ".net", "lambda", "" ]
I want to simulate N-sided biased die? ``` def roll(N,bias): '''this function rolls N dimensional die with biasing provided''' # do something return result >> N=6 >> bias=( 0.20,0.20,0.15,0.15,0.14,0.16,) >> roll(N,bias) 2 ```
A little bit of math here. A regular die will give each number 1-6 with equal probability, namely `1/6`. This is referred to as [uniform distribution](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)) (the discrete version of it, as opposed to the continuous version). Meaning that if `X` is a random variable describing the result of a single role then `X~U[1,6]` - meaning `X` is distributed equally against all possible results of the die roll, 1 through 6. This is equal to choosing a number in `[0,1)` while dividing it into 6 sections: `[0,1/6)`, `[1/6,2/6)`, `[2/6,3/6)`, `[3/6,4/6)`, `[4/6,5/6)`, `[5/6,1)`. You are requesting a different distribution, which is biased. The easiest way to achieve this is to divide the section `[0,1)` to 6 parts depending on the bias you want. So in your case you would want to divide it into the following: `[0,0.2)`, `[0.2,0.4)`, `[0.4,0.55)`, `0.55,0.7)`, `[0.7,0.84)`, `[0.84,1)`. If you take a look at the [wikipedia entry](https://en.wikipedia.org/wiki/Uniform_distribution_(continuous)), you will see that in this case, the cumulative probability function will not be composed of 6 equal-length parts but rather of 6 parts which differ in length according to the *bias* you gave them. Same goes for the mass distribution. Back to the question, depending on the language you are using, translate this back to your die roll. In Python, here is a very sketchy, albeit working, example: ``` import random sampleMassDist = (0.2, 0.1, 0.15, 0.15, 0.25, 0.15) # assume sum of bias is 1 def roll(massDist): randRoll = random.random() # in [0,1] sum = 0 result = 1 for mass in massDist: sum += mass if randRoll < sum: return result result+=1 print(roll(sampleMassDist)) ```
More language agnostic, but you could use a lookup table. Use a random number in the range 0-1 and lookup the value in a table: ``` 0.00 - 0.20 1 0.20 - 0.40 2 0.40 - 0.55 3 0.55 - 0.70 4 0.70 - 0.84 5 0.84 - 1.00 6 ```
How do I simulate biased die in python?
[ "", "python", "numpy", "probability", "" ]
**What's a reliable way in JavaScript to determine the media type (e.g. screen, print, handheld) of the page?** I've seen references to `document.styleSheets[0].media`, but I've had no luck using this, either because of browser support issues or because I'm not understanding something. I'm asking because I want something to be hidden by Javascript in screen view, but not in print view. Media-dependent styles can't be relied on to do this because I'm using Prototype to run a toggle switch for the element, and Prototype won't allow an element to be switched to visible if it was declared invisible (`display: none`) with non-inline CSS\*. I tried to just set media-specific inline styles for the element (`<div style="@media print { foo: bar; } @media screen { blargh: bfargle; }">`), but from what I can tell, that's not supported. I know that I can cycle through the stylesheets and check to see if a print-specific linked stylesheet is active or not, but I'm currently in a situation where various media-specific style declarations are all mixed around in a single linked stylesheet, so that's no good. And yeah, I can just split up the stylesheets into different media types, but I'd first like to figure out whether or not I can just reliably pull the media type out of the DOM with JavaScript, **completely independently of CSS**. I've tried that trick of "hide an element for the print view, then check to see if it's visible with JavaScript" but that's always resulted in (when I load up print preview) JavaScript determining that the supposed-to-be-hidden elements are visible and performing whatever DOM manipulation I tell it to, *despite* the fact that those elements *aren't* visible. If anybody would like more details about what I'm talking about here, I can elaborate in an edit. \*This is something that I haven't understood and am constantly irritated by.
> [..], Prototype won't allow an element to be switched to visible if it was declared invisible (`display: none`) with non-inline CSS. This is something that I haven't understood and am constantly irritated by. You probably already seen this but the documentation for e.g. [`show`](http://www.prototypejs.org/api/element/show) (there are other related functions with the same note) states that: > `Element.show` *cannot* display elements hidden via CSS stylesheets. Note that this is not a Prototype limitation but a consequence of how the CSS `display` property works. So, it's a known problem and they blame CSS. However, consider the following document (I haven't used Prototype before, so I'm not sure if this is the recommended way to wait for the DOM to load, but it seems to work): ``` <!doctype html> <script src="prototype.js"></script> <script> document.observe("dom:loaded", function() { $("victim").show(); }); </script> <style> p#victim {display:none;} </style> <p id="victim">Hello world! ``` As you already know, this will not work. Why? Well, how would Prototype know what to "reset" the `display` property to when you tell `p#victim` to `show` itself? (In other words: how can it find out what should have been the value of `display` if the `display: none` wasn't present in the ruleset with the `p#victim` selector.) The answer is simple: it can't. (Think about it for a second. What if another ruleset would modify the value of `display` if the `display: none` wasn't present in our ruleset with the `p#victim` selector? (I.e. we can't assume that e.g. `p` always should be set to `block`, other rulesets may have changed that value.) We can't remove the `display` property from a ruleset in an style sheet, and we can't remove the entire connection between the element and the ruleset because it may contain other properties and so on (even if it would be possible it would be, imho, non-obvious to find *which* ruleset to do this with). Of course, we could go on and on with this, but afaik there is no known solution to this problem.) Then why does the inline alternative work? First, lets look at how `show` is implemented: ``` show: function(element) { element = $(element); element.style.display = ''; // <-- the important line return element; } ``` Afaict the only important thing this function does is to set `element.style.display` to an empty string (`''`), which "removes" `display` from `style`. Great! But what does that mean? Why would we want to remove it?! First we have to find out what `element.style` actually represents and modifies when we modifies its values. The MDC documentation for [`element.style`](https://developer.mozilla.org/en/DOM/element.style) states that: > Returns an object that represents the element's `style` attribute. Note the last word: *attribute*. `element.style` ≠ the current "calculated" style for the element, it's just an list of the properties in the `style` attribute (see MDC for a longer/better explanation). Consider the following document: ``` <!doctype html> <script src="prototype.js"></script> <script> document.observe("dom:loaded", function() { $("victim").show(); }); </script> <p id="victim" style="display:none;">Hello world! ``` `style="display:none;"` hides `p#victim` but when the DOM finish loading Prototype will change it to `style=""`, and the browser will recalculate the value for the `display` property (the value from the browser's default style sheet in this case). *But*, consider the following document: ``` <!doctype html> <script src="jquery.js"></script> <script> $(document).ready(function(){ $("#victim").show(); }); </script> <style> p#victim {display:none;} </style> <p id="victim">Hello world! ``` jQuery handles the style sheets stuff correctly, in this case anyway! This isn't as simple to explain as the Prototype solution and there are to many layers of awesomeness for me to read through right now, and there are many cases where jQuery fails to calculate the correct value for `display` . (Quick last note: Firebug..., but I guess it uses some Firefox exclusive stuff or something.)
See if this works... I think you can do this for every type and just check if the statement returns null or equivalent, then apply your rules. From this site: **<http://www.webdeveloper.com/forum/showthread.php?t=82453>** > IE: > > `if (document.styleSheets[0].media == 'screen'){...}` > > FF/NS: > > `document.getElementsByTagName ('LINK')[0].getAttribute ('media')` > > or > > `document.styleSheets[0].media.mediaText` and a script to check it in all browsers (except for some new ones, so be careful :)) **[http://student.agh.edu.pl/~marcinw/cssmedia/](http://student.agh.edu.pl/%7Emarcinw/cssmedia/)** this script works in a if-statement as a boolean true/false! Hope you'll get it to work!
How do you determine media type in JavaScript?
[ "", "javascript", "stylesheet", "media", "styles", "javascript-framework", "" ]
If have this in the setter of a property: ``` decimal? temp = value as decimal?; ``` value = "90" But after the cast, temp is **null**... What is the proper way to do this cast?
Unboxing only works if the type is identical! You can't unbox an `object` that does not contain the target value. What you need is something along the lines of ``` decimal tmpvalue; decimal? result = decimal.TryParse((string)value, out tmpvalue) ? tmpvalue : (decimal?)null; ``` This looks whether the value is parsable as a `decimal`. If yes, then assign it to `result`; else assign `null`. The following code does approximately the same and might be easier to understand for people not familiar with the conditional operator `?:`: ``` decimal tmpvalue; decimal? result = null; if (decimal.TryParse((string)value, out tmpvalue)) result = tmpvalue; ```
you should parse the decimal. But if you want your decimal to be null when the string is not correct, use TryParse : ``` decimal parsedValue; decimal? temp = decimal.TryParse(value, out parsedValue) ? value : (decimal?)null; ``` This way you will avoid exceptions while parsing ill formated strings. Almost all primitive types provide a Parse and TryParse methods to convert from string. Is is also recommended to pass a culture for the provider argument to the method to avoid problems with the decimal separator. If you're reading from another system, CultureInfo.InvariantCulture is probably the way to go (but it's not the default). ``` bool TryParse(string s, NumberStyles style, IFormatProvider provider, out decimal result) ```
Cast object to decimal? (nullable decimal)
[ "", "c#", ".net", "casting", "nullable", "" ]
I am trying to attach a LINQ entity to the data context after I receive it from a form POST. However, all I get is the following exception: ``` An entity can only be attached as modified without original state if it declares a version member or does not have an update check policy. ``` I have also tried attaching the original row, like so: ``` dataContext.People.Attach(person, originalPerson); ``` In this case, I get the following exception: ``` Object reference not set to an instance of an object. ``` Here's the code in my controller: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, Person person) { var prevPerson = dataContext.People.Single(p => p.ID == id); dataContext.People.Attach(person, prevPerson); dataContext.SubmitChanges(); return Redirect("~/People/Index"); } ``` Any ideas on what I'm doing wrong here? I can post the entity code if needed.
In the LinqToSQL designer set all of the Update Checks to Never and when you attach call it like so: ``` context.entity.Attach(entity, true); ``` Alternatively, you could also grab the entity from the db and change it using the data from the POSTed entity, then submit that as a change.
Try following: ``` dataContext.People.Attach(person); dataContext.Refresh(RefreshMode.KeepCurrentValues, person); dataContext.SubmitChanges(); ```
Entity attachment issues in LINQ
[ "", "c#", "asp.net-mvc", "linq-to-sql", "" ]
A few months ago I read about a technique so that if there parameters you passed in matched the local variables then you could use some short hand syntax to set them. To avoid this: ``` public string Method(p1, p2, p3) { this.p1 = p1; this.p2 = p2; this.p3 = p3; } ``` Any ideas?
You may be thinking about the new object initializer syntax in C# 3.0. It looks like this: ``` var foo = new Foo { Bar = 1, Fizz = "hello" }; ``` So that's giving us a new instance of Foo, with the "Bar" property initialized to 1 and the "Fizz" property to "hello". The trick with this syntax is that if you leave out the "=" and supply an identifier, it will assume that you're assigning to a property of the same name. So, for example, if I already had a Foo instance, I could do this: ``` var foo2 = new Foo { foo1.Bar, foo1.Fizz }; ``` This, then, is getting pretty close to your example. If your class has p1, p2 and p3 properties, and you have variables with the same name, you could write: ``` var foo = new Foo { p1, p2, p3 }; ``` Note that this is for constructing instances only - not for passing parameters into methods as your example shows - so it may not be what you're thinking of.
There's an even easier method of doing this in C# 7 - Expression bodied constructors. Using your example above - your constructor can be simplified to one line of code. I've included the class fields for completeness, I presume they would be on your class anyway. ``` private string _p1; private int _p2; private bool _p3; public Method(string p1, int p2, bool p3) => (_p1, _p2, _p3) = (p1, p2, p3); ``` See the following link for more info :- <https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members>
C# Object Constructor - shorthand property syntax
[ "", "c#", "class", "object", "" ]
I have an issue whereby the company uses a business tracking system that captures a users first visit and redirects them to the page they were trying to visit but with a refferer URL attached... Now as the referer URL carries the url that the person was trying to visit (dont ask why, Ive no idea) it causes me to have a duplicate of every value. So visiting this... **home.aspx?test=test&test2=test2** becomes **home.aspx?test=test&test2=test2&referrerurl=home.aspx?test=test&test2=test2** Now, URL Encoding the referrer would sort the issue but i've more chance of being molested by a gorilla; so the question stands. How do I dedupe the output from .QueryString ? Currently I'm using this ... ``` private string queryClean(string entity) { try { if(Request.QueryString["referrerUrl"] != null){ string[] Split = entity.Split(new Char[] { ',' }); string tmpValue = Convert.ToString(Split[0]); return tmpValue; }else{ return entity; } } catch (Exception cleanError) { errors.Text += "-clean-" + cleanError + "-endclean-"; return entity; } } ``` (ignore the try/catch we have app level error catching, but I'm still playing with it). I'm using C# .net 2 Thanks --- [Additional Info] The reffererURL will always be on the end of the string so it could be possible to delete all of the query string after this point? I've tried using ``` string test = Convert.ToString(Request.QueryString); string[] tRSplit = Regex.Split(test, "&referrerUrl"); Response.Write(tRSplit[0]); ``` and... ``` System.Collections.Generic.List<string> testb = new System.Collections.Generic.List<string>(Convert.ToString(Request.QueryString).Split('&')); for (int i = 0; i < testb.Count; i++) { Response.Write(i +": "+ testb[i].ToString()+"<br><br>"); } ``` Both still produce the duplicates --- I could use [Trim](http://www.developerfusion.com/code/4398/string-manipulation-in-c/) But is there a cleaner/faster way of achieving this.
**[Example URL]** Default2.aspx?test=test&test2=test2&referrerURL=<http://www.test.com/home.aspx?test=test&test=test> **[This Would Produce]** test=test test=test test2=test2 referrerURL=<http://www.test.com/home.aspx?test=test> **[So an edited version of gustafc's answer...]** ``` //Capture the raw url test = Request.RawUrl.ToString(); //Set the start index as 1 after the query ? int startTxt = (test.IndexOf("?") + 1); //Find the number of characters between ? and &referrerURL int countTxt = ((test.IndexOf("&referrerURL")-1) - test.IndexOf("?")); //Capture the substring and split into a string array using & string[] aTest = test.Substring(startTxt, countTxt).Split(new Char[] { '&' }); ``` **[Running a test produces the following]** -0~test=test -1~test2=test2 **[Which is what I expected to recieve]** ***(for completeness heres the simple for statement)*** ``` for (int i = 0; i < aTest.Length; i++) { Response.Write("<br>-" + i + "~" + Convert.ToString(aTest[i]) + "<br>"); } ```
Something like this should work: ``` NameValueCollection fixedQueryString = new NameValueCollection(); foreach (string key in Request.QueryString.Keys) { string value = Request.QueryString[key]; if(value.Contains(",")) { value = value.Split(',')[0]; } fixedQueryString.Add(key, value); } ``` This code will create a new NameValueCollection where we rebuild the query string. We then check each value for a , which usually indicates that a value is repeated more than once. For instance the url home.aspx?test=test&test2=test2&referrerurl=home.aspx?test=test&test2=test2 will generate the value "test, test" for the query string value "test".
Whats the quickest way to dedupe a querystring in C# (ASP.net)
[ "", "c#", "asp.net-2.0", "query-string", "" ]
I have a problem with the .NET's Uri implementation. It seems that if the scheme is "ftp", the query part is not parsed as a Query, but as a part of the path instead. Take the following code for example: ``` Uri testuri = new Uri("ftp://user:pass@localhost/?passive=true"); Console.WriteLine(testuri.Query); // Outputs an empty string Console.WriteLine(testuri.AbsolutePath); // Outputs "/%3Fpassive=true" ``` It seems to me that the Uri class wrongfully parses the query part as a part of the path. However changing the scheme to http, the result is as expected: ``` Uri testuri = new Uri("http://user:pass@localhost/?passive=true"); Console.WriteLine(testuri.Query); // Outputs "?passive=true" Console.WriteLine(testuri.AbsolutePath); // Outputs "/" ``` Does anyone have a solution to this, or know of an alternative Uri class that works as expected?
Well, the problem is not that I am unable to create a FTP connection, but that URI's are not parsed accoding to RFC 2396. What I actually intended to do was to create a Factory that provides implementations of a generic File transfer interface (containing get and put methods), based on a given connection URI. The URI defines the protocol, user info, host and path, and any properties needed to be passed should be passed through the Query part of the URI (such as the Passive mode option for the FTP connection). However this proved difficult using the .NET Uri implementation, because it seems to parse the Query part of URI's differently based on the schema. So I was hoping that someone knew a workaround to this, or of an alternative to the seemingly broken .NET Uri implementation. Would be nice to know before spending hours implementing my own.
I have been struggling with the same issue for a while. Attempting to replace the existing UriParser for the "ftp" scheme using `UriParser.Register` throws an `InvalidOperationException` because the scheme is already registered. The solution I have come up with involves using reflection to modify the existing ftp parser so that it allows the query string. This is based on a workaround to [another UriParser bug](http://connect.microsoft.com/VisualStudio/feedback/details/386695/system-uri-incorrectly-strips-trailing-dots#). ``` MethodInfo getSyntax = typeof(UriParser).GetMethod("GetSyntax", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); FieldInfo flagsField = typeof(UriParser).GetField("m_Flags", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); if (getSyntax != null && flagsField != null) { UriParser parser = (UriParser)getSyntax.Invoke(null, new object[] { "ftp"}); if (parser != null) { int flagsValue = (int)flagsField.GetValue(parser); // Set the MayHaveQuery attribute int MayHaveQuery = 0x20; if ((flagsValue & MayHaveQuery) == 0) flagsField.SetValue(parser, flagsValue | MayHaveQuery); } } ``` Run that somewhere in your initialization, and your ftp Uris will have the query string go into the `Query` parameter, as you would expect, instead of `Path`.
Alternative to .NET's Uri implementation?
[ "", "c#", ".net", "ftp", "uri", "" ]
It has been quite a while since I am getting this error in the standard <cstring> header file for no apparent reason. A google search brought up many answers but none of them worked.
Ok I fixed it myself. It was a stupid mistake! I have a file called "String.h" in a library project which is being picked up by the <cstring> header. Probably because I have added the path to <String.h> as an additional include directory in my test project (where I am getting this error.) Hope this helps someone.
Your compiler may be (correctly) placing the memchr function in the C++ std namespace. Try prefixing memchr call with std:: and if that fails, post the code that causes the problem.
error C2039: 'memchr' : is not a member of '`global namespace''
[ "", "c++", "" ]
I recently set up, for a learning exercise, an Ubuntu desktop PC with KDE 4.2, installed Eclipse and started to look for information on how to develop for KDE. I know there's KDevelop and will probably have a look at that at some time in the future. Right now, however, I don't have the correct headers and libraries for creating KDE applications in C/C++ using Eclipse. If I have the following: ``` #include <kapplication.h> ``` it fails to compile since there are dependancies on other header files that are not present on my hard disk or reference classes that aren't declared anywhere. So, the question is, what packages do I need to install in order to have the correct set of headers to allow me to write applications for KDE 4.2? Are there any packages I shouldn't have? Alternatively, if there are no packages then where can I get the appropriate files? As a corollary, are there any good tutorials on KDE development, something like the Petzold Windows book? EDIT: Clarifying what I'm really after: where can I download the correct set of header files / libraries in order to build a KDE application? IDEs to compile code aren't a real problem and are easy to get, as is setting up compiler options for include search paths and so on. Does the KDevelop package have all the correct include and library files or are they separate? I guess they are separate as KDevelop is an IDE that can do other languages as well, but I'm probably wrong. So, the KDE/Qt header files I have don't work, where do I get the right ones? Skizz
Make sure you have installed the *build-essential* package. For more documentation available from the command line, install glibc-doc, manpages-dev, gcc-\*-doc, libstdc++\*-doc (replace '\*' with suitable version numbers for your system) [Getting Started/Build/KDE4/Kubuntu and Debian](https://techbase.kde.org/Getting_Started/Build/KDE4/Kubuntu_and_Debian) had a pair of `sudo aptitude install` commands which I used to get some required packages. I also got the KDevelop and QDevelop applications, although I'm not sure they are required. There was also another package I needed (kdelibs5-dev) and this one appears to be the key package. Everything eventually worked after getting that one. Eclipse and KDevelop were both happy building a simple application once the compiler settings were set up; Eclipse required setting search paths and library filenames. From first impressions, Eclipse appears better than KDevelop for the single reason that the tool windows in Eclipse can be detached from the main window and float - useful on a dual monitor setup. I couldn't see anyway to do that in KDevelop (I'm sure someone will comment on how to do this).
You might have some clue as to what include in your `.classpath` and `.project` files if you have a look and examine the [content of the **CMake**](http://techbase.kde.org/Development/Tutorials/CMake) used for developing application for KDE4.2 I believe the development section of their KDE site is quite complete when it comes to explain their development environment. [![alt text](https://i.stack.imgur.com/JKBZN.png)](https://i.stack.imgur.com/JKBZN.png) (source: [kde.org](http://techbase.kde.org/images/thumb/2/25/Action_configure.svg/40px-Action_configure.svg.png)) especially their [Programming tutorials](http://techbase.kde.org/Development/Tutorials) section.
How to set up headers and libraries for Linux development
[ "", "c++", "linux", "eclipse", "ubuntu", "kde-plasma", "" ]
I have a number of stored procedures I call from code with `ExecuteNonQuery`. It was all good but 2 of my stored procedures started timing out intermittently today with: > Timeout expired. The timeout period > elapsed prior to completion of the > operation or the server is not > responding. The statement has been > terminated. If I execute the sp manually from management studio it's still all good. Nothing recently changed in my db - my command timeout is the default one. Any clue? **EDIT** the table against the SPs are running it's huge --> 15 Gigs. Rebooted the box - same issue but this time can't get the sp to run from Management Studio either. Thanks!
Ok - this is how I fixed it in the end. A clustered index on a table with 45 million records was killing my SQL server - every insert from code was resulting in the nasty timeouts described in the answer. Increasing the timeout tolerance wasn't gonna solve my scalability issues so I played around with indexes and making the clustered index on the primary key **nonclustered** unlocked the situation. I'd appreciate comments on this to better understand how this fixed the problem.
Try to recompile these procedures. I've such problems few times and didn't find the cause of problem, but recompiling always helps. EDIT: To recompile proc, you go to management studio, open procedure to modify and hit F5 or execute: EXEC sp\_recompile 'proc\_name'
Stored procedures are timing out intermittently!
[ "", "sql", "sql-server", "stored-procedures", "timeout", "sql-server-2000", "" ]