Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I understand overriding a method/function redefines its implementation in the derived class from its implementation in the base class. Now what confuses me, is if I override a class in ASP.NET such as `CreateChildControls()` (I picked it randomly for no particular reason), VS2008 auto generates: ``` protected override void CreateChildControls() { base.CreateChildControls(); } ``` Good enough, the default implementation just calls the base class' `CreateChildControls()`. So if I want to run some code, since I do not know how `base.CreateChildControls()`, should I do this: ``` protected override void CreateChildControls() { /*My Code Here*/ base.CreateChildControls(); } ``` or, ignore what `base.CreateChildControls()` altogether and just do ``` protected override void CreateChildControls() { /*My Code Here*/ } ```
That's up to you. Generally, you want to call the base class method because it might do a lot of stuff you're not privy to (especially in a class you don't control .. get it? Control.) But, if you are very confident you don't need (or want) the base class "stuff" to happen, you can remove the call.
It's simply a question of whether you want to entirely replace the behavior or add behavior. For something like CreateChildControls, you will probably retain the call to the base class.
Should I call the base class implementation when overriding a method in C# for ASP.NET?
[ "", "c#", "asp.net", "oop", "overriding", "" ]
Does anyone know of *real* (i.. no vaporware) implementations of ECMAScript targeting the **.NET CLR/DLR**? Ideally something like **what Rhino is for Java**. A solid port of Rhino running on .NET Framework / Mono Framework would be perfect. I've only seen a handful of projects mentioned but never seen any come to light or in reality anything that I've ever been able to run script on. Here's what I know about already: * **[MSScriptControl ActiveX Control](http://msdn.microsoft.com/en-us/library/hbxc2t98(VS.85).aspx)**: AFAIK, this was Microsoft's last real ECMAScript-compliant implementaiton (runs JScript 5.7). I've integrated with MSScriptControl but don't consider COM interop to be an answer to this question. x64 is a killer for this option. * **[JScript.NET](http://www.west-wind.com/WebLog/posts/10688.aspx)**: I don't count JScript.NET as it could never successfully parse any of my real scripts. It seems to have trouble with closures. * **[Managed JScript](http://en.wikipedia.org/wiki/JScript#Managed_JScript)**: Sounds like what I want but it appears to be dead in the water. It was a major example implementation for the DLR but then got entangled with SilverLight and seems to have faded as a priority since 2007. Creditable sources on the status of this would be helpful. * **[MyJScript](http://myjscript.codeplex.com/)**: Built as a tutorial implementation for the DLR. Anyone know how complete of an implementation this is? * **[Jint](http://jint.codeplex.com/)**: JavaScript interpreter for .NET. Doesn't as of yet support Currying or `try`-`catch`-`finally`. * **[RemObjects Script for .NET](http://www.remobjects.com/roscript.aspx)**: An interesting contender still in the works. I'm confused by their marketing as to what it will actually be, but it sounds like it might eventually be a fit. If anyone knows more about it that would be helpful as well. * **[V8 for .NET](https://stackoverflow.com/questions/356948/referencing-googles-v8-engine-from-a-net-app)**: This would be great if someone ported V8 to .NET. As far as I know there isn't a large effort around this either. The link is to an idea for calling into it from a managed C++ wrapper. For background, I want to be able to execute JavaScript from within .NET; i.e. load up a set of scripts into context and call into that context and retrieve the execution results. Currently I jump through hoops to use MSScriptControl via cumbersome COM Interop. The inconsistency of COM makes it really tough for deployment and ensuring consistent execution. I'd like to be able to execute reasonably complex JavaScript test harnesses from within .NET. This isn't for creating user macros or simple tiny scripts; I need a real JavaScript environment like Rhino. If the implementation was running on top of the CLR (rather than COM) this would really help with some of the current issues.
Currently, I've modified a version of the [EcmaScript.NET](http://code.google.com/p/ecmascript-net/) inside my [YUICompressor.NET](http://yuicompressor.codeplex.com/) port (project). If you grab the [source code from here](http://yuicompressor.codeplex.com/SourceControl/ListDownloadableCommits.aspx), I've included my modified code in the project, which you can reference. This is the only source of code i've found in .NET which can handle parsing javascript, server side. Unfortunately, I can't remember how I finally found it. It was a tough process, I must admit. I think i found some references Mozilla dev pages somewhere about Rhino (the java code) which led me to finding that C# .NET implimentation. I had to modify it slighty to sync up with some changes the YUI Compressor guys did to their code branch. So the modified branch I have might not be the best .. but it's the closest I've seen to the original Java branch. The original c# code for EcmaScript.NET hasn't been touched since 2007 ... at least for the downloads page. Maybe this might help?? HTH.
Still Roughly alive: * [Jurassic](http://jurassic.codeplex.com/) (Had a commit within the last year.) * [Jint](https://github.com/sebastienros/jint) (currently taking pull requests.) Other Projects, Mostly Dead: * [IronJS](http://github.com/fholm/IronJS): A DLR-hosted JS Implementation; [IronJS Google Group](http://groups.google.com/group/ironjs). (Last commit was in 2013, last [blog update](http://ironjs.wordpress.com/) in 2012.) * [Managed JScript](http://blogs.msdn.com/deepak/archive/2007/05/02/managed-jscript-is-availaible.aspx): Died [on the vine](http://dlr.codeplex.com/Thread/View.aspx?ThreadId=58121). * MyJScript: Mentioned in the original post, for those who want more info, there's an article : [Create your own language on top of the DLR](http://www.dotnetguru.org/us/dlrus/DLR2.htm). * [MonoJS](http://www.mono-project.com/JScript): Mono had an implementation of JScript.Net, but they quit bothering. Crazy Method: * [Rhino over IKVM](http://www.codeproject.com/KB/cs/EmbeddingJSCS.aspx) (Mentioned in comments, but here's a link to more information about doing it.)
Are there any .NET CLR/DLR implementations of ECMAScript?
[ "", ".net", "javascript", "clr", "dynamic-language-runtime", "ecma262", "" ]
Consider the following example. I have an interface MyInterface, and then two abstract classes MyAbstractClass1 and MyAbstractClass2. MyAbstractClass1 implements MyInterface, but MyAbstractClass2 does not. Now I have three concrete classes. 1. MyConcreteClass1 is derived from MyAbstractClass1 but does not implement MyInterface. 2. MyConcreteClass2 is derived from MyAbstractClass2, but does implement MyInterface. 3. MyConcreteClass3 is derived from MyAbstractClass1, and does implement MyInterface. Does ConcreteClass1 also implicitly implement MyInterface because it derives from MyAbstractClass1? Assuming MyAbstractClass1 implements the methods of MyInteface implicitly then ConcreteClass1 should not have to be cast to a MyInterface to access the MyInteface methods right? MyAbstractClass1 can implicitly implement a method of MyInterface as an abstract method, but can't explicitly implement a method of MyInterface as an abstract method. Why is this? Is MyConcreteClass3 excessive because it's implementing an interface that is already implemented by its base class? Would there be a reason you would want to do that even if you knew all classes that derive from MyAbstractClass1 should also implement MyInterface. Here's a class diagram [alt text http://files.getdropbox.com/u/113068/abstractclassesandinterfaces.png](http://files.getdropbox.com/u/113068/abstractclassesandinterfaces.png) Here's the code: ``` //interface public interface MyInterface { void MyMethodA(); void MyMethodB(); void MyMethodC(); } //abstract classes public abstract class MyAbstractClass1 : MyInterface { public void MyMethodA() { } void MyInterface.MyMethodB() { } //Error: "the modifier abstract is not valid for this item" //abstract void MyInterface.MyMethodC(); //This works public abstract void MyMethodC(); public abstract void MyMethodZ(); } public abstract class MyAbstractClass2 { public void MyMethodX() { } public abstract void MyMethodY(); } //Concrete classes //ConcreteClass 1: Only Abstract class implements the interface public class ConcreteClass1 : MyAbstractClass1 { public override void MyMethodC() { } public override void MyMethodZ() { } } //ConcreteClass 1: Only Concrete class implements the interface public class ConcreteClass2 : MyAbstractClass2, MyInterface { public override void MyMethodY() { } public void MyMethodA() { } public void MyMethodB() { } public void MyMethodC() { } } //ConcreteClass 1: Both concrete and abstract class implement the interface public class ConcreteClass3 : MyAbstractClass1, MyInterface { public override void MyMethodC() { } public override void MyMethodZ() { } } ```
> Does ConcreteClass1 also implicitly implement MyInterface because it derives from MyAbstractClass1? Yes. > ConcreteClass1 should not have to be cast to a MyInterface to access the MyInteface methods right? Correct. `(myConcreteClass1 is MyInterface)` will evaluate `true`. > MyAbstractClass1 can implicitly implement a method of MyInterface as an abstract method, but can't explicitly implement a method of MyInterface as an abstract method. Explicit implementation is to distinguish between overlapping member signatures. The explicit implementation is private to the class you are implementing it on, so it is not accessible to derived classes (and thus cannot be abstract). You also cannot force classes which derive from MyAbstractClass1 to explicitly implement MyInterface, so there is no way to ensure the abstract member will ever be implemented. > Is MyConcreteClass3 excessive because it's implementing an interface that is already implemented by its base class? Would there be a reason you would want to do that even if you knew all classes that derive from MyAbstractClass1 should also implement MyInterface. Not necessarily, If you need to explicitly implement a member of the interface to distinguish it from an overlapping member on MyConcreteClass3. Otherwise it is unnecessary.
In this case, all three classes implement the interface (directly or indirectly). This is because MyAbstractClass1 implements MyInterface, and since MyConcreteClass1 derives from MyAbstractClass1, it also follows that you can treat MyConcreteClass1 as a MyInterface. MyConcreteClass2 can be treated with something that derives from MyAbstractClass1, as long as you treat it as a MyInterface. the derivation from MyInterface in ConcreteClass3 is a bit redundant since MyAbstractClass1 already implements MyInterface. With all of that information, i'd say that yes, it is redundant to implement MyInterface on MyConcreteClass3 since it derives from MyAbstractClass1 which already implements MyInterface. I think the reason that you cant have an abstract implementation of an interface method is that it provides no code itself and you cannot guarantee that it will be overriden in subcalsses. Use Virtual instead.
Need help understanding abstract classes that implement an interface
[ "", "c#", "inheritance", "interface", "abstract-class", "" ]
What's the difference between implicit exception and explicit exception? If I declare catch block like: catch(Exception e). Is this implicitly declaring an exception, or explicitly? Thanks in advance.
I don't believe there's any such term as "implicit exception" or "explicit exception". Are you thinking checked and unchecked exceptions perhaps? I've just downloaded the language specification as a PDF, and the phrases "implicit exception" and "explicit exception" don't exist anywhere within it. Could you say where you came across the terms?
I think implicitly instantiating an object is done without explicitly calling a constructor. I don't think you can do that in Java. Example: ``` throw new Exception(); ``` calls a constructor and then throws the newly created `Exception` object.
Implicit and explicit exception difference
[ "", "java", "" ]
Hey. I have a very large array and I want to find the Nth largest value. Trivially I can sort the array and then take the Nth element but I'm only interested in one element so there's probably a better way than sorting the entire array...
Sorting would require O(nlogn) runtime at minimum - There are very efficient [selection algorithms](http://en.wikipedia.org/wiki/Quick_select) which can solve your problem in linear time. `Partition-based selection` (sometimes `Quick select`), which is based on the idea of quicksort (recursive partitioning), is a good solution (see link for pseudocode + [Another example](http://goanna.cs.rmit.edu.au/~stbird/Tutorials/QuickSelect.html)).
A heap is the best data structure for this operation and Python has an excellent built-in library to do just this, called heapq. ``` import heapq def nth_largest(n, iter): return heapq.nlargest(n, iter)[-1] ``` Example Usage: ``` >>> import random >>> iter = [random.randint(0,1000) for i in range(100)] >>> n = 10 >>> nth_largest(n, iter) 920 ``` Confirm result by sorting: ``` >>> list(sorted(iter))[-10] 920 ```
Finding Nth item of unsorted list without sorting the list
[ "", "python", "arrays", "sorting", "" ]
As title: is size\_t always unsigned, i.e. for `size_t x`, is `x` always `>= 0` ?
**Yes**. It's *usually* defined as something like the following (on 32-bit systems): ``` typedef unsigned int size_t; ``` Reference: C++ Standard Section 18.1 defines `size_t` is in `<cstddef>` which is described in C Standard as `<stddef.h>`. C Standard Section 4.1.5 defines `size_t` as an unsigned integral type of the result of the `sizeof` operator
According to the 1999 ISO C standard (C99), `size_t` is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3). The standard also recommends that `size_t` shouldn't have an integer conversion rank greater than `long` if possible, ie casting `size_t` to `unsigned long` is unproblematic if the recommendation is followed. The 1989 ANSI C standard (ANSI C) doesn't mention a minimal size or recommended conversion rank. The 1998 ISO C++ standard (C++98) (as well as the current draft for C++0x) refers to the C standard. Section 18.1 reads: > The contents are the same as the Standard C library header `<stddef.h>` [...] According to section 1.2, this means the library as defined by the 1990 ISO C standard (C90), including its first amendment from 1995 (C95): > The library described in clause 7 of > ISO/IEC 9899:1990 and clause 7 of > ISO/IEC 9899/Amd.1:1995 is hereinafter > called the *Standard C Library*. The parts regarding `size_t` should be inherited from ANSI C: Frontmatter and section numbering aside, the standards for C90 and ANSI C are identical. I'd need a copy of the normative amendment to be sure that there weren't any relevant changes to `stddef.h`, but I doubt it. The minimal size seems to be introduced with `stdint.h`, ie C99. Please also consider the following quote from section 1.2 of C++98: > All standards are subject to revision, > and parties to agreements based on > this International Standard are > encouraged to investigate the > possibility of applying the most > recent editions of the standards > indicated below.
is size_t always unsigned?
[ "", "c++", "standards", "" ]
I have a `DataGridView` where one of the columns is a `DataGridViewComboBoxColumn`. When the grid is populated, that column looks different because of the drop-down arrow appearing on each cell in the column. I'd like to change this so that the drop-down arrow is hidden and only shows up when the row is actually highlighted or when the combobox cell is selected for editing. The behavior I wanted is like how the *Properties* window in *Visual Studio* handles its values.
In the `DataGridViewComboBoxColumn`, there is a property called `DisplayStyle`. Set it to `Nothing` to hide the DropDownButton Further information about the `DataGridViewComboBoxDisplayStyle` enumeration is available at this [MSDN link](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcomboboxdisplaystyle.aspx)
If you set `DataGridViewComboBoxColumn.DisplayStyleForCurrentCellOnly = True`, then the dropdown only appears when the cell is the current cell.
How can I hide the drop-down arrow of a DataGridViewComboBoxColumn like Visual Studio Properties window?
[ "", "c#", ".net", "winforms", "datagridview", "" ]
I want to create and open a file but only if it doesnt exist. I dont want to use a File.Exists because a thread by switch after it creating a file with the same name. How do i check if the exception System.IO.IOException was caused by the file existing? I prefer not to parse the error msg (even tho it can be as simple as .indexOf("exist")) How should i do this?
You should avoid ever making logic decisions based on the contents of the Exception.Message property. That is defined to be a human-readable message, not something for a program to read. Such messages are subject to change without notice. Human-readable messages often change to make them more readable to humans. That won't make your program any happier. --- As you might be able to tell, the issue of program logic depending on human-readable messages is a pet peeve of mine - I won't tell you for how long, since that would make me feel old. This has distracted me from something that should have been obvious. Please check to see if you get a [System.IO.FileNotFoundException](http://msdn.microsoft.com/en-us/library/system.io.filenotfoundexception.aspx) when the file does not exist. Try catching that instead of IOException.
I'm not sure he wants to open the file at all if it already exists. I think he is actually after `FileMode.CreateNew` this will throw an `IOException` if the file already exists, but otherwise will create and open it.
How to detect System.IO.IOException cause by existing file?
[ "", "c#", "asp.net", "exception", "ioexception", "" ]
**Edit:** I put this snippet of code in jsbin: <http://jsbin.com/eneru> --- I am trying to let the user resize (only vertically) a DIV element with jQuery. I read about jQuery UI, I tried it, and in some minutes, I had it working. But the library is adding a ~25KB overhead that I would like to avoid, since I only want simple vertical resizing. So I tried to do it on my own. Here it is the HTML, I am using inline styling for clarity: ``` <div id="frame" style="border: 1px solid green; height: 350px"> <div style="height: 100%">Lorem ipsum blah blah</div> <span id="frame-grip" style="display: block; width: 100%; height: 16px; background: gray"></span> </div> ``` As you can see, there is a little bar under the DIV element, so the user can drag it up or down to resize the DIV. Here it is the Javascript code (using jQuery): ``` $(document).ready(function(){ var resizing = false; var frame = $("#frame"); var origHeightFrame = frame.height(); var origPosYGrip = $("#frame-grip").offset().top; var gripHeight = $("#frame-grip").height(); $("#frame-grip").mouseup(function(e) { resizing = false; }); $("#frame-grip").mousedown(function(e) { resizing = true; }); $("#frame-grip").mousemove(function(e) { if(resizing) { frame.height(e.pageY - origPosYGrip + origHeightFrame - gripHeight/2); } }); }); ``` It works, more or less, but if you drag the bar too fast, it stops following the mouse movement and everything breaks. It is the first time I try to do something *serious* (ahem) with JS and jQuery, so I may be doing something dumb. If so, please do tell me :)
You **are** doing something dumb: You're trying to do it yourself. Hear me out, hear me out: Javascript across browsers is a horrible, horrible thing. There are many engines in many versions with many different operating systems, all of which have many subtleties, all of which make Javascript pretty much hell to work with. There is a perfectly good reason why librabries such as jQuery (and their extensions) have exploded in popularity: a lot of great programmers have spent a lot of hours abstracting all these horrible inconsistencies away so we don't have to worry about it. Now, I am not sure about your user base, maybe you are catering to old housewives that still have dialup. But for the most part in this day and age the 25KB hit on the initial page load (as it will be cached afterwards) for the peace of mind that this is going to work in all browsers consistently is a small price to pay. There is no such thing as "simple" resizing when it comes to Javascript, so you're better off using UI.
I worked on a similar thing and managed to get it to work with maximum and minimum height and to me seems to work very fluid, this was my code. ``` $(document).ready(function() { var resizing = false; var frame = $("#frame").height(); $(document).mouseup(function(event) { resizing = false; frame = $("#frame").height(); }); $("#frame-grip").mousedown(function(event) { resizing = event.pageY; }); $(document).mousemove(function(event) { if (resizing) { $("#frame").height(frame + resizing - event.pageY); } }); }); ``` live example of how I used it, pull the red button, lacked images so i replaced with simple color. <http://jsbin.com/ufuqo/23>
How to let resize vertically a DIV with only jQuery - no plugins?
[ "", "javascript", "jquery", "resize", "" ]
I have an application consisting of different modules written in C++. One of the modules is meant for handling distributed tasks on SunGrid Engine. It uses the DRMAA API for submitting and monitoring grid jobs.If the client doesn't supports grid, local machine should be used The shared object of the API libdrmaa.so is linked at compile time and loaded at runtime. If the client using my application has this ".so" everything is fine but in case the client doesn't have that , the application exits failing to load shared libraries. To avoid this , I have replaced the API calls with function pointers obtained using dlsym() and dlopen(). Now I can use the local machine instead of grid if the call to dlopen doesn't succeeds and my objective is achieved. The problem now is that the application now runs successfully for small testcases but with larger testcases it throws segmentation fault while the same code using dynamic loading works correctly. Am I missing something while using dlsym() and dlopen()? Is there any other way to achieve the same goal? Any help would be appreciated. Thanx,
It is very unlikely to be a direct problem with the code loaded via `dlsym()` - in the sense that the dynamic loading makes it seg-fault. What it may be doing is exposing a separate problem, probably by moving stuff around. This probably means a stray (uninitialized) pointer that points somewhere 'legitimate' in the static link case but somewhere else in the dynamic link case - and the somewhere else triggers the seg-fault. Indeed, that is a benefit to you in the long run - it shows that there is a problem that otherwise might remain undetected for a long time. I regard this as particularly likely since you mention that it occurs with larger tests and not with small ones.
As Jonathan Leffler says, the problem very likely exists in the case where you are using the API directly; it just hasn't caused a crash yet. Your very first step when you get a `SIGSEGV` should be analyzing the resulting core dump (or just run the app directly under debugger), and looking *where* it crashed. I'll bet $0.02 that it's crashing somewhere inside `malloc` or `free`, in which case the problem is plain old heap corruption, and there are many heap-checker tools available to help you catch it. Solaris provides [`watchmalloc`](http://docs.oracle.com/cd/E23823_01/html/816-5168/watchmalloc-3malloc.html#scrolltoc), which is a good start.
Problem in using C dynamic loading routines
[ "", "c++", "shared-libraries", "sungridengine", "dlsym", "drmaa", "" ]
What's the best data structure (in java) for the task of loading 51 million primes and then iterating over them? I need to know, for example, the primes that are between 1000000000 and that same number minus 100000.
A binary search isn't going to be wonderful for this data, since the first half of the primes are going to be closer to each other than the last half of them. You might be able to improve on your search by knowing [how many primes there are under x](http://primes.utm.edu/howmany.shtml). Maybe skew the cut by using the approximation mentioned in the link. --- My first try would be this. I'd have two arrays. 1. An array of all the primes. 2. An array that tells me where in the first array the first prime above 1000\*n was. So if I wanted to find the first prime with a value of 5000 or more, I'd look at secondArray[5000/1000-1]. I'd get a rough position with array 2 before doing anything with array 1.
Why store them in a map at all? Is this so you have fast lookup to see if any given number is a prime? That would make sense and give you fast access. The cost of adding them can be mitigated (but not eliminated) by setting the initial capacity of the TreeMap. This will still incur tree rebalancing costs however. An alternative storage might be simply to sort them and put them in an array. This will give you O(log n) lookup with a bisection search but will make getting ranges trivial. You can use [Arrays.binarySearch()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#binarySearch%28int%5B%5d,%20int%29).
Iterating over a data structure with 51 million primes quickly
[ "", "java", "data-structures", "primes", "" ]
I have a PHP page I need to limit execution access of to only clients inside our firewall. How would I write a php-script that can look up the clients ip-address and match it to a ip-range (for instance 10.*.*.\* or 200.10.10.\*).
You can use [ip2long](http://php.net/ip2long) to convert dotted quads to long values, then just perform some arithmetic to check a given network/mask combination: ``` $network=ip2long("200.10.10.0"); $mask=ip2long("255.255.255.0"); $remote=ip2long($_SERVER['REMOTE_ADDR']); if (($remote & $mask) == $network) { //match! } else { //does not match! } ```
Well, assuming you're using Apache, there's a module called mod\_authz\_host that you can use. Together with the file directive, you could limit access to a given php script for a range of ip addresses. Here is the link to the documentation on that module: <http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html> Here's a quick example (assuming your php file is called admin.php): ``` <file admin.php> Order Deny,Allow Deny from all Allow from 200.10.10 </file> ``` The added benefit to the other solution suggested here is that you can control the security aspects from outside your application logic - a more flexible approach that does not impose any limitations on your PHP code.
Limit execution of a php-page to requests made from a certain ip-range
[ "", "php", "security", "ip-address", "access-control", "" ]
**I have a piece of code with a) which I replaced with b) purely for legibility ...** **a)** ``` if ( WORD[ INDEX ] == 'A' ) branch = BRANCH.A; /* B through to Y */ if ( WORD[ INDEX ] == 'Z' ) branch = BRANCH.Z; ``` **b)** ``` switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A; break; /* B through to Y */ case 'Z' : branch = BRANCH.Z; break; } ``` ### ... will the switch version cascade through all the permutations or jump to a case ? EDIT: *Some of the answers below regard alternative approaches to the approach above.* *I have included the following to provide context for its use.* *The reason I asked, the Question above, was because the speed of adding words empirically improved.* *This isn't production code by any means, and was hacked together quickly as a PoC.* *The following seems to be a confirmation of failure for a thought experiment.* *I may need a much bigger corpus of words than the one I am currently using though.* *The failure arises from the fact I did not account for the null references still requiring memory.* ( doh ! ) ``` public class Dictionary { private static Dictionary ROOT; private boolean terminus; private Dictionary A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z; private static Dictionary instantiate( final Dictionary DICTIONARY ) { return ( DICTIONARY == null ) ? new Dictionary() : DICTIONARY; } private Dictionary() { this.terminus = false; this.A = this.B = this.C = this.D = this.E = this.F = this.G = this.H = this.I = this.J = this.K = this.L = this.M = this.N = this.O = this.P = this.Q = this.R = this.S = this.T = this.U = this.V = this.W = this.X = this.Y = this.Z = null; } public static void add( final String...STRINGS ) { Dictionary.ROOT = Dictionary.instantiate( Dictionary.ROOT ); for ( final String STRING : STRINGS ) Dictionary.add( STRING.toUpperCase().toCharArray(), Dictionary.ROOT , 0, STRING.length() - 1 ); } private static void add( final char[] WORD, final Dictionary BRANCH, final int INDEX, final int INDEX_LIMIT ) { Dictionary branch = null; switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A = Dictionary.instantiate( BRANCH.A ); break; case 'B' : branch = BRANCH.B = Dictionary.instantiate( BRANCH.B ); break; case 'C' : branch = BRANCH.C = Dictionary.instantiate( BRANCH.C ); break; case 'D' : branch = BRANCH.D = Dictionary.instantiate( BRANCH.D ); break; case 'E' : branch = BRANCH.E = Dictionary.instantiate( BRANCH.E ); break; case 'F' : branch = BRANCH.F = Dictionary.instantiate( BRANCH.F ); break; case 'G' : branch = BRANCH.G = Dictionary.instantiate( BRANCH.G ); break; case 'H' : branch = BRANCH.H = Dictionary.instantiate( BRANCH.H ); break; case 'I' : branch = BRANCH.I = Dictionary.instantiate( BRANCH.I ); break; case 'J' : branch = BRANCH.J = Dictionary.instantiate( BRANCH.J ); break; case 'K' : branch = BRANCH.K = Dictionary.instantiate( BRANCH.K ); break; case 'L' : branch = BRANCH.L = Dictionary.instantiate( BRANCH.L ); break; case 'M' : branch = BRANCH.M = Dictionary.instantiate( BRANCH.M ); break; case 'N' : branch = BRANCH.N = Dictionary.instantiate( BRANCH.N ); break; case 'O' : branch = BRANCH.O = Dictionary.instantiate( BRANCH.O ); break; case 'P' : branch = BRANCH.P = Dictionary.instantiate( BRANCH.P ); break; case 'Q' : branch = BRANCH.Q = Dictionary.instantiate( BRANCH.Q ); break; case 'R' : branch = BRANCH.R = Dictionary.instantiate( BRANCH.R ); break; case 'S' : branch = BRANCH.S = Dictionary.instantiate( BRANCH.S ); break; case 'T' : branch = BRANCH.T = Dictionary.instantiate( BRANCH.T ); break; case 'U' : branch = BRANCH.U = Dictionary.instantiate( BRANCH.U ); break; case 'V' : branch = BRANCH.V = Dictionary.instantiate( BRANCH.V ); break; case 'W' : branch = BRANCH.W = Dictionary.instantiate( BRANCH.W ); break; case 'X' : branch = BRANCH.X = Dictionary.instantiate( BRANCH.X ); break; case 'Y' : branch = BRANCH.Y = Dictionary.instantiate( BRANCH.Y ); break; case 'Z' : branch = BRANCH.Z = Dictionary.instantiate( BRANCH.Z ); break; } if ( INDEX == INDEX_LIMIT ) branch.terminus = true; else Dictionary.add( WORD, branch, INDEX + 1, INDEX_LIMIT ); } public static boolean is( final String STRING ) { Dictionary.ROOT = Dictionary.instantiate( Dictionary.ROOT ); return Dictionary.is( STRING.toUpperCase().toCharArray(), Dictionary.ROOT, 0, STRING.length() - 1 ); } private static boolean is( final char[] WORD, final Dictionary BRANCH, final int INDEX, final int INDEX_LIMIT ) { Dictionary branch = null; switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A; break; case 'B' : branch = BRANCH.B; break; case 'C' : branch = BRANCH.C; break; case 'D' : branch = BRANCH.D; break; case 'E' : branch = BRANCH.E; break; case 'F' : branch = BRANCH.F; break; case 'G' : branch = BRANCH.G; break; case 'H' : branch = BRANCH.H; break; case 'I' : branch = BRANCH.I; break; case 'J' : branch = BRANCH.J; break; case 'K' : branch = BRANCH.K; break; case 'L' : branch = BRANCH.L; break; case 'M' : branch = BRANCH.M; break; case 'N' : branch = BRANCH.N; break; case 'O' : branch = BRANCH.O; break; case 'P' : branch = BRANCH.P; break; case 'Q' : branch = BRANCH.Q; break; case 'R' : branch = BRANCH.R; break; case 'S' : branch = BRANCH.S; break; case 'T' : branch = BRANCH.T; break; case 'U' : branch = BRANCH.U; break; case 'V' : branch = BRANCH.V; break; case 'W' : branch = BRANCH.W; break; case 'X' : branch = BRANCH.X; break; case 'Y' : branch = BRANCH.Y; break; case 'Z' : branch = BRANCH.Z; break; } if ( branch == null ) return false; if ( INDEX == INDEX_LIMIT ) return branch.terminus; else return Dictionary.is( WORD, branch, INDEX + 1, INDEX_LIMIT ); } } ```
In bytecode there are two forms of switch: `tableswitch` and `lookupswitch`. One assumes a dense set of keys, the other sparse. See the description of [compiling switch in the JVM spec](http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14942). For enums, the ordinal is found and then the code continues as the `int` case. I am not entirely sure how the proposed `switch` on `String` little feature in JDK7 will be implemented. However, heavily used code is typically compiled in any sensible JVM. The optimiser is not entirely stupid. Don't worry about it, and follow the usual heuristics for optimisation.
Don't worry about performance; use the syntax that best expresses what you're doing. Only after you have (a) demonstrated a performance deficiency; and (b) localized it to the routine in question, only then should you worry about performance. For my money, the case syntax is more appropriate here.
Java: If vs. Switch
[ "", "java", "comparison", "switch-statement", "if-statement", "" ]
I'm looking for a container that maps from a double to object pointers. However, each key is simply a range of doubles that would correspond to that object. For example, there could be a key/value pair that's <(0.0 3.0), ptr>, or <(3.5 10.0), ptr2> container[1.0] should return ptr, container[3.0] should also return ptr, and container[-1.0] should be undefined. Is there any object with similar behaviour by default or will I have to implement it myself? **Edit** Here's the actual code that I've written, it might be easier to debug/offer advice on it. ``` // Behavior: A range is defined mathematically as (min, max] class dblRange { public: double min; double max; dblRange(double min, double max) { this->min = min; this->max = max; }; dblRange(double val) { this->min = val; this->max = val; }; int compare(const dblRange rhs) { // 1 if this > rhs // 0 if this == rhs //-1 if this < rhs if (rhs.min == rhs.max && min == max) { /*if (min > rhs.min) return 1; else if (min == rhs.min) return 0; else return -1;*/ throw "You should not be comparing values like this. :(\n"; } else if (rhs.max == rhs.min) { if (min > rhs.min) return 1; else if (min <= rhs.min && max > rhs.min) return 0; else // (max <= rhs.min) return -1; } else if (min == max) { if (min >= rhs.max) return 1; else if (min < rhs.max && min >= rhs.min) return 0; else // if (min < rhs.min return -1; } // Check if the two ranges are equal: if (rhs.min == min && rhs.max == max) { return 0; } else if (rhs.min < min && rhs.max <= min) { // This is what happens if rhs is fully lower than this one. return 1; } else if (rhs.min > min && rhs.min >= max) { return -1; } else { // This means there's an undefined case. Ranges are overlapping, // so comparisons don't work quite nicely. throw "Ranges are overlapping weirdly. :(\n"; } }; int compare(const dblRange rhs) const { // 1 if this > rhs // 0 if this == rhs //-1 if this < rhs if (rhs.min == rhs.max && min == max) { /*if (min > rhs.min) return 1; else if (min == rhs.min) return 0; else return -1;*/ throw "You should not be comparing values like this. :(\n"; } else if (rhs.max == rhs.min) { if (min > rhs.min) return 1; else if (min <= rhs.min && max > rhs.min) return 0; else // (max <= rhs.min) return -1; } else if (min == max) { if (min >= rhs.max) return 1; else if (min < rhs.max && min >= rhs.min) return 0; else // if (min < rhs.min return -1; } // Check if the two ranges are equal: if (rhs.min == min && rhs.max == max) { return 0; } else if (rhs.min < min && rhs.max <= min) { // This is what happens if rhs is fully lower than this one. return 1; } else if (rhs.min > min && rhs.min >= max) { return -1; } else { // This means there's an undefined case. Ranges are overlapping, // so comparisons don't work quite nicely. throw "Ranges are overlapping weirdly. :(\n"; } }; bool operator== (const dblRange rhs ) {return (*this).compare(rhs)==0;}; bool operator== (const dblRange rhs ) const {return (*this).compare(rhs)==0;}; bool operator!= (const dblRange rhs ) {return (*this).compare(rhs)!=0;}; bool operator!= (const dblRange rhs ) const {return (*this).compare(rhs)!=0;}; bool operator< (const dblRange rhs ) {return (*this).compare(rhs)<0;}; bool operator< (const dblRange rhs ) const {return (*this).compare(rhs)<0;}; bool operator> (const dblRange rhs ) {return (*this).compare(rhs)>0;}; bool operator> (const dblRange rhs ) const {return (*this).compare(rhs)>0;}; bool operator<= (const dblRange rhs ) {return (*this).compare(rhs)<=0;}; bool operator<= (const dblRange rhs ) const {return (*this).compare(rhs)<=0;}; bool operator>= (const dblRange rhs ) {return (*this).compare(rhs)>=0;}; bool operator>= (const dblRange rhs ) const {return (*this).compare(rhs)>=0;}; }; ``` Right now I'm having trouble having the map accept a double as a key, even though the comparison operators are defined. Here's some driving code that I'm using to test if it would work: ``` std::map<dblRange, int> map; map[dblRange(0,1)] = 1; map[dblRange(1,4)] = 2; map[dblRange(4,5)] = 3; map[3.0] = 4; ```
Create a class `DoubleRange` to store the double range, and implement the comparison operators on it. That way, `std::map` will do the rest for you, with the `DoubleRange` class as the key.
I mostly agree with Earwicker in that you can define a range. Now, I am in favor of implementing operators with the real meaning (do what basic types do: two ranges compare equal if both ranges ARE equal). Then you can use the third map parameter to pass it a comparison functor (or function) that solves your particular problem with this map. ``` // Generic range, can be parametrized for any type (double, float, int...) template< typename T > class range { public: typedef T value_type; range( T const & center ) : min_( center ), max_( center ) {} range( T const & min, T const & max ) : min_( min ), max_( max ) {} T min() const { return min_; } T max() const { return max_; } private: T min_; T max_; }; // Detection of outside of range to the left (smaller values): // // a range lhs is left (smaller) of another range if both lhs.min() and lhs.max() // are smaller than rhs.min(). template <typename T> struct left_of_range : public std::binary_function< range<T>, range<T>, bool > { bool operator()( range<T> const & lhs, range<T> const & rhs ) const { return lhs.min() < rhs.min() && lhs.max() <= rhs.min(); } }; int main() { typedef std::map< range<double>, std::string, left_of_range<double> > map_type; map_type integer; // integer part of a decimal number: integer[ range<double>( 0.0, 1.0 ) ] = "zero"; integer[ range<double>( 1.0, 2.0 ) ] = "one"; integer[ range<double>( 2.0, 3.0 ) ] = "two"; // ... std::cout << integer[ range<double>( 0.5 ) ] << std::endl; // zero std::cout << integer[ range<double>( 1.0 ) ] << std::endl; // one std::cout << integer[ 1.5 ] << std::endl; // one, again, implicit conversion kicks in } ``` You must be careful with equality and comparisons among double values. Different ways of getting to the same value (in the real world) can yield slightly different floating point results.
C++ STL Range Container
[ "", "c++", "stl", "range", "containers", "" ]
This question is similar to [this other one](https://stackoverflow.com/questions/1021464/python-how-to-call-a-property-of-the-base-class-if-this-property-is-being-overwr), with the difference that the data member in the base class is *not* wrapped by the descriptor protocol. In other words, how can I access a member of the base class if I am overriding its name with a property in the derived class? ``` class Base(object): def __init__(self): self.foo = 5 class Derived(Base): def __init__(self): Base.__init__(self) @property def foo(self): return 1 + self.foo # doesn't work of course! @foo.setter def foo(self, f): self._foo = f bar = Base() print bar.foo foobar = Derived() print foobar.foo ``` Please note that I also need to define a setter because otherwise the assignment of self.foo in the base class doesn't work. All in all the descriptor protocol doesn't seem to interact well with inheritance...
Defining ``` def __init__(self): self.foo = 5 ``` in `Base` makes `foo` a member (attribute) of the *instance*, not of the class. The *class* `Base` has no knowledge of `foo`, so there is no way to access it by something like a `super()` call. This is not necessary, however. When you instanciate ``` foobar = Derived() ``` and the `__init__()` method of the base class calls ``` self.foo = 5 ``` this will not result in the creation / overwriting of the attribute, but instead in `Derived`'s setter being called, meaning ``` self.foo.fset(5) ``` and thus `self._foo = 5`. So if you put ``` return 1 + self._foo ``` in your getter, you pretty much get what you want. If you need the value that `self.foo` is set to in `Base`'s constructor, just look at `_foo`, which was set correctly by the `@foo.setter`.
Life is simpler if you use delegation instead of inheritance. This is Python. You aren't obligated to inherit from `Base`. ``` class LooksLikeDerived( object ): def __init__( self ): self.base= Base() @property def foo(self): return 1 + self.base.foo # always works @foo.setter def foo(self, f): self.base.foo = f ``` But what about other methods of Base? You duplicate the names in `LooksLikeDerived` and simply. ``` def someMethodOfBase( self, *args, **kw ): return self.base.someMethodOfBase( *args **kw ) ``` Yes, it doesn't feel "DRY". However, it prevents a lot of problems when "wrapping" some class in new functionality like you're trying to do.
How to call a data member of the base class if it is being overwritten as a property in the derived class?
[ "", "python", "inheritance", "overloading", "descriptor", "" ]
I work on applications developed in C#/.NET with Visual Studio. Very often ReSharper, in the prototypes of my methods, advises me to replace the type of my input parameters with more generic ones. For instance, List<> with IEnumerable<> if I only use the list with a foreach in the body of my method. I can understand why it looks smarter to write that but I'm quite concerned with the performance. I fear that the performance of my apps will decrease if I listen to ReSharper... Can someone explain to me precisely (more or less) what's happening behind the scenes (i.e. in the CLR) when I write: ``` public void myMethod(IEnumerable<string> list) { foreach (string s in list) { Console.WriteLine(s); } } static void Main() { List<string> list = new List<string>(new string[] {"a", "b", "c"}); myMethod(list); } ``` and what is the difference with: ``` public void myMethod(List<string> list) { foreach (string s in list) { Console.WriteLine(s); } } static void Main() { List<string> list = new List<string>(new string[] {"a", "b", "c"}); myMethod(list); } ```
You're worried about performance - but do you have any grounds for that concern? My guess is that you haven't benchmarked the code at all. *Always* benchmark before replacing readable, clean code with more performant code. In this case the call to `Console.WriteLine` will utterly dominate the performance anyway. While I suspect there may be a *theoretical* difference in performance between using `List<T>` and `IEnumerable<T>` here, I suspect the number of cases where it's significant in real world apps is vanishingly small. It's not even as if the sequence type is being used for many operations - there's a single call to `GetEnumerator()` which is declared to return `IEnumerator<T>` anyway. As the list gets larger, any difference in performance between the two will get even *smaller*, because it will only have any impact at all at the very start of the loop. Ignoring the analysis though, the thing to take out of this is to *measure* performance before you base coding decisions on it. As for what happens behind the scenes - you'd have to dig into the deep details of exactly what's in the metadata in each case. I suspect that in the case of an interface there's one extra level of redirection, at least in theory - the CLR would have to work out where in the target object's type the vtable for `IEnumerable<T>` was, and then call into the appropriate method's code. In the case of `List<T>`, the JIT would know the right offset into the vtable to start with, without the extra lookup. This is just based on my somewhat hazy understanding of JITting, thunking, vtables and how they apply to interfaces. It may well be slightly wrong, but more importantly it's an implementation detail.
You'd have to look at the generated code to be certain, but in this case, I doubt there's much difference. The *foreach* statement always operates on an IEnumerable or `IEnumerable<T>`. Even if you specify `List<T>`, it will still have to get the `IEnumerable<T>` in order to iterate.
Performance impact of changing to generic interfaces
[ "", "c#", ".net", "performance", "interface", "clr", "" ]
I am actually finding that `chkContactType.Items` is empty when I step through the code. I even added a Watch to `chkContactType.Items.Count` and it is never anything but 0. I am severly confused now as it obviously isn't as my Insert method works fine which uses these same boxes and inserts the Value Member for each item.... --- I have some checked list box controls that I need to set the CheckState based on the item value as that is what is stored in the DB for an exsiting record. Unfortunately, I only see a way to set this by index which is not stored. The index is local to the control so, for example, control ContactType has 15 items in it. Index is 0-14. Item Value is 39,40,41,42,43,44,45,46,47,48,49,50,2077,2078,2079 respectively. How can I either get the index value with the Value Member value OR set the checkstate of each returned item with the Value Member value? Thanks ``` private void PaintDetails(Guid cNoteID) { var cNoteDetailDT = CurrentCaseNote.GetCNoteDetail(cNoteID); LoadCaseNoteDetailData(cNoteDetailDT.Rows[0]); // Load Contact Type Data for this CaseNote // contactTypeDT returns ItemID of chk items // that were checked for this Guid using (var contactTypeDT = CurrentCaseNote.GetCNoteContactType(cNoteID)) { if (contactTypeDT.Rows.Count > 0) foreach (DataRow row in contactTypeDT.Rows) { LoadContactTypeData(row); } } } private void LoadContactTypeData(DataRow row) { // This does not work var theItem = row["ItemID"].ToString(); // itemIndex always ends up set to -1 var itemIndex = chkContactType.Items.IndexOf(theItem); chkContactType.SetItemChecked((int) itemIndex, true); // This works I just need to supply the correct index chkContactType.SetItemChecked(0,true); } ``` ## EDIT in response to comment This is how I populate the Checked ListBox. I know there is a "magic number" there. I am working on it. It relates to the CategoryID in the DB of ContactType. ``` // Contact Type Check List Box chkContactType.DataSource = CurrentCaseNote.GetMaintItems(1); chkContactType.DisplayMember = "ItemDescription"; chkContactType.ValueMember = "ItemID"; ``` and then CurrentCaseNote BLL(kinda)--> ``` public static DataTable GetMaintItems(int iCat) { IQueryable<tblCaseNotesMaintItem> tItems = CaseNoteDAL.GetCNTable(); return (tItems.Where(item => item.CategoryID == iCat & item.IsActive).OrderBy( item => item.OrderID).Select(item => new {item.ItemID, item.ItemDescription})).CopyLinqToDataTable(); } ``` and finally the DAL --> ``` public static Table<tblCaseNotesMaintItem> GetCNTable() { return dcCaseNotes.GetTable<tblCaseNotesMaintItem>(); } ``` ## EDIT 2 This is what my code NOW looks like but still no go. It is like ItemCount is never populated.... ``` // Load Contact Type Data for this CaseNote using (var contactTypeDT = CurrentCaseNote.GetCNoteContactType(cNoteID)) { if (contactTypeDT.Rows.Count > 0) foreach (DataRow row in contactTypeDT.Rows) { LoadContactTypeData(row); } } } private void LoadContactTypeData(DataRow row) { // This does not work var theItem = row["ItemID"]; for (int i = 0; i < chkContactType.ItemCount; i++) { if(theItem == chkContactType.GetItemValue(i)) chkContactType.SetItemChecked(i,true); } } ```
This seems to work: ``` int index = checkedListBox1.Items.IndexOf("42"); checkedListBox1.SetItemChecked(index, true); ```
``` For j As Integer = 0 To chklst_distributorlist.Items.Count - 1 If chklst_distributorlist.GetItemText(chklst_distributorlist.Items.Item(j)) = ds1.Tables(0).Rows(0)("suppliername").ToString Then chklst_distributorlist.SetSelected(j, True) chklst_distributorlist.SetItemCheckState(j, CheckState.Checked) End If Next ```
Get index with value in Checked List Box
[ "", "c#", "winforms", "data-binding", "devexpress", "checkedlistbox", "" ]
I have a class ``` template <typename Iterator, typename Value> class Foo { public: Foo(const Iterator& it) { ... } ... private: map<Value, int> m_; } }; ``` Is there any way to get rid of Value in the template? The Iterator may or may not be an STL iterator, but it's guaranteed that \*it type is Value. I know about `iterator_traits<T>::value_type` for STL iterators, but wonder if there's any way to get Value type automatically for an arbitrary Iterator type? One trick I'm thinking about - say, we have a helper class ``` template <typename Iterator, typename Value> class Bar { public: Bar(const Iterator& dummy_iterator, const Value& dummmy_value) {} ... }; ``` Then if we instantiate Bar as Bar(it, \*it), the type of Value will be known inside Bar. But I can't find a good way to combine Bar with Foo.
*Any* iterator should provide `iterator_traits<Iterator>::value_type`. If it does not, then it is not an iterator. ISO C++ 2003 24.3.1[lib.iterator.traits] "Iterator traits": > To implement algorithms only in terms > of iterators, it is often necessary to > determine the value and difference > types that correspond to a particular > iterator type. Accordingly, it is > required that if `Iterator` is the type > of an iterator, the types > > ``` > iterator_traits<Iterator>::difference_type > iterator_traits<Iterator>::value_type > iterator_traits<Iterator>::iterator_category > ``` > > be defined as the iterator’s > difference type, value type and > iterator category, respectively. Aside from that, there's no general way to obtain a type of an arbitrary C++ expression. C++0x will rectify it by providing `decltype`.
Sorry. The correct way to get rid of `Value` is to use `iterator_traits` as you suggested. If your non-STL iterator is a naked pointer, then you get correct iterator\_traits typedefs for free. Otherwise the non-STL iterator class must define the correct typedefs. See the [iterator traits documentation](http://www.sgi.com/tech/stl/iterator_traits.html) for more information.
Is it possible to get the value type from an arbitrary iterator (C++)?
[ "", "c++", "templates", "" ]
I had a (friendly but heated) argument with my lead developer the other day because our project has TSQL Scripts that I code directly into SQL files which I then run against the database. I find that when I do this, it's easy to work out the schema in advance without fiddly pointing and clicking and then there's no opportunity to forget to generate a script to put into source control as generating the script no longer becomes a chore you have to do after the fact, but is an implicit part of the process (and also leads to cleaner scripts without the extra crap that SQL Server Management Studio inserts into the scripts it generates). My lead developer insists that having to manually script it out is a pain in the arse and that he absolutely refuses to write his scripts by hand when there are perfectly good tools to do it without coding. I've noticed that the copying of his changes into the actual scripts tends to get delayed a bit as a result though. What are your thoughts on the pros and/or cons of doing it one way vs the other? Am I being too rigid/old-school in my sticking to hand coding schema scripts or is he being too reliant on third party tools and losing something in the process?
I always script stuff myself because the wizards sometimes don't script things in a way that I like it and will also give funky names to defaults scripting things yourself is also good in case you get laid off and you have to go for an interview where they ask you to script DDL on the whiteboard
As I usually collaborate with a colleague during the schema design, I tend to design the schema using the GUI tools, as its easier to discuss it with a diagram of the tables in front of you. I then generate the scripts, being careful to select the exact options that I want to avoid having to make manual changes post-export.
Scripting your database first versus building the database via SQL Server Management Studio and then generating the script
[ "", "sql", "sql-server", "" ]
Consider this simple XML document. The serialized XML shown here is the result of an XmlSerializer from a complex POCO object whose schema I have no control over. ``` <My_RootNode xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns=""> <id root="2.16.840.1.113883.3.51.1.1.1" extension="someIdentifier" xmlns="urn:hl7-org:v3" /> <creationTime xsi:nil="true" xmlns="urn:hl7-org:v3" /> </My_RootNode> ``` The goal is to extract the value of the extension attribute on the id node. In this case, we are using the SelectSingleNode method, and given an XPath expression as such: ``` XmlNode idNode = myXmlDoc.SelectSingleNode("/My_RootNode/id"); //idNode is evaluated to null at this point in the debugger! string msgID = idNode.Attributes.GetNamedItem("extension").Value; ``` The problem is that the `SelectSingleNode` method returns null for the given XPath expression. **Question:** any ideas on this XPath query's correctness, or why this method call + XPath expression would return a null value? Perhaps the namespaces are part of the problem?
I strongly suspect the problem is to do with namespaces. Try getting rid of the namespace and you'll be fine - but obviously that won't help in your real case, where I'd assume the document is fixed. I can't remember offhand how to specify a namespace in an XPath expression, but I'm sure that's the problem. EDIT: Okay, I've remembered how to do it now. It's not terribly pleasant though - you need to create an `XmlNamespaceManager` for it. Here's some sample code that works with your sample document: ``` using System; using System.Xml; public class Test { static void Main() { XmlDocument doc = new XmlDocument(); XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable); namespaces.AddNamespace("ns", "urn:hl7-org:v3"); doc.Load("test.xml"); XmlNode idNode = doc.SelectSingleNode("/My_RootNode/ns:id", namespaces); string msgID = idNode.Attributes["extension"].Value; Console.WriteLine(msgID); } } ```
If you want to ignore namespaces completely, you can use this: ``` static void Main(string[] args) { string xml = "<My_RootNode xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\">\n" + " <id root=\"2.16.840.1.113883.3.51.1.1.1\" extension=\"someIdentifier\" xmlns=\"urn:hl7-org:v3\" />\n" + " <creationTime xsi:nil=\"true\" xmlns=\"urn:hl7-org:v3\" />\n" + "</My_RootNode>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(xml); XmlNode idNode = doc.SelectSingleNode("/*[local-name()='My_RootNode']/*[local-name()='id']"); } ```
SelectSingleNode returning null for known good xml node path using XPath
[ "", "c#", "xml", "xpath", "" ]
This is simple, but I am taking an entire directory listing (in PHP with `dir()`), and making sure it both: * isn't "." or "..", and * ends in a file extension .jpg, .jpeg, .gif, or .png. Right now I have ``` function isValidFile($filename) { $dirDotExpr = "/^\.{1,2}$/"; //matches against "." and ".." $extExpr = "/\.(jpg|jpeg|gif|png)$/i"; //checks file extension return (1 && ! preg_match($dirDotExpr, $filename) && preg_match($extExpr, $filename) ) } ``` but it'd be nice to do it all in one regular expression. However, I don't know how to make sure one thing matches, and one thing doesn't--how can I accomplish this?
You may be overthinking it. If you're verifying that `$filename` ends in .jpg, .jpeg, .gif, or .png, it clearly can't be "." or "..".
``` function isValidFile($filename) { return (bool) preg_match('/\.(?:jpe?g|gif|png)$/iD', (string) $filename); } ``` Note that I made the parentheses non-capturing, for a minor speed increase. Also merged `jpg` and `jpeg` into `jpe?g`. Also, I added the `D` modifier. If you don't, `$` will allow final newlines; a filename like "hello.jpg\n" would be considered valid. Be very aware of that.
How can I make sure one thing matches, and one doesn't, in a single regex?
[ "", "php", "regex", "" ]
I previously worked a lot with Java and now I am working more with Ruby. One thing I cannot figure out though is what is the ruby equivalent to the Java "NullPointerException"? I want to test variables when I enter a function and if they are nil I want to raise this type of exception. Is there a specific ruby error class to raise this type of exception?
Raising an ArgumentError could suit your situation. You could do something like this: ``` def i_dont_take_nils_from_nobody x raise ArgumentError.new "You gave me a nil!" if x.nil? puts "thanks for the #{x}" end i_dont_take_nils_from_nobody nil #=> ArgumentError: You gave me a nil! i_dont_take_nils_from_nobody 1 #=> thanks for the 1 ```
The exception list includes no such thing. nil is an object, and items can be checked to ensure they are not nil. ``` result = Base.find(blah) result.nil? ``` Calling a method on nil that nil (the object) doesn't have should give you a NoMethodError exception. ``` result = Base.find(blah) #returning no result result.my_advanced_functionality(42) ``` Since result is nil, and the nil object defines no function my\_advanced\_functionality, you'll get a NoMethodError One of the things I see a fair amount as I learn is "You have mistakenly called id on nil, which would be 4" (because the object id of nil is 4) The exception heirarchy has an ArgumentError exception, which I've never used, but looks like it might serve you.
raise "NullPointerException" in Ruby
[ "", "java", "ruby", "" ]
**Requirements**: I have a table of several thousand questions. Users can view these multiple choice questions and then answer them. Once a question is answered, it should not be shown to the same user again even if he logs in after a while. **Question** How would I go about doing this efficiently? Would [Bloom Filters](http://en.wikipedia.org/wiki/Bloom_filter) work?
Create a **QuestionsAnswered** table and join on it in your select. When the user answers a question, insert the question ID and the user ID into the table. ``` CREATE TABLE QuestionsAnswered (UserID INT, QuestionID INT) SELECT * FROM Question WHERE ID NOT IN (SELECT QuestionID FROM QuestionsAnswered WHERE UserID = @UserID) INSERT INTO QuestionsAnswered (UserID, QuestionID) VALUES (@UserID, @QuestionID) ```
Could you add something to the users info in the database which contains a list of answered questions? So when that user comes back you can only show them questions which are NOT answered?
SQL Statement that never returns same row twice?
[ "", "sql", "" ]
For a simple web application, I'd like to be able to take advantage of several UNIX features that are stable, have a long history, and are well proven in production, rather than having to write my own code. Take users, for example. Rather than having an entire user, group, permission infrastructure in my webapp, I'd like to be able to simply piggyback on top of the equivalent features of UNIX. Is there a PHP library that will allow me to register users, log them in, manage permissions, etc. ?
Based on your comment to deceze's answer, are you looking for something like PHP's [filesystem functions](http://us.php.net/manual/en/ref.filesystem.php)? Then, there is [system](http://us.php.net/manual/en/function.system.php) and its related functions, which gives access to Unix commands, but I'd recommend other ways of doing things if possible. Edit: In response to the comments about needing user and group functionality: * Firstly, in case your plan is to let web users have access to the whole file system (or even just their regular log in directories), I just want to advise against that - lots of security concerns (eg. if someone else gets into a user's account, they could delete everything to which they have access). * The little experience I have with handling users in PHP was in some beginner level training. In that class, we had our users in an SQL database and used [sessions](http://us.php.net/manual/en/book.session.php). We didn't use SSL, but I'd advise some sort of crypto when passing passwords around. * If you're using [Apache](http://httpd.apache.org/), it can handle the authentication for you. Other server software can probably do the same, but Apache is all I've ever worked with. I can't address whether Apache can handle sessions itself and don't have the time to research it right now.
It's really not a good idea to fumble around with the user and permission settings **of the actual system that is hosting your site**. If you want to protect individual directories of your site, you're better off using `.htaccess` files. If OTOH you're working with virtual URLs, you'll have a hard time mapping the UNIX directory permissions to them anyway.
UNIX wrapper in PHP
[ "", "php", "unix", "" ]
Does anyone know a cross-browser, reliable solution for catching presses of the tab-key in a textarea field, and replacing (in the correct position) 4 spaces? The textarea is being used to input an essay, and needs this feature. Note: I tried using FCKEditor, among others, which did not catch tabs and had a bunch of features I didn't need. I want a simple solution just for catching tabs.
I didn't test extensively, but this seems to work: (I found the "insertAtCursor" function at <http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript#comment-3817>) ``` <textarea id="text-area" rows="20" cols="100"></textarea> <script> document.getElementById("text-area").onkeydown = function(e) { if (!e && event.keyCode == 9) { event.returnValue = false; insertAtCursor(document.getElementById("text-area"), " "); } else if (e.keyCode == 9) { e.preventDefault(); insertAtCursor(document.getElementById("text-area"), " "); } }; //http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript#comment-3817 function insertAtCursor(myField, myValue) { //IE support if (document.selection) { var temp; myField.focus(); sel = document.selection.createRange(); temp = sel.text.length; sel.text = myValue; if (myValue.length == 0) { sel.moveStart('character', myValue.length); sel.moveEnd('character', myValue.length); } else { sel.moveStart('character', -myValue.length + temp); } sel.select(); } //MOZILLA/NETSCAPE support else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart; var endPos = myField.selectionEnd; myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length); myField.selectionStart = startPos + myValue.length; myField.selectionEnd = startPos + myValue.length; } else { myField.value += myValue; } } </script> ``` **EDIT**: Modified the script so it doesn't use jQuery.
``` <html> <head> <script type="text/javascript"> function keyHandler(e) { var TABKEY = 9; var backSlash = 8; var code = e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which; if(code == TABKEY && !e.shiftKey && !e.ctrlKey && !e.altKey) { var val = document.getElementById("t1"); val.value=(val.value).substring(0,getCaret(val)) + " " + (val.value).substring(getCaret(val)); //document.getElementById("t1").value += " "; if(e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } val.focus(); return false; } if(code == backSlash) { var val = document.getElementById("t1"); val.value=(val.value).substring(0,getCaret(val)-4) + (val.value).substring(getCaret(val)); if(e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } return false; } } function getCaret(el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; } </script> </head> <body> <textarea id="t1" onkeydown="javascript:keyHandler(event)"></textarea> </body> </hrml> ```
Catching Tabs in TextArea
[ "", "javascript", "html", "dom-events", "keylistener", "" ]
Hey, I need to delete all images from a string and I just can't find the right way to do it. Here is what I tryed, but it doesn't work: ``` preg_replace("/<img[^>]+\>/i", "(image) ", $content); echo $content; ``` Any ideas?
Try dropping the `\` in front of the `>`. Edit: I just tested your regex and it works fine. This is what I used: ``` <? $content = "this is something with an <img src=\"test.png\"/> in it."; $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); echo $content; ?> ``` The result is: ``` this is something with an (image) in it. ```
You need to assign the result back to `$content` as `preg_replace` does not modify the original string. ``` $content = preg_replace("/<img[^>]+\>/i", "(image) ", $content); ```
PHP - remove <img> tag from string
[ "", "php", "string", "" ]
What's going on here? I'm trying to create a list of functions: ``` def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(lambda x:f(i,x)) ``` This isn't doing what I expect. I would expect the list to act like this: ``` funcs[3](3) = 9 funcs[0](5) = 0 ``` But all the functions in the list seem to be identical, and be setting the fixed value to be 9: ``` funcs[3](3) = 27 funcs[3](1) = 9 funcs[2](6) = 54 ``` Any ideas?
lambdas in python are closures.... the arguments you give it aren't going to be evaluated until the lambda is evaluated. At that time, i=9 regardless, because your iteration is finished. The behavior you're looking for can be achieved with functools.partial ``` import functools def f(a,b): return a*b funcs = [] for i in range(0,10): funcs.append(functools.partial(f,i)) ```
Yep, the usual "scoping problem" (actually a binding-later-than-you want problem, but it's often called by that name). You've already gotten the two best (because simplest) answers -- the "fake default" `i=i` solution, and `functools.partial`, so I'm only giving the third one of the classic three, the "factory lambda": ``` for i in range(0,10): funcs.append((lambda i: lambda x: f(i, x))(i)) ``` Personally I'd go with `i=i` if there's no risk of the functions in `funcs` being accidentally called with 2 parameters instead of just 1, but the factory function approach is worth considering when you need something a little bit richer than just pre-binding one arg.
Python create function in a loop capturing the loop variable
[ "", "python", "lambda", "" ]
I have a table column I’m trying to expand and hide. jQuery seems to hide the `<td>` elements when I select it by `class` but not by the element’s `name`. For example: ``` $(".bold").hide(); // Selecting by class works. $("tcol1").hide(); // Selecting by name does not work. ``` Note the HTML below. The second column has the same `name` for all rows. How could I create this collection using the `name` attribute? ``` <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> <tr> <td>data1</td> <td name="tcol1" class="bold"> data2</td> </tr> ```
You can use the [jQuery attribute selector](https://api.jquery.com/category/selectors/attribute-selectors/): ``` $('td[name="tcol1"]') // Matches exactly 'tcol1' $('td[name^="tcol"]' ) // Matches those that begin with 'tcol' $('td[name$="tcol"]' ) // Matches those that end with 'tcol' $('td[name*="tcol"]' ) // Matches those that contain 'tcol' ```
Any attribute can be selected using `[attribute_name=value]` way. See the sample [here](http://myvedham.blogspot.in/2013/09/jquery-select-by-name-and-id.html): ``` var value = $("[name='nameofobject']"); ```
How can I select an element by name with jQuery?
[ "", "javascript", "jquery", "html", "dom", "jquery-selectors", "" ]
I've been looking at the new features in C++11 and it really looks like it will be possible to program in a very functional programming style using it. I've gotten use to using the types List, Seq, Array in F# and I see no reason why their members couldn't be ported into some sort of C++11 template. What problems or advantages do you see in using C++11 vs something like F# for a mixed functional programming style? Maybe the Boost guys will make a new `functional` once C++11 comes out.
The biggest problem with trying to program in a functional style in C++ is that it does not support tail recursion. In a functional language you don't have to worry about stack explosion when you tail recurse correctly, but in C++ you always have to worry about that. Therefore, many "functional" type algorithms will be clumsy or heavy.
Here are some of the problems I encountered trying to write functional code in C#, mixed with some goodies from my time when I was still using C++: 1. Lack of pattern matching. Once you get used to it, not having it can drive me crazy. 2. Lack of syntactic sugar for tuples. 3. Lack of syntax for copying records and setting fields in one go. 4. Lack of syntax for lists and arrays. That goes for constructors and pattern-matching. 5. Not having a GC, and unsafe memory accesses. Not being constrained by a GC is an advantage, but remembering the reports I got from my first runs of Valgrind on C++ code I thought was bug free scared me for ever. 6. Understanding template code isn't exactly accessible to all mortals. I don't have problem understanding mine, but whenever I looked into implementations of the STL, boost or cgal I found myself wondering what language they were using. My C++ and their C++ don't live in the same world. 7. The total lack of fun in dealing with a library that uses another version of boost (or any library that uses templates). 8. Verbosity of separate header/implementation files. 9. Type inference in C++ does not go as far as e.g. F#. I know it's been improved in C++11, but as I understand it's similar to var in C#, which isn't enough once you tasted F#-style inference. 10. Lack of computation expressions, including sequence expressions, comprehensions, async... It would not surprise me if several of these points were actually possible in C++ using some template and preprocessor magic, but you can't really use these in a production environment unless you have very adventurous and tolerant co-workers. I was a die-hard C++ enthusiast before. Then I started using generic programming with templates and higher-order functions using function objects. It just was too tiresome to write. After I tried a functional language I never looked back.
Functional programming in C++11, F# style
[ "", "c++", "c++11", "f#", "functional-programming", "" ]
I am running a windows service and using a loop and Thread.Sleep to repeat a task, would it be better to use a timer method? If yes a code example would be great I am currently using this code to repeat ``` int curMinute; int lastMinute = DateTime.Now.AddMinutes(-1).Minute; while (condition) { curMinute = DateTime.Now.Minute; if (lastMinute < curMinute) { // do your once-per-minute code here lastMinute = curMinute; } Thread.Sleep(50000); // sleeps for 50 seconds if (error condition that would break you out of this) { break; // leaves looping structure } } ```
``` class Program { static void Main(string[] args) { Timer timer = new Timer(new TimerCallback(TimeCallBack),null,1000,50000); Console.Read(); timer.Dispose(); } public static void TimeCallBack(object o) { curMinute = DateTime.Now.Minute; if (lastMinute < curMinute) { // do your once-per-minute code here lastMinute = curMinute; } } ``` The code could resemble something like the one above
A timer is a better idea, IMO. That way, if your service is asked to stop, it can respond to that very quickly, and just not call the timer tick handler again... if you're sleeping, the service manager will either have to wait 50 seconds or kill your thread, neither of which is terribly nice.
C# Timer or Thread.Sleep
[ "", "c#", "timer", "" ]
How to enable tcp/ip through t-sql script on sql server 2008?
In order to do that using a t-sql script, you might have to fiddle with the registry settings. I haven't done that before myself using t-sql so can't be of much help. But you may like to look up for **xp\_instance\_regread** and **xp\_instance\_regwrite**. They are extended stored procedures which allow you to read/write registry values. Here is an example which might be of some help - <http://codebetter.com/blogs/raymond.lewallen/archive/2005/09/12/131869.aspx> The following links should help you locate the whereabouts of TCP/IP settings in the registry. <http://support.microsoft.com/kb/315236> <http://www.pctools.com/guides/registry/detail/1171/> cheers
``` ALTER ENDPOINT [TSQL Default TCP] STATE = STOPPED; ``` I reckon though I'm not sure if they fix it to actually work in 2k8. In 2k5 this was a no-op. I don't have a 2k8 instance to test it.
Enabling TCP/IP protocol through t-sql script?
[ "", "sql", "t-sql", "tcp", "" ]
I have a folder of PHP scripts, they are mostly utility scripts. How to share those scripts among different PHP applications so that reuse and deployment are easy? I would have to package my app into an installer, and let the user install it. I could put the lib and hardcode the `include` path, but that means I haven to change the PHP code every time i deploy the web application to a new customer. This is not desirable. Another route I consider is to copy the lib to other apps, but still, since the lib is constantly updating, that means that I need to constantly do the copying, and this will introduce a lot of problems. I want an automated way to do this. **Edit: Some of the applications are Symfony, some are not.**
You could create a PEAR package. See [Easy PEAR Package Creation](http://www.electricmonk.nl/log/2009/04/12/easy-pear-package-creation/) for more information on how to do this. This assumes that when you say anyone, you mean outside your immediate organisation. Updated: You do not need to upload to a website to install the PEAR package. Just extract your archive into the pear folder to use in a PHP application. Added: Why not create a new SVN repository for your library? Lets say you create a library called FOO. Inside the repostory you could use the folder heirachy of trunk\lib\foo. Your modules could then go into trunk\lib\foo\modules and have a file called trunk\lib\foo\libfoo.php. Now libfoo.php can include once or require once all the modules as required.
PHP now supports Phar archives. There's full documentation on php.net. There's a complete tutorial on IBM website as well. One neat thing you can do with Phar archives is package an entire application and distribute it that way. [http://php.net/phar](http://fr.php.net/phar) <http://www.ibm.com/developerworks/opensource/library/os-php-5.3new4/index.html>
What is the Best Practices to share PHP scripts among different PHP applications?
[ "", "php", "" ]
A method that overrides another method does not inherit documentation of the method it is overriding. Is there any way to explicitly tell it to inherit the documentation? ``` /** * {@inheritDoc} * * This implementation uses a dynamic programming approach. */ @Override public int[] a(int b) { return null; } ```
According to the [javadoc documentation](http://java.sun.com/javase/6/docs/technotes/tools/solaris/javadoc.html): > Inheriting of comments occurs in all > three possible cases of inheritance > from classes and interfaces: > > * When a method in a class overrides a method in a superclass > * When a method in an interface overrides a method in a superinterface > * When a method in a class implements a method in an interface Comments can be explicitly inherited using the [{@inheritDoc}](http://java.sun.com/javase/6/docs/technotes/tools/solaris/javadoc.html#@inheritDoc) tag. If no comments are provided for an overriding method, comments will be implicitly inherited. Aspects of the inheriting comments (e.g. params, return value, etc.) can be overridden if you so desire. Importantly, you need to make sure that the source file containing the code with the comment to be inherited is available to the javadoc tool. You can do this by using the -[sourcepath](http://java.sun.com/javase/6/docs/technotes/tools/solaris/javadoc.html#sourcepath) option.
From [the 1.4.2 Javadoc manual](http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/javadoc.html#inheritingcomments) > **Algorithm for Inheriting Method Comments** - If a method does not have a doc comment, or has an {@inheritDoc} tag, the Javadoc tool searches for an applicable comment using the following algorithm, which is designed to find the most specific applicable doc comment, giving preference to interfaces over superclasses: > > 1. Look in each directly implemented (or extended) interface in the order they appear following the word implements (or extends) in the method declaration. Use the first doc comment found for this method. > 2. If step 1 failed to find a doc comment, recursively apply this entire algorithm to each directly implemented (or extended) interface, in the same order they were examined in step 1. > 3. If step 2 failed to find a doc comment and this is a class other than Object (not an interface): > 1. If the superclass has a doc comment for this method, use it. > 2. If step 3a failed to find a doc comment, recursively apply this entire algorithm to the superclass. I believe (though I could be wrong) that this basic algorithm still applies to Java 1.5 and 1.6... though it really would be awfully nice of Sun to publish a complete self-contained definitive document for each version of the toolset... I guess it's an overhead they just can't afford, atleast for a free toolset. Cheers. Keith. --- **Edit:** Here's a quick and dirty example. **Code** ``` package forums; interface Methodical { /** * A no-op. Returns null. * @param i int has no effect. * @return int[] null. */ public int[] function(int i); } interface Methodological extends Methodical { /** * Another no-op. Does nothing. */ public void procedure(); } class Parent implements Methodological { @Override public int[] function(int i) { return null; } @Override public void procedure() { // do nothing } } class Child extends Parent { /** {@inheritDoc} */ @Override public int[] function(int i) { return new int[0]; } /** {@inheritDoc} */ @Override public void procedure() { System.out.println("I'm a No-op!"); } } public class JavaDocTest { public static void main(String[] args) { try { new Child().procedure(); } catch (Exception e) { e.printStackTrace(); } } } ``` **Javadoc** ``` C:\Java\home\src\forums>javadoc -package -sourcepath . JavaDocTest.java Loading source file JavaDocTest.java... Constructing Javadoc information... Standard Doclet version 1.6.0_12 Building tree for all the packages and classes... Generating forums/\Child.html... Generating forums/\JavaDocTest.html... Generating forums/\Methodical.html... Generating forums/\Methodological.html... Generating forums/\Parent.html... Generating forums/\package-frame.html... Generating forums/\package-summary.html... Generating forums/\package-tree.html... Generating constant-values.html... Building index for all the packages and classes... Generating overview-tree.html... Generating index-all.html... Generating deprecated-list.html... Building index for all classes... Generating allclasses-frame.html... Generating allclasses-noframe.html... Generating index.html... Generating help-doc.html... Generating stylesheet.css... ``` **Produces** file:///C:/Java/home/src/forums/index.html ``` function public int[] function(int i) A no-op. Returns null. Specified by: function in interface Methodical Overrides: function in class Parent Parameters: i - int has no effect. Returns: int[] null. procedure public void procedure() Another no-op. Does nothing. Specified by: procedure in interface Methodological Overrides: procedure in class Parent ```
Java Documentation Override Method does not InheritDoc
[ "", "java", "eclipse", "documentation", "inheritdoc", "" ]
Is it good to use such approach for keeping read-only list of string, for example, a list of fields in ADO.NET. ``` var list = new System.Collections.ObjectModel.ReadOnlyCollection<string>( new List<string>(4) { "type", "currency", "date", "amount" }); ``` Or this is a superfluous solution?
Depends on your position. `ReadOnlyCollection` works very well when you have an internal modifiable list that needs to be given to some other code that isn't allowed to change the list. For simple code, using `ReadOnlyCollection` is probably overkill. If the code is large and there's a risk some other programmer (or you, down the road) might accidentally attempt to modify the list, then it might be worth it. In short: don't use `ReadOnlyCollection` idiomatically, use it when it makes sense.
If possible, prefer static type checking. `IEnumerable<string>` is readonly. ``` IEnumerable<string> list = new List<string> { "type", "currency", "date", "amount" }; ``` Subsequent code can't modify the list, and mistakes will be caught at compile time - unless you use reflection, but then reflection could be used to circumvent runtime checks as well.
Read-only list of strings
[ "", "c#", ".net", "list", "collections", "readonly", "" ]
I wanted to write a regex to count the number of spaces/tabs/newline in a chunk of text. So I naively wrote the following:- ``` numSpaces : function(text) { return text.match(/\s/).length; } ``` For some unknown reasons it always returns `1`. What is the problem with the above statement? I have since solved the problem with the following:- ``` numSpaces : function(text) { return (text.split(/\s/).length -1); } ```
**tl;dr: Generic Pattern Counter** ``` // THIS IS WHAT YOU NEED const count = (str) => { const re = /YOUR_PATTERN_HERE/g return ((str || '').match(re) || []).length } ``` For those that arrived here looking for a generic way to count the number of occurrences of a regex pattern in a string, and don't want it to fail if there are zero occurrences, this code is what you need. Here's a demonstration: ``` /* * Example */ const count = (str) => { const re = /[a-z]{3}/g return ((str || '').match(re) || []).length } const str1 = 'abc, def, ghi' const str2 = 'ABC, DEF, GHI' console.log(`'${str1}' has ${count(str1)} occurrences of pattern '/[a-z]{3}/g'`) console.log(`'${str2}' has ${count(str2)} occurrences of pattern '/[a-z]{3}/g'`) ``` **Original Answer** The problem with your initial code is that you are missing the [global identifier](http://www.javascriptkit.com/jsref/regexp.shtml): ``` >>> 'hi there how are you'.match(/\s/g).length; 4 ``` Without the `g` part of the regex it will only match the first occurrence and stop there. Also note that your regex will count successive spaces twice: ``` >>> 'hi there'.match(/\s/g).length; 2 ``` If that is not desirable, you could do this: ``` >>> 'hi there'.match(/\s+/g).length; 1 ```
As mentioned in [my earlier answer](https://stackoverflow.com/a/23385429/1338292), you can use [`RegExp.exec()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec) to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using [`String.match()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match). ``` var re = /\s/g, count = 0; while (re.exec(text) !== null) { ++count; } return count; ```
Count number of matches of a regex in Javascript
[ "", "javascript", "regex", "" ]
In my table I have a Month(tinyint) and a Day(tinyint) field. I would like to have a function that takes this month and day and produces a datetime for the next date(including year) given this month and day. So if I had Month = 9, Day = 7 it would produce 9/7/2009. If I had Month 1, Day 1 it would produce 1/1/2010.
something like this would work. It's variation on your method, but it doesn't use the MM/DD/YYYY literal format, and it won't blowup against bad input (for better or for worse). ``` declare @month tinyint declare @day tinyint set @month = 9 set @day = 1 declare @date datetime -- this could be inlined if desired set @date = convert(char(4),year(getdate()))+'0101' set @date = dateadd(month,@month-1,@date) set @date = dateadd(day,@day-1,@date) if @date <= getdate()-1 set @date = dateadd(year,1,@date) select @date ``` Alternatively, to create a string in YYYYMMDD format: ``` set @date = right('0000'+convert(char(4),year(getdate())),4) + right('00'+convert(char(2),@month),2) + right('00'+convert(char(2),@day),2) ``` Another method, which avoids literals all together: ``` declare @month tinyint declare @day tinyint set @month = 6 set @day = 24 declare @date datetime declare @today datetime -- get todays date, stripping out the hours and minutes -- and save the value for later set @date = floor(convert(float,getdate())) set @today = @date -- add the appropriate number of months and days set @date = dateadd(month,@month-month(@date),@date) set @date = dateadd(day,@day-day(@date),@date) -- increment year by 1 if necessary if @date < @today set @date = dateadd(year,1,@date) select @date ```
Here is my sql example so far. I don't really like it though... ``` DECLARE @month tinyint, @day tinyint, @date datetime SET @month = 1 SET @day = 1 -- SET DATE TO DATE WITH CURRENT YEAR SET @date = CONVERT(datetime, CONVERT(varchar,@month) + '/' + CONVERT(varchar,@day) + '/' + CONVERT(varchar,YEAR(GETDATE()))) -- IF DATE IS BEFORE TODAY, ADD ANOTHER YEAR IF (DATEDIFF(DAY, GETDATE(), @date) < 0) BEGIN SET @date = DATEADD(YEAR, 1, @date) END SELECT @date ```
SQL: How to produce next date given month and day
[ "", "sql", "" ]
I have an HTML page that opens another page via JavaScript. When a user clicks a button in the other page, I want to post a message in a DIV of the opening page via JQuery. I cannot put my finger on it, but I cannot seem to get this to work. Here is my opener page ``` <html> <head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> </head> <body> <input type="button" onclick="window.open('dialog.html', '_blank', 'height=200, width=300');" value="launch!" /> <div id="testDiv"></div> </body> </html> ``` When the user clicks the "launch!" button, a dialog will appear. The code for the dialog looks like this: ``` <html> <head> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> </head> <body> <input type="button" onclick="updateOpener()" value="Update Opener" /> <script type="text/javascript"> function updateOpener() { var testDiv = window.opener.jQuery("#testDiv"); if (testDiv != null) { alert("here"); testDiv.html("Updated!"); } } </script> </body> </html> ``` Surprisingly, the alert box appears. However, I cannot seem to update the HTML of the DIV in my opening page. Does anyone know how to do this?
You're referencing "confirmDiv". Where is that DIV?
You can't do that if the parent page (the opener) resides on another domain. Otherwise, your code works perfectly. Also, your != null check is probably not doing what you think it is doing, as the jQuery function never returns null. If you are checking for the existence of an element, you need to do it this way... ``` var el = $("#myElementId"); if(el.length == 0) alert('Not found!'); ```
JQuery - Write to opener window
[ "", "javascript", "jquery", "html", "" ]
I got the code below from a C++ book, and I cannot figure out how the initialization works. From what I can see, there is an outer for loop cycling trough the rows, and the inner loop cycling trough the column. But its is the assignment of the values into the array that I do not understand. ``` #include <iostream> using namespace std; int main() { int t,i, nums[3][4]; for(t=0; t < 3; ++t) { for(i=0; i < 4; ++i) { nums[t][i] = (t*4)+i+1; //I don't understand this part/line cout << nums[t][i] << ' '; } cout << '\n'; } return 0; } ``` so here are some questions. * I cannot understand the initialization of the 2D int array `nums[3][4]`. What separates the `(t*4)+i+1`, so that the compiler knows what to assign where? * How do I know what values will be stored in the rows and columns, based on what values have been assigned? * Why is there an asterisk? * What are the parentheses around `t*4` for? I understand that initialization two-dimensional arrays look like the following example. ``` #include <iostream> using namespace std; int main() { char str[3][20] = {{"white" "rabbit"}, {"force"}, {"toad"}}; //initialize 2D character array cout << str[0][0] << endl; //first letter of white cout << str[0][5] << endl; //first letter of rabbit cout << str[1][0] << endl; //first letter of force cout << str[2][0] << endl; //first letter of toad return 0; } ``` And from what I know, like this in memory. ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 w h i t e r a b b i t 0 1 f o r c e 0 2 t o a d 0 ``` Thank you.
``` (t*4)+i+1 ``` Is an arithmetic expression. t and i are ints, the \* means multiply. So for row 1, column 2, t = 1, i = 2, and nums[1][2] = 1x4+2+1 = 7. Oh, forgot a couple things. First, the () is to specify the order of operations. So the t\*4 is done first. Note that in this case the () is unnecessary, since the multiply operator takes precedence over the plus operator anyway. Also, I couldn't tell from your question if you knew this already or not, but the meaning of rows[t][i] is array notation for accessing rows at row t and column i.
For the first part, isn't it just assigning the a value equal to the row number \* 4 plus the column number? I.E. the end result of the assignment should be: ``` 1 2 3 4 5 6 7 8 9 10 11 12 ``` So the expression (t\*4)+i+1 means "4 multiplied by the row number plus the column number plus 1". Note that the row number and column numbers in this case start from 0.
Initializing 2D int array in run-time
[ "", "c++", "arrays", "initialization", "declaration", "multidimensional-array", "" ]
Is it possible for a Swing based Java to have the Aero Glass effect as the background under Windows Vista/7?
I know it is possible, as it was achieved by the person who asked [this question](https://stackoverflow.com/questions/3627683/combining-aero-glass-effects-and-swt). I am currently researching the same thing and will post here if I find out how.
As of Java SE 6 Swing's native look and feel for windows uses Aero. There's a blog post with a lot of details about this from Chet Haase entitled [Java on Vista : Yes it works](http://weblogs.java.net/blog/chet/archive/2006/10/java_on_vista_y.html)
Is it possible for Java apps to use the Aero Glass effect?
[ "", "java", "swing", "windows-vista", "aero", "" ]
How can I rotate the hue of an image using GDI+'s `ImageAttributes` (and presumably `ColorMatrix`)? Note that I want to rotate the hue, not tint the image. **EDIT**: By rotating the hue, I mean that each color in the image should be shifted to a different color, as opposed to making the entire image a shade of one color. For example, Original:<http://www.codeguru.com/img/legacy/gdi/Tinter03.jpg> Rotated: <http://www.codeguru.com/img/legacy/gdi/Tinter15.jpg> or <http://www.codeguru.com/img/legacy/gdi/Tinter17.jpg>
I ended up porting [QColorMatrix](http://www.codeguru.com/cpp/g-m/gdi/gdi/article.php/c3667) to C# and using its `RotateHue` method.
[I threw this together](http://rexmorgan.net/journal/rotate_image_hue_in_cnet) for this question (ZIP file with c# project linked at the bottom of the post). It does not use `ImageAttributes` or `ColorMatrix`, but it rotates the hue as you've described: ``` //rotate hue for a pixel private Color CalculateHueChange(Color oldColor, float hue) { HLSRGB color = new HLSRGB( Convert.ToByte(oldColor.R), Convert.ToByte(oldColor.G), Convert.ToByte(oldColor.B)); float startHue = color.Hue; color.Hue = startHue + hue; return color.Color; } ```
Rotate Hue using ImageAttributes in C#
[ "", "c#", ".net", "image", "gdi+", "colormatrix", "" ]
I have a bunch of python methods that follow this pattern: ``` def delete_session(guid): conn = get_conn() cur = conn.cursor() cur.execute("delete from sessions where guid=%s", guid) conn.commit() conn.close() ``` Is there a more pythonic way to execute raw sql. The 2 lines at the beginning and end of every method are starting to bother me. I'm not looking for an orm, I want to stick with raw sql.
You could write a context manager and use the with statement. For example, see [this blog post (archived)](https://web.archive.org/web/20160329070622/http://jessenoller.com/2009/02/03/get-with-the-program-as-contextmanager-completely-different/) Also the python documentation has a sample that pretty much matches your needs. See section 8.1 on this page, in particular the snippet that begins: ``` db_connection = DatabaseConnection() with db_connection as cursor: cursor.execute('insert into ...') cursor.execute('delete from ...') # ... more operations ... ``` * <https://docs.python.org/2.5/whatsnew/pep-343.html>
Careful about that `execute`, the second argument needs to be [guid] (a list with just one item). As for your question, I normally just use a class encapsulating connection and cursor, but it looks like you may prefer to use an *execution context* object whose `__enter__` method gives you a cursor while `__leave__` commits or rollbacks depending on whether the termination was normal or by exception; this would make your code ``` def delete_session(): with get_cursor() as cur: cur.execute(etc etc) ``` If you like this style, let us know and I'll show you how to write `get_cursor`. Others will no doubt propose a decorator instead, so you'd write: ``` @withcursor def delete_session(cur): cur.execute(etc etc) ``` but I think this makes commit/rollback, among other issues, a bit murkier. Still, if *this* is your preference, again let us know and I can show you how to write that form, too.
looking for a more pythonic way to access the database
[ "", "python", "mysql", "" ]
I am using c++ , I want to do alpha blend using the following code. ``` #define CLAMPTOBYTE(color) \ if ((color) & (~255)) { \ color = (BYTE)((-(color)) >> 31); \ } else { \ color = (BYTE)(color); \ } #define GET_BYTE(accessPixel, x, y, scanline, bpp) \ ((BYTE*)((accessPixel) + (y) * (scanline) + (x) * (bpp))) for (int y = top ; y < bottom; ++y) { BYTE* resultByte = GET_BYTE(resultBits, left, y, stride, bytepp); BYTE* srcByte = GET_BYTE(srcBits, left, y, stride, bytepp); BYTE* srcByteTop = GET_BYTE(srcBitsTop, left, y, stride, bytepp); BYTE* maskCurrent = GET_GREY(maskSrc, left, y, width); int alpha = 0; int red = 0; int green = 0; int blue = 0; for (int x = left; x < right; ++x) { alpha = *maskCurrent; red = (srcByteTop[R] * alpha + srcByte[R] * (255 - alpha)) / 255; green = (srcByteTop[G] * alpha + srcByte[G] * (255 - alpha)) / 255; blue = (srcByteTop[B] * alpha + srcByte[B] * (255 - alpha)) / 255; CLAMPTOBYTE(red); CLAMPTOBYTE(green); CLAMPTOBYTE(blue); resultByte[R] = red; resultByte[G] = green; resultByte[B] = blue; srcByte += bytepp; srcByteTop += bytepp; resultByte += bytepp; ++maskCurrent; } } ``` however I find it is still slow, it takes about 40 - 60 ms when compose two 600 \* 600 image. Is there any method to improve the speed to less then 16ms? Can any body help me to speed this code? Many thanks!
[Use SSE](http://www2.units.it/~csia/calcolointensivo/tartaglia/intel/cce/intref_cls.pdf) - start around page 131. The basic workflow 1. Load 4 pixels from src (16 1 byte numbers) RGBA RGBA RGBA RGBA (streaming load) 2. Load 4 more which you want to blend with srcbytetop RGBx RGBx RGBx RGBx 3. Do some swizzling so that the A term in 1 fills every slot I.e xxxA xxxB xxxC xxxD -> AAAA BBBB CCCC DDDD In my solution below I opted instead to re-use your existing "maskcurrent" array but having alpha integrated into the "A" field of 1 will require less loads from memory and thus be faster. Swizzling in this case would probably be: And with mask to select A, B, C, D. Shift right 8, Or with origional, shift right 16, or again. 4. Add the above to a vector that is all -255 in every slot 5. Multiply 1 \* 4 (source with 255-alpha) and 2 \* 3 (result with alpha). You should be able to use the "multiply and discard bottom 8 bits" SSE2 instruction for this. 6. add those two (4 and 5) together 7. Store those somewhere else (if possible) or on top of your destination (if you must) Here is a starting point for you: ``` //Define your image with __declspec(align(16)) i.e char __declspec(align(16)) image[640*480] // so the first byte is aligned correctly for SIMD. // Stride must be a multiple of 16. for (int y = top ; y < bottom; ++y) { BYTE* resultByte = GET_BYTE(resultBits, left, y, stride, bytepp); BYTE* srcByte = GET_BYTE(srcBits, left, y, stride, bytepp); BYTE* srcByteTop = GET_BYTE(srcBitsTop, left, y, stride, bytepp); BYTE* maskCurrent = GET_GREY(maskSrc, left, y, width); for (int x = left; x < right; x += 4) { //If you can't align, use _mm_loadu_si128() // Step 1 __mm128i src = _mm_load_si128(reinterpret_cast<__mm128i*>(srcByte)) // Step 2 __mm128i srcTop = _mm_load_si128(reinterpret_cast<__mm128i*>(srcByteTop)) // Step 3 // Fill the 4 positions for the first pixel with maskCurrent[0], etc // Could do better with shifts and so on, but this is clear __mm128i mask = _mm_set_epi8(maskCurrent[0],maskCurrent[0],maskCurrent[0],maskCurrent[0], maskCurrent[1],maskCurrent[1],maskCurrent[1],maskCurrent[1], maskCurrent[2],maskCurrent[2],maskCurrent[2],maskCurrent[2], maskCurrent[3],maskCurrent[3],maskCurrent[3],maskCurrent[3], ) // step 4 __mm128i maskInv = _mm_subs_epu8(_mm_set1_epu8(255), mask) //Todo : Multiply, with saturate - find correct instructions for 4..6 //note you can use Multiply and add _mm_madd_epi16 alpha = *maskCurrent; red = (srcByteTop[R] * alpha + srcByte[R] * (255 - alpha)) / 255; green = (srcByteTop[G] * alpha + srcByte[G] * (255 - alpha)) / 255; blue = (srcByteTop[B] * alpha + srcByte[B] * (255 - alpha)) / 255; CLAMPTOBYTE(red); CLAMPTOBYTE(green); CLAMPTOBYTE(blue); resultByte[R] = red; resultByte[G] = green; resultByte[B] = blue; //---- // Step 7 - store result. //Store aligned if output is aligned on 16 byte boundrary _mm_store_si128(reinterpret_cast<__mm128i*>(resultByte), result) //Slow version if you can't guarantee alignment //_mm_storeu_si128(reinterpret_cast<__mm128i*>(resultByte), result) //Move pointers forward 4 places srcByte += bytepp * 4; srcByteTop += bytepp * 4; resultByte += bytepp * 4; maskCurrent += 4; } } ``` To find out which AMD processors will run this code (currently it is using SSE2 instructions) see [Wikipedia's List of AMD Turion microprocessors](http://en.wikipedia.org/wiki/List_of_AMD_Turion_microprocessors). You could also look at other lists of processors on Wikipedia but my research shows that AMD cpus from around 4 years ago all support at least SSE2. You should expect a good SSE2 implimentation to run around 8-16 times faster than your current code. That is because we eliminate branches in the loop, process 4 pixels (or 12 channels) at once and improve cache performance by using streaming instructions. As an alternative to SSE, you could probably make your existing code run much faster by eliminating the if checks you are using for saturation. Beyond that I would need to run a profiler on your workload. Of course, the best solution is to use hardware support (i.e code your problem up in DirectX) and have it done on the video card.
You can always calculate the alpha of red and blue at the same time. You can also use this trick with the SIMD implementation mentioned before. ``` unsigned int blendPreMulAlpha(unsigned int colora, unsigned int colorb, unsigned int alpha) { unsigned int rb = (colora & 0xFF00FF) + ( (alpha * (colorb & 0xFF00FF)) >> 8 ); unsigned int g = (colora & 0x00FF00) + ( (alpha * (colorb & 0x00FF00)) >> 8 ); return (rb & 0xFF00FF) + (g & 0x00FF00); } unsigned int blendAlpha(unsigned int colora, unsigned int colorb, unsigned int alpha) { unsigned int rb1 = ((0x100 - alpha) * (colora & 0xFF00FF)) >> 8; unsigned int rb2 = (alpha * (colorb & 0xFF00FF)) >> 8; unsigned int g1 = ((0x100 - alpha) * (colora & 0x00FF00)) >> 8; unsigned int g2 = (alpha * (colorb & 0x00FF00)) >> 8; return ((rb1 | rb2) & 0xFF00FF) + ((g1 | g2) & 0x00FF00); } ``` 0 <= alpha <= 0x100
How to alpha blend RGBA unsigned byte color fast?
[ "", "c++", "performance", "" ]
I have the following JavaScript code: ``` oCoord = {x: null, y: null}; var aStack = []; oCoord.x = 726; oCoord.y = 52; aStack.push(oCoord); oCoord.x = 76; oCoord.y = 532; aStack.push(oCoord); oCoord.x = 716; oCoord.y = 529; aStack.push(oCoord); ``` Now this creates the following structure (an array of three objects). ``` Array[Object, Object, Object]; ``` However, when I try and access the properties of each object they are all coming out the same. Why is this? ``` alert(aStack[0].x); // Outputs 716 alert(aStack[1].x); // Outputs 716 alert(aStack[2].x); // Outputs 716 ``` What am I doing wrong?
You are using the same oCoord for all your coordinates objects. Try this instead: ``` var aStack = []; aStack.push( { x: 726, y: 52} ); aStack.push( { x: 532, y: 76} ); aStack.push( { x: 716, y: 529} ); ```
You are using the same reference to your object. You need to create a new one each time. E.g. ``` var aStack = []; aStack.push( { x: 2, y: 23 }); aStack.push( { x: 3, y: 4 }); aStack.push( { x: 33, y: 2 }); ``` Or, if you prefer the style you wrote it in, do: ``` var aStack = []; var o = {}; o.x=1; o.y=3; aStack.push(o); var o = {}; o.x=21; o.y=32; aStack.push(o); var o = {}; o.x=14; o.y=43; aStack.push(o); alert( aStack[0].x ); alert( aStack[1].x ); alert( aStack[2].x ); ``` Note we are re-declaring with `var` each time to create a new instance.
JavaScript object literal and array
[ "", "javascript", "" ]
I'm using a class that forwards events in C#. I was wondering if there's a way of doing it that requires less code overhead. Here's an example of what I have so far. ``` class A { public event EventType EventA; } class B { A m_A = new A(); public event EventType EventB; public B() { m_A.EventA += OnEventA; } public void OnEventA() { if( EventB ) { EventB(); } } } ``` Class A raises the original event. Class B forwards it as EventB (which is essentially the same event). Class A is hidden from other modules so they can't subscribe to EventA directly. What I'm trying to do is reduce the code overhead in class B for forwarding the event, as typically there's no real handling of the events in class B. Also I'll have several different events so it would require writing a lot of OnEvent() methods in class B that only serve to forward the events. Is it possible to automatically link EventA to EventB in some way, so I'd have something like this: ``` class B { A m_A = new A(); public event EventType EventB; public B() { m_A.EventA += EventB; // EventA automatically raises EventB. } } ``` I'm using a C# 2.0 compiler btw.
Absolutely: ``` class B { private A m_a = new A(); public event EventType EventB { add { m_a.EventA += value; } remove { m_a.EventA -= value; } } } ``` In other words, the EventB subscription/unsubscription code just passes the subscription/unsubscription requests on to EventA. Note that this doesn't allow you to raise the event *just* for subscribers who subscribed to EventB, however. It's like passing someone's address directly onto a mass marketing company, whereas your original way is more like subscribing to the mass marketing company yourself, and allowing people to ask you to send copies of the mails to them.
IMO, your original code is (more or less) correct. In particular, it allows you to provide the correct `sender` (which should be the `B` instance for people who think they are subscribing to an event on `B`). There are some tricks to reduce the overheads at runtime if the event isn't subscribed, but this adds *more* code: ``` class B { A m_A = new A(); private EventType eventB; public event EventType EventB { add { // only subscribe when we have a subscriber ourselves bool first = eventB == null; eventB += value; if(first && eventB != null) m_A.EventA += OnEventB; } remove { // unsubscribe if we have no more subscribers eventB -= value; if(eventB == null) m_A.EventA -= OnEventB; } } protected void OnEventB(object sender, EventArgsType args) { eventB?.Invoke(this, args); // note "this", not "sender" } } ```
Forwarding events in C#
[ "", "c#", "events", "event-handling", "c#-2.0", "" ]
I'm looking for a sorted data structure, that will be similar to the STL set(T). I found SortedList, but it requires (key, val), I'm looking for something like List(string) - only sorted. I found on the web Spring.Collections, but my framework does not recognize it. Is there a simple SortedSet I could use in the regular basic framework? Thanks, Gal
You can do this with A System.Collections.Generic.Dictionary. Here's a good article: [Dictionarys and sorting](http://dotnetperls.com/sort-dictionary-values) **Edit:** The SortedDictionary seems even [better](http://dotnetperls.com/sorteddictionary).
A SortedSet < T > introduced in .NET 4.0 is what you are looking for, see MSDN [here](http://msdn.microsoft.com/en-us/library/dd412070(VS.100).aspx)
C# alternative for the C++ STL set<T>
[ "", "c#", "sorting", "" ]
Im using this code for mysql connection ``` $con = mysql_connect("localhost:/var/lib/mysql/mysql.sock", "abc" , "xyz"); if (!$con) { die('Could not connect: '); } mysql_select_db("database_name", $con); ``` Im including this file on the top of every php file that im using for parsing and then storing the data in database.Now when the original site gets down then my parsing files starts giving error "Warning: mysql\_connect(): Too many connections in /home/clickindia/public\_html/appuonline/db.php on line 2 Could not connect:" What should i do to save my site from these errors.Do you think that i should use mysql\_close($con); But how and where??? Im using die in my code is that correct or should i use close etc. plz help!!
You say you put this connection code "on the top of every php file". My question is: do you use several of these files for a single page? If this is the case, then you should open the connection only once for a page. This could be the explanation of the error. Artem's advises are pertinent too.
You might want to consider wrapping a singleton around database access. Benefits: * You can only use one connection. * You only open a connection if you need it (rather than arbitrarily connect on every page). You can roll your own singleton or get one from a framework, thought that might be overkill depending on what you're working on. The basics would be something like this: ``` class DatabaseAccess { private static $instance; private $connection; //declare the constructor private so we can only use it in this class private function __construct( $host, $user, $pass, $db ) { $this->connection = mysql_connect( $host, $user, $pass ); mysql_select_db( $db, $this->connection ); } //provide access to a single instance public static function instance() { if ( ! isset( self::$instance ) ) { self::$instance = new DatabaseAccess('host', 'user', 'pass', 'db'); } return self::$instance; } //functions to execute/query the db public function query( $query ) { return mysql_query( $query, $this->connection ); } } ``` If I were to go down this route, I'd probably do this by controlling access to an instance of mysqli and use it directly rather than wrap the mysql\_\* functions. You can find out more about the singleton pattern on wikipedia. Your application would then work with the class like this: ``` $dba = DatabaseAccess::instance(); $result = $dba->query('select * from pages'); mysql_fetch_assoc($result); //blah blah blah ``` Hope that helps!
mysql connection
[ "", "php", "mysql", "database-connection", "" ]
I have a winform program that uses Merge Replication to keep a local SQL Express sync'd with a Central SQL Server on our network. Due to the nature of this app the sync process runs automatically on App open and close. The way I am doing it (below) seems quite time consuming. What would be a faster way? Thinking outside the box it would probably be okay if I just checked for the Server itself though that could present a hole for an edge case where the Server is available but SQL is down. Alternately, maybe just checking if our domain is available though that could leave the same hole I guess. Thanks! ``` private static bool IsSqlAvailable() { try { var conn = new SqlConnection("Data Source=WWCSTAGE;Initial Catalog=Connect;Integrated Security=True"); conn.Open(); conn.Close(); HUD.IsSQLAvailable = true; return true; } catch (Exception) { HUD.IsSQLAvailable = false; return false; } } ``` --- As an additional note. The above is particularly slow when off network. I even set the Connection Timeout = 1 and it still sits at this point for quite some time.
My usual advice in this kind of scenario, where you're checking for the existence/connectivity of something that is out of your control is: don't. Your check can pass and an instant later, the result is no longer true. So just try to do whatever it is you want to do, assuming that the SQL server is available, and handle the inevitable errors gracefully.
I would wrap my Connection in a using clause and probably lower the connection timeout in my connection string (generally, if the server is up, it should connect more quickly than the default), but other than that, it's fine.
Fastest way to tell if SQL Server is available
[ "", "c#", "sql-server", "winforms", "network-programming", "" ]
I've bound my TextBox to a string value via ``` Text="{Binding AgeText, Mode=TwoWay}" ``` How can I display string.empty or "" for the string "0", and all other strings with their original value? Thanks for any help! Cheers PS: One way would be a custom ViewModel for the string.. but I'd prefer to do it somehow in the XAML directly, if it's possible.
I think the only way beside using the ViewModel is creating a custom ValueConverter. So basically your choices are: ViewModel: ``` private string ageText; public string AgeText{ get{ if(ageText.equals("0")) return string.empty; return ageText; } ... } ``` ValueConverter: ``` public class AgeTextConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value.Equals("0")) return string.Empty; return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { } } ```
I found something on <http://www.codeproject.com/KB/books/0735616485.aspx> This will do the trick: ``` Text="{Binding AgeText, StringFormat='\{0:#0;(#0); }'}" ``` Cheers
C#/WPF Display Custom Strings (e.g. replace "0" with string.empty)
[ "", "c#", "wpf", "string-formatting", "" ]
Trying to figure this out... I'm trying to accessthe top level of the dom from inside an iframe. How possible is this?
From inside of a frame you can always get to the top level using `window.top`. You can check to see if you are in a frame using: ``` var iAmInAFrame = (window.top == window.self); ``` You should be able to use `window.top.document.whatever` (e.g. body, getElementById(), etc.) to manipulate the top level document provided that you share a domain.
You can append window.parent.document to your calls to get to the parent. e.g. ``` $('body', window.parent.document).append("this is coming from my iframe"); ``` **Edit:** As noted in the comments below the iframe must be served from the same domain as the parent or the browser's security restrictions will prevent this.
How do you access the top level of the DOM from jQuery?
[ "", "javascript", "jquery", "dom", "iframe", "" ]
Let's say I have two files `default.aspx` and the associated `default.aspx.cs`. default.aspx.cs: ``` protected void Page_Load(object sender, EventArgs e) { var myObject = new MyObject(); } ``` Is there a way that in the `default.aspx` I could do something like: ``` <%= myObject.SomePropertyOfThisObject%> ``` ... or something similar, without having to use databinders or something complicated like this? And if there's no way around binding the data, what would be the best way to do it?
You can, but you'll have to do it a bit differently. In your default.aspx.cs, add a member: ``` protected MyObject _myObject; ``` Then, in Page\_Load: ``` protected void Page_Load(object sender, EventArgs e) { _myObject = new MyObject(); } ``` Then, in default.aspx, you can do: ``` <%= _myObject.SomePropertyOfThisObject %> ``` Of course, this assumes that class MyObject has a property named Awesome. You didn't mean the System.Object class, did you, since it doesn't have a property named Awesome. --- Since your question was asking about the *best* way, I'll go further. The way I showed is not the best. The best is more often to use a data binding expression. If you don't like those, then you can set things in the codebehind: ``` protected void Page_Load(object sender, EventArgs e) { _myObject = new MyObject(); // _myLabel.Text = _myObject.SomePropertyOfThisObject; } ``` Assuming: ``` <asp:Label runat="server" id="_myLabel" /> ```
The <%= ... %> is ASPX short-hand for `Response.Write( .... )`. If you change myObject to be strongly types (rather than just types as Object) you can certain use the line: ``` <%= myObject.Awesome %> ``` to emit a value. Be aware, however, that the <%= syntax has limitations - specifically: * it cannot be used within HTML attribute as a value * it cannot emit server-side elements * it cannot be used within ASP UpdatePanels - you will get a exception when you perform a partial postback You are probably better off creating a Label control on you page, and programmatically setting the `Text` property to the value. This also gives you more control over how value-to-string conversions are performed. And will work correctly with update panel controls.
Best way to access properties of my code behind class from the markup in ASP.NET
[ "", "c#", "asp.net", "scope", "" ]
I currently have a java library in subversion under package: ``` com.company.product.foo.* ``` Unfortunately, I have to refactor this into: ``` com.othercompany.bar.* ``` That'd be fine as a *one-shot*. But this has to be performed only on a specific branch. The problem is then to merge changes from trunk to the branch with totally different names. The only solution I see would be to create a patch file, run some *search & replace* and then apply it on the branch. Is there any better option ?
The first most obvious solution is to not use either company name as the package, but rather a trademarked name, or a neutral domain name that would be used going forward. If that isn't possible (as in the customer doesn't want the two code bases to be seen as connected) the next most obvious solution is to use a source control system that is more friendly to the concept. Git might have better options, or [perforce](https://stackoverflow.com/questions/967633/how-to-make-a-perforce-branch-with-a-different-java-package-name). If you have to stick with subversion, then I would have it in source control under a neutral package name and then have the build process that checks out the code, moves it, renames the packages, and compiles, once for each company. Or If your IDE can understand it use a Java pre-processor. Of course, that last one only works if both customers stay on the same base, but if not then the customer would have its own branch, and the build process could copy the code only as appropriate for the correct branch.
I can't see any really good solutions, but would it be an option to just create subclasses under the new package name? Then the patches could be applied to the super classes, and the sub classes would never actually contain anything.
Change Java package name in a SVN branch
[ "", "java", "svn", "" ]
(Long time reader of SO, first time asking a q. I'm quite new to C# having been in the PHP/Ruby/Python world for many years so I apologise if this is a dopey question.) I'm doing some maintenance on an old C# app that is crashing whenever SmtpClient.Send() fails. From the little I've gleaned from the MSDN, I can see the obvious way to fix this, but my question is also concerned with the more general case. As per the MSDN: ``` try { client.Send(message); } catch (Exception ex) { Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString() ); } ``` This all makes sense to me, but I've also always thought that whenever you can prevent the possibility of the error you do so. Is there anything you can (and should?) do here to reduce the possibility of the Send() throwing exceptions? I'm assuming there are situations where it's impossible to prevent the possibility of an exception, so you have to handle it, but are there any general style guide or rules that people use to guide them? Again, sorry if this is a crap question. I tried searching SO and Google as much as I could. EDIT: I just found this question [Best practices for exception management in java or C](https://stackoverflow.com/questions/409563/best-practices-for-exception-management-in-java-or-c) which may well go someway to answering my question. EDIT2: Thanks for the prompt feedback, incredibly fast. I've been thinking about the problem a bit more and perhaps this could further refine what I'm asking. Is it correct to say that certain exceptions, like SmtpException, really can't be avoided? Is it even more correct to say that it is the correct style to use exceptions like SmtpException to tell you that something went wrong with the send and you just handle it however you'd like? I feel like I'm sounding a bit dim in this question, but I'm asking because anything I can learn is good for my confidence.
When catching exceptions, be as specific as possible if you know what kinds of exceptions to expect from the invoked method. This will allow, for example, errors such as OutOfMemoryException to continue to bubble up the stack where it should go unhandled and then your app will fail fast (which is probably a good thing because your system is now in an unknown state and you should not carry on). There are different schools of thought on this, however; in some instances (say you're an NT service) you want high availability of your app, and crashing in production because you get NullPointerException on some unforeseen code path may not be desirable as long as that exception gets logged and you have the ability to then issue a QFE (not to mention revise your test regime). If you're a console or forms app, then recovery is a different story since the exception could be surfaced to the user and they can interactively decide what the appropriate action is. My general advice: catch specific exceptions as close to the source as possible, let the rest bubble up the stack and have it logged at a point where you have enough context to later on try and repro the exception. Be wary that catching then re-throwing is expensive; a scenario in your example where you might want to do this would be if, say, the SmtpException was a connection timeout (I'm making this up), then one strategy might be exponential back off and retry up to n times since the mail server might be down, then finally give up and rethrow if you don't succeed. The really short answer is: It All Depends.
This is a good example of what I call an "exogenous" exception situation. [http://ericlippert.com/2008/09/10/vexing-exceptions/](http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx) Consider an analogous case -- opening a file. You can reduce the chance of getting an exception by: * checking whether the file exists * checking whether the user has permission to open the file * checking whether another application has locked the file * blah * blah blah * blah blah blah You can do all that and STILL get an exception when you open the file. Because between doing all those checks and you trying to open the file, something might have changed. Another process might have changed the permissions, or locked the file, or the user removed the CD-ROM from the drive, or whatever. Whether the action succeeds or not is based on an exogenous, real-world condition that you cannot test for in any kind of guaranteed way. Exogenous exceptions are a pain to deal with, because you HAVE to handle them even if you do lots of work to eliminate them. Sending mail is the same way. You can check all kinds of things to try to eliminate the exception, which probably will work 99% of the time, but you still cannot GUARANTEE that between all your checks and the actual attempt to send mail, that someone didn't unplug the router at exactly the wrong moment. You're just going to have to suck it up and handle the exceptions.
C# SmtpClient.Send() - Any alternative (or companion) to handling the exception?
[ "", "c#", "exception", "" ]
I'm curious if there is an efficient way to wait for the front page of a site to load, and then pre-load CSS and script files that I know will likely be needed for the other pages on the site. I want the front page of the site to be as fast as possible (lean and mean). It's likely that the user will not immediately click on a link. Since there will likely be some idle time, this seems like an opportune time to pre-load some of the external assets. Pre-loading should cause them to become cached. When the user does click on another page, the only request needed will be for the content and possibly some images, etc. Has anyone done this? Is it a bad idea? Is there an elegant way to implement it?
That's an interesting idea, I'm not sure if it could be done via Javascript (at least the CSS part). You might place an IFRAME on the page with the other resources you want to load, but put some CSS on it to hide it... ``` .preload { position : absolute; top : -9999px; height : 1px; width : 1px; overflow : hidden; } ``` If you put this at the end of the page then I would think it would load *after* the rest of the page. If not then you could use some Javascript and setTimeout to actually create the IFRAME after the page loads.
The hidden iFrame idea that people are advocating will work just fine. If page load time of the landing page is a priority too though, the thing to to do would be to create the iFrame dynamically in javascript once the page has finished loading.
Pre-loading external files (CSS, JavaScript) for other pages
[ "", "javascript", "jquery", "html", "css", "preload", "" ]
I am planing a database to store lots of text. (blog posts, news articles, etc.) The database needs to have the title, content (50k characters max), date, link and language fields. The same content can't occur on one link. Old content (older then 30 days, for example) will be deleted. Now, the problem is the primary key. I could just set a automatically incrementing (SERIAL type) field and use it as a primary key. But, it seems stupid and a waste of disc space, because the field wouldn't serve any purpose but to be a primary key. (and the field could eventually run out, or not?) And there's always the other performance issue: the content of each new row inserted needs to be checked for duplicates. So the other solution for the primary key I've come up with would be to calculate a sha256 hash of content+link value and then put that in a new 'hash' column and use that as a primary key. Two birds with one stone. Of course, the problem with that are hash collisions. Is it a big threat? I don't have any experience with PostgreSQL, and very little experience with DBMS's generally, so I would appreciate a second opinion before a create a database with the performance characteristics of a snail on the highway (horrible comparison). Please help me out here if you have any experience with large databases. Is setting a 64 character string as a primary key field a good idea in my situation? (because I'm under the impression that generally this is avoided)
Just did this exact test for a rather medium-large DB (200GB+), bigserial won by quite a large margin. It was faster to generate, faster to join, less code, smaller footprint. Because of the way postgres stores it, a bigint is negligible compared to a normal int. You'll run out of storage space from your content long before you ever have to worry about overflowing the bigint. Having done the computed hash vs bigint - surrogate bigint all the way.
I would choose to use a surrogate key, ie. a key that isn't part of the business data of your application. The additional space requirements of an additional 64-bit integer when you're dealing with upto 50 kilobytes of text per record is negligible. You will actually be using *less* space as soon as you're starting using this key as a foreign key in other tables. Using a hash of the data stored in a record is a very bad candidate for a primary key, should the data on which the hash is based ever change. You will then have changed the primary key as well, resulting in updates all over the place if you have relations from other tables to this one. PS. A similar question has been asked and answered here [before](https://stackoverflow.com/questions/337503/whats-the-best-practice-for-primary-keys-in-tables). Here's another nice write-up about the topic: <http://www.agiledata.org/essays/keys.html>
PostgreSQL: Defining a primary key on a large database
[ "", "sql", "database", "database-design", "postgresql", "" ]
Are there any security exploits that could occur in this scenario: ``` eval(repr(unsanitized_user_input), {"__builtins__": None}, {"True":True, "False":False}) ``` where `unsanitized_user_input` is a str object. The string is user-generated and could be nasty. Assuming our web framework hasn't failed us, it's a real honest-to-god str instance from the Python builtins. If this is dangerous, can we do anything to the input to make it safe? We definitely *don't* want to execute anything contained in the string. See also: * [Funny blog post about eval safety](http://blog.thetonk.com/archives/dont-be-lazy-dont-use-eval/comment-page-2#comments) * [Previous Question](https://stackoverflow.com/questions/661084/security-of-pythons-eval-on-untrusted-strings) * [Blog: Fast deserialization in Python](http://blog.metaoptimize.com/2009/03/22/fast-deserialization-in-python/) The larger context which is (I believe) not essential to the question is that we have thousands of these: ``` repr([unsanitized_user_input_1, unsanitized_user_input_2, unsanitized_user_input_3, unsanitized_user_input_4, ...]) ``` in some cases nested: ``` repr([[unsanitized_user_input_1, unsanitized_user_input_2], [unsanitized_user_input_3, unsanitized_user_input_4], ...]) ``` which are themselves converted to strings with `repr()`, put in persistent storage, and eventually read back into memory with eval. Eval deserialized the strings from persistent storage much faster than pickle and simplejson. The interpreter is Python 2.5 so json and ast aren't available. No C modules are allowed and cPickle is not allowed.
It is indeed dangerous and the safest alternative is `ast.literal_eval` (see the [ast](http://docs.python.org/library/ast.html#module-ast) module in the standard library). You can of course build and alter an `ast` to provide e.g. evaluation of variables and the like before you eval the resulting AST (when it's down to literals). The possible exploit of `eval` starts with any object it can get its hands on (say `True` here) and going via .\_\_class\_ to its type object, etc. up to `object`, then gets its subclasses... basically it can get to ANY object type and wreck havoc. I can be more specific but I'd rather not do it in a public forum (the exploit is well known, but considering how many people still ignore it, revealing it to wannabe script kiddies could make things worse... just avoid `eval` on unsanitized user input and live happily ever after!-).
If you can prove beyond doubt that `unsanitized_user_input` is a `str` instance from the Python built-ins with nothing tampered, then this is always safe. In fact, it'll be safe even without all those extra arguments since `eval(repr(astr)) = astr` for all such string objects. You put in a string, you get back out a string. All you did was escape and unescape it. This all leads me to think that `eval(repr(x))` isn't what you want--no code will ever be executed unless someone gives you an `unsanitized_user_input` object that looks like a string but isn't, but that's a different question--unless you're trying to copy a string instance in the slowest way possible :D.
Safety of Python 'eval' For List Deserialization
[ "", "python", "eval", "" ]
Using C#, I want to generate 1,000,000 files from DB, each record in separate file. What is the best way to generate this files in minimum time? Here is my code without threading : ``` AppDomain.CurrentDomain.ProcessExit += new EventHandler(CurrentDomain_ProcessExit); // to calculate the execution time in case of using threading SqlCommand cmd = new SqlCommand(@"select top 1000000 p1+','+p2+','+p3+','+p4 as line from lines ", con); con.Open(); var rdr = cmd.ExecuteReader(); int i = 0; while (rdr.Read()) { string line = rdr.Getring(0); string filename = String.Format("file{0}.txt", ++i); File.WriteAllText(filename, line); } rdr.Close(); con.Close(); ```
Since your operations are IO bound and not CPU bound, the best way is to have 2 threads, one that reads from DB the records and put it into a queue, the other read from the queue and generate the files. Alternatively, you can use the CLR thread pool for that, something like ``` while (rdr.Read()) { string line = rdr.Getring(0); ThreadPool.QueueUserWorkItem (new WaitCallback(writeData), line); } ``` and writeData would look like ``` static void writeData(Object line) { string filename = String.Format("file{0}.txt", ++i); File.WriteAllText(filename, line); } ``` The disadvantage of using the ThreadPool is you could end up more threads than you want, since your threads will be blocked in IO most of the time, the thread pool will create new threads to service your requests. You can try the thread pool first and measure the performance, if you are not satisfied, you can try the 2 threads, 1 queue approach; well known as Producer/Consumer problem.
You would benefit from having more threads; the best way to figure out the exact number is empirically, but don't limit yourself to one per CPU core the way you might with CPU-bound tasks. The very easiest way is to use a ThreadPool, but a Producer/Consumer queuing system would be more flexible and tunable.
Best code to generate 1,000,000 files from Database
[ "", "c#", "multithreading", "io", "" ]
I thought BeautifulSoup will be able to handle malformed documents, but when I sent it the source of a page, the following traceback got printed: ``` Traceback (most recent call last): File "mx.py", line 7, in s = BeautifulSoup(content) File "build\bdist.win32\egg\BeautifulSoup.py", line 1499, in __init__ File "build\bdist.win32\egg\BeautifulSoup.py", line 1230, in __init__ File "build\bdist.win32\egg\BeautifulSoup.py", line 1263, in _feed File "C:\Python26\lib\HTMLParser.py", line 108, in feed self.goahead(0) File "C:\Python26\lib\HTMLParser.py", line 150, in goahead k = self.parse_endtag(i) File "C:\Python26\lib\HTMLParser.py", line 314, in parse_endtag self.error("bad end tag: %r" % (rawdata[i:j],)) File "C:\Python26\lib\HTMLParser.py", line 115, in error raise HTMLParseError(message, self.getpos()) HTMLParser.HTMLParseError: bad end tag: u"", at line 258, column 34 ``` Shouldn't it be able to handle this sort of stuff? If it can handle them, how could I do it? If not, is there a module that can handle malformed documents? EDIT: here's an update. I saved the page locally, using firefox, and I tried to create a soup object from the contents of the file. That's where BeautifulSoup fails. If I try to create a soup object directly from the website, it works.[Here's](http://pastie.org/541966) the document that causes trouble for soup.
Worked fine for me using BeautifulSoup version 3.0.7. The latest is 3.1.0, but there's a note on the BeautifulSoup home page to try 3.0.7a if you're having trouble. I think I ran into a similar problem as yours some time ago and reverted, which fixed the problem; I'd try that. If you want to stick with your current version, I suggest removing the large `<script>` block at the top, since that is where the error occurs, and since you cannot parse that section with BeautifulSoup anyway.
The problem appears to be the `contents = contents.replace(/</g, '&lt;');` in line 258 plus the similar `contents = contents.replace(/>/g, '&gt;');` in the next line. I'd just use re.sub to clobber all occurrences of r"replace(/[<>]/" with something inocuous before feeding it to BeautifulSoup ... moving away from BeautifulSoup would be like throwing out the baby with the bathwater IMHO.
Why is BeautifulSoup throwing this HTMLParseError?
[ "", "python", "exception", "parsing", "beautifulsoup", "malformed", "" ]
In my Java code I have function that gets file from the client in http request and converts that in to the file. I have this line there: ``` byte[] buffer = new byte[8192]; ``` what does 8192 bytes (8 kb) means here? [This is one of the responses that I got](https://stackoverflow.com/questions/1111130/basic-file-upload-in-gwt/1111606#1111606), and want to make sure that I understand that code.
That it uses a buffer to read and write 8kB blocks at once. The number is fairly arbitary, but for performance reasons it makes sense to use a multiple of 512 bytes when writing a file, and preferably a multiple of the disks cluster size. 8kB is a reasonable buffer size for most purposes.
This is the size of the array of bytes, meaning that your buffer will hold 8192 bytes at a time.
8192 bytes when creating file
[ "", "java", "arrays", "" ]
I have run into a problem w/ my model for databinding in WPF. I have an object which has a collection of objects (Variable), and each in turn has yet another collection of objects (VariableCode). What I need to be able to do is somehow expose a single collection from the highest level object - which is a fusing of the lowest level collections (VariableCode) where each member object meets a condition. So that I can bind that collection to a ListBox, which should display VariableCodes that belong to 1 or more variables. So the code looks something like this: ``` public class CrossTab { public VariableList Variables{get; set;} } public class Variable { public VariableCodeList VariableCodes{get; set;} } public class VariableCode { public bool IsShown{get; set;} } ``` What I'd really like to do is expose a property on CrossTab (preferably an ObservableCollection<VariableCode>) which is a view on all the contained VariableCodes where IsShown == true. Currently, they're separate collections - each contained in their own Variable object. ``` public class CrossTab { public ObservableCollection<VariableCode> ShownCodes { get { //This is where I could picture some brute force looping // and building of a new collection - but that's not really // what I'm after. What I want is a live view on the data // that's in there } } } ``` The brute force code that I was toying with which returns the correct data - just not as a live view, but rather as a static collection. ``` ObservableCollection<VariableCode> output = new ...(); Variables.ForEach(v => v.VariableCodes.Where(vc => vc.IsShown) .ForEach(vc => output.Add(vc)) ); return output; ``` Thoughts? Is such a thing possible?
You can use the SelectMany Linq method to achieve this, as follows: ``` public class CrossTab { public VariableList Variables { get; set; } public ObservableCollection<VariableCode> ShownCodes { get { return new ObservableCollection<VariableCode>( Variables .SelectMany(variable => variable.VariableCodes) .Where(code => code.IsShown) ); } } } ```
I think SelectMany (LINQ) is what you are looking for. See if [this](http://team.interknowlogy.com/blogs/danhanan/archive/2008/10/10/use-linq-s-selectmany-method-to-quot-flatten-quot-collections.aspx) helps. Trying to use the above link for your example & writing it in SO (without compiler). I will be amazed, if this works ;) ``` var allTeams = from v in Variables.SelectMany( v => v.VariableCodes ).SelectMany(vc) where vc.IsShown == true; select vc; ```
Expose multiple collections as a single collection
[ "", "c#", "collections", "view", "" ]
I hope this is a quick question I hope. I need to write some reports and then have the user prompted to save it to his/her local machine. The last time I did this I wrote a file to the webserver and then sent it to the client via `Response` object. to create on the webserver ``` TextWriter tw = new StreamWriter(filePath); ``` to send to client ``` page.Response.WriteFile(path); ``` The question is, Is there a way to skip the writing of the physical file to to the webserver and go right from an object that represent the document to the response?
You could use the Response.ContentType like this ``` Response.ContentType = "text/plain"; Response.OutputStream.Write(buffer, 0, buffer.Length); Response.AddHeader("Content-Disposition", "attachment;filename=yourfile.txt"); ``` This of course works if you want to write a text file. In case you want to write a .doc for example you change the ContentType to "application/msword" etc...
You can. Try this: ``` Table oTable = new Table(); //Add data to table. Response.Clear(); Response.Buffer = true; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename="test.xls""); Response.Charset = ""; this.EnableViewState = false; System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); System.Web.UI.Html32TextWriter oHtmlTextWriter = new System.Web.UI.Html32TextWriter(oStringWriter); 0Table.RenderControl(oHtmlTextWriter); Response.Write(oStringWriter.ToString()); Response.End(); ``` This will give prompt the user to open or save test.xls file. similarly you can provide other ASP.NET objects in place of Table.
C# Asp.net write file to client
[ "", "c#", "response", "" ]
Just curious what is the best practice for solving the following issue. I have institutions, accounts and users tables. Institutions and accounts have a one-to-many relationship. Institutions and users have a one-to-many relationship. Users and accounts have a many-to-many relationship or alternatively they could have a many-to-all (or \*) accounts. Meaning, that a user could be designated to all accounts, and any new accounts that are added to the institution the user would have access to without explicitly adding the relationship.
I'd do it like so: ``` Institutions InstitutionID INT IDENTITY(1,1) NOT NULL PRIMARY KEY Name VARCHAR(255) Users UserID INT IDENTITY(1,1) NOT NULL PRIMARY KEY Username VARCHAR(255) NOT NULL InstitutionID INT NOT NULL Accounts AccountID INT IDENTITY(1,1) NOT NULL PRIMARY KEY Account VARCHAR(255) NOT NULL InstitutionID INT NOT NULL Users_Accounts Users_AccountsID INT IDENTITY(1,1) NOT NULL PRIMARY KEY UserID INT NOT NULL AccountID INT NULL ``` Have a UserID w/ a `NULL` entry in the `Users_Accounts` table have global (\*) access. This way, you can determine the Institution on any Account and/or User, as well as their permissions. Edit: Columns w/ the same name in different tables imply a Foreign Key. Please use them if you aren't doing heavy loads.
Make `Accounts` have a foreign key to `Institutions`. Make `Users` have a foreign key to `Institutions`. Make a flag on the `Users` account that indicates that they will have access to all `Accounts` on that `Institution`. Create a many-to-many mapping table for `Users` to `Accounts`. This will be used only if the `User` does not have their flag set such that they have access to all `Accounts` on the `Institution`. This should solve your problem.
What is the best practice for accommodating both a one-to-many and a one-to-all (or one-to-*) relationship?
[ "", "sql", "database", "sql-server-2005", "" ]
I was reading [this question](https://stackoverflow.com/questions/1071935/i-need-a-python-class-that-keep-tracks-of-how-many-times-it-is-instanciated) (which you do not have to read because I will copy what is there... I just wanted to give show you my inspiration)... So, if I have a class that counts how many instances were created: ``` class Foo(object): instance_count = 0 def __init__(self): Foo.instance_count += 1 ``` My question is, if I create Foo objects in multiple threads, is instance\_count going to be correct? Are class variables safe to modify from multiple threads?
It's not threadsafe even on CPython. Try this to see for yourself: ``` import threading class Foo(object): instance_count = 0 def inc_by(n): for i in xrange(n): Foo.instance_count += 1 threads = [threading.Thread(target=inc_by, args=(100000,)) for thread_nr in xrange(100)] for thread in threads: thread.start() for thread in threads: thread.join() print(Foo.instance_count) # Expected 10M for threadsafe ops, I get around 5M ``` The reason is that while INPLACE\_ADD is atomic under GIL, the attribute is still loaded and store (see *dis.dis(Foo.\_\_init\_\_)*). Use a lock to serialize the access to the class variable: ``` Foo.lock = threading.Lock() def interlocked_inc(n): for i in xrange(n): with Foo.lock: Foo.instance_count += 1 threads = [threading.Thread(target=interlocked_inc, args=(100000,)) for thread_nr in xrange(100)] for thread in threads: thread.start() for thread in threads: thread.join() print(Foo.instance_count) ```
No it is not thread safe. I've faced a similar problem a few days ago, and I chose to implement the lock thanks to a decorator. The benefit is that it makes the code readable: ``` def threadsafe_function(fn): """decorator making sure that the decorated function is thread safe""" lock = threading.Lock() def new(*args, **kwargs): lock.acquire() try: r = fn(*args, **kwargs) except Exception as e: raise e finally: lock.release() return r return new class X: var = 0 @threadsafe_function def inc_var(self): X.var += 1 return X.var ```
Is modifying a class variable in python threadsafe?
[ "", "python", "multithreading", "" ]
I understand that Python loggers cannot be instantiated directly, as the documentation suggests: > Note that Loggers are never > instantiated directly, but always > through the module-level function > `logging.getLogger(name)` .. which is reasonable, as you are expected *not* to create logger objects for every class/module for there is a [better alternative](https://stackoverflow.com/questions/401277/naming-python-loggers/402471#402471). However, there are cases where I want to *create* a logger object and attach a file to it exclusively for logging some app-specific output to that file; and then close the log file. For instance, I have a program that builds all packages in [PyPI](http://pypi.python.org/). So basically assume there is a `for` loop going over every package. Inside the loop, I want to "create" a logger, attach a file handler (eg: /var/logs/pypi/django/20090302\_1324.build.log and send the output of `python setup.py build` (along with other things) to this log file. Once that is done, I want to close/destroy the logger and `continue` building other packages in similar fashion. So you see .. the normal Pythonic way of calling `logging.getLogger` does not apply here. One needs to create **temporary** logger objects. Currently, I achieve this by passing the file name itself as the logger name: ``` >>> packagelog = logging.getLogger('/var/..../..34.log') >>> # attach handler, etc.. ``` I want to ask .. is there a better way to do this?
Instead of many loggers, you could use one logger and many handlers. For example: ``` log = logging.getLogger(name) while some_condition: try: handler = make_handler(filename) log.addHandler(handler) # do something and log finally: log.removeHandler(handler) handler.close() ```
There are two issues here: 1. Being able to direct output to different log files during different phases of the process. 2. Being able to redirect stdout/stderr of arbitrary commands to those same log files. For point 1, I would go along with `ars`'s answer: he's spot on about just using multiple handlers and one logger. his formatting is a little messed up so I'll reiterate below: ``` logger = logging.getLogger("pypibuild") now_as_string = datetime.datetime.utcnow().strftime("%Y%m%d_%H%M") for package in get_pypi_packages(): fn = '/var/logs/pypi/%s/%s.log' % (package, now_as_string) h = logging.FileHandler(fn, 'w') logger.addHandler(h) perform_build(package) logger.removeHandler(h) h.close() ``` As for point 2, the `perform_build()` step, I'll assume for simplicity's sake that we don't need to worry about a multicore environment. Then, the `subprocess` module is your friend. In the snippet below, I've left out error handling, fancy formatting and a couple of other niceties, but it should give you a fair idea. ``` def perform_build(package): logger.debug("Starting build for package %r", package) command_line = compute_command_line_for_package(package) process = subprocess.Popen(command_line, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() logger.debug("Build stdout contents: %r", stdout) logger.debug("Build stderr contents: %r", stderr) logger.debug("Finished build for package %r", package) ``` That's about it.
Pythonic way to log specific things to a file?
[ "", "python", "logging", "" ]
How can I map a DataReader object into a class object by using generics? For example I need to do the following: ``` public class Mapper<T> { public static List<T> MapObject(IDataReader dr) { List<T> objects = new List<T>(); while (dr.Read()) { //Mapping goes here... } return objects; } } ``` And later I need to call this class-method like the following: ``` IDataReder dataReader = DBUtil.Fetchdata("SELECT * FROM Book"); List<Book> bookList = Mapper<Book>.MapObject(dataReder); foreach (Book b in bookList) { Console.WriteLine(b.ID + ", " + b.BookName); } ``` Note that, the Mapper - class should be able to map object of any type represented by T.
I use [ValueInjecter](http://valueinjecter.codeplex.com/) for this I'm doing like this: ``` while (dr.Read()) { var o = new User(); o.InjectFrom<DataReaderInjection>(dr); yield return o; } ``` you gonna need this ValueInjection for this to work: ``` public class DataReaderInjection : KnownSourceValueInjection<IDataReader> { protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps) { for (var i = 0; i < source.FieldCount; i++) { var activeTarget = targetProps.GetByName(source.GetName(i), true); if (activeTarget == null) continue; var value = source.GetValue(i); if (value == DBNull.Value) continue; activeTarget.SetValue(target, value); } } } ```
Well, i don't know if it fits here, but you could be using the yield keyword ``` public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction) { while (dr.Read()) { yield return convertFunction(dr); } } ```
C# - IDataReader to Object mapping using generics
[ "", "c#", "ado.net", "mapping", "automapping", "" ]
I want to write a file where an external application can read it, but I want also some of the IsolatedStorage advantages, basically insurance against unexpected exceptions. Can I have it?
You can retrieve the path of an isolated storage file on disk by accessing a private field of the `IsolatedStorageFileStream` class, by using reflection. Here's an example: ``` // Create a file in isolated storage. IsolatedStorageFile store = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null); IsolatedStorageFileStream stream = new IsolatedStorageFileStream("test.txt", FileMode.Create, store); StreamWriter writer = new StreamWriter(stream); writer.WriteLine("Hello"); writer.Close(); stream.Close(); // Retrieve the actual path of the file using reflection. string path = stream.GetType().GetField("m_FullPath", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(stream).ToString(); ``` I'm not sure that's a recommended practice though. Keep in mind that the location on disk depends on the version of the operation system and that you will need to make sure your other application has the permissions to access that location.
Instead of creating a temp file and get the location you can get the path from the store directly: ``` var path = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(store).ToString(); ```
Can I get a path for a IsolatedStorage file and read it from external applications?
[ "", "c#", ".net", "isolatedstorage", "" ]
How do I formulate this query ``` update forge..dimInteg2 set duplicates = (select count(*) from (select idCover from x90..dimCover group by idCover having count(*) > 1)) where dimTable = 'dimCover' ``` to avoid this error ``` Line 6: Incorrect syntax near ')'. ``` Similar to [[SQL Server subquery syntax](https://stackoverflow.com/questions/1102673/sql-server-syntax-question][1]) but I can't seem to get the alias trick to work. I am on SQL Server 2000
Are you missing a bracket? ``` update forge..dimInteg2 set duplicates = (select count(*) from (select idCover from x90..dimCover group by idCover having count(*) > 1) ) --HERE where dimTable = 'dimCover' ``` Then the alias solution should work.
You need to name the derived table. update forge..dimInteg2 set duplicates = (select count(dimCover.idCover) from (select idCover from x90..dimCover group by idCover having count(\*) > 1) dimCover) where dimTable = 'dimCover'
SQL Server Syntax for update via a subquery
[ "", "sql", "sql-server", "" ]
With the help of fiddler, I did this "replay attack" with the following HTTP GET request <http://svr/Default.aspx>?**\_\_EVENTTARGET=LinkButton1**&\_\_EVENTARGUMENT=&\_\_VIEWSTATE=%2snipg%3D%3D&\_\_EVENTVALIDATION=%2snip To my surprise, it works as long as there is valid viewstate and event validation. The following stops GET on my click event, but... ``` protected void BtnUploadClick(object sender, EventArgs e) { if(Request.RequestType == "GET") throw new HttpException(405, "GET not allowed for this."); } ``` I have events *all* over my code. Is there a way to globally add this behavior to events that are normally postback events?
You can yes. Attach to application's [PreRequestHandlerExecute](http://msdn.microsoft.com/en-us/library/system.web.httpapplication.prerequesthandlerexecute.aspx) event. Do it either as a separate `HttpModule` or in `Global.asax`. In event hadler you can either check: 1. `_EVENTTARGET_` , `_VIEWSTATE_` are not part of `Request.QueryString` property (on each request) 2. on GET you can check that `Request.Form` is empty. Because asp.net only posts a form on POST actions.
Accepted answer has solved very well the issue for me. As it only contains some suggestions, I would like to post my own answer with an example of implementation, hoping it will be helpful for somebody (the method name is the one to use for Global.asax, for a httpmodule feel free to adapt) : ``` public void Application_PreRequestHandlerExecute(Object sender, EventArgs e) { // The code below is intended to block incoming HTTP GET requests which contains in query string parameters intended to be used in webform POST if (Request.HttpMethod != "GET") { return; // Nothing to do } var hasPostParams = (Request.QueryString["__EVENTTARGET"] ?? Request.QueryString["__VIEWSTATE"] ?? Request.QueryString["__EVENTARGUMENT"] ?? Request.QueryString["__EVENTVALIDATION"]) != null; if (hasPostParams) { // TODO : log error (I suggest to also log HttpContext.Current.Request.RawUrl) and throw new exception } } ```
How to prevent HTTP GET for ASP.NET events? or How to check for Request.Type on all events?
[ "", "c#", "asp.net", "" ]
i'm trying to make my site with a few languages. Every page includes config-file, wich checks variable 'lang' in session. If it doesn't exist, wi'll be redirected to the page of lang choosing. After choosing u'll come to the page before. But it works only in Mozilla Firefox. In other browser after language checking i always get this page (lang checking). What i did wrong? Config-file: ``` // Here is session start... if (!isset($_SESSION['site_lang'])) { $_SESSION['page_refer'] = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; echo '<meta http-equiv="Refresh" content="0; URL=lang_choose.php">'; exit; } else { require_once 'languages/'.$lang.'.php'; } ?> ``` lang\_choose.php: ``` // Session start @extract($_POST); if (isset($_POST['lang'])) { $lang = $_POST['lang']; $lang = replace($lang); $_SESSION['site_lang'] = $lang; echo '<meta http-equiv="Refresh" content="0; URL='.$_SESSION['page_refer'].'">'; } else { // Showing form with flags... which returns var 'lang' } ``` --- **EDIT:** If there is ``` < input type="image" src="img/langs/en.png" width="290" height="200" border="1" name="lang" value="en" /> ``` in form it doesn't work in another browsers (except mozilla) but if i use: ``` < input type="submit" name="lang" value="en" /> ``` Everything is good. Any ideas? Thanks.
Try using this to perform the redirect: ``` <?php header('HTTP/1.1 302 Found'); header('Location: ' . $_SESSION['page_refer']); // And just in case that doesn't work echo '<html>', '<head>', '<title>Redirect</title>', '</head>', '<body>', '<script type="text/javascript">', 'window.location.href = "' . $_SESSION['page_refer'] . '";', '</script>', '<a href="' . $_SESSION['page_refer'] . '">Click here to continue</a>', '</body>', '</html>'; ?> ``` Also note that use of the `<meta>` tag to redirect is [discouraged by the W3C](http://www.w3.org/TR/WCAG10-CORE-TECHS/#auto-page-refresh "W3C Page of Web Accessibility").
Try a javascript redirect if setting the location header doesn't work: ``` echo '<script>window.location.href="',$_SESSION['page_refer'],'"</script>'; ```
PHP +redirecting with sessions
[ "", "php", "session", "redirect", "" ]
I currently use: ``` BufferedReader input = new BufferedReader(new FileReader("filename")); ``` Is there a faster way?
While what you've got isn't necessarily the absolute fastest, it's simple. In fact, I wouldn't use *quite* that form - I'd use something which allows me to specify a charset, e.g. ``` // Why is there no method to give this guaranteed charset // without "risk" of exceptions? Grr. Charset utf8 = Charset.forName("UTF-8"); BufferedReader input = new BufferedReader( new InputStreamReader( new FileInputStream("filename"), utf8)); ``` You can probably make it go faster using NIO, but I wouldn't until I'd seen an actual problem. If you see a problem, but you're doing other things *with* the data, make sure they're not the problem first: write a program to *just* read the text of the file. Don't forget to do whatever it takes on your box to clear file system caches between runs though...
If it's /fast/ you want, keep the character data in encoded form (and I don't mean UTF-16). Although disc I/O is generally slow (unless it's cached), decoding and keeping twice the data can also be a problem. Although the fastest to load is probably through `java.nio.channels.FileChannel.map(MapMode.READ_ONLY, ...)`, that has severe problems with deallocation. Usual caveats apply.
What is the fastest method for reading from a text file in Java?
[ "", "java", "file-io", "" ]
I have a program that is been implemented in C++ which I now want to add MPI support. There is an MPI binding for C++, with namespace MPI and everything. In my case I have a specific object that is suitable to be the parallelized process into the cluster. My questions are: * Has anyone done something like this before? Can I get some advices on how best to implement this? * How do I initialize MPI inside the constructor? After initializing MPI inside the constructor of the Class, will all the intermediate calls be parallelized too? For example: ``` MyClass obj; x = x; //this will be parallelized ? onj.calc(); y = x++; //this will be parallelized ? z = obj.result(); ```
I would really recommend picking up the [Gropp MPI Book](http://www.mcs.anl.gov/research/projects/mpi/usingmpi/index.html), it really helps for basic MPI!
MPI doesn't parallelize anything automatically, it only gives you an interface for sending data between nodes. Your code is written and runs as usual sequential code independently on each node and every once in a while you send data to some other node or try to receive data from some other node.
Adding MPI support to a C++ program
[ "", "c++", "parallel-processing", "mpi", "openmpi", "" ]
I am just getting started with OSGI and Declarative Services (DS) using Equinox and Eclipse PDE. I have 2 Bundles, A and B. Bundle A exposes a component which is consumed by Bundle B. Both bundles also expose this service to the OSGI Service registry again. Everything works fine so far and Equinox is wireing the components together, which means the Bundle A and Bundle B are instanciated by Equinox (by calling the default constructor) and then the wireing happens using the bind / unbind methods. Now, as Equinox is creating the instances of those components / services I would like to know what is the best way of getting this instance? So assume there is **third class** class which is NOT instantiated by OSGI: ``` Class WantsToUseComponentB{ public void doSomethingWithComponentB(){ // how do I get componentB??? Something like this maybe? ComponentB component = (ComponentB)someComponentRegistry.getComponent(ComponentB.class.getName()); } ``` I see the following options right now: **1. Use a ServiceTracker in the Activator** to get the Service of ComponentBundleA.class.getName() (I have tried that already and it works, but it seems to much overhead to me) and make it available via a static factory methods ``` public class Activator{ private static ServiceTracker componentBServiceTracker; public void start(BundleContext context){ componentBServiceTracker = new ServiceTracker(context, ComponentB.class.getName(),null); } public static ComponentB getComponentB(){ return (ComponentB)componentBServiceTracker.getService(); }; } ``` **2. Create some kind of Registry** where each component registers as soon as the activate() method is called. ``` public ComponentB{ public void bind(ComponentA componentA){ someRegistry.registerComponent(this); } ``` or ``` public ComponentB{ public void activate(ComponentContext context){ someRegistry.registerComponent(this); } } ``` } **3. Use an existing registry inside osgi / equinox** which has those instances? I mean OSGI is already creating instances and wires them together, so it has the objects already somewhere. But where? How can I get them? **Conclusion** Where does the class **WantsToUseComponentB** (which is NOT a Component and NOT instantiated by OSGI) get an instance of ComponentB from? Are there any patterns or best practises? As I said I managed to use a ServiceTracker in the Activator, but I thought that would be possible without it. What I am looking for is actually something like the BeanContainer of Springframework, where I can just say something like Container.getBean(ComponentA.BEAN\_NAME). But I don't want to use Spring DS. I hope that was clear enough. Otherwise I can also post some source code to explain in more detail. Thanks Christoph --- **UPDATED:** Answer to Neil's comment: > Thanks for clarifying this question against the original version, but I think you still need to state why the third class cannot be created via something like DS. Hmm don't know. Maybe there is a way but I would need to refactor my whole framework to be based on DS, so that there are no "new MyThirdClass(arg1, arg2)" statements anymore. Don't really know how to do that, but I read something about ComponentFactories in DS. So instead of doing a ``` MyThirdClass object = new MyThirdClass(arg1, arg2); ``` I might do a ``` ComponentFactory myThirdClassFactory = myThirdClassServiceTracker.getService(); // returns a if (myThirdClassFactory != null){ MyThirdClass object = objectFactory.newInstance(); object.setArg1("arg1"); object.setArg2("arg2"); } else{ // here I can assume that some service of ComponentA or B went away so MyThirdClass Componenent cannot be created as there are missing dependencies? } ``` At the time of writing I don't know exactly how to use the ComponentFactories but this is supposed to be some kind of pseudo code :) Thanks Christoph
Christoph, Thanks for clarifying this question against the original version, but I think you still need to state why the third class cannot be created via something like DS. DS causes components to be published as services, therefore the only way to "get" any component from DS is to access it via the service registry. Unfortunately the service registry can be hard to use correctly using the lower level APIs because it is dynamic, so you have to cope with the possibility of services going away or not being available at precisely the moment you want them to be available, and so on. This is why DS exists: it gives you an abstraction for depending on services and managing the lifecycle of your components based on the availability of services that they reference. If you really need to access a service without using DS or something like it (and there is quite a choice of "things like it" e.g. Spring-DM, iPOJO, Guice/Peaberry, etc) then you should use ServiceTracker. I agree there is a lot of overhead -- again, this is why DS exists instead. To answer your suggestion no (2), no you should not create your own registry of services because the service registry already exists. If you created a separate parallel registry then you would still have to handle all the dynamics, but you would have to handle it in two places instead of one. The same applies to suggestion (3). I hope this helps. Regards, Neil UPDATED: Incidentally, although Spring has the Container.getBean() backdoor, you notice that in all Spring documentation it is strongly recommended not to use that backdoor: to get hold of a Spring bean, just create another bean that references it. The same applies to DS, i.e. the best way to get hold of a DS component is to create another DS component. Also note that in the OSGi world, even if you're using Spring-DM there is no easy way to just call getBean() because you need to get hold of the Spring ApplicationContext first. That is itself an OSGi service, so how to you get that service?
christoph, dont know if I really understand your problem. per ex. Bundle A is providing a service using DS component: ``` <service> <provide interface="org.redview.lnf.services.IRedviewLnfSelectedService"/> ``` Bundle B requires this service using DS component: ``` <implementation class="ekke.xyz.rcp.application.internal.XyzApplicationLnfComponent"/> ``` as soon as Bundle A provides the Service, Bundle B "gets" it through the bind() methode of the implementation class: ``` public class XyzApplicationLnfComponent { public void bind(IRedviewLnfSelectedService lnfSelectedService) { // here it is } ``` hope this helps ekke
OSGI Declarative Services (DS): What is a good way of using service component instances
[ "", "java", "service", "osgi", "declarative", "equinox", "" ]
my site keeps going down on my shared hosting account and this is what my host said: > It appears that the IP address of your > site is being blocked on the firewall > due to your site causing excessive > connections to itself. > > "101 connections to self" Anyone know what this means, i've never heard of a 101 error before. My site is built on PHP / MySQL.
Since you mention PHP, maybe you're requiring or including files through http requests instead of from the local disk? Something like the following would cause PHP to include the file, but get it via a http request, which gets served by your webserver. Essentially a 'connection to self'. ``` include 'http://www.example.com/file.php?foo=1&bar=2'; ``` Or maybe you're defined a Constant *PATH* somewhere, expecting to do: ``` require _PATH_ . "/file.php"; ``` As long as *PATH* is actually a path, it'll be fine, but if you accidentally set it to be a url, you'll cause the require to go through the webserver again. Not very efficient. Check your code or logs for connections like that.
Is it possible you're opening several connections to MySQL without closing them? Perhaps using persistent connections for some reason?
101 connections to self error
[ "", "php", "hosting", "shared-hosting", "" ]
Is there a Maven "phase" or "goal" to simply execute the main method of a Java class? I have a project that I'd like to test manually by simply doing something like "mvn run".
See the [exec maven plugin](http://www.mojohaus.org/exec-maven-plugin/). You can run Java classes using: ``` mvn exec:java -Dexec.mainClass="com.example.Main" [-Dexec.args="argument1"] ... ``` The invocation can be as simple as `mvn exec:java` if the plugin configuration is in your pom.xml. The plugin site on Mojohaus has a [more detailed example](http://www.mojohaus.org/exec-maven-plugin/examples/example-exec-using-plugin-dependencies.html). ``` <project> <build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.2.1</version> <configuration> <mainClass>com.example.Main</mainClass> <arguments> <argument>argument1</argument> </arguments> </configuration> </plugin> </plugins> </build> </project> ```
## 1. Edit POM.xml Add the following property in `pom.xml`. Make sure you use the fully qualified class name (i.e. with package name) which contains the `main` method: ``` <properties> <exec.mainClass>fully-qualified-class-name</exec.mainClass> </properties> ``` ## 2. Run Command Now from the terminal, trigger the following command: ``` mvn clean compile exec:java ``` **NOTE** You can pass further arguments via `-Dexec.args="xxx"` flag.
Maven Run Project
[ "", "java", "maven", "" ]
In Ruby, I'm used to using Enumerable#inject for going through a list or other structure and coming back with some conclusion about it. For example, ``` [1,3,5,7].inject(true) {|allOdd, n| allOdd && n % 2 == 1} ``` to determine if every element in the array is odd. What would be the appropriate way to accomplish the same thing in Python?
To determine if every element is odd, I'd use [`all()`](http://docs.python.org/library/functions.html#all) ``` def is_odd(x): return x%2==1 result = all(is_odd(x) for x in [1,3,5,7]) ``` In general, however, Ruby's `inject` is most like Python's [`reduce()`](http://docs.python.org/library/functions.html#reduce): ``` result = reduce(lambda x,y: x and y%2==1, [1,3,5,7], True) ``` `all()` is preferred in this case because it will be able to escape the loop once it finds a `False`-like value, whereas the `reduce` solution would have to process the entire list to return an answer.
Sounds like `reduce` in Python or `fold(r|l)'?'` from Haskell. ``` reduce(lambda x, y: x and y % == 1, [1, 3, 5]) ```
Equivalent for inject() in Python?
[ "", "python", "functional-programming", "" ]
I've been looking through a lot of Javascript Optimizing and most of them talk about string concatenation and a few other big ones found [here](http://code.google.com/speed/articles/optimizing-javascript.html), but I figured there had to be *more details* that you can optimize for when speed is **critical** and the processing of those pieces of code is **very high**. Say you run this code for some reason: (unlikely, I know, but bear with me) ``` for( var i = 0; i < 100000000000; i++ ) { //Do stuff } ``` And there's no way of getting around having a loop that big... You're going to want to make sure that all the stuff you're doing in that loop is optimized to the point that you can't optimize it anymore... or your website will hang. **Edit:** I'm not necessarily talking about a loop, what about a function that's repeatedly called such as onmousemove? Although in most cases we shouldn't need to use onmousemove, **there are some cases that do**. **This questions is for those cases.** Using JQuery as our JS library So what I would like is tips for optimizing, but only the more uncommon ones - ie. [Speed differences between switch or if-else](https://stackoverflow.com/questions/129029/which-is-faster-switch-or-if-else) If you'd like to see the more common ones, you can find them here: * [Optimizing Javascript for Execution Speed](http://archive.devnewz.com/2003/0527.html) * [Javascript Tips and Tricks; Javascript Best Practices](https://stackoverflow.com/questions/724826/javascript-tips-and-tricks-javascript-best-practices) * [Optimize javascript pre-load of images](https://stackoverflow.com/questions/959989/optimize-javascript-pre-load-of-images) * [How do you optimize your Javascript](https://stackoverflow.com/questions/197160/how-do-you-optimise-your-javascript) * [Object Oriented Javascript best practices](https://stackoverflow.com/questions/907225/object-oriented-javascript-best-practices)
You can speed up this mofo thus: ``` for (var i = 100000000; i--;) { //Do stuff } ``` Reverses the loop and checks only for ``` i-- ``` instead of ``` i < 10000000 and i < 10000000 = true ``` Performance gain of 50% in most browsers Saw this in a great Google Code talk @ <http://www.youtube.com/watch?v=mHtdZgou0qU> The talk contains some other great tricks. Good luck!
"And there's no way of getting around having a loop that big... " In the real world of RIA, you HAVE to get around the big loops. As important as optimization is learning how to break large loops into small loops, and giving time to the browser to deal with its UI. Otherwise you'll give your users a bad experience and they won't come back. So I'd argue that BEFORE you learn funky JS optimizations, you should know how to break a large loop into chunks called by setTimeout() and display a progress bar (or let animated GIFs loop). Perceived speed is often more important than actual speed. The world of the client is different from the world of the server. --- When animating, learn how to find out if you're running on a lame browser (usually IE) and try for a worse framerate (or just don't animate). I can get some animations to go 90fps in a good browser but just 15fps in IE. You can test for the browser, but it's usually better to use timeouts and the clock to see how animations are performing. --- Also, for genuine speedups, learn how to use [web workers](http://www.whatwg.org/specs/web-workers/current-work/) in Gears and in newer browsers.
Javascript: Optimizing details for Critical/Highly Processed Javascript code
[ "", "javascript", "optimization", "" ]
I am using an NLP library (Stanford NER) that throws `java.lang.OutOfMemoryError` errors for rare input documents. I plan to eventually isolate these documents and figure out what about them causes the errors, but this is hard to do (I'm running in Hadoop, so I just know the error occurs 17% through split 379/500 or something like that). As an interim solution, I'd like to be able to apply a CPU and memory limit to this particular call. I'm not sure what the best way to do this would be. My first thought is to create a fixed thread pool of one thread and use the timed get() on Future. This would at least give me a wall clock limit which would likely help somewhat. My question is whether there is any way to do better than this with a reasonable amount of effort.
Just catch the OutOfMemoryError, log which document you were on, then move on to the next one. The garbage collector will make sure you have enough memory for the next document. (This is one of the strategies I use with the Stanford dependency parser to move on to the next sentence if one sentence is too long or convoluted to parse.)
I'm not familiar with Hadoop, but don't forget that your JVM will have an implicit upper memory boundary imposed on it (64Mb for a server, if my memory is correct). I would check what memory configuration your JVM is running with (options [here](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp)) You can override this by specifying the upper memory limit thus: ``` java -Xmx512m ``` to (say) set the limit to 512Mb. Setting CPU allocation is outside the remit of the JVM, and will be an OS-specific mechanism (if you can do it at all) If you're dispatching these jobs in parallel from a JVM then running a single-thread (or limited thread) threadpool may well help you. However (again) this is dependent upon your implementation and more details are required.
Limit CPU / Stack for Java method call?
[ "", "java", "nlp", "stanford-nlp", "" ]
Can I call public method from within private one: ``` var myObject = function() { var p = 'private var'; function private_method1() { // can I call public method "public_method1" from this(private_method1) one and if yes HOW? } return { public_method1: function() { // do stuff here } }; } (); ```
do something like: ``` var myObject = function() { var p = 'private var'; function private_method1() { public.public_method1() } var public = { public_method1: function() { alert('do stuff') }, public_method2: function() { private_method1() } }; return public; } (); //... myObject.public_method2() ```
Why not do this as something you can instantiate? ``` function Whatever() { var p = 'private var'; var self = this; function private_method1() { // I can read the public method self.public_method1(); } this.public_method1 = function() { // And both test() I can read the private members alert( p ); } this.test = function() { private_method1(); } } var myObject = new Whatever(); myObject.test(); ```
Javascript calling public method from private one within same object
[ "", "javascript", "oop", "" ]
*The question is closely related to my past question here, but it is not the same.* **Problem:** to add a Play/Pause button in Chromeless Youtube here. **Attack:** I added the below code like here (search "SERVERFAULT" in the code) or like below: ``` var playingtimes = 0; function playPauseVideo(playingtimes) { if (playingtimes % 2 == 0){ playVideo(); }else{ pauseVideo(); } playingtimes += 1; } ``` Then, I added near the end: ``` <a href="javascript:void(0);" onclick="playPauseVideo(playingtimes);">Play/Pause</a> ``` **Error:** the button works like Play-button, because playingtimes is EVEN ie 0 all the time. Errror is in the playingtimes-variable. **Question:** How can I add a Play/Pause Button to the Chromeless Youtube?
You can get the state of the player directly by using ytplayer.getPlayerState(), so you can make a simple function like this to do it: ``` function playPause() { if (ytplayer.getPlayerState() != 1) { // player is not playing, so tell it to play playVideo(); } else { pauseVideo(); } } ``` The cool thing about a setup like this, it should also work if the video is ENDED or CUED.
Can you add this line into your code. click the Play/Pause button a bunch of times and edit your question with the results. ``` alert("Value of 'playingtimes' global is " + playingtimes); ``` Place here: ``` var playingtimes = 0; function playPauseVideo(playingtimes) { if (playingtimes % 2 == 0){ playVideo(); }else{ pauseVideo(); } playingtimes += 1; alert("Value of 'playingtimes' global is " + playingtimes); } ```
Play/Pause Button in Chromeless Youtube?
[ "", "javascript", "youtube", "" ]
I've posted the same question here a few days ago([Java reading standard output from an external program using inputstream](https://stackoverflow.com/questions/1088941/java-reading-standard-output-from-an-external-program-using-inputstream)), and I found some excellent advices in dealing with a block in while reading ( while(is.read()) != -1)), but I still cannot resolve the problem. After reading the answers to this similar question, [Java InputStream blocking read](https://stackoverflow.com/questions/611760/java-inputstream-read-blocking) (esp, the answer posted by Guss), I am beginning to believe that looping an input stream by using is.read() != -1 condition doesn't work if the program is interactive (that is it takes multiple inputs from user and present additional outputs upon subsequent inputs, and the program exits only when an explicit exit command is given). I admit that I don't know much about multi-threading, but I think what I need is a mechanism to promptly pause input stream threads(one each for stdout, stderr) when an user input is needed, and resume once the input is provided to prevent a block. The following is my current code which is experiencing a block on the line indicated: ``` EGMProcess egm = new EGMProcess(new String[]{directory + "/egm", "-o", "CasinoA", "-v", "VendorA", "-s", "localhost:8080/gls/MessageRobot.action ", "-E", "glss_env_cert.pem", "-S", "glss_sig_cert.pem", "-C", "glsc_sig_cert.pem", "-d", "config", "-L", "config/log.txt", "-H", "GLSA-SampleHost"}, new String[]{"PATH=${PATH}"}, directory); ``` ``` egm.execute(); BufferedReader stdout = new BufferedReader(new InputStreamReader(egm.getInputStream())); BufferedReader stderr = new BufferedReader(new InputStreamReader(egm.getErrorStream())); EGMStreamGobbler stdoutprocessor = new EGMStreamGobbler(stdout, egm); EGMStreamGobbler stderrprocessor = new EGMStreamGobbler(stderr, egm); BufferedWriter stdin = new BufferedWriter(new OutputStreamWriter(egm.getOutputStream())); stderrprocessor.run(); //<-- the block occurs here! stdoutprocessor.run(); //EGM/Agent test cases //check bootstrap menu if(!checkSimpleResult("******** EGM Bootstrap Menu **********", egm)) { String stdoutdump = egm.getStdOut(); egm.cleanup(); throw new Exception("can't find '******** EGM Bootstrap Menu **********'" + "in the stdout" + "\nStandard Output Dump:\n" + stdoutdump); } //select bootstrap stdin.write("1".toCharArray()); stdin.flush(); if(!checkSimpleResult("Enter port to receive msgs pushed from server ('0' for no push support)", egm)){ String stdoutdump = egm.getStdOut(); egm.cleanup(); throw new Exception("can't find 'Enter port to receive msgs pushed from server ('0' for no push support)'" + "in the stdout" + "\nStandard Output Dump:\n" + stdoutdump); } ``` ... public class EGMStreamGobbler implements Runnable{ private BufferedReader instream; private EGMProcess egm; public EGMStreamGobbler(BufferedReader isr, EGMProcess aEGM) { instream = isr; egm = aEGM; } public void run() { try{ int c; while((c = instream.read()) != 1) { egm.processStdOutStream((char)c); } } catch(IOException e) { e.printStackTrace(); } } } I apologize for the length of the code, but my questions are, 1) Is there any way to control the process of taking in inputstreams (stdout, stderr) without using read()? Or am I just implementing this badly? 2) Is multi-threading the right strategy for developing the process of taking in inputstreams and writing an output? PS: if anyone can provide a similar problem with solution, it will help me a lot!
instead of ``` stderrprocessor.run(); //<-- the block occurs here! stdoutprocessor.run(); ``` You need to start threads: ``` Thread errThread = new Thread(stderrprocessor); errThread.setDaemon( true ); errThread.start(); Thread outThread = new Thread(stdoutprocessor); outThread.setDaemon( true ); outThread.start(); ``` `run()` is just a method specified in `Runnable`. `Thread.start()` calls `run()` on the `Runnable` in a new `Thread`.
1. If you just call #run() on a runnable, it will not be executed in parallel. To run it in parallel, you have to spawn a java.lang.Thread, that executes the #run() of your Runnable. 2. Whether a stream blocks depends on both sides of the stream. If either the sender does not send any data or the receiver does not receive data, you have a block situation. If the processor has to do something, while the stream is blocked, you need to spawn a(nother) thread within the processor to wait for new data and to interrupt the alternate process, when new data is streamed.
Java IO inputstream blocks while reading standard output & standard error of an external C program
[ "", "java", "java-io", "" ]
It now makes sense that the versions aren't right. I know I am using Castle Windsor 2.0 and I would like to use NHibernate with Fluent NHibernate - what versions do I need of these two? **Edit** Ok, I think I got it wired up. I'm still having a version issue. I now get this error when using the direct download from their site. The only library at 1.0.3 is the NHibernateFacility. > {"Could not load file or assembly > 'Castle.Core, Version=1.0.3.0, > Culture=neutral, > PublicKeyToken=407dd0808d44fbdc' or > one of its dependencies. The located > assembly's manifest definition does > not match the assembly reference. > (Exception from HRESULT: > 0x80131040)":"Castle.Core, > Version=1.0.3.0, Culture=neutral, > PublicKeyToken=407dd0808d44fbdc"} ## *Old Problem* Why would I be getting this? > Method '{MethodName}' in type 'Class' > from assembly '{ClassLibrary}, > Version=1.0.0.0, Culture=neutral, > PublicKeyToken=' does not have an > implementation. It compiles just fine and it is implemented. I don't even call that the class yet. I am using IoC - Castle Windsor with Fluent NHibernate. The interface I have to implement is `Castle.Facilities.NHibernateIntegration.Internal.IConfigurationBuilder`
There's probably a versioning conflict. Try getting the Castle and NH assemblies from the [Castle build server](http://www.castleproject.org:8090/?guest=1).
Two possibilities: Most likely: You have an outdated dll in the chain - Somewhere you have updated an assembly but not all of the library assemblies it requires. Update your whole toolchain and verify the versions are correct. Or: You are referencing assembly "Alpha.dll", and calling something in it that exposes a type in assembly "Beta.dll". Alpha references Beta, but your assembly only references Alpha. In this case, you will get the above error message. Most of the time you get this problem, you'll see a clearer message, (Add reference to Beta), but this happens sometimes. If you figure out when, let me know! To fix it, simply add a reference to Beta.
Fluent NHibernate with Castle Windsor 2.0?
[ "", "c#", "nhibernate", "exception", "castle-windsor", "" ]
First let me say I have read [this useful article](https://stackoverflow.com/questions/219594/net-whats-the-best-way-to-implement-a-catch-all-exceptions-handler) thoroughly and am using the SafeThread class from CodeProject. I get the same result whether using Thread or SafeThread. I have reduced my problem down to an app consisting of two forms each with one button. The main program displays a form. When you click that button, a new thread starts which displays a second form. When you click the button on the second form, internally it just does "throw new Exception()" When I run this under VS2008, I see "Exception in DoRun()". When I run outside of VS2008, I get a dialog box "Unhandled exception has occurred in your application. If you click continue, the application ...." I have tried setting legacyUnhandledExceptionPolicy in the app.config to both 1 and 0. What do I need to do to capture the exception thrown in my second form, when not running under VS2008? Here's my Program.cs ``` static class Program { [STAThread] static void Main() { Application.ThreadException += new ThreadExceptionEventHandler (Application_ThreadException); Application.SetUnhandledExceptionMode (UnhandledExceptionMode.CatchException); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { Application.Run(new Form1()); } catch(Exception ex) { MessageBox.Show("Main exception"); } } static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { MessageBox.Show("CurrentDomain_UnhandledException"); } static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) { MessageBox.Show("Application_ThreadException"); } } ``` Here's Form1: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { SafeThread t = new SafeThread(new SimpleDelegate(ThreadMain)); try { t.ShouldReportThreadAbort = true; t.ThreadException += new ThreadThrewExceptionHandler(t_ThreadException); t.ThreadCompleted += new ThreadCompletedHandler(t_ThreadCompleted); t.Start(); } catch(Exception ex) { MessageBox.Show(string.Format("Caught externally! {0}", ex.Message)); } } void t_ThreadCompleted(SafeThread thrd, bool hadException, Exception ex) { MessageBox.Show("t_ThreadCompleted"); } void t_ThreadException(SafeThread thrd, Exception ex) { MessageBox.Show(string.Format("Caught in safe thread! {0}", ex.Message)); } void ThreadMain() { try { DoRun(); } catch (Exception ex) { MessageBox.Show(string.Format("Caught! {0}", ex.Message)); } } private void DoRun() { try { Form2 f = new Form2(); f.Show(); while (!f.IsClosed) { Thread.Sleep(1); Application.DoEvents(); } } catch(Exception ex) { MessageBox.Show("Exception in DoRun()"); } } } ``` And here is Form2: ``` public partial class Form2 : Form { public bool IsClosed { get; private set; } public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { throw new Exception("INTERNAL EXCEPTION"); } protected override void OnClosed(EventArgs e) { IsClosed = true; } } ```
1.) I would recommend using the BackgroundWorker instead of separate threads like this. Your worker will catch exceptions and pass them along as a parameter to the complete handler. 2.) I would use ShowDialog() instead of Show() when displaying the second form, this will block the DoRun() at that method call and exceptions should then be caught by your surrounding try / catch (or the BackgroundWorker if you're using that instead). I think the problem comes that since you're calling Show() you're essentially dispatching that call onto the Invoker, which ends up being queued in the UI thread. So when an exception happens there is nothing higher up the callstack to catch it. I believe calling ShowDialog() will fix this (and also allow you to drop that nasty for loop). Something like this: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // NOTE: I forget the event / method names, these are probably a little wrong. BackgroundWorker worker = new BackgroundWorker(); worker.DoWork += (o, e) => { Form2 f = new Form2(); e.Result = f.ShowDialog(); }; worker.DoWorkComplete += (o, e) => { if(e.Error != null) MessageBox.Show(string.Format("Caught Error: {0}", ex.Message)); // else success! // use e.Result to figure out the dialog closed result. }; worker.DoWorkAsync(); } } ``` Actually, now that I think about it, it's sort of weird to be opening a dialog from a background thread but I think this will still work.
If you really want your second Form opened on a separate UI thread (not as `ShowDialog()`) to catch the exception and send it to your `Application_ThreadException` method, you need to ensure that the second thread is also set to `CatchException` *and* you need to subscribe to the `Application.ThreadException` *on that thread*, too. Both of these are thread-specific (and a bit quirky). You can set the default "unhandled exception mode" by calling: ``` Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, false); ``` This sets the application-wide mode to `CatchException` for any UI thread you create. (But this call will fail when running in the Visual Studio debugger and some other cases.) Or, your new UI thread can set its own mode with the usual call (same as passing true to this overload). Either way, the new UI thread also needs to subscribe to the `Application.ThreadException` event itself, because the subscriber is stored in a [ThreadStatic] variable. ``` Application.ThreadException += Program.Application_ThreadException; ``` Or it could use a separate handler instead of routing to the same one, if that's helpful. I'm not sure how this might intersect with using `SafeThread` to accomplish it, but I think if this is done correctly for the second UI thread it wouldn't be necessary to use `SafeThread`. It's much like you'd do it on your main UI thread. Also see my answer to [this question](https://stackoverflow.com/questions/545760/which-config-element-affects-exception-handling-with-unhandledexceptionmode-set) for more on the quirks of this stuff.
Preventing Unhandled Exception Dialog Appearing
[ "", "c#", ".net", "exception", "" ]
When compiling : ``` #include <vector> template<class T> class foo { void bar() { std::vector<T> x; std::vector<T>::iterator i = x.begin(); } }; int main() { return 0; } ``` I get : ``` # g++ ~test.cpp test.cpp: In member function `void foo<T>::bar()': test.cpp:7: error: expected `;' before "i" ``` Shouldn't this work? g++ version 3.4.3 on RHEL.
You can, but you need to tell it that `iterator` there is a type (it doesn't know, because in general it can depend on `T` - as `vector` is a template type, and could in theory have specializations for some `T` where `iterator` is a function or something else). So, you have to use `typename` to indicate that it is always a type: ``` typename std::vector<T>::iterator i = x.begin(); ```
This should do: ``` template<class T> class foo { void bar() { std::vector<T> x; typename std::vector<T>::iterator i = x.begin(); } }; ``` I'll quote the IBM C++ compiler manual: > The *typename* keyword (C++ only) Use > the keyword typename if you have a > qualified name that refers to a type > and depends on a template parameter. > Only use the keyword typename in > template declarations and definitions. > The following example illustrates the > use of the keyword typename: > > ``` > template<class T> class A > { > T::x(y); > typedef char C; > A::C d; > } > ``` > > The statement *T::x(y)* is ambiguous. It > could be a call to function x() with a > nonlocal argument y, or it could be a > declaration of variable y with type > *T::x.* C++ will interpret this > statement as a function call. In order > for the compiler to interpret this > statement as a declaration, you would > add the keyword typename to the > beginning of it. The statement *A::C d;* > is ill-formed. The class A also refers > to *A* and thus depends on a template > parameter. You must add the keyword > typename to the beginning of this > declaration: > > *typename A::C d;* You can also use > the keyword *typename* in place of the > keyword class in template parameter > declarations.
Why can't you use a Template when iterating
[ "", "c++", "templates", "g++", "" ]
This is a C# problem. I have a big object in memory at a certain time. I want to serialize it to a file. There are two steps to do it. 1st, I need to change the object to csv string. 2nd, I need to serialize the csv string. I have a utility tool, which can append strings to a MemoryStream. I use this utility tool to convert the big object to csv string (in a big trunk of MemoryStream). After converting the big object to a MemoryStream, I create a StreamReader of the MemoryStream and call its method StreamReader.ReadToEnd() to convert the MemoryStream to a (long) string. Then I call info.AddValue("BigObject", string); to serialize the string. As one can see, in the memory, I will actually hold three copies of the big object. The first one is the object itself, the second will be the MemoryStream, holding the csv string and the third is the string, which is actually a redundant of the MemoryStream. Is there any way to reduce the memory consumption in this procedure? It seems that if not MemoryStream, I will anyway need to use a StringBuilder to hold the csv string of the big object and I will anyway need to call StringBuilder.ToString() to get the final string. Then the final string and the StringBuilder will coexist in the memory and consume the same amount of memory as currently the MemoryStream and string. Any idea is welcomed. Thank you.
If you're worried about peak memory usage, I suppose you could manually force a garbage collection after you're done with the orignal object and then again after you're done with the memory stream. (Let me just point out that, while there are a few cases where taking control of garbage collection is necessary, it's generally a bad idea. Usually, it's better to let things get collected in due time.)
Give the following a try. ``` public void SerializeToFile<T>(T target, string filename) { XmlSerializer serializer = new XmlSerializer(typeof (T)); using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write)) { serializer.Serialize(stream, target); } } ``` Edit: Assuming you can get your object to implement ISerializable and tie your utility into the GetObjectData method. Edit2: Missed the CSV part. Icky. Try using an XSLT on the XML after serializing it. Link to an [article](http://www.stylusstudio.com/xmldev/200404/post60210.html) about converting xml to csv via an xslt.
How to reduce the memory consumption?
[ "", "c#", ".net", "memory-management", "" ]
I use the following code try to create an array of string vectors, I hope to have an array of 3 items, each item is a string vector : ``` Vector<String> Result_Vector_Array[]=new Vector<String>[3]; ``` But NB highlighted the line as error(generic array creation), what's wrong ? What's the correct way to do it ? I know there is also Arraylist, but it's not synchronized, so I want to use vector.
Due to [type erasure](http://en.wikipedia.org/wiki/Type_erasure#Type_erasure), the JVM doesn't know at runtime that you have a `Vector` of `String`. The best it can do is create a 'raw' Vector. It can't guarantee for you that all `Vector`s actually contain `String`s. That's why you get a warning from your IDE. One way to work around this, it cast it, as jgubby suggests. Another is to put a `List` into your `Vector`s, instead of an array. But, more importantly, why can the array have only 3 items? Wouldn't it be better to create a class with three fields to put into your `Vector`? With three items, that's not too much work, and you get the added bonus that you can give each of the three elements a helpful name, which should make your code a lot clearer. Also, since Java 6, there exist a number of useful new synchronized `List` implementations, which might perform better than `Vector`, such as [`CopyOnWriteArrayList`](http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html), or wrap a regular `List` in a [`Collections.synchronizedList`](http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29).
You cannot create an array like that, do this: ``` Vector<String> Result_Vector_Array[] = (Vector<String>[]) new Vector[3]; ``` I would suggest a different approach - arrays of containers like that are often quite hard to use, and don't help in the understanding of your code. PS Also worth noting that the java naming convention would be ``` Vector<String> resultVectorArray[] = (Vector<String>[]) new Vector[3]; ``` and it's not usual to include the type in the name (I suspect this will be contentious!), why not just call it 'result' and let the type system worry about the type?
How to create an array of string vectors in Java?
[ "", "java", "arrays", "vector", "" ]
I'm having problems with a slow memory leak in my mixed mode C++/CLR .NET application. (It's C++ native static libraries linked into a VS2008 C++/CLR Windows Forms app with the "/clr" compiler setting) Typical behaviour: app starts using 30 MB (private memory). Then leaks memory slowish, say a MB every hour when running under simulated heavy load. This simulates the app being live for days or weeks. I've tried using several tools to track down memory leaks including both the CRT debugging stuff that comes with the Visual Studio CRT libs. I've also used a commercial leak detection tool ("Memory Validator"). Both report negligible memory leaks at shutdown (a few minor entries that amount to a few KB that I'm not worried about). Also, I can see when running that the tracked memory doesn't seem to amount to that much (so I don't believe it is just memory that is being held and only released at app exit). I get around 5 MB of listed memory (out of total > 30MB). The tool (Memory Validator) is setup to track all memory usage (including malloc, new, Virtual memory allocation and a whole bunch of other types of memory allocation). Basically, every setting for which memory to track has been selected. The .NET image reports that it is using around 1.5 MB of memory (from perfmon). Here's a final bit of information: we have a version of the app which runs as a native console application (purely native - not CLR at all). This is 95% the same as the mixed mode except without the UI stuff. This doesn't seem to leak memory at all, and peaks at around 5MB private bytes. So basically what I'm trying to get across here is that I don't think any of the native code is leaking memory. Another piece of the puzzle: I found this which refers to memory leaks in mixed mode applications when targeting 2.0 framework (which I am): <http://support.microsoft.com/kb/961870> Unfortunately the details are infuriatingly sparse so I'm not sure if it's relevant. I did try targeting 3.5 framework instead of 2.0 but still had the same problem (maybe I didn't do this right). Anyone have any suggestions? A few things that might help me: * Are there any other kind of memory allocations that I'm not tracking? * How come the figures don't add up? I get 5 MB of CRT memory usage, 1.5 MB of .NET memory so how come the whole app uses 30MB private bytes? Is that all tied up in the .NET framework? Why don't I see these in the leak tool? Won't the .NET framework appear as some kind of allocated memory? * Any other leak detection tools which work well with mixed mode apps? Thanks for any help John
OK I finally found the problem. It was caused by an incorrect setting for /EH (Exception Handling). Basically, with mixed mode .NET apps, you need to make sure all statically linked libs are compiled with /EHa instead of the default /EHs. (The app itself must also be compiled with /EHa, but this is a given - the compiler will report error if you don't use it . The problem is when you link in other static native libs.) The problem is that exceptions caught in the managed bit of the app, which were thrown within native libraries compiled with /EHs end up not handling the exception correctly. Destructors for C++ objects are not then called correctly. In my case, this only occurred in a rare place, hence why it took me ages to spot.
Like Spence was saying, but for C++/CLI ;).... For any object which you are using in C++/CLI, if you create more that object's from you C++ code, you should try to use stack allocation seymantics, even though this is a compiler magic sort of thing, it is able to setup the nested \_\_try {} \_\_finally {} statements you may be used to using from native code (that is setup them in a way to not loose a call to Dispose). [Nish's](http://blog.voidnish.com/) [article at the code project here](http://www.codeproject.com/KB/mcpp/cppclidtors.aspx) on C++/CLI stack allocation semantics is pretty good and goes into depth about how to emulate using{}. You should also make sure to delete any object's that implment IDisposable as you can not call Dispose in C++/CLI, delete does this for you, if your not using stack semantics.. I usually call Close myself on Streams and try to assign nullptr when I am finished with object's, just in case. You may also want to check out [this article on memory issues](http://msdn.microsoft.com/en-us/magazine/cc163528.aspx), perticularly about event subscribers, if you are assigning event's to your objects, you may be leaking... As a last resort (or maybe first:), one thing I have done in the past is make use of the CLR profiler API, [here's another article](http://msdn.microsoft.com/en-ca/magazine/cc188781.aspx) on how to do this, the author's writer (Jay Hilyard) has an example that answers; * Of each .NET type that is used, how many object instances are being allocated? * How big are the instances of each type? * What notifications does the GC provide as it goes through a garbage collection and what can you find out? * When does the GC collect the object instances? Should get you a better idea than some commodity profiler, I've noticed that they can be occasionally misleading depending on your allocation porofile (btw. watch out for large object heap issues, > ~83kb objects are specially handled, in that case, I'd reccomend, getting out of the large object heap :). Given your comments, a few more things... I've posted before about image load's not charging quota or any other disernable statistic, what this means, you may need to track down some handle or loader issue (see loader lock eventually), but before that, you can try setting up some [Constrained Execution Regions](http://msdn.microsoft.com/en-us/library/ms228973(VS.100).aspx), they can work wonders, but are also unfortunately difficult to retro-fit into non-pure code. This recent [MSDN Mag](http://msdn.microsoft.com/en-ca/magazine/dd882521.aspx), article document's a lot of perfmon type memory sperlunking (followup for [this older one](http://msdn.microsoft.com/en-ca/magazine/cc163528.aspx)). From the [VS Perf Blog](http://blogs.msdn.com/clrperfblog/archive/2008/07/22/track-down-dll-loading-using-visual-studio.aspx), they show how to use SOS in visual studio, which can be handy, to track down rouge DLL's, related posts are also good. [Maoni Stephen's Blog](http://blogs.msdn.com/maoni/default.aspx) and [company](http://blogs.msdn.com/vancem/), he say's he's on the perf team, but essentially 100% of his posts are with respect to the GC so much so he may of well of wrote it. [Rick Byers](http://blogs.msdn.com/rmbyers/default.aspx) is a dev with the CLR diagnostics team, many of his blog-buddies are also good source's, however, I would strongly suggest also refering to the quite new [dev/diagnostics forum](http://social.msdn.microsoft.com/Forums/en-US/netfxtoolsdev/threads/). They have recently expanded the scope of their discussions. [Code Coverage Tools](http://msdn.microsoft.com/en-ca/magazine/cc163981.aspx) and [tracing](http://msdn.microsoft.com/en-us/library/6da106y8(VS.100).aspx) can often help, to give you an overview of what's actually running. (specically, those perticular stat's may not be giving you a global view of what is plauging your code, I can say that recently, I have found (even with .net4beta binaries, the profiler from [this company](http://www.softwareverify.com/dotNet/memory/index.html), is quite good, it is capable of deriving native/managed leaks's from it's profile traces, brings you back to the exact source lines (even if optimized, quite nice (and it has a 30day trial)))). Good luck!! Hope some of this helps, it's only fresh in my mind, as I am doing much of the same work right now ;)
Memory leak in Mixed Mode C++/CLR application
[ "", ".net", "c++", "memory-leaks", "mixed-mode", "" ]
**Usecase** maintain a list of the last n visited URLs (where n is a fix number). As new URLs are added to the list, older urls are removed automatically (in order to keep it at n elements) **Requirement** The data structure needs to be sorted by time (should be no problem if it accepts a Comparator).
In java there are several implementation of [Queue](http://localhost/api/java6/java/util/Queue.html). It should be trivial to inherit or warp an existing implementation and implement the add() method like this: ``` boolean add(E e) { if(q.size()==MAX_SIZE) { remove(); } q.add(e) } ```
You need a circular buffer. Just keep an array b[] of size N and index k, that points to the oldest URL. Every time you need to add new URL, assign it to b[k] and increment k, wrapping it if needed: k = (k + 1) % N. All your URLs will be naturally sorted, the oldest is at k, the second oldest at k+1, and so on, the newest is at k-1. (The sequence wraps at the end of the array).
Looking for datastructure that maintains a size & purges older elements in the process
[ "", "java", "algorithm", "data-structures", "" ]
just think that when I opened my file then when I want to write something in it ,one Exception will be thrown,and if I used file.close() in the try block ,So because of that Exception will not work, where should I close my file???
The proper way to do so is: ``` FileOutputStream out = null; try { out = ... ... out.write(...); ... out.flush(); } catch (IOException ioe) { ... } finally { if(out!=null) { try { out.close(); } catch (IOException ioe) { ... } } } ```
The general pattern for resources is `acquire; try { use; } finally { release; }`. If you try to rearrange that you'll often end up in a situation where you, say, release a lock without acquiring it. Note, in general there is no need to clutter with a null check. If you need to catch an exception from it all, surround all the code with a `try-catch`. So ``` try { final InputStream in = new FileInputStream(file); try { ... } finally { in.close(); } } catch (IOException exc) { throw new SomeException(exc); } ```
How can I close my file with the special condition?
[ "", "java", "file", "" ]
I just want to know if there is a program that can convert an XSD file to a Python class as **JAXB** does for Java?
[generateDS](http://www.davekuhlman.org/generateDS.html) : I think this is the good tool I need Edit : Actually, generateDS does very well the job !! It generates the Python class with all methods (setters and getters, export to XML, import from XML). It works very well !
[xsdata](https://xsdata.readthedocs.io/en/latest/) generates [dataclasses](https://docs.python.org/3/library/dataclasses.html) from an XSD file. According to the [documentation](https://xsdata.readthedocs.io/en/v20.5/about.html) it was inspired by JAXB.
How to convert XSD to Python Class
[ "", "python", "xml", "data-binding", "xsd", "xsd2code", "" ]
Can anyone explain why isn't the operator[] implemented for a std::list? I've searched around a bit but haven't found an answer. It wouldn't be too hard to implement or am I missing something?
Retrieving an element by index is an O(n) operation for linked list, which is what `std::list` is. So it was decided that providing `operator[]` would be deceptive, since people would be tempted to actively use it, and then you'd see code like: ``` std::list<int> xs; for (int i = 0; i < xs.size(); ++i) { int x = xs[i]; ... } ``` which is O(n^2) - very nasty. So ISO C++ standard specifically mentions that all STL sequences that support `operator[]` should do it in amortized constant time (23.1.1[lib.sequence.reqmts]/12), which is achievable for `vector` and `deque`, but not `list`. For cases where you actually need that sort of thing, you can use `std::advance` algorithm: ``` int iter = xs.begin(); std::advance(iter, i); int x = *iter; ```
It would not be too hard (for the implementer) but it would be too hard at runtime, since the performance will be terrible in most cases. Forcing the user to go through each link will make it more obvious what is going on in there than 'myList[102452]' would.
Why isn't there an operator[] for a std::list?
[ "", "c++", "list", "stl", "" ]
What are my best options for creating a financial open-high-low-close (OHLC) chart in a high level language like Ruby or Python? While there seem to be a lot of options for graphing, I haven't seen any gems or eggs with this kind of chart. <http://en.wikipedia.org/wiki/Open-high-low-close_chart> (but I don't need the moving average or Bollinger bands) JFreeChart can do this in Java, but I'd like to make my codebase as small and simple as possible. Thanks!
You can use [matplotlib](http://matplotlib.sourceforge.net/) and the the optional `bottom` parameter of [matplotlib.pyplot.bar](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.bar). You can then use line `plot` to indicate the opening and closing prices: For example: ``` #!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt from matplotlib import lines import random deltas = [4, 6, 13, 18, 15, 14, 10, 13, 9, 6, 15, 9, 6, 1, 1, 2, 4, 4, 4, 4, 10, 11, 16, 17, 12, 10, 12, 15, 17, 16, 11, 10, 9, 9, 7, 10, 7, 16, 8, 12, 10, 14, 10, 15, 15, 16, 12, 8, 15, 16] bases = [46, 49, 45, 45, 44, 49, 51, 52, 56, 58, 53, 57, 62, 63, 68, 66, 65, 66, 63, 63, 62, 61, 61, 57, 61, 64, 63, 58, 56, 56, 56, 60, 59, 54, 57, 54, 54, 50, 53, 51, 48, 43, 42, 38, 37, 39, 44, 49, 47, 43] def rand_pt(bases, deltas): return [random.randint(base, base + delta) for base, delta in zip(bases, deltas)] # randomly assign opening and closing prices openings = rand_pt(bases, deltas) closings = rand_pt(bases, deltas) # First we draw the bars which show the high and low prices # bottom holds the low price while deltas holds the difference # between high and low. width = 0 ax = plt.axes() rects1 = ax.bar(np.arange(50), deltas, width, color='r', bottom=bases) # Now draw the ticks indicating the opening and closing price for opening, closing, bar in zip(openings, closings, rects1): x, w = bar.get_x(), 0.2 args = { } ax.plot((x - w, x), (opening, opening), **args) ax.plot((x, x + w), (closing, closing), **args) plt.show() ``` creates a plot like this: ![enter image description here](https://i.stack.imgur.com/4dWF7.png) Obviously, you'd want to package this up in a function that drew the plot using `(open, close, min, max)` tuples (and you probably wouldn't want to randomly assign your opening and closing prices).
You can use Pylab (`matplotlib.finance`) with Python. Here are some examples: <http://matplotlib.sourceforge.net/examples/pylab_examples/plotfile_demo.html> . There is some good material specifically on this problem in [Beginning Python Visualization](https://rads.stackoverflow.com/amzn/click/com/1430218436). Update: I think you can use [matplotlib.finance.candlestick](http://doc.astro-wise.org/matplotlib.finance.html) for the Japanese candlestick effect.
Financial Charts / Graphs in Ruby or Python
[ "", "python", "ruby", "charts", "graph", "financial", "" ]
I have this method for grabbing the file name from a string URI. What can I do to make it more robust? ``` private string GetFileName(string hrefLink) { string[] parts = hrefLink.Split('/'); string fileName = ""; if (parts.Length > 0) fileName = parts[parts.Length - 1]; else fileName = hrefLink; return fileName; } ```
You can just make a System.Uri object, and use IsFile to verify it's a file, then [Uri.LocalPath](http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx) to extract the filename. This is much safer, as it provides you a means to check the validity of the URI as well. --- Edit in response to comment: To get just the full filename, I'd use: ``` Uri uri = new Uri(hreflink); if (uri.IsFile) { string filename = System.IO.Path.GetFileName(uri.LocalPath); } ``` This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.
Uri.IsFile doesn't work with http urls. It only works for "file://". From [MSDN](http://msdn.microsoft.com/zh-cn/library/system.uri.isfile(v=vs.110).aspx) : "The IsFile property is **true** when the Scheme property equals UriSchemeFile." So you can't depend on that. ``` Uri uri = new Uri(hreflink); string filename = System.IO.Path.GetFileName(uri.LocalPath); ```
Get file name from URI string in C#
[ "", "c#", "string", "uri", "filenames", "" ]
I have a table in database that is having some fields one of which is 'action' action is having data like bse-similar,bse-action.....nse-similar,nse-action...etc. now i want to fetch the data that is having 'bse' in its action field. How can i do that in mysql????? One more thing i want to copy this data to another table.How can i do that in simple query?????
``` SELECT * FROM table WHERE action LIKE "bse-%" ``` or, in PHP: ``` mysql_connect($host, $user, $pass); mysql_select_db($database); $res = mysql_query("SELECT * FROM table WHERE action LIKE 'bse-%'"); while (($row = mysql_fetch_array($res)) != null) { echo $row[0] . "<br />"; } ``` just fill out $host, $user, $pass, and $database with your information and your good to go. You should really look at these tutorials: <http://w3schools.com/php/php_mysql_intro.asp> :) **EDIT** ``` INSERT INTO table2 (column1, columnx, action) SELECT column1, columnx, action FROM table1 WHERE action LIKE "bse-%" ``` should be what your looking for
Use [pattern-matching](http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html): ``` mysql> SELECT action FROM mytable WHERE action LIKE 'bse%'; +-------------+ | action | +-------------+ | bse-action | | bse-similar | +-------------+ ``` > SQL pattern matching allows you to use > “\_” to match any single character and > “%” to match an arbitrary number of > characters (including zero > characters).
select with likewise data
[ "", "php", "mysql", "select", "where-clause", "" ]
I am almost embarrassed to ask this question, but as a long time C programmer I feel that perhaps I am not aware of the best way to do this in C#. I have a member function that I need to return two lists of a custom type (`List<MyType>`) and I know beforehand that I will always have a return value of only two of these lists. The obvious options are : ``` public List<List<MyType>> ReturnTwoLists(); ``` or ``` public void ReturnTwoLists(ref List<MyType> listOne, ref List<myType> listTwo); ``` Both seem to be non-optimal. Any suggestions on how to improve this? The first way doesn't make it clear in the syntax that only 2 lists are being returned, and the second uses references rather then a return value, which seem so non-c#.
First of all, that should probably be `out`, not `ref`. Second, you can declare and return a type containing the two lists. Third, you can declare a generic `Tuple` and return an instance of that: ``` class Tuple<T,U> { public Tuple(T first, U second) { First = first; Second = second; } public T First { get; private set; } public U Second { get; private set; } } static class Tuple { // The following method is declared to take advantage of // compiler type inference features and let us not specify // the type parameters manually. public static Tuple<T,U> Create<T,U>(T first, U second) { return new Tuple<T,U>(first, second); } } return Tuple.Create(firstList, secondList); ``` You can extend this idea for different number of items.
Return this: ``` public class MyTwoLists { public List<MyType> ListOne {get;set;} public List<MyType> ListTwo {get;set;} } ```
What is the best way to return two lists in C#?
[ "", "c#", "list", "coding-style", "" ]
How can we find a particular stored procedure. I need to find a stored procedure which I don't know is in which database. Can somebody please, help with a script. Thanks
Which database server? With MS SQL Server, you can use [sp\_help 'procname'](http://msdn.microsoft.com/en-us/library/aa933429(SQL.80).aspx).
One way by using the ANSI information\_schema.routines view, change ProcNameHere to the name you want ``` select * from information_schema.routines where routine_type = 'PROCEDURE' and specific_name = 'ProcNameHere' ```
Finding a stored procedure
[ "", "sql", "stored-procedures", "" ]
I have a page with 3 columns of links at the bottom. Each column is put into a div and all three divs are wrapped into a big div that is centered on the page. Is this something that is better suited to a table or is a table the wrong element for the job?
You can also use [`<ul>`](http://www.w3schools.com/tags/tag_ul.asp) & [`<li>`](http://www.w3schools.com/TAGS/tag_li.asp) for this. ``` #horizontal { width: 100%; background: #eee; float: left; } #horizontal ul { list-style: none; margin: 0; padding: 0; width: 12em; float: left; } ``` This will create horizontal columns using li elements, and then you can stuff the HTML to create individual links in each li.
The Rule of Thumb is: Use Divs for layout, tables for tabular data. On a side note, check out etymology of the term Rule of Thumb, quite humorous.
Is it better to use divs or tables to contain columns of links?
[ "", "javascript", "html", "css", "css-tables", "" ]
I am trying to access member variables of a class without using object. please let me know how to go about. ``` class TestMem { int a; int b; public: TestMem(){} void TestMem1() { a = 10; b = 20; } }; void (TestMem::*pMem)(); int main(int argc, char* argv[]) { TestMem o1; pMem = &(TestMem::TestMem1); void *p = (void*)&pMem; // How to access a & b member variables using variable p getch(); return 0; } ```
The "right" way to do this is by using the [`offsetof()`](http://en.wikipedia.org/wiki/Offsetof) macro from `<stddef.h>`. Unfortunately `offsetof()` has some fairly [draconian restrictions](http://www.cplusplus.com/reference/clibrary/cstddef/offsetof/) in C++: > Because of the extended functionality of structs in C++, in this language, the use of `offsetof` is restricted to "POD [plain old data] types", which for classes, more or less corresponds to the C concept of struct (although non-derived classes with only public non-virtual member functions and with no constructor and/or destructor would also qualify as POD). So if you make `a` and `b` public and get rid of `TestMem`'s constructor, you can write something like this to access `a`: ### C++ style: ``` #include <cstddef> int vala = *reinterpret_cast<int *>(reinterpret_cast<char *>(&o1) + offsetof(TestMem, a)); ``` ### C style: ``` #include <stddef.h> int vala = *(int *) ((char *) &o1 + offsetof(TestMem, a)); ``` Notice that you need to use `&o1` here, not `p`, which is a function pointer. The address of `TestMem::TestMem1` won't have any relation to the locations of `a` and `b`. Class methods don't reside in memory anywhere near class member variables. --- The "wrong" way is to just guess at where `a` and `b` are in memory. Most likely they are at offsets 0 and 4 from the start of `o1`, respectively. So this code would work most of the time: ``` int vala = *(int *) ((char *) &o1 + 0); int valb = *(int *) ((char *) &o1 + 4); ``` There are a lot of assumptions here. This assumes that ints are 4 bytes and that there's no padding between `a` and `b`. On the other hand it doesn't have any of the restrictions from above: `a` and `b` don't need to be public, you can have a constructor, whatever.
Simple answer: Don't do it. There just can not be any situation where you can justify accessing like this. There just has to be a different solution.
How to gain Access to member variables of a class using void pointer but Not Object
[ "", "c++", "pointers", "" ]
Below I am creating an object in JavaScript. Within the constructor I am setting up an event listener. The problem is that when the event gets fired, `this.prop` cannot be found, and undefined prints out. How do I solve this? ``` var someObj = function someObj(){ this.prop = 33; this.mouseMoving = function() { console.log(this.prop);} document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving, true); } ```
When the event handler gets called, "this" no longer references the "someObj" object. You need to capture "this" into a local variable that the mouseMoving function will capture. ``` var someObj = function someObj(){ this.prop = 33; var self = this; this.mouseMoving = function() { console.log(self.prop);} document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving, true); } ``` I'm assuming "someObj is a constructor, i.e. intended to be called with as `new someObj()`, otherwise "this" will be the global scope. The "this" keyword can be confusing in JavaScript, because it doesn't work the same way as in other languages. The key thing to remember is that it is bound to the calling object **when the function is called**, not when the function is created.
The javascript built-in Function.prototype.bind() is intended for this purpose. For example: ``` var someObj = function someObj(){ this.prop = 33; this.mouseMoving = function() { console.log(this.prop);} document.getElementById("someDiv").addEventListener('mousemove', this.mouseMoving.bind(this),true); } ``` More on the bind method here: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind> Other wise you have to pass a reference of the object someObj to the element and use that reference in the line: ``` console.log(this.referenceToObject.prop); //this references the DOM element in an event. ```
Accessing an object's property from an event listener call in JavaScript
[ "", "javascript", "events", "event-handling", "dom-events", "" ]
What is the best method [pattern] to close a newly opened Windows form in C#/.NET if there is a trappable error in the CTOR/\_Load event ? i.e., ``` bool loadError; MyForm_Load(...) { try { } catch (SomeException ex) { // Alert the user MessageBox.Show("There was a critical error. The form will close. Please try again."); // There was some sort of error, and I just want the form to close now. loadError = true; return; } } ``` Now I want to act on loadError. I've tired using the Activate event, but that yielded no results. Any suggestions on what the best way to go about doing this is ? **Update:** Perhaps I should have been a little more explicit. Doing a "this.Close();" during the forms Load event will cause an exception to be thrown as a form can't be closed and the exception will be "Cannot call Close() while doing CreateHandle()".
As I mentioned in the comments, I tried with a sample example and called this.Closed() inside of the catch block. It worked just fine. The application showed the message box and didn't show me the form. I am using .NET3.5 SP1, though. Suppose this error happens in earlier version of .NET Framework, can you try to see whether any of the followings works for you or not? They, again, seem to work fine on my machine, yet, cannot guarantee whether they will work on yours, though. 1. Put this.Close() in the finally block to see it works `finally { if (this.loadError) this.Close(); }` 2. Defer the Form.Close() after Form.OnLoad event handler completes. See the sample below: this does not contain any anonymous delegate or lambda expression for older versions of .NET FW. Please forgive me for partial class :) ``` using System; using System.Windows.Forms; namespace ClosingFormWithException { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public delegate void InvokeDelegate(); private void Form1_Load(object sender, EventArgs e) { try { MyTroublesomeClass myClass = new MyTroublesomeClass(); } catch (ApplicationException ex) { MessageBox.Show("There was a critical error. The form will close. Please try again."); this.BeginInvoke(new InvokeDelegate(CloseTheForm)); } } private void CloseTheForm() { this.Close(); } } class MyTroublesomeClass { public MyTroublesomeClass() { throw new ApplicationException(); } } } ``` 3. Use the combination of 1 and 2 if 2 does not work: `finally { if (this.loadError) this.BeginInvoke(new InvokeDelegate(CloseTheForm)); }`
Have you tried calling this.Close() in the FormShown event? That event is fired once when your form is first shown. You could check your error condition there and then call close.
In C# what is the best way to close a newly opened form if there is a failure in CTOR/Load event?
[ "", "c#", "winforms", "" ]
Let's say I've got a SQL Server Indexed View, **vwIndexedView**, that reads from two tables, **tbTableOne**, and **tbTableTwo**. If I perform an action on one of the two tables inside a transaction, what happens to my indexed view? Is it refreshed immediately, or do I have to commit my transaction before the results will feed into it? For instance: ``` BEGIN TRANSACTION testTransaction INSERT INTO tbTableOne VALUES ('1', '2') SELECT * FROM vwIndexedView COMMIT TRANSACTION SELECT * FROM vwIndexedView ``` Would the results of the first SELECT be different than the second?
An index or an indexed view is updated immediately as part of the DML statement doing the update. In your case if you analyze the actual execution plan of the INSERT you'll see that it contains operators for update of all physical 'partitions', and you indexed view is one of such partitions.
Indexed views refresh immediately, you can have a look at the execution plan and see for yourself. This causes a lot of lock contention: [be ready to drop your indexed view](http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/06/02/be-ready-to-drop-your-indexed-view.aspx)
Do Indexed Views Update During a Transaction?
[ "", "sql", "sql-server", "transactions", "indexed-view", "" ]
So lets say I've added some prototype methods to the Array class: ``` Array.prototype.containsKey = function(obj) { for(var key in this) if (key == obj) return true; return false; } Array.prototype.containsValue = function(obj) { for(var key in this) if (this[key] == obj) return true; return false; } ``` then I create an associative array and attempt to loop through it's keys: ``` var arr = new Array(); arr['One'] = 1; arr['Two'] = 2; arr['Three'] = 3; for(var key in arr) alert(key); ``` this returns five items: ``` -One -Two -Three -containsKey -containsValue ``` but I want (expect?) only three. Am I approaching this wrong? is there a way to "hide" the prototype methods? or should I be doing something differently?
You can use JavaScript's [hasOwnProperty](http://javascript.about.com/od/reference/g/shasownproperty.htm) method to achieve this in the loop, like this: ``` for(var key in arr) { if (arr.hasOwnProperty(key)) { ... } } ``` Reference: [This YUI blog article](http://yuiblog.com/blog/2006/09/26/for-in-intrigue/).
You can achieve desired outcome from the other end by making the prototype methods not enumerable: ``` Object.defineProperty(Array.prototype, "containsKey", { enumerable: false, value: function(obj) { for(var key in this) if (key == obj) return true; return false; } }); ``` This usually works better if you have control over method definitions, and in particular if you have no control over how your code will be called by other people, which is a common assumption in library code development.
Javascript: hiding prototype methods in for loop?
[ "", "javascript", "arrays", "prototype", "loops", "for-loop", "" ]