Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I've recently been working with a simple Twitter API for PHP and came across this code to make @username be linked with twitter.com/username. Unfortunately this code creates it so @username links to <http://twitter.com/@username>, resulting in error. There are many parts to this code I do not understand, such as ^\v and others (seen below). Can anyone give me an explanation of what they signify? ``` $ret = preg_replace('/(^|[^\w])(@[\d\w\-]+)/', '\\1<a href="http://twitter.com/$2">$2</a>' ,$ret); ```
Easy one: ``` $ret = preg_replace('/(^|[^\w])@([\d\w\-]+)/', '\\1<a href="http://twitter.com/$2">@$2</a>' ,$ret); ``` The only difference is the @ was moved out of the capturing group, which means it has to be manually added to the output within the link. Also, \w includes digits so the \d is superfluous. So you could simply it to: ``` $ret = preg_replace('/^|([^\w])@([\w\-]+)/', '\\1<a href="http://twitter.com/$2">@$2</a>' ,$ret); ```
to remove the @, use: ``` $ret = preg_replace('/(^|[^\w])@([\d\w\-]+)/', '\\1<a href="http://twitter.com/$2">$2</a>' ,$ret); ``` This moves the @ outside the of the second capture group Also see <http://www.regular-expressions.info/> for some excellent information on regular expressions (in multiple languages)
preg_replace(), and the abbreviations that go with it?
[ "", "php", "regex", "api", "twitter", "" ]
I have an odd sorting case I'm struggling to work out using LINQs GroupBy method. I have two classes: Category and Item. Every Item has a category, and a Category can have a parent Category. What I need to do is organize all of the Items by their proper Category, but I also want to sort the Categories by the parent Category if there is one. So ideally I should be able to visualize my results like: ``` <Category 1> <Item 1> <Item 2> </Category 1> <Category 2> <Category 3> <Item 3> <Item 4> </Category 3> </Category 2> <Category 4> <Item 5> </Category 4> <Category 5> <Item 6> </Category 5> ``` I'm currently using `items.GroupBy(x => x.Category)` which gives me everything except the parent categories. So my results look like: ``` <Category 1> <Item 1> <Item 2> </Category 1> <Category 3> <Item 3> <Item 4> </Category 3> <Category 4> <Item 5> </Category 4> <Category 5> <Item 6> </Category 5> ``` The issue being that (in this example) the parent category for Category 3 (Category 2) isn't listed. I started goofing around with nested groups, but I didn't get very far before considering just manually walking the tree myself (foreach'ing). Before I do that, I'm hoping the LINQ gurus here can help me out...
Well, what data type are you expecting to get back? Currently, it'll be `IGrouping<Category, Item>` but if you want the topmost category to be the key, then the values could presumably be items *or* categories. You've shown the results as XML, but how are you actually going to use them? Given the results you've got, can't you easily get the parent category anyway? Do you need to use the parent category in the actual *grouping* part? If two categories have the same parent category, do you want all the items in that parent category to be mashed together? Sorry for all the questions - but the more we know, the better we'll be able to help you. EDIT: If you just want to group items by the topmost category, you can do ``` items.GroupBy(x => GetTopmostCategory(x)) ... public Category GetTopmostCategory(Item item) { Category category = item.Category; while (category.Parent != null) { category = category.Parent; } return category; } ``` (You could put this into `Category` or `Item`, potentially.) That would give you exactly the same return type, but the grouping would just be via the topmost category. Hope this is actually what you want...
If you had a tree to walk, you'd already have items grouped by category. Do you control the interface of your view? ``` public abstract class TreeNode { private readonly int name; private Category c = null; public int Name { get { return name; } } public Category Parent { get { return c; } } public abstract string Tag { get; } public TreeNode(int n, Category c) { this.name = n; AssignCategory(c); } public void AssignCategory(Category c) { if (c != null) { this.c = c; c.AddChild(this); } } public virtual IList<TreeNode> Children { get { return null; } } } ``` Item and Category look like ``` public class Item : TreeNode { public Item(int n, Category c) : base(n, c) {} public override string Tag { get { return "Item"; } } } public class Category : TreeNode { List<TreeNode> kids = new List<TreeNode>(); public Category(int n, Category c) : base(n, c) {} public void AddChild(TreeNode child) { kids.Add(child); } public override string Tag { get { return "Category"; } } public override IList<TreeNode> Children { get { return kids; } } } ``` Then you can show them with, say, a corny console display: ``` public class CornyTextView { public int NodeDepth(TreeNode n) { if (n.Parent == null) return 0; else return 1 + NodeDepth(n.Parent); } public void Display(IEnumerable<TreeNode> nodes) { foreach (var n in nodes.OrderBy(n => n.Name)) { for (int i = 0; i < NodeDepth(n); i++) Console.Write(" "); Console.WriteLine("- " + n.Tag + " " + n.Name.ToString()); if (n.Children != null) Display(n.Children); } } } ``` So to generate output for your example: ``` public static void Main() { var cats = new [] { new Category(1, null), new Category(2, null), new Category(3, null), new Category(4, null), new Category(5, null), }; cats[2].AssignCategory(cats[1]); var items = new[] { new Item(6, cats[4]), new Item(5, cats[3]), new Item(3, cats[2]), new Item(4, cats[2]), new Item(1, cats[0]), new Item(2, cats[0]), }; new CornyTextView() .Display(cats.Where(c => c.Parent == null) .Select(c => c as TreeNode)); } ``` Notice that even though `items` is shuffled, the output is ``` - Category 1 - Item 1 - Item 2 - Category 2 - Category 3 - Item 3 - Item 4 - Category 4 - Item 5 - Category 5 - Item 6 ```
Grouping nested objects using List(T).GroupBy()
[ "", "c#", "linq", "" ]
I have a base class called Component. I also have 2 interfaces I2DComponent, and I3DComponent. I am currently working on the I2DComponent. ### The implementation: ``` /// <summary> /// Represtions a 2D object. These objects will be drawn after 3D objects, /// and will have modifiers automatically provided in the editor. /// </summary> public interface I2DComponent { /// <summary> /// Gets or sets the rectangle. /// </summary> /// <value>The rectangle.</value> Rectangle Rectangle { get; set; } /// <summary> /// Gets the local position on the game screen. /// </summary> /// <value>The local position on the game screen.</value> /// <remarks>The rectangle position minus the parent screen position.</remarks> Rectangle LocalPosition { get; } /// <summary> /// Gets or sets the scale. /// </summary> /// <value>The scale.</value> float Scale { get; set; } } ``` So the problem is that I need access to the global position or the Rectangle for checking whether the mouse is over it. ``` if (component.Rectangle.Contains(mouse.Rectangle)) { do somthing. } ``` But when I am just accessing to moving it around i want to just be accessing the local position so that if i have a game screen at position 50, 50 then i can set the local position to 0, 0 and it will be at the top left corner of the parent game screen. I guess the real problem is that I don't want to be able to accidentally set the Rectangle by saying ``` component.Rectangle = new Rectangle(component.Rectangle.X + 5, component.Rectangle.Y + 5, component.Rectangle.Width, component.Rectangle.Height); ``` This is more or less an accessor design issue than anything and I want to make it look right, but I am having trouble doing so. **Update:** What if i changed changed it so that the I2D component only had Bounds and scale and then had a function in GameScreen to get the current "Global" position of the component. **Update:** These 2D objects are all objects that are draw as a hud or a gui object not in 3D space. just a clareification. **Update:** I am thinking about doing it recursively now but im not sure how i would go about doing this.
Your original question is a bit vague as to what these 2D objects are, and the best answer depends on a more rigorous definition. If these are objects in your game world, (eg. names above heads, billboards), then they need a world position, and you translate that to a screen position typically via a camera class, as described in another answer. If however these are GUI objects, such as menus, forms, heads-up displays, etc, then that's quite different. You only need to store a position relative to a parent element in that case (ie. the local position), and drawing them can be done recursively. Each element's position is basically its parent's global position plus its own local position, and that goes up the tree to any top-level parents whose local positions are also global positions. EDIT: example given to clarify. Python-style untested pseudocode (apologies, as I don't know C#) ``` def draw(element, parentScreenX, parentScreenY): # Draw this element relative to its parent screenX = parentScreenX + element.localX screenY = parentScreenY + element.localY render(element, screenX, screenY) # Draw each child relative to this one for childElement in element.children: draw(childElement, screenX, screenY) # Normal usage (root element should be at 0,0, # and typically just an invisible container.) draw(rootElement, 0, 0) # Slightly different mathematics for the mouseover test, # but that's just personal preference def elementAtPos(element, posX, posY): # Translate that space to element local space posX -= element.localX posY -= element.localY # Compare against this element's dimensions if (posX, posY) is within (0, 0, element.width, element.height): # it's within this element - now check children for childElement in element.children: # Do this same check on the child element (and its children, etc) targetedChildElement = elementAtPos(childElement, posX, posY) if targetedChildElement is not None: return targetedChildElement # it wasn't within any of our descendants so return this one return element # It wasn't within our bounds at all, so return None return None #Normal usage targetedElement = elementAtPos(rootElement, mouseScreenX, mouseScreenY) ``` You may want 2 separate functions: one that gets the exact targeted element (as above) and one that merely returns if the mouse is anywhere over an element, which may return true for several elements at the same time, eg. a button, the panel the button is on, the form the panel is on, etc. There are several ways you could implement that, but probably the easiest is to implement a recursive call to allow any element to get its screen position: ``` def screen_position(element): if element.parent is not None: (parentLocalX, parentLocalY) = screen_position(element.parent) else: (parentLocalX, parentLocalY) = (0,0) return (element.localX + parentLocalX, element.localY + parentLocalY) ``` Watch out for the circular reference now between parent and children now. These all require a root element at 0,0 - this facilitates the transformation between screen space and local space for the root element, because they are effectively the same. Then the rest of the algorithm can work in local space.
I would only ever worry about modifying the local position of your game object, never it's screen position, because that is Dependant on the location and view port of your camera. There are two ways you can tackle finding the position of something on screen. The first is with an accessor method that takes the Camera, and the other is by using the camera as a translation method in the first place. I prefer the later, and rewrite thusly: ``` public interface I2DComponent { /// <summary> /// Gets or sets the local (world) bounds of the object. /// </summary> /// <value>The rectangle.</value> Rectangle Bounds{ get; } /// <summary> /// Gets or sets the scale. /// </summary> /// <value>The scale.</value> float Scale { get; set; } } ``` Then in camera have two methods ``` public class Camera { public Rectangle WorldToScreen(Rectangle rect); public Rectangle ScreenToWorld(Rectangle point); } ``` This way you keep an encapsulated Object which doesn't care at all about the screen, and a Camera that handles all of the translation.
How to have a local position and global position in a game
[ "", "c#", "recursion", "2d", "" ]
A friend was showing me an API made with a COM Object and a SOAP interface. He showed me how it worked in php on windows but I have serious doubts if it is achievable on linux or any other non-windows OS. Thanks!
Depends on where the COM object is running. A Linux box can serve a COM object (ActiveX) to a windows client browser. A Linux box can make a SOAP call to a COM object running on a Windows box. But if you want to run the COM object on Linux, it needs to at least be rebuilt for Linux, and probably into something more Linuxy (an .so). Probably any PHP COM support isn't ported to the Linux version, but you can call into .so files through C bindings.
The COM library in PHP is a part of the [Windows only extension.](http://is.php.net/manual/en/refs.utilspec.windows.php)
Is it possible to access to a COM object in linux with PHP?
[ "", ".net", "php", "com", "" ]
I'm pretty sure this problem isn't new, and pretty sure it's hard to solve. Hopefully I'm wrong about the latter. I'm trying to use the Loki::Singleton from Modern C++ Design in a program of mine. However, I can't seem to get it to work across DLLs. I think I know why this is happening: the templated code gets instantiated in every source module, so instead of there being one global variable, each module has its own. Obviously, this makes the Singleton very much non-single. Is there any way to get around this behavior?
I see in the Loki source directory that they have a specific [SingletonDLL directory](http://loki-lib.svn.sourceforge.net/viewvc/loki-lib/trunk/test/SingletonDll/) under test, looks like they use an exported, explicitly instantiated template (which would work). Hopefully that contains the code you want.
Note this is not going to address the question. An explicitly instantiated and exported singleton should do the trick... -Rick Check out #pragma data\_seg [here](http://msdn.microsoft.com/en-us/library/h90dkhs0(VS.80).aspx) basically, you need to declare an instance of the singleton in a shared section of your code. By default statics are scoped to the dll. It may get tricky with templates, but this is the path to success here that doesn't involve passing / copying static data around.
Getting Loki Singleton to work in DLLs in VS 2008 C++
[ "", "c++", "visual-studio-2008", "singleton", "c++-loki", "" ]
How can we use them in our codes, and what will cause NaN(not a number)?
[This](http://introcs.cs.princeton.edu/java/91float/) may be a good reference if you want to learn more about floating point numbers in Java. Positive Infinity is a positive number so large that it can't be represented normally. Negative Infinity is a negative number so large that it cannot be represented normally. NaN means "Not a Number" and results from a mathematical operation that doesn't yield a number- like dividing 0 by 0. In Java, the Double and Float classes both have constants to represent all three cases. They are POSITIVE\_INFINITY, NEGATIVE\_INFINITY, and NaN. Plus consider this: ``` double a = Math.pow(10, 600) - Math.pow(10, 600); //==NaN ``` Mathematically, everybody can see it is 0. But for the machine, it is an "Infinity" - "Infinity" (of same Rank), which is indeed NaN.
* Positive infinity means going to infinity in the positive direction -- going into values that are larger and larger in magnitude in the positive direction. * Negative infinity means going to infinity in the negative direction -- going into values that are larger and larger in magnitude in the negative direction. * [Not-a-number](http://en.wikipedia.org/wiki/Not_a_number) (NaN) is something that is undefined, such as the result of `0/0`. And the constants from the specification of the [`Float`](http://java.sun.com/javase/6/docs/api/java/lang/Float.html) class: * [`Float.NEGATIVE_INFINITY`](http://java.sun.com/javase/6/docs/api/java/lang/Float.html#NEGATIVE_INFINITY) * [`Float.POSITIVE_INFINITY`](http://java.sun.com/javase/6/docs/api/java/lang/Float.html#POSITIVE_INFINITY) * [`Float.NaN`](http://java.sun.com/javase/6/docs/api/java/lang/Float.html#NaN) More information can be found in the [IEEE-754 page in Wikipedia](http://en.wikipedia.org/wiki/IEEE_754-1985). Here's a little program to illustrate the three constants: ``` System.out.println(0f / 0f); System.out.println(1f / 0f); System.out.println(-1f / 0f); ``` Output: ``` NaN Infinity -Infinity ```
What do these three special floating-point values mean: positive infinity, negative infinity, NaN?
[ "", "java", "floating-point", "nan", "infinity", "" ]
How can you pass refernces in C#?
``` private void functionName (ref Type variableName) { } ``` To Call it ``` functionName(ref variable); ```
Your question is extremely unclear, but it's quite possible that my [article on parameter passing in C#](http://pobox.com/~skeet/csharp/parameters.html) will answer whatever you really intended to ask. In particular, you need to distinguish between passing a reference *by value*, and passing an argument *by reference*. If you're hazy on value types and reference types, you might also want to look at [my article on that topic](http://pobox.com/~skeet/csharp/references.html).
How to pass references as arguments in a method in c#
[ "", "c#", "console", "" ]
I was wondering why the vector templates perform two allocations, when only one seems to be necessary. For example this: ``` #include <vector> #include <iostream> class A { public: A(const A &a) { std::cout << "Calling copy constructor " << this << " " << &a << "\n"; } A() { std::cout << "Calling default constructor " << this << "\n"; } ~A() { std::cout << "Calling destructor " << this << "\n"; } }; int main(int argc, char **argv) { std::vector <A> Avec; std::cout << "resize start\n"; Avec.resize(1); std::cout << "resize end\n"; return 0; } ``` Outputs: ``` resize start Calling default constructor 0x7fff9a34191f Calling copy constructor 0x1569010 0x7fff9a34191f Calling destructor 0x7fff9a34191f resize end ```
It isn't performing two allocations, it is creating an object by the default constructor to pass into resize, then copying that object into the new position, then destructing the argument. If you look at the arguments to resize: ``` void resize(n, t = T()) ``` It has as a defaulted argument a default constructed object of type T (this is the default constructor being called in your output). Then, within the function, it copies this into the correct position (this is the copy constructor). After the resize function ends, destroys the argument (the destructor call in the output).
If you initialize objects that way the vector template creates objects by making a copy. If you don't want to call copy constructor you should make : ``` vector<A*> Avec; avec.push_back(new A()); ``` <http://www.cplusplus.com/reference/stl/vector/vector/>
STL vector allocations
[ "", "c++", "stl", "" ]
I have a Windows Service which I install using the InstallUtil.exe. Even though I have set the Startup Method to Automatic, the service does not start when installed, I have to manually open the services and click start. Is there a way to start it either via the command line, or through the code of the Service?
In your Installer class, add a handler for the AfterInstall event. You can then call the ServiceController in the event handler to start the service. ``` using System.ServiceProcess; public ServiceInstaller() { //... Installer code here this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall); } void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e) { ServiceInstaller serviceInstaller = (ServiceInstaller)sender; using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName)) { sc.Start(); } } ``` Now when you run InstallUtil on your installer, it will install and then start up the service automatically.
After refactoring a little bit, this is an example of a complete windows service installer with automatic start: ``` using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; namespace Example.of.name.space { [RunInstaller(true)] public partial class ServiceInstaller : Installer { private readonly ServiceProcessInstaller processInstaller; private readonly System.ServiceProcess.ServiceInstaller serviceInstaller; public ServiceInstaller() { InitializeComponent(); processInstaller = new ServiceProcessInstaller(); serviceInstaller = new System.ServiceProcess.ServiceInstaller(); // Service will run under system account processInstaller.Account = ServiceAccount.LocalSystem; // Service will have Automatic Start Type serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "Windows Automatic Start Service"; Installers.Add(serviceInstaller); Installers.Add(processInstaller); serviceInstaller.AfterInstall += ServiceInstaller_AfterInstall; } private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e) { ServiceController sc = new ServiceController("Windows Automatic Start Service"); sc.Start(); } } } ```
Automatically start a Windows Service on install
[ "", "c#", "windows-services", "" ]
I recently discovered that the java.lang.String.substring method does not return a new string, but a view of the original string that was substringed. This can have memory implications. For example, if you're reading an ascii file, and parsing tokens in the file using substring and storing the result of substring in memory somewhere -- what you're actually storing in memory is the entire string prior to the substring operation! You can of course solve this by wrapping substring in your own version that returns a new string of the subtring result.
I've been bitten by it once, reading a dictionary file line by line. Each line was very short, but the buffer created by `BufferedReader` meant that each string was backed by an 80-char array. That was when I first learned the point of writing: ``` word = new String(word); ``` Most of the time it's not a problem though - and of course it *can* be more efficient than the "take a completely separate copy" approach.
In the year 2000 or 2001, one of the early `XML` parsers (I can't remember which) suffered from this problem. It took us a while to track down how we were going out of memory by reading about 3 fields out of some early `FpML` (very big `XML` documents which describe financial products). What is really annoying is that if a write ``` String copy = new String(s); ``` IntelliJ IDEA warns me that this is redundant! Stupid IDE.
How many people have been stung by Java substring memory issues?
[ "", "java", "substring", "" ]
I have a Java program running in command line mode. I would like to display a progress bar, showing the percentage of job done. The same kind of progress bar you would see using wget under unix. Is this possible?
I have implemented this sort of thing before. Its not so much about java, but what characters to send to the console. The key is the difference between `\n` and `\r`. `\n` goes to the start of a new line. But `\r` is just *carriage return* - it goes back to the start of the same line. So the thing to do is to print your progress bar, for example, by printing the string ``` "|======== |\r" ``` On the next tick of the progress bar, overwrite the same line with a longer bar. (because we are using \r, we stay on the same line) For example: ``` "|========= |\r" ``` What you have to remember to do, is when done, if you then just print ``` "done!\n" ``` You may still have some garbage from the progress bar on the line. So after you are done with the progress bar, be sure to print enough whitespace to remove it from the line. Such as: ``` "done |\n" ```
There is <https://github.com/ctongfei/progressbar>, License: MIT Simple console progress bar. Progress bar writing now runs on another thread. ![](https://i.gyazo.com/1c02d51927e769cf245a108f5a8dfaf5.gif) Menlo, Fira Mono, Source Code Pro or SF Mono are recommended for optimal visual effects. For Consolas or Andale Mono fonts, use `ProgressBarStyle.ASCII` (see below) because the box-drawing glyphs are not aligned properly in these fonts. ![](https://i.gyazo.com/e01943454443f90c9499c00a6c197a41.gif) [Maven](https://search.maven.org/artifact/me.tongfei/progressbar): ``` <dependency> <groupId>me.tongfei</groupId> <artifactId>progressbar</artifactId> <version>0.5.5</version> </dependency> ``` Usage: ``` ProgressBar pb = new ProgressBar("Test", 100); // name, initial max // Use ProgressBar("Test", 100, ProgressBarStyle.ASCII) if you want ASCII output style pb.start(); // the progress bar starts timing // Or you could combine these two lines like this: // ProgressBar pb = new ProgressBar("Test", 100).start(); some loop { ... pb.step(); // step by 1 pb.stepBy(n); // step by n ... pb.stepTo(n); // step directly to n ... pb.maxHint(n); // reset the max of this progress bar as n. This may be useful when the program // gets new information about the current progress. // Can set n to be less than zero: this means that this progress bar would become // indefinite: the max would be unknown. ... pb.setExtraMessage("Reading..."); // Set extra message to display at the end of the bar } pb.stop() // stops the progress bar ```
Command line progress bar in Java
[ "", "java", "command-line", "progress-bar", "" ]
It's easier with an example. I have two tables: Books and Chapters. Both have Title and Id columns. Chapters also has a Book column which is a foreign key to Books.Id. Books.Title is unique (I don't want two books with the same title). Now my problem is defining Chapter.Title uniqueness. I want it to be unique as long as Books.Id is the same. So that one book may not have two chapters with the same title but two different books may have the same title in a chapter. Is this possible on SQL Server 2008? How?
UNIQUE CONSTRAINT or UNIQUE index. Either one will do. ``` ALTER TABLE dbo.MyTable WITH CHECK ADD CONSTRAINT UQ_MyTable_BookTitle UNIQUE (BookID, Title) ``` or ``` CREATE UNIQUE INDEX IXU_MyTable_BookTitle ON dbo.MyTable (BookID, Title) ```
Create a UNIQUE INDEX on Chapters using columns BookID and Title (indexes may include several columns, not just one)
How do I specify a column to be unique in the scope of a relationship in SQL Server 2008?
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "constraints", "" ]
Is there anyway in Java to find out if the given path is absolute or not regardless of the platform the program is currently running. So, what I want is probably something like the following example: On Linux: ``` new File("/home/").isAbsolute() // Should return true. new File("C:/My Documents").isAbsolute() // Should *also* return true. ``` On Windows: ``` new File("C:/Documents").isAbsolute() // Should return true. new File("/home/").isAbsolute() // Should *also* return true. ``` I can probably code something to get around with this, but I just wanted to find out if anyone knew a built-in class provided in Java to solve this problem. Or has anyone ever come this problem? And how did you solve it? Thanks!
Nope. There are some underlying [FileSystem](http://docjar.com/docs/api/java/io/FileSystem.html) classes (that's Java 7, but they exist prior to it as well) that expose isAbsolute(), but they're not public - so you *shouldn't* use them, and even if you did your code would be full of reflection junk - and only the "correct" OS ones are included in the JRE, so you'd have to code around them anyway. Here are the Java 7 implementations of isAbsolute(...) to get you started. Note that File.getPrefixLength() is package-private. [Win32FileSystem](http://docjar.com/docs/api/java/io/Win32FileSystem.html): ``` public boolean isAbsolute(File f) { int pl = f.getPrefixLength(); return (((pl == 2) && (f.getPath().charAt(0) == slash)) || (pl == 3)); } ``` [UnixFileSystem](http://docjar.com/docs/api/java/io/UnixFileSystem.html): ``` public boolean isAbsolute(File f) { return (f.getPrefixLength() != 0); } ```
In Java 7: ``` new File(path).isAbsolute() ```
Java: How to find out if path is absolute regardless of the OS
[ "", "java", "path", "absolute-path", "" ]
On one page of my website the user has the ability to choose and remove up to 2000 items through selecting multiple string representations of them in a dropdown list. On page load, the objects are loaded onto the page from a previous session into 7 different drop-down lists. In the window.onload event, the function looping through the items in the drop-downs makes an internal collection of the objects by adding them to a global array - This makes the page ridiculously slow to load, so, I'm fairly certain probably doing it wrong! How else am I supposed to store these variables? This is their internal representation: ``` function Permission(PName, DCID, ID) { this.PName = PName; this.DCID = DCID; this.ID = ID; } ``` where: PName is string. DCID is int. ID is int. **EDIT:** Thanks for the quick replies! I appreciate the help, I'm not great with JS! Here is more information: 'selectChangeEvent' is added to the Change and Click event of the Drop down list. ``` function selectChangeEvent(e) { //... addListItem(id); //... } ``` 'addListItem(id)' sets up the visual representation of the objects and then calls : ``` function addListObject(x, idOfCaller) { var arIDOfCaller = idOfCaller.toString().split('-'); if (arIDOfCaller[0] == "selLocs") { var loc = new AccessLocation(x, arIDOfCaller[1]); arrayLocations[GlobalIndexLocations] = loc; GlobalIndexLocations++; totalLocations++; } else { var perm = new Permission(x, arIDOfCaller[1], arIDOfCaller[2]); arrayPermissions[GlobalIndexPermissions] = perm; GlobalIndexPermissions++; totalPermissions++; } } ```
Still not enough to go on, but there are some small improvements I can see. Instead of this pattern: ``` var loc = new AccessLocation(x, arIDOfCaller[1]); arrayLocations[GlobalIndexLocations] = loc; GlobalIndexLocations++; totalLocations++; ``` which seems to involve redundant counters and has surplus assignment operations, try: ``` arrayLocations[arrayLocations.length] = new AccessLocation(x, arIDOfCaller[1]); ``` and just use arrayLocations.length where you would refer to GlobalIndexLocations or totalLocations (which fromt he code above would seem to always be the same value). That should gain you a *little* boost, but this is not your main problem. I suggest you add some debugging Date objects to work out where the bottleneck is.
You may want to consider a design change to support the load. Some sort of paged result set or similar, to cut down on the number of concurrent records being modified. As much as we desperately want them to be, browsers aren't quite there yet in terms of script execution speed that allow us to do certain types of heavy lifting on the client.
JS 1-2k variables make page load slow
[ "", "javascript", "memory", "variables", "performance", "" ]
How can I get the Windows user and domain from an Active Directory DirectoryEntry (SchemaClassName="user") object? The user name is in the sAMAccountName property but where can I look up the domain name? (I can't assume a fixed domain name because the users are from various subdomains.)
I found a partitions container in CN=Partitions,CN=Configuration that contains all domains. When you match the user to the partion you can read the real domain name from the nETBIOSName+"\"+sAMAccountName property.
This assumes that `results` is a SearchResultCollection obtained from a DirectorySearcher, but you should be able to get the objectsid from a DirectoryEntry directly. ``` SearchResult result = results[0]; var propertyValues = result.Properties["objectsid"]; var objectsid = (byte[])propertyValues[0]; var sid = new SecurityIdentifier(objectsid, 0); var account = sid.Translate(typeof(NTAccount)); account.ToString(); // This give the DOMAIN\User format for the account ```
How can I get DOMAIN\USER from an AD DirectoryEntry?
[ "", "c#", ".net", "active-directory", "" ]
So I have some SMTP stuff in my code and I am trying to unit test that method. So I been trying to Mockup MailMessage but it never seems to work. I think none of the methods are virtual or abstract so I can't use moq to mock it up :(. So I guess I have to do it by hand and that's where I am stuck. \*by hand I mean witting the interface and the wrapper but letting moq still mockup the interface. I don't know how to write my Interface and my Wrapper(a class that will implement the interface that will have the actual MailMessage code so when my real code runs it actually does the stuff it needs to do). So first I am not sure how to setup my Interface. Lets take a look at one of the fields that I have to mockup. ``` MailMessage mail = new MailMessage(); mail.To.Add("test@hotmail.com"); ``` so this is the first thing that I have to fake. so looking at it I know that "To" is a property by hitting F12 over "To" it takes me to this line: ``` public MailAddressCollection To { get; } ``` So it is MailAddressCollection Property. But some how I am allowed to go further and do "Add". So now my question is in my interface what do I make? do I make a property? Should this Property be MailAddressCollection? Or should I have a method like? ``` void MailAddressCollection To(string email); or void string To.Add(string email); ``` Then how would my wrapper look? So as you can see I am very confused. Since there is so many of them. I am guessing I just mockup the ones I am using. edit code I guess in in a true sense I would only have to test more the exceptions but I want to test to make sure if everything gets sent then it will get to response = success. ``` string response = null; try { MembershipUser userName = Membership.GetUser(user); string newPassword = userName.ResetPassword(securityAnswer); MailMessage mail = new MailMessage(); mail.To.Add(userName.Email); mail.From = new MailAddress(ConfigurationManager.AppSettings["FROMEMAIL"]); mail.Subject = "Password Reset"; string body = userName + " Your Password has been reset. Your new temporary password is: " + newPassword; mail.Body = body; mail.IsBodyHtml = false; SmtpClient smtp = new SmtpClient(); smtp.Host = ConfigurationManager.AppSettings["SMTP"]; smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["FROMEMAIL"], ConfigurationManager.AppSettings["FROMPWD"]); smtp.EnableSsl = true; smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["FROMPORT"]); smtp.Send(mail); response = "Success"; } catch (ArgumentNullException ex) { response = ex.Message; } catch (ArgumentException ex) { response = ex.Message; } catch (ConfigurationErrorsException ex) { response = ex.Message; } catch (ObjectDisposedException ex) { response = ex.Message; } catch (InvalidOperationException ex) { response = ex.Message; } catch (SmtpFailedRecipientException ex) { response = ex.Message; } catch (SmtpException ex) { response = ex.Message; } return response; } ``` Thanks
Why mock the MailMessage? The SmtpClient receives MailMessages and sends them out; that's the class I'd want to wrap for testing purposes. So, if you're writing some type of system that places Orders, if you're trying to test that your OrderService always emails when an order is placed, you'd have a class similar to the following: ``` class OrderService : IOrderSerivce { private IEmailService _mailer; public OrderService(IEmailService mailSvc) { this. _mailer = mailSvc; } public void SubmitOrder(Order order) { // other order-related code here System.Net.Mail.MailMessage confirmationEmail = ... // create the confirmation email _mailer.SendEmail(confirmationEmail); } } ``` With the default implementation of IEmailService wrapping SmtpClient: This way, when you go to write your unit test, you test the behavior of the code that uses the SmtpClient/EmailMessage classes, not the behavior of the SmtpClient/EmailMessage classes themselves: ``` public Class When_an_order_is_placed { [Setup] public void TestSetup() { Order o = CreateTestOrder(); mockedEmailService = CreateTestEmailService(); // this is what you want to mock IOrderService orderService = CreateTestOrderService(mockedEmailService); orderService.SubmitOrder(o); } [Test] public void A_confirmation_email_should_be_sent() { Assert.IsTrue(mockedEmailService.SentMailMessage != null); } [Test] public void The_email_should_go_to_the_customer() { Assert.IsTrue(mockedEmailService.SentMailMessage.To.Contains("test@hotmail.com")); } } ``` Edit: to address your comments below, you'd want two separate implementations of EmailService – only one would use SmtpClient, which you'd use in your application code: ``` class EmailService : IEmailService { private SmtpClient client; public EmailService() { client = new SmtpClient(); object settings = ConfigurationManager.AppSettings["SMTP"]; // assign settings to SmtpClient, and set any other behavior you // from SmtpClient in your application, such as ssl, host, credentials, // delivery method, etc } public void SendEmail(MailMessage message) { client.Send(message); } } ``` Your mocked/faked email service (you don't need a mocking framework for this, but it helps) wouldn't touch SmtpClient or SmtpSettings; it'd only record the fact that, at some point, an email was passed to it via SendEmail. You can then use this to test whether or not SendEmail was called, and with which parameters: ``` class MockEmailService : IEmailService { private EmailMessage sentMessage;; public SentMailMessage { get { return sentMessage; } } public void SendEmail(MailMessage message) { sentMessage = message; } } ``` The actual testing of whether or not the email was sent to the SMTP Server and delivered should fall outside the bounds of your unit testing. You need to know whether this works, and you can set up a second set of tests to specifically test this (typically called Integration Tests), but these are distinct tests separate from the code that tests the core behavior of your application.
*disclaimer: I work at Typemock* Instead of finding some hack you can use Typemock Isolator to simply fake that class in only one line of code: ``` var fakeMailMessage = Isolate.Fake.Instance<MailMessage>(); ``` Then you can set behavior on it using *Isolate.WhenCalled*
How do I make a mockup of System.Net.Mail MailMessage?
[ "", "c#", "asp.net-mvc", "unit-testing", "mocking", "" ]
Consider this ``` Class* p = NULL; if( p != NULL && p->Method() == OK ){ // stuff } ``` On all compilers I've worked with, this is quite safe. I.e. the first part of the boolean expression will evaluate to *false*, and the call to Method() will thus not be attempted since evaluating the second part is redundant. Is this because most compilers will optimize away the evaluation of the second part, or is it a dictated behavior from the C/C++ standards?
This is called boolean short circuiting and is defined into many languages. [Here](http://en.wikipedia.org/wiki/Short-circuit_evaluation) is a wikipedia article that describes which languages have this feature. Now that you know the correct name for the feature, there are [other SO articles](https://stackoverflow.com/search?q=short+circuit) about it as well.
С++ Standard 1998 Section 5.14 > The && operator groups left-to-right. > The operands are both implicitly > converted to type bool(clause 4). The > result is true if both operands are > true and false otherwise. Unlike &, && > guarantees left-to-right evaluation: > the second operand is not evaluated if > the first operand is false.
Is "boolean short circuiting" dictated by standard or just mostly used as optimization?
[ "", "c++", "c", "standards-compliance", "boolean-logic", "boolean-expression", "" ]
I'm trying to validate a drivers license for a form that i am making. I was trying to use a single regex. 1. Max length 9 characters 2. Alphanumeric characters only 3. Must have at least 4 numeric characters 4. Must have no more than 2 alphabetic characters 5. The third and fourth character must be numeric I'm new at regex I'm googling trying to work it out. Help with this would be appreciated.
Trying to solve this with just one regex is probably a little hard as you need to keep track of multiple things. I'd suggest you try validating each of the properties separately (unless it makes sense to do otherwise). For example you can verify the first and second properties easily by checking for a [character class](http://www.regular-expressions.info/charclass.html) including all alphanumeric characters and a [quantifier](http://www.regular-expressions.info/repeat.html) which tells that it should be present at most 9 times: ``` ^[0-9a-zA-Z]{4,9}$ ``` The [anchors](http://www.regular-expressions.info/anchors.html) `^` and `$` ensure that this will, in fact, match the entire string and not just a part of it. As Marc Gravell pointed out the string `"aaaaa"` will match the expression `"a{3}"` because it can match partially as well. Checking the fifth property can be done similarly, although this time we don't care about the rest: ``` ^..[0-9]{2} ``` Here the `^` character is an [anchor](http://www.regular-expressions.info/anchors.html) for the start of the string, the [dot (`.`)](http://www.regular-expressions.info/dot.html) is a placeholder for an arbitrary character and we're checking for the third and fourth character being numeric again with a character class and a repetition quantifier. Properties three and four are probably easiest validated by iterating through the string and keeping counters as you go along. **EDIT:** [Marc Gravell](https://stackoverflow.com/questions/1021362/noob-need-help-with-regex-im-lost/1021382#1021382) has a very nice solution for those two cases with regular expressions as well. Didn't think of those. If you absolutely need to do this in one regular expression this will be a bit work (and probably neither faster nor more readable). Basically I'd start with enumerating all possible options such a string could look like. I am using `a` here as placeholder for an alphabetic characters and `1` as a placeholder for a number. We need at least four characters (3) and the third and fourth are always fixed as numbers. For four-character strings this leaves us with only one option: ``` 1111 ``` Five-character strings may introduce a letter, though, with different placements: ``` a1111 1a111 1111a ``` and, as before, the all-numeric variant: ``` 11111 ``` Going on like this you can probably create special rules for each case (basically I'd divide this into "no letter", "one letter" and "two letters" and enumerate the different patterns for that. You can then string together all patterns with the [pipe (`|`)](http://www.regular-expressions.info/alternation.html) character which is used as an alternative in regular expressions.
Does it have to be a single regex? I'd keep things simple by keeping them separate: ``` static bool IsValid(string input) { return Regex.IsMatch(input, @"^[A-Za-z0-9]{4,9}$") // length and alphanumeric && Regex.IsMatch(input, "^..[0-9]{2}") // 3rd+4th are numeric && Regex.IsMatch(input, "(.*[0-9]){4}") // at least 4 numeric && !Regex.IsMatch(input, "(.*[A-Za-z]){3}"); // no more than 2 alpha } ```
Help with drivers license number validation regex
[ "", "c#", "regex", "" ]
I am using ``` <url-pattern>/*</url-pattern> ``` to map all the requests to one sevlet,where i do all the authentication work. but I want to skip some static content (like css files).so I tried fowrding them from that sevlet to where the resource file is ``` if(isResourceFile){ RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("static/" + fileName); dispatcher.forward(request, response); } ``` but this will start a infinite loop because this will again call the same sevlet is there any way to work around this without mapping all the resource(css) files in web.xml?
Assuming that you're looking to authenticate just JSP files, you could change the URL: ``` /*.jsp ``` I think it's a better idea to handle your authentication using a filter rather than a servlet. And in a production environment, you should use a front-end webserver for static content.
The `url-pattern` of `/*` is better to be used exclusively by `Filter`s, not `Servlet`s. Put all your static files in a certain folder (maybe covered by the `url-pattern` of a more effective [FileServlet](https://balusc.omnifaces.org/2009/02/fileservlet-supporting-resume-and.html)?) and let the Filter check it. E.g. (pseudo) ``` public void doFilter(request, response, chain) { if (requestURI.startsWith("/static")) { chain.doFilter(request, response); // Just continue. Do nothing. } else { request.getRequestDispatcher("/pages").forward(request, response); // Forward to page controller. } } ``` ### See also: * [Difference between / and /\* in servlet mapping url pattern](https://stackoverflow.com/questions/4140448/difference-between-and-in-servlet-mapping-url-pattern)
RequestDispatcher.forward loop
[ "", "java", "jsp", "jakarta-ee", "servlets", "" ]
I've tried to inspect the AjaxContext that ASP.NET-MVC uses on for instance Ajax Actionlinks and their onSucces, onComplete etc. clientside functions. But I don't understand very much of it... Where is the documentation on this thing? **Does anybody know how to I get the 'target' or 'srcElement' (e.target or window.event.srcElement) when I am in a onSuccess or onComplete javascript event?** ``` <%=Ajax.ActionLink( "LinkText", "Action", New With {.Controller = "ControllerName"}, New AjaxOptions With { .UpdateTargetId = "divElement", .OnSuccess = "function(ajaxContext) {console.log(ajaxContext);}" }) %> ``` Which results in: ``` <a href="/Popout/ApplicationCodePopout" onclick="Sys.Mvc.AsyncHyperlink.handleClick( this, new Sys.UI.DomEvent(event), { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: 'divElement', onSuccess: Function.createDelegate(this, function(ajaxContext) {console.log(ajaxContext);} ) } );" >LinkText</a> ```
You could change the onSuccess method to this: ``` <%=Ajax.ActionLink( "LinkText", "Action", New With {.Controller = "ControllerName"}, New AjaxOptions With { .UpdateTargetId = "divElement", .OnSuccess = "function(ajaxContext) {debugger;}" }) %> ``` (**Note the debugger keyword**) Then you can break into it using VS2008 (assuming IE, if you're using Firefox, then install [Firebug](http://getfirebug.com/) as Jake said) and then you can use the quick watch window (in VS or equivalent in Firebug etc) to view the object and it's properties/ methods etc. As for some documentation, check out [this](http://code.google.com/p/rpxlib/source/browse/trunk/src/RPX.Web.MVC/Scripts/MicrosoftMvcAjax.debug.js?spec=svn2&r=2) link to see the code comments, and [this](http://msmvps.com/blogs/luisabreu/archive/2009/03/04/the-mvc-framework-a-deep-dive-on-the-client-ajax-api.aspx) article for some more information.
Okay so you need to get [Firebug](http://getfirebug.com/) installed (If you havnot already done so do it now :) Now start using [console.log](http://getfirebug.com/console.html) in your code to help you find out what properties and functions each object has available. Try typing in console.log(document) - You can do this in the Console window in the textbox (next to the >>>). Notice how you can click on the links in the console to interigate and see what properties and functions the object has available.
ASP.NET MVC - AjaxContext
[ "", "javascript", "asp.net-mvc", "ajaxcontext", "" ]
following is the code listed in MainClass.java. ``` public class MainClass { public static void main(String[] args) { System.out.println("main started..."); Class c = MyClass.class ; //this class variable seems to be public static. //But, as it is clearly visible in the MyClass, //no reference variable is declared. //My problem is that from where this class variable //came from. //i also check out the Object.java file, but it also don't //have any public static class variable of Class class //like there is //out (instance of PrintStream class) in System class. //Hope all u mindoverflow guys help me to sort out //this probz. try { Class.forName( c.getName() ) ; System.out.println("classloader of MyClass : " + MyClass.class.getClassLoader()); System.out.println("classloader of MyClass : " + String.class.getClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("main ended..."); } } class MyClass{ static{ System.out.println("static block of MyClass class."); } } ``` thnx coobird... i found the article quite useful. :) But, about litereals my knowledge is only limited to: ``` int i = 5 ; //here 5 is an integer literal float f = 5.6f ; //here 5.6f is a float literal ``` the only non-primitive litereal, i know is ``` String str = "java" ; //"java" is a String litereal ``` and class literal, which u and Jon Skeet make clear to me very well. **are there more literals found in java???** --- agreed... so as per the discussion, total literals are categorized as:- * primitive literals * string literals * class literal * null are there some more literals (to make the list a little longer **:)** ) --- ***when i decompile the MainClass.class using decomipler, two Class type static variables (may be coz, i have used class literal 2 times) are found to be automatically added, but never found to be used in the code. Also, both the class literals are directly replaced from the class file where i have used them in the java file.*** **My code :-** ``` public class MainClass { public static void main(String[] args) { System.out.println("main started..."); Class c = MyClass.class ; try { Class.forName( c.getName() ) ; System.out.println("classloader of MyClass : " + MyClass.class.getClassLoader()); System.out.println("classloader of MyClass : " + String.class.getClassLoader()); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("main ended..."); } } ``` **Decompiler generated code :-** ``` import java.io.PrintStream; public class MainClass { public MainClass() { } public static void main(String args[]) { System.out.println("main started..."); Class c = MyClass; try { Class.forName(c.getName()); System.out.println((new StringBuilder("classloader of MyClass : ")).append(MyClass.getClassLoader()).toString()); System.out.println((new StringBuilder("classloader of MyClass : ")).append(java/lang/String.getClassLoader()).toString()); } catch(ClassNotFoundException e) { e.printStackTrace(); } System.out.println("main ended..."); } static Class class$0; static Class class$1; } ```
It's "class literal" - a simple way of getting the `Class<T>` for a particular type. See [section 15.8.2](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2) of the Java Language Specification for more details. Note that it's not a "field" of the class, it's a special piece of syntactic sugar. Due to type erasure, you may run into interesting restrictions around generics. The [`TypeLiteral`](http://google-guice.googlecode.com/svn/trunk/latest-javadoc/com/google/inject/TypeLiteral.html) introduced in Guice gives more information and a workaround. In terms of implementation, it depends on which bytecode version you're targeting. If you use `-target 1.4` (or below), a call to `Class.forName()` is inserted into your code in a static method which is called during type initialization. If you use `-target 1.5` (or above) the constant pool gets a "class" entry. I don't know the details of how this is handled though.
Writing `MyClass.class` gives an object of the type `Class<MyClass>`. So, in the above code, if one is to use generics correctly, it should rather say: ``` Class<MyClass> c = MyClass.class; ``` or ``` Class<?> c = MyClass.class; ``` The `class` keyword will give the `Class` object that models the class. As mentioned by Jon Skeet, [Section 15.8.2: Class Literals](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.8.2) of [The Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html) says the following about the class literal: > A class literal is an expression > consisting of the name of a class, > interface, array, or primitive type, > or the pseudo-type void, followed by a > '.' and the token `class`. The type of a > class literal, `C.Class`, where `C` is the > name of a class, interface or array > type, is `Class<C>`. > > A class literal evaluates to the `Class` object for the named type (or for void) as defined > by the defining class loader of the class of the current instance.
what is MyClass.class?
[ "", "java", "" ]
Should I prefer binary serialization over ascii / text serialization if performance is an issue? Has anybody tested it on a large amount of data?
I used boost.serialization to store matrices and vectors representing lookup tables and some meta data (strings) with an in memory size of about 200MByte. IIRC for loading from disk into memory it took 3 minutes for the text archive vs. 4 seconds using the binary archive on WinXP.
Benchmarked it for a problem involving loading a large class containing lots (thousands) of nested archived classes. To change the format, use archive streams ``` boost::archive::binary_oarchive boost::archive::binary_iarchive ``` instead of ``` boost::archive::text_oarchive boost::archive::text_iarchive ``` The code for loading the (binary) archive looks like: ``` std::ifstream ifs("filename", std::ios::binary); boost::archive::binary_iarchive input_archive(ifs); Class* p_object; input_archive >> p_object; ``` The files and walltimes for an optimised gcc build of the above code snippet are: * ascii: **820MB** (100%), **32.2** seconds (100%). * binary: **620MB** (76%), **14.7** seconds (46%). This is from a solid state drive, without any stream compression. So the gain in speed is larger than the file size would suggest, and you get an additional bonus using binary.
Boost serialization performance: text vs. binary format
[ "", "c++", "boost-serialization", "" ]
I was working with java code that is supposedly using the Factory pattern, but I'm not completely convinced by the pattern. My code does this: ``` // the factory class SomeFactoryImpl { Set<SomeClass> getSomeListOfObjects(); } ``` And somewhere in the code: ``` { ... SomeFactory factory = new SomeFactoryImpl(); Set<SomeClass> list = factory.getSomeListOfObjects(); } ``` The point I'm pondering is, if factory classes don't have a static create() method, then one will need to *instantiate* a factory, which IMO should be just as complex as instantiating an object itself. I don't consider the argument that such a factory can return collections of objects to be produced is good enough. I feel there can be cleaner workarounds, if a factory instance needs to be created before actually creating objects from the factory. I feel that it is better if the create method a static method of the factory class. But I'm also sure that my opinion is not completely "correct". So can the SO community give examples where instantiating a Factory object is better than using static create methods? Also, I came across an answer to a similar question, which listed these links and the answer: so I need to know clearly the difference between [FactoryMethodPattern](http://c2.com/cgi/wiki?FactoryMethodPattern), [FactoryMethod](http://c2.com/cgi/wiki?FactoryMethod) and [CreationMethod](http://c2.com/cgi/wiki?CreationMethod) with code examples.
Using an instance of a factory shows the real benefits when combined with dependency injection. So in your example, instead of: ``` { ... SomeFactory factory = new SomeFactoryImpl(); Set<SomeClass> list = factory.getSomeListOfObjects(); } ``` You would have: ``` public ThisClass(SomeFactory someFactory) { this.factory = someFactory; } ``` then later... ``` { ... Set<SomeClass> list = factory.getSomeListOfObjects(); } ``` Some points: * In this circumstance your class does not have any reference to a concrete factory, and doesn't need to know about SomeFactoryImpl, it only knows about the abstracted SomeFactory. * In this case the factory instance that's being passed around can be configured on an instance basis, rather than a static basis, which tends to be (in my opinion) a nicer way to deal with it. If you can make the factory instance immutable then you can really cut down the multi-threading worries. * Having a static call to give you an instance isn't really much better, the reference to the class that creates it is still a concrete implementation detail, it's just higher up - though that may make it high enough to solve your problem. I know this only addresses a subset of your question...
I guess, a static method for the object creation is the most popular approach, but there are also some use-cases where first creating a factory instance makes sense. For example if you want to combine it with a registry (where multiple registries should be allowed to co-exist). Also if the factory relies on some dynamic context information (database connections, ...) it is in my opinion better to let a factory-instance handle this.
Factory pattern in java
[ "", "java", "design-patterns", "factory-pattern", "" ]
I'm trying to build a standard compliant website framework which serves XHTML 1.1 as application/xhtml+xml or HTML 4.01 as text/html depending on the browser support. Currently it just looks for "application/xhtml+xml" anywhere in the accept header, and uses that if it exists, but that's not flexible - text/html might have a higher score. Also, it will become more complex when other formats (WAP, SVG, XForms etc.) are added. So, does anyone know of a tried and tested piece of PHP code to select, from a string array given by the server, either the one best supported by the client or an ordered list based on the client score?
You can leverage [apache's mod\_negotiation module](http://httpd.apache.org/docs/2.2/content-negotiation.html). This way you can use the full range of negotiation capabilities the module offers, including *your own preferences* for the content type (e,g, "I really want to deliver application/xhtml+xml, unless the client very much prefers something else"). basic solution: * create a .htaccess file with ``` AddHandler type-map .var ``` as contents * create a file foo.var with ``` URI: foo URI: foo.php/html Content-type: text/html; qs=0.7 URI: foo.php/xhtml Content-type: application/xhtml+xml; qs=0.8 ``` as contents * create a file foo.php with ``` <?php echo 'selected type: ', substr($_SERVER['PATH_INFO'], 1); ``` as contents. * request <http://localhost/whatever/foo.var> For this to work you need mod\_negotiation enabled, the appropriate AllowOverride privileges for AddHandler and [AcceptPathInfo](http://httpd.apache.org/docs/2.0/mod/core.html#acceptpathinfo) not being disabled for $\_SERVER['PATH\_INFO']. With my Firefox sending "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" and the example .var map the result is "selected type: xhtml". You can use other "tweaks" to get rid of PATH\_INFO or the need to request foo*.var*, but the basic concept is: let mod\_negotiation redirect the request to your php script in a way that the script can "read" the selected content-type. > So, does anyone know of a tried and tested piece of PHP code to select It's not a pure php solution but I'd say mod\_negotiation has been tried and tested ;-)
Little snippet from my library: ``` function getBestSupportedMimeType($mimeTypes = null) { // Values will be stored in this array $AcceptTypes = Array (); // Accept header is case insensitive, and whitespace isn’t important $accept = strtolower(str_replace(' ', '', $_SERVER['HTTP_ACCEPT'])); // divide it into parts in the place of a "," $accept = explode(',', $accept); foreach ($accept as $a) { // the default quality is 1. $q = 1; // check if there is a different quality if (strpos($a, ';q=')) { // divide "mime/type;q=X" into two parts: "mime/type" i "X" list($a, $q) = explode(';q=', $a); } // mime-type $a is accepted with the quality $q // WARNING: $q == 0 means, that mime-type isn’t supported! $AcceptTypes[$a] = $q; } arsort($AcceptTypes); // if no parameter was passed, just return parsed data if (!$mimeTypes) return $AcceptTypes; $mimeTypes = array_map('strtolower', (array)$mimeTypes); // let’s check our supported types: foreach ($AcceptTypes as $mime => $q) { if ($q && in_array($mime, $mimeTypes)) return $mime; } // no mime-type found return null; } ``` example usage: ``` $mime = getBestSupportedMimeType(Array ('application/xhtml+xml', 'text/html')); ```
How to select content type from HTTP Accept header in PHP
[ "", "php", "http-headers", "" ]
I'm trying to retrofit/fix lots of legacy web code and unfortunately most of it is poorly formatted JavaScript. I'm looking for a batch/scriptable utility that can fix JavaScript that is missing simicolons at the end of executable statements. I've tried the beautify-cl.js script with Rhino but that does not does not add semicolons. In addition, I have tried [JSTidy](http://www.howtocreate.co.uk/tutorials/jsexamples/JSTidy.html) thinking I could modify it to be scriptable, but it strips all comments. Considering we have something like 2000-3000 files, any solution has to be scriptable. The following topics were referenced, however none of the solutions were sufficient for various reasons: [Javascript Beautifier](https://stackoverflow.com/questions/18985/javascript-beautifier) - Doesn't handle semicolon [Best source code formatter for Javascript?](https://stackoverflow.com/questions/351298/best-source-code-formatter-for-javascript) - Not scriptable Any ideas/solutions? Thanks in advance.
Obviously you'll need to do this if you want to minify the files on deployment. Missing semicolons are probably the #1 reason JS files don't minify properly, so I understand your motivation. Write a little Python (or whatever) script to run the file through jslint, then use the output from jslint to see which lines need semicolons, then spin through the js source and add them. I think you can be fairly fearless here, because JavaScript implicitly adds the semicolons anyway. --- Update: [This set of tools may be what you are looking for](http://jsutility.pjoneil.net/). The "format" tab offers missing semicolon insertion.
I've found a winning combination in [`js-beautify`](https://www.npmjs.com/package/js-beautify) and Google's [Closure Linter](https://developers.google.com/closure/utilities/docs/linter_howto): ``` # legacy.js is your poorly formatted JavaScript file, and will be modified in-place js-beautify -s 2 -n -b end-expand -x -r legacy.js && fixjsstyle legacy.js ``` Explanation of `js-beautify` options: * `-s 2`: indent with two spaces * `-n`: ensure newline at end of file * `-b end-expand`: puts `{` braces at the end of the line, but always gives `}` braces their own line. * `-x`: unescape `\xNN`-escaped characters in strings * `-r`: make changes in-place `fixjsstyle`, which is installed with the Closure Linter suite, makes changes in-place by default. This pipeline **retains comments** (!), indents everything (mostly) how I like, adds semicolons where appropriate, and even changes double quotes to single quotes where feasible. Both commands can be given a list of files (e.g., `**/*.js`), instead of just one. To install the required packages on Mac OS X: ``` npm install -g js-beautify brew install closure-linter ```
What is a good stand-alone JavaScript formatter for fixing missing semicolons?
[ "", "javascript", "formatting", "" ]
I am going to post some data from one website to another website. I need a way for the receiving website to be sure that the data was sent from the sending website and not sent by some other malicious user. I am using PHP4. How can I do this? Thanks!
**For a PHP-only solution:** If you can keep a secret (on both ends), then you can use a self-implemented variant (yes, a variant) of [Keyed-Hash Message Authentication Code (HMAC or KHMAC).](http://en.wikipedia.org/wiki/HMAC) The concept is that if you have the same secret on both ends, you can hash (message+secret) on the sending end, and hash (message+secret) on the recieving end. If the hashes match, then you have a valid message. The secret is the key (pun intended). Because without the secret, it is infeasible that an attacker could alter the message AND generate a new hash that will verify on the receiving end. **Here is some example PHP code:** ``` // On the sending end: define('SECRET', '12734981273912379128739128739127938794729327492'); $message = 'your-message'; $packet = $message . sha1($message . SECRET); // On the receiving end: define('SECRET', '12734981273912379128739128739127938794729327492'); $message = substr($packet, 0, -40); if(sha1($message . SECRET) != substr($packet, -40)) throw new Exception("Message Authentication failed!") else do_something_with($message); ``` If you wanted additional security from a hacker re-posting the same message, you could add a random request identifier to each request, and ensure that the same hash is NEVER accepted. **DISCLAIMER: this as with all security sensitive code should be peer reviewed and verified before being trusted with sensitive data. Do through research on the topic, or better yet, use an existing library that handles this type of verification+authentication.**
Just use two-way ssl. The client authenticates itself at the server with a ssl certificate not only the other way around. So the server knows it's the right client he gets the data form. The client knows he sends the data to the right server
securely send data from one site to another?
[ "", "php", "security", "php4", "data-transfer", "" ]
Did anyone handle such scenario in the code? User is typing something in the input area (say, rich text box). This causes multiple TextChanged events to fire. We want to capture only last changed event when user stops typing (i.e.: no changed events for 5 seconds). Does anyone have a clean C# snippet of doing that?
Make a `Timer` with an interval of five (or whatever) seconds, and, in your `TextChanged` event, stop the timer and start it again. Then, move your handler code to the timer's `Tick` event.
Ok, after using System.Threading.Timer as suggested by **SLaks**, I've got this extremely simple snippet: ``` public sealed class CallBuffer : IDisposable { private readonly TimeSpan _timeSpan; private readonly Timer _timer; public CallBuffer(Action call, TimeSpan timeSpan) { _timeSpan = timeSpan; _timer = new Timer(state => call()); } public void Buffer() { _timer.Change(_timeSpan, TimeSpan.FromMilliseconds(-1)); } void IDisposable.Dispose() { _timer.Dispose(); GC.SuppressFinalize(this); } } ``` Did I miss something here? One note, is that it does not care about the UI thread (caller should pass proper invocation) and this allows to separate this code from the views.
Stacking and delaying multiple UI change notifications
[ "", "c#", ".net", "user-interface", "asynchronous", "" ]
I'm trying to create a message validation program and would like to create easily modifiable rules that apply to certain message types. Due to the risk of the rules changing I've decided to define these validation rules external to the object code. I've created a basic interface that defines a rule and am wondering what the best way to store this simple data would be. I was leaning towards XML but it seems like it might be too heavy. Each rule would only need a very small set of data (i.e. type of rule, value, applicable mask, etc). Does anyone know of a good resource that I could look at that would perform a similar functionality. I'd rather not dig too deep into XML on a problem that seems to barely need a subset of the functionality I see in most of the examples I bump into. If I can find a concise example to examine I would be able to decide on whether or not to just go with a flat file. Thanks in advance for your input!
Personally, for small, easily modifiable XML, I find [TinyXML](http://www.grinninglizard.com/tinyxmldocs/tutorial0.html) to be an excellent library. You can make each class understand it's own format, so your object hierarchy is represented directly in the XML. However, if you don't think you need XML, you might want to go with a lighter storage like [yaml](http://code.google.com/p/yaml-cpp/). I find it is much easier to understand the underlying data, modify it and extend functionality. (Also, [boost::serialization](http://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/index.html) has an XML archive, but it isn't what I'd call easily modifiable)
The simplest is to use a flat file designed to be easy to parse using the C++ >> operator. Just simple tokens separated by whitespace.
XML Representation of C++ Objects
[ "", "c++", "xml", "" ]
In other words, what options do I have to allocate memory in JavaScript? I know you can allocate memory either globally, or inside function scope. Can I allocate memory dynamically? What does the `new` operator really mean? **Edit:** here's a specific example. How would you implement reading an integer value from the user - `n`, and then read `n` integers into an array?
you can't allocate memory. you can create objects. that's what `new` does. now, javascript is a queer creature: functions are also objects in javascript. So this mean that you can instantiate prettymuch everything using `new`. So, the `new` operator means that a new object is being created. Javascript also garbage-collects these variables, just like it happens in java. So if you know java, it should be easy for you to draw parallels. cheers, jrh PS: when you allocate objects, you really are allocating memory. Only, you are not doing that explicitly. You can allocate an array, and make it behave like a memory buffer, but that will degrade javascript performance drastically: javascript arrays are not in-memory buffers, they are also objects (like everything else).
JavaScript has garbage collection and handles this for you. However, you can help it by using the [`delete`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/delete_Operator) operator where appropriate. From the [Apple JavaScript Coding Guidelines](http://developer.apple.com/DOCUMENTATION/ScriptingAutomation/Conceptual/JSCodingGuide/OOJavaScript/OOJavaScript.html#//apple_ref/doc/uid/TP40006539-SW1): > Just as you used the new operator to > create an object, you should delete > objects when you are finished with > them, like this: > > `delete myObjectVariable;` > > The JavaScript runtime automatically > garbage collects objects when their > value is set to null. However, setting > an object to null doesn’t remove the > variable that references the object > from memory. Using delete ensures that > this memory is reclaimed in addition > to the memory used by the object > itself. (It is also easier to see > places where your allocations and > deallocations are unbalanced if you > explicitly call delete.) Steve
Does JavaScript have a memory heap?
[ "", "javascript", "" ]
I want to do some logging while executing my JUnit test. In JUnit 3.x it was always easy to obtain the name of the currently running test case, no matter how the test case was instantiated: ``` public void testFoo() throws Exception() { String testName = this.getName(); // [...] do some stuff } ``` In JUnit 4 things seem to be not so easy. Does anyone know a solution to this? Is there any option to reflect into the current Runner instance?
OK. I've found another approach [somewhere on the Internet](<http://www.nabble.com/What-happened-to-getName()--td23456371.html)>: ``` @RunWith(Interceptors.class) public class NameTest { @Interceptor public TestName name = new TestName(); @Test public void funnyName() { assertEquals("funnyName", name.getMethodName()); } } ```
In JUnit 4.7, you can also get the name of the currently executed test method. May be nice when logging. Taken from JUnit 4.7 Release Notes (read them [here at github](http://github.com/KentBeck/junit/raw/23ffc6baf5768057e366e183e53f4dfa86fbb005/doc/ReleaseNotes4.7.txt)) : ``` public class NameRuleTest { @Rule public TestName name = new TestName(); @Test public void testA() { assertEquals("testA", name.getMethodName()); } @Test public void testB() { assertEquals("testB", name.getMethodName()); } } ```
How to obtain test case name in JUnit 4 at runtime?
[ "", "java", "reflection", "junit", "" ]
In a servlet, is destroy() called before or after finalize()?
destroy() is called first. destroy() will be called by the servlet-container at the time the servlet will be shut-down. finalize() is called by the JVM before the garbage-collector claims the objects (and isn't guaranteed to be called at all).
Also, finalize() may or may not be called. Don't ever rely on that happening.
In servlet destroy() is called first or finalize()?
[ "", "java", "servlets", "" ]
I know this issue has been touched on here but I have not found a viable solution for my situation yet, so I'd like to but the brain trust back to work and see what can be done. I have a textarea in a form that needs to detect when something is pasted into it, and clean out any hidden HTML & quotation marks. The content of this form is getting emailed to a 3rd party system which is particularly bitchy, so sometimes even encoding it to the html entity characters isn't going to be a safe bet. I unfortunately cannot use something like FCKEditor, TinyMCE, etc, it's gotta stay a regular textarea in this instance. I have attempted to dissect FCKEditor's paste from word function but have not had luck tracking it down. I am however able to use the jQuery library if need be, but haven't found a jQuery plugin for this just yet. I am specifically looking for information geared towards cleaning the information pasted in, not how to monitor the element for change of content. Any constructive help would be greatly appreciated.
I am looking at David Archer's answer and he pretty much answers it. I have used in the past a solution similar to his: ``` $("textarea").change( function() { // convert any opening and closing braces to their HTML encoded equivalent. var strClean = $(this).val().replace(/</gi, '&lt;').replace(/>/gi, '&gt;'); // Remove any double and single quotation marks. strClean = strClean.replace(/"/gi, '').replace(/'/gi, ''); // put the data back in. $(this).val(strClean); }); ``` If you are looking for a way to completely REMOVE HTML tags ``` $("textarea").change( function() { // Completely strips tags. Taken from Prototype library. var strClean = $(this).val().replace(/<\/?[^>]+>/gi, ''); // Remove any double and single quotation marks. strClean = strClean.replace(/"/gi, '').replace(/'/gi, ''); // put the data back in. $(this).val(strClean); }); ```
You could check out [Word HTML Cleaner](http://ethilien.net/websoft/wordcleaner/cleaner.htm) by Connor McKay. It is a pretty strong cleaner, in that it removes a lot of stuff that you might want to keep, but if that's not a problem it looks pretty decent.
Need Pure/jQuery Javascript Solution For Cleaning Word HTML From Text Area
[ "", "javascript", "jquery", "html", "ms-word", "" ]
I am having a bizare problem where I have a script that works elsewhere on the site but refuses to work for me now. The problem is exclusive to IE, it works fine in Mozilla. Below is the form: ``` <form class="element_form" action="general_image.php" method="post"> <?php generate_input('hidden', '', 'id', $id);?> <input type="image" src="../images/delete.gif" name="action" value="delete" class="button" /> <input type="image" src="../images/tick.gif" name="action" value="active_switch" class="button" /> </form> ``` Here is the code that is supposed to work: ``` <?php include('header.php'); $db->connect(); $table = 'general_image'; $page = 'general'; $region = $_SESSION['region']; $action = $secure->secure_string($_REQUEST['action']); $id = $secure->secure_string($_POST['id']); $max_active = 1; if($action == 'active_switch' || $action == 'delete'){ $response = array(); $response['action'] = $action; $response['id'] = $id; if($action == 'active_switch'){ $query = 'SELECT * FROM general WHERE region = "' . $region . '"'; $result = mysql_query($query); if(!$result) { $utility->fail($action, 'query error: ' . $query); }else{ $row = mysql_fetch_assoc($result); $already_active = false; $active = ''; if($id == $row['fifi']){ $already_active = true; } $active .= $row['fifi']; $response['results'] = $active; if(!$already_active){ $update = ''; $active = ''; $update .= 'fifi="' . $id . '"'; $active .= $id; $query = 'UPDATE general SET ' . $update . ' WHERE region = "' . $region . '"'; $response['results'] = $active; }else{ $utility->redirect($page . '.php'); } } }elseif($action == 'delete') { $query = "DELETE FROM $table WHERE id=" . $id; } echo $query . "hello"; if(!mysql_query($query)) { $utility->fail($action, 'query error: ' . $query); } ``` If someone could tell me what I'm doing wrong that would be great. Thanks EDIT ``` $action = $secure->secure_string does the following: function secure_string($string) { return (strip_tags(addslashes(mysql_real_escape_string(stripslashes($string))))); } ```
i have found that sometimes it is better to have a hidden field for action then a submit button or image. if someone press RETURN or ENTER to submit the form which action will be returned ?
For example, the button image has: `name="submitP"` and `value="Print"` In the FORM post PHP, I used so: ``` if(isset($_REQUEST['submitP']) || isset($_REQUEST['submitP_x'])) { something.... } ``` If this second clause is to treat post IE
$_REQUEST information not being passed through in IE
[ "", "php", "" ]
I am planning to build a web application and am going to host it. Since hosting cost less for php and it being similar to .net i am planning to go for php. I am basically a .net guy. But have no issues in learning php if it is similar to .net. Please give in your opinoins in doing so. Also please tell me if php supports asynchronous calls like the AJAX in asp.net. Give me your comments.
AJAX stands for **Asynchronous Javascript And XML**. PHP isn't mentioned anywhere, and doesn't need to be asynchronous to facilitate this. The process is that a Javascript function calls a synchronous PHP page that returns results and the users browser is updated. The asycnhronous bit is that the javascript function doesn't block when it makes the call, and a callback function is fired when the PHP page returns. I've implemented AJAX in PHP with no special programming above normal PHP HTML rendering and Javascript calls.
PHP has no built in support for asynchronous calls. You can make pseudo-asynchronous calls using [curl](https://www.php.net/curl).
Does PHP support asynchronous calls?
[ "", "php", "" ]
I want to create a webservice that allows users to enter the longitude and latitude for a particular building. Buildings will belong to a broader category called a Region. If a specific building does not exist in a region the user could add the longitude and latitude data through the webservice. Similarly if a user finds data to be inaccurate, they could update it. This webservice would not need to have a web front-end only a RESTful API that would only be accessible to my application(s). I want the webservice to be able to accept new and updated data (as described above) and also print out relevant data (in xml format) based on the appropriate API calls. I need to ensure that this data would be secure - i.e. nobody would be able to gain access to the data i have accumulated. What is the best way to do this? I have familiar with client side Java and not much server side technology (not familiar with server-side Java, rails, django, etc...). What language/frameworks should i use that would accomplish my needs with the shallowest learning curve?
If you have never programmed server-side code you will be facing a pretty steep learning curve, I'm afraid. If you are comfortable with Java then the Restlet framework mentioned by another commenter is a good choice. It is easy to use, includes both client and server tools, and has pretty decent documentation. The video screencasts are very good. Another option is Ruby on Rails. I am currently implementing something very similar to what you are planning and Rails has worked extremely well. Rails has built-in support for XML output through both the ActiveRecord class and XML Builder templates. I used Atom Authentication (<http://www.xml.com/pub/a/2003/12/17/dive.html>) between the client and server and it is working beautifully. There is a learning curve for both Ruby and Rails but the power of the framework makes it worth it. I am partial to the Ruby and Rails books at The Pragmatic Programmer but O'Reilly has some good ones, too.
I've used the [Restlet](http://www.restlet.org/) framework to deploy web services that are password protected. It supports basic authentification and several others out of the box. You can also set up your services behind an https "server connector". Another approach is to run your application in a Java EE application server which supports JSR 196 (eg, Glassfish or JBoss). You would then use the server's facilities to establish the authentication. Here is the [Glassfish security page](https://glassfish.dev.java.net/javaee5/security/).
Create a webservice that keeps data secure?
[ "", "java", "ruby-on-rails", "web-services", "web-applications", "server-side", "" ]
I am using winforms, and I update a text box once in a while (showing messages). however, when the text reaches the end of the box it produces scrollbars and I don't know how to scroll down to the bottom. The only thing I see is ScrollToCaret, but Caret is at the beginning of the text. What is the command to scroll?
You can do this by making use of a function called ScrollToCaret. You need to first set the caret position to the end of the text box, then you can scroll to it. Here's how to do it: ``` //move the caret to the end of the text textBox.SelectionStart = textBox.TextLength; //scroll to the caret textBox.ScrollToCaret(); ```
This is a bit of an old question, but none of the suggested answers worked for me (ScrollToCaret() only works when the TextBox has focus). So in case any more should be searching for this at some point, I thought I'd share what I found to be the solution: ``` public class Utils { [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int SendMessage(IntPtr hWnd, int wMsg, IntPtr wParam, IntPtr lParam); private const int WM_VSCROLL = 0x115; private const int SB_BOTTOM = 7; /// <summary> /// Scrolls the vertical scroll bar of a multi-line text box to the bottom. /// </summary> /// <param name="tb">The text box to scroll</param> public static void ScrollToBottom(TextBox tb) { SendMessage(tb.Handle, WM_VSCROLL, (IntPtr)SB_BOTTOM, IntPtr.Zero); } } ``` Credit for the solution should go to this post at bytes.com: <http://bytes.com/topic/c-sharp/answers/248500-scroll-bottom-textbox#post1005377>
How to scroll down in a textbox by code in C#
[ "", "c#", "winforms", "textbox", "scroll", "" ]
I am a .NET developer. I have no experience on Python. Which platform is more scalable? Which platform is more suitable for large-size high-traffic web sites? If you have any experience about scalability on these platforms, please inform us. Thank you.
Much as I love Python (and, that's a LOT!-), if you're highly skilled at C# and, as you say, "have no experience on Python", *your* code will be more scalable and suitable (for the next several months, at least) if you stick with what you know best. For a hypothetical developer extremely skilled at both platforms, scalability would essentially be a wash, and Python would enhance that developer's productivity; but getting really good at any technology takes some months of practice, it doesn't "just happen" magically. So, unless you're trying to broaden your range of skills and job opportunities, or enhance your productivity, but rather are specifically, strictly focused on the scalability of the web apps you're coding right now, I have, in good conscience, to recommend you stick with C#. You should also try IronPython (and get the great "IronPython in Action" book from Mannings -- bias alert, I'm friends with the author and was a tech reviewer of that book;-) for all sorts of non-production supporting code, to get a taste of it and the incredible productivity boost it can give you... but, to deliver best value to your clients or employers, stick with what you REALLY master, C#, for *any* scalability-critical work you deliver to them!
Almost all the well known frameworks and languages can scale. It doesn't really matter which one you use. Its about how well you structure the code that matters most. On a personal level it is always good to know more than one language. But, you can create perfectly scalable Python, PHP, .NET applications. The quality of the code is the first place scalability will fall down not the language.
Python/Django or C#/ASP.NET for web development?
[ "", "asp.net", "python", "django", "scalability", "" ]
After seeing joomla's way of having arrows to order items (articles, menu entries and the likes), I was wondering what is considered best practice to shift elements inside a table. You obviously must have a field inside a table that hold numbers, letters, or anything you may want to use to define an order, then you have to change this order, I can't think on any elegant way to achieve this, can you help me? Thank you very much EDIT: Reading the answer I realize that i may not have been clear, I don't need to order items based on standard parameters (like I don't know, date, id, etc). I need to decide an order myself. Like this: ``` id - name - order 1 one 2 2 two 1 3 three 3 ``` I want to know the correct way to change the order of the items (like if I want to have one go into the first position I would need to change the order value of two to '2' and the value of one to '1'. Hope I explained myself correctly
Use big numbers for ordering: ``` id - name - order 1 one 200000 2 two 100000 3 three 300000 ``` When you need to move 3 between 2 and 1 just change its order value in the middle between 100000 and 200000: 150000. Eventualy you'll need to insert element between two adjacent numbers. If that happens just rewrite order column for all rows first, using 100000 step again. Choose your step carefully, that you'll not overflow your type, and that you'll not have to rewrite the whole table too often.
Looing at the EDIT that you have put in, I understand what you are trying. I have implemented a solution in a similar way as you have mentioned, using and Order column. And then using the Order column in the ORDER BY clause. One best practise tip would be to use numbers like 10, 20, 30 etc instead of 1, 2 ,3. This gave me the flexibility to insert a new Order value row between say, 10 and 20, like 15, for something new that came along at a later point in time.
Ordering items inside a table based on user preferences, what is the correct way?
[ "", "php", "mysql", "" ]
I would like to index a list with another list like this ``` L = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] Idx = [0, 3, 7] T = L[ Idx ] ``` and T should end up being a list containing ['a', 'd', 'h']. Is there a better way than ``` T = [] for i in Idx: T.append(L[i]) print T # Gives result ['a', 'd', 'h'] ```
``` T = [L[i] for i in Idx] ```
If you are using numpy, you can perform extended slicing like that: ``` >>> import numpy >>> a=numpy.array(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) >>> Idx = [0, 3, 7] >>> a[Idx] array(['a', 'd', 'h'], dtype='|S1') ``` ...and is probably much faster (if performance is enough of a concern to to bother with the numpy import)
In Python, how do I index a list with another list?
[ "", "python", "list", "indexing", "" ]
I am having a hard time figuring out how to show an Image (or ImageIcon) in a Java applet. The following is my code. The picture (test.bmp) does exist and is on the D drive but when I run this I get the applet window with nothing in it. Can somebody tell me what I am missing to make the ImageIcon show? ``` public class Form1 extends JApplet { ImageIcon i; public void init(){ i = new ImageIcon("D:\test.bmp"); } public void paint(Graphics g){ i.paintIcon(this, g, 0, 0); } } ``` Thanks, Steve.
Referencing your image through an absolute local file path might not work when you run your applet from a server. Use the ImageIcon (URL location) constructor and Have the URL point to the image resource on the server. Use the JApplet.getCodeBase() to determine where your applet originates and append the file name to it. ``` public class Form1 extends JApplet { Image i; public void init() { try { i = ImageIO.read(new URL(getCodeBase(), "test.bmp")); } catch (MalformedURLException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } public void paint(Graphics g) { g.drawImage(i, 0, 0, null); } } ``` **Edit:** ImageIO supports BMP and the changed sample works for me. **Edit 2:** If it still doesn't display the image, try "../test.bmp" because when you run an applet from lets say Eclipse it has the `bin` directory as the codebase. **Edit 3:** If you put your test.bmp into the jar or on the classpath, you can load it using the same way but replacing ``` new URL(getCodeBase(), "test.bmp") ``` with ``` Form1.class.getResource("test.bmp") ```
To start with, it's probably a good idea to correctly escape your \ as \\. Edited to add: You probably want to learn your language's (or library's) equivalent of Path.combine (or File.join) which is a method for taking a list of file path parts and combining them with the platform-appropriate path separator. Or you can write it yourself quickly in Java, as the path separator is documented in [File.pathSeparator](http://java.sun.com/j2se/1.4.2/docs/api/java/io/File.html). (Off the top of my head, I didn't know that forward slash always works in ImageIcon, but note the other response that indicates this). Additionally, make sure you are loading a supported file type, such as .png, .gif or .jpg. BMP may be supported in JDK 1.5 Also, if you are running in an Applet context, you may not have access to the path in question due to sandboxing rules. In that case, make it available in the same path as to the HTML file hosting the applet (possibly in the Jar's path, if memory serves me), and use a relative path.
How can I display a bitmap image in a Java applet?
[ "", "java", "image", "swing", "applet", "" ]
I have a string with quotes around the path as follows: "C:\Program Files (x86)\Windows Media Player\wmplayer.exe" arg1 arg2 If I use `Text.Split(new Char[] { ' ' }, 2);` then I get the first space. How to get the path and args ?
Try splitting on the double quotes (Text.Split(new Char[] { '/"' }, 3);) then taking the last string in that array and splitting again on the space. ``` string[] pathAndArgs = Text.Split(new Char[] { '/"' }, 3); string[] args = pathAndArgs[2].Split(new Char[] { ' ' }, 2); ``` I may have a syntax error in there, but you get what I mean.
Use a regular expression like: `("".*?"")|(\S+)` So your code would be something like: ``` Regex r = new Regex(@"("".*?"")|(\S+)"); MatchCollection mc = r.Matches(input); for (int i = 0; i < mc.Count; i++) { Console.WriteLine(mc[i].Value); } ```
C# string handling how get path and args from a string
[ "", "c#", "string", "path", "args", "" ]
I am using java.util.Zip and java.util.ZipEntry to successfully extra a zip file's contents to disk. I would like to maintain the file permissions set when extracting on a \*nix file-system. Can anyone point me to the "correct" way to do this?
Essentially, you can't STORE (unix) file permissions in Zip/Jar files, so you can't preserve them when extracting your jar (they were lost when the jar was created to begin with). See this question: [creating a jar file - preserving file permissions](https://stackoverflow.com/questions/28178375/creating-a-jar-file-preserving-file-permissions) If you need the file permissions preserved in the archive and restored when extracting, you need to consider the alternative .tar or .tar.gz / .tar.bz2 format, which is also natively supported by most Java build tools (Ant, Gradle, Maven...)
I think it is actually impossible to keep the permissions correctly. Permissions are very OS specific: while POSIX file permissions allow the user to set whether you can read, write or execute a file for the file owner, the group and others, the NTFS file system has a similar system but the concept for an execute permission is inexistant. And the early FAT/FAT32 file syste, do not have file permissions at all (a part from the read-only attribute). Being cross-platform, it would be difficult for java to set the permission properly on the newly created (unzipped) files depending on the underlying OS.... That said, Java 6 has a new [java.io.File class](http://java.sun.com/javase/6/docs/api/java/io/File.html) that allows you to set permissions (with methods like setExecutable(), setReadable(), etc...) These helped me a lot, especially the setExecutable() which was my main concerned when having to unzip executables on a Linux file system. And you don't have to bother about figuring out what OS you are running on as the method will simply do nothing if running under Windows or other systems without the concept of executable files.
Maintain file permissions when extracting from a zip file using JDK 5 api
[ "", "java", "zip", "io", "" ]
My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad). Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration): ``` Row | Name | Year | Priority ------------------------------------ 1 | Cat | 1998 | 1 2 | Fish | 1998 | 2 3 | Dog | 1999 | 1 4 | Aardvark | 2000 | 1 5 | Wallaby | 2000 | 1 6 | Zebra | 2001 | 3 ``` Notes: 1. Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory. 2. Names are unique. Things I do with the data: 1. Look-up a row based on either ID (iteration) or name (direct access). 2. Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc. 3. I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc. I know this "cries" for SQL... I'm trying to figure out what's the best choice for data structure. Following are several choices I see: List of row lists: ``` a = [] a.append( [1, "Cat", 1998, 1] ) a.append( [2, "Fish", 1998, 2] ) a.append( [3, "Dog", 1999, 1] ) ... ``` List of column lists (there will obviously be an API for add\_row etc): ``` a = [] a.append( [1, 2, 3, 4, 5, 6] ) a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] ) a.append( [1998, 1998, 1999, 2000, 2000, 2001] ) a.append( [1, 2, 1, 1, 1, 3] ) ``` Dictionary of columns lists (constants can be created to replace the string keys): ``` a = {} a['ID'] = [1, 2, 3, 4, 5, 6] a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001] a['Priority'] = [1, 2, 1, 1, 1, 3] ``` Dictionary with keys being tuples of (Row, Field): ``` Create constants to avoid string searching NAME=1 YEAR=2 PRIORITY=3 a={} a[(1, NAME)] = "Cat" a[(1, YEAR)] = 1998 a[(1, PRIORITY)] = 1 a[(2, NAME)] = "Fish" a[(2, YEAR)] = 1998 a[(2, PRIORITY)] = 2 ... ``` And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). What's the recommended approach? EDIT: To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.
Having a "table" in memory that needs lookups, sorting, and arbitrary aggregation really does call out for SQL. You said you tried SQLite, but did you realize that SQLite can use an in-memory-only database? ``` connection = sqlite3.connect(':memory:') ``` Then you can create/drop/query/update tables in memory with all the functionality of SQLite and no files left over when you're done. And as of Python 2.5, `sqlite3` is in the standard library, so it's not really "overkill" IMO. Here is a sample of how one might create and populate the database: ``` import csv import sqlite3 db = sqlite3.connect(':memory:') def init_db(cur): cur.execute('''CREATE TABLE foo ( Row INTEGER, Name TEXT, Year INTEGER, Priority INTEGER)''') def populate_db(cur, csv_fp): rdr = csv.reader(csv_fp) cur.executemany(''' INSERT INTO foo (Row, Name, Year, Priority) VALUES (?,?,?,?)''', rdr) cur = db.cursor() init_db(cur) populate_db(cur, open('my_csv_input_file.csv')) db.commit() ``` If you'd really prefer not to use SQL, you should probably use a list of dictionaries: ``` lod = [ ] # "list of dicts" def populate_lod(lod, csv_fp): rdr = csv.DictReader(csv_fp, ['Row', 'Name', 'Year', 'Priority']) lod.extend(rdr) def query_lod(lod, filter=None, sort_keys=None): if filter is not None: lod = (r for r in lod if filter(r)) if sort_keys is not None: lod = sorted(lod, key=lambda r:[r[k] for k in sort_keys]) else: lod = list(lod) return lod def lookup_lod(lod, **kw): for row in lod: for k,v in kw.iteritems(): if row[k] != str(v): break else: return row return None ``` Testing then yields: ``` >>> lod = [] >>> populate_lod(lod, csv_fp) >>> >>> pprint(lookup_lod(lod, Row=1)) {'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'} >>> pprint(lookup_lod(lod, Name='Aardvark')) {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'} >>> pprint(query_lod(lod, sort_keys=('Priority', 'Year'))) [{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'}, {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'}, {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'}, {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'}, {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'}, {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}] >>> pprint(query_lod(lod, sort_keys=('Year', 'Priority'))) [{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'}, {'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'}, {'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'}, {'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'}, {'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'}, {'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}] >>> print len(query_lod(lod, lambda r:1997 <= int(r['Year']) <= 2002)) 6 >>> print len(query_lod(lod, lambda r:int(r['Year'])==1998 and int(r['Priority']) > 2)) 0 ``` Personally I like the SQLite version better since it preserves your types better (without extra conversion code in Python) and easily grows to accommodate future requirements. But then again, I'm quite comfortable with SQL, so YMMV.
A very old question I know but... A pandas DataFrame seems to be the ideal option here. <http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html> From the blurb > Two-dimensional size-mutable, potentially heterogeneous tabular data > structure with labeled axes (rows and columns). Arithmetic operations > align on both row and column labels. Can be thought of as a dict-like > container for Series objects. The primary pandas data structure <http://pandas.pydata.org/>
Data structure for maintaining tabular data in memory?
[ "", "python", "data-structures", "" ]
Is there any way of specifying the current directory in a java properties file? i.e. something like: ``` fileLocation={currentDir}/fileName.txt ```
No. Properties files do not have any builtin macro facilities. You can programmatically get the currect directory of the user running the Java app through the [user.dir system property](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#getProperties()).
I'm pretty sure it just defaults to the current directory, if not you can do ``` fileLocation="./fileName.txt" ```
Current directory in java properties file
[ "", "java", "properties", "path", "" ]
Please can someone convert the following to ternary for me? ``` if ($idd == 1521) { return "Home<br /><img src=\"images/b-value.gif\" /><br />Best for Value"; } else if ($idd == 1595) { return "Home<br /><img src=\"images/b-dload.gif\"/><br />Best for Downloads"; } else if ($idd == 1522) { return "Business<br /><img src=\"images/b-value.gif\" /><br />Best for Value"; } else if ($idd == 1596) { return "Business<br /><img src=\"images/b-dload.gif\"/><br />Best for Downloads"; } else if ($idd == 1523) { return "Voice Product<br /><img src=\"images/vstream200.gif\" /><br />4 Guaranteed Calls"; } else if ($idd == 1524) { return "Voice Product<br /><img src=\"images/vstream350.gif\" /><br />7 Guaranteed Calls"; } else if ($idd == 1525) { return "Voice Product<br /><img src=\"images/vstream700.gif\"/><br />14 Guaranteed Calls"; } else return ""; ``` Thanks.
Ternary operator does not appear to be appropriate in your situation. Why don't you use simple **mapping**? ``` $map = array( 1521 => array('Home', 'b-value.gif', 'Best for Value'), 1595 => array('Home', 'b-dload.gif', 'Best for Downloads'), 1522 => array('Business', 'b-value.gif', 'Best for Value'), // and so on ); if (array_key_exists($idd, $map)) { $item = $map[$idd]; echo "{$item[0]} <br/> <img src=\"{$item[1]}\"/> <br/> {$item[2]}"; } ``` Alternatively, you can pull the map from file or database.
As nobody else seems willing to just do what you asked, here's the ternary: ``` return ($idd == 1521 ? "Home<br /><img src=\"images/b-value.gif\" /><br />Best for Value" : ($idd == 1595 ? "Home<br /><img src=\"images/b-dload.gif\"/><br />Best for Downloads" : ($idd == 1522 ? "Business<br /><img src=\"images/b-value.gif\" /><br />Best for Value" : ($idd == 1596 ? "Business<br /><img src=\"images/b-dload.gif\"/><br />Best for Downloads" : ($idd == 1523 ? "Voice Product<br /><img src=\"images/vstream200.gif\" /><br />4 Guaranteed Calls" : ($idd == 1524 ? "Voice Product<br /><img src=\"images/vstream350.gif\" /><br />7 Guaranteed Calls" : ($idd == 1525 ? "Voice Product<br /><img src=\"images/vstream700.gif\"/><br />14 Guaranteed Calls" : "" ) ) ) ) ) ) ); ``` But, like everyone else, I suggest you either use a switch or array mapping.
Convert If Else to Ternary
[ "", "php", "" ]
My JSON response looks like: ``` {rc: "200", test: "", user: "<div class='sub1'> <div class='avatar'> <a href='/blah'>blah</a><br /> <strong>0</strong> </div> <div class='sl'> <p> you droppped the ball this time </p> </div> <div class='clear'> </div> </div>"} ``` **Update** I updated my code to put quotes on the key values, still doesn't work: ``` {"rc": "200", "m" : "", "o": "<div class='s1'> <div class='avatar'> <a href='\/asdf'>asdf<\/a><br \/> <strong>0<\/strong> <\/div> <div class='sl'> <p> 444444444 <\/p> <\/div> <div class='clear'> <\/div> <\/div>"} ```
I used [jsonlint](http://www.jsonlint.com/) to validate your latest example, and the line breaks are what it flagged. When they were removed, it validated. ``` { "rc": "200", "m" : "", "o": "<div class='s1'><div class='avatar'><a href='\/asdf'>asdf<\/a><br \/><strong>0<\/strong> <\/div> <div class='sl'><p>444444444<\/p><\/div><div class='clear'><\/div><\/div>" } ```
In your example, you won't have to escape anything. But, if the HTML comes with double quotes, you'll have to escape them, obviously.
What do I need to escape in my HTML (JSON response)
[ "", "javascript", "asp.net-mvc", "json", "" ]
I'd like to build a base (abstract) class (let's call it `type::base`) with some common funcionality and a fluent interface, the problem I'm facing is the return type of all those methods ``` class base { public: base(); virtual ~base(); base& with_foo(); base& with_bar(); protected: // whatever... }; ``` Now I could make subtypes, e.g.: ``` class my_type : public base { public: myType(); // more methods... }; ``` The problem comes when using those subtypes like this: ``` my_type build_my_type() { return my_type().with_foo().with_bar(); } ``` This won't compile because we're returning base instead of my\_type. I know that I could just: ``` my_type build_my_type() { my_type ret; ret.with_foo().with_bar(); return ret; } ``` But I was thinking how can I implement it, and I've not found any valid ideas, some suggestion?
This problem of "losing the type" can be solved with templates - but it's rather complicated. Eg. ``` class Pizza { string topping; public: virtual double price() const; }; template <class T, class Base> class FluentPizza : public Base { T* withAnchovies() { ... some implementation ... }; }; class RectPizza : public FluentPizza<RectPizza, Pizza> { double price() const { return length*width; :) } }; class SquarePizza : public FluentPizza<SquarePizza, RectPizza> { ... something else ... }; ``` You can then write ``` SquarePizza* p=(new SquarePizza)->withAnchovies(); ``` The pattern is that instead of ``` class T : public B ``` you write ``` class T : public Fluent<T, B> ``` Another approach could be not to use fluent interface on the objects, but on pointers instead: ``` class Pizza { ... }; class RectPizza { ... }; class SquarePizza { ... whatever you might imagine ... }; template <class T> class FluentPizzaPtr { T* pizza; public: FluentPizzaPtr withAnchovies() { pizza->addAnchovies(); // a nonfluent method return *this; } }; ``` Use like this: ``` FluentPizzaPtr<SquarePizza> squarePizzaFactory() { ... } FluentPizzaPtr<SquarePizza> myPizza=squarePizzaFactory().withAnchovies(); ```
You should be returning references/pointers, and you should not need to keep the type information. ``` class base { public: base(); virtual ~base(); base &with_foo(); base &with_bar(); protected: // whatever... }; class my_type : public base { public: my_type(); // more methods... }; base *build_my_type() { return &new my_type()->with_foo().with_bar(); } ``` You already have a virtual destructor. Presumably you have other virtual functions. Access everything through the base type and the virtual functions declared there.
Fluent interfaces and inheritance in C++
[ "", "c++", "inheritance", "fluent-interface", "" ]
Say I have these two strings: "Some Text here" and "some text Here" And I have a collection that contains the words that I would like to match against the text in the strings. "Some", "Text", "Here" If one of the words match a certain word in the string (regardless if it is upper- or lower-case) I would like to take the original word from the string and add some HTML markup around it like this `<dfn title="Definition of word">Original word</dfn>`. I was playing around with the string.Replace() method but not sure how to get it to match regardless of case and how to still keep the original word intact (so that I don't replace "word" with `<dfn title="">Word</dfn` or vice versa).
Indeed, the `string.Replace` method is not versatile enough for your requirements in this case. Lower-level text manipulation should do the job. The alternative is of course regex, but the algorithm I present here is going to be the most efficient method, and I thought it would be helpful to write it anyway to see how you can a lot of text manipulation *without* regex for a change. Here's the function. **Update:** 1. Now works with a `Dictionary<string, string>` instead of a `string[]`, which enables a definition to be passed to the function along with the word. 2. Now works with arbitrary ordering of definitions dictionary. ... ``` public static string HtmlReplace(string value, Dictionary<string, string> definitions, Func<string, string, string> htmlWrapper) { var sb = new StringBuilder(value.Length); int index = -1; int lastEndIndex = 0; KeyValuePair<string, string> def; while ((index = IndexOf(value, definitions, lastEndIndex, StringComparison.InvariantCultureIgnoreCase, out def)) != -1) { sb.Append(value.Substring(lastEndIndex, index - lastEndIndex)); sb.Append(htmlWrapper(def.Key, def.Value)); lastEndIndex = index + def.Key.Length; } sb.Append(value.Substring(lastEndIndex, value.Length - lastEndIndex)); return sb.ToString(); } private static int IndexOf(string text, Dictionary<string, string> values, int startIndex, StringComparison comparisonType, out KeyValuePair<string, string> foundEntry) { var minEntry = default(KeyValuePair<string, string>); int minIndex = -1; int index; foreach (var entry in values) { if (((index = text.IndexOf(entry.Key, startIndex, comparisonType)) < minIndex && index != -1) || minIndex == -1) { minIndex = index; minEntry = entry; } } foundEntry = minEntry; return minIndex; } ``` And a small test program. (Notice the use of a lambda expression for convenience.) ``` static void Main(string[] args) { var str = "Definition foo; Definition bar; Definition baz"; var definitions = new Dictionary<string, string>(); definitions.Add("foo", "Definition 1"); definitions.Add("bar", "Definition 2"); definitions.Add("baz", "Definition 3"); var output = HtmlReplace(str, definitions, (word, definition) => string.Format("<dfn title=\"{1}\">{0}</dfn>", word, definition)); } ``` Output text: > Definition <dfn title="Definition 1">foo</dfn>; Definition <dfn title="Definition 2">bar</dfn>; Definition <dfn title="Definition 3">baz</dfn> Hope that helps.
You might use a regular expression: ``` class Program { static string ReplaceWord(Match m) { return string.Format("<dfn>{0}</dfn>",m.Value); } static void Main(string[] args) { Regex r = new Regex("some|text|here", RegexOptions.IgnoreCase); string input = "Some random text."; string replaced = r.Replace(input, ReplaceWord); Console.WriteLine(replaced); } } ``` `RegexOptions.IgnoreCase` is used to match words in the list regardless of their case. The `ReplaceWord` function returns the matched string (correctly cased) surrounded by the opening and closing tag (note that you still might need to escape the inner string).
Inject HTML markup around certain words in a string
[ "", "c#", "html", "regex", "" ]
If I had two divs, both with id="myDiv", would `$("#myDiv").fadeOut();` fade both divs out? Or would it fade only the first/second? Or none at all? How do I change which one it fades out? **Note:** I know duplicate id's is against standards but I'm using the fancybox modal popup and it duplicates specified content on your page for the content of the popup. If anyone knows a way around this (maybe I'm using fancybox wrong) please let me know.
jQuery matches exactly one element when querying for an ID. An array of at most one `Element` object will be returned by `$("#foo").get()`. See the [jQuery documentation](http://docs.jquery.com/Selectors/id) for more information, or try it yourself. ``` $(function() { alert($("#foo").length); }); ```
Element IDs are supposed to be unique. Having multiple DIVs of the same ID would be incorrect and unpredictable, and defies the purpose of the ID. If you did this: ``` $('.myDiv').fadeOut(); ``` That would fade both of them out, assuming you give them a class of myDiv and unique IDs (or none at all).
Do duplicate ID values screw up jQuery selectors?
[ "", "javascript", "jquery", "html", "" ]
I have an ASP.NET `GridView` control with two `asp:CommandField` columns that are both using the Select command to perform different tasks. How do I distinguish which column was selected in the `OnRowCommand` event when both return "Select" when I check the `CommandName` property of the `GridViewCommandEventArgs` object? Here is my source code: ASPX page: ``` <asp:GridView ID="MyGridView" runat="server" AutoGenerateColumns="false" OnRowCommand="MyGridView_OnRowCommand"> <Columns> <asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="Click Me!" /> <asp:CommandField ButtonType="Link" ShowSelectButton="true" SelectText="No Click Me!" /> </Columns> </asp:GridView> ``` Code behind: ``` protected void MyGridView_OnRowCommand(object sender, GridViewCommandEventArgs e) { string x = e.CommandName //returns "Select" for both asp:CommandField columns } ```
Use a button column instead that way you can specify the specific command names and work with it from there ``` <asp:ButtonField ButtonType="Link" Text="Click Me" CommandName="MyCommand1" /> <asp:ButtonField ButtonType="Link" Text="No Click Me" CommandName="MyCommand2" /> ``` Then you can take action based on e.CommandName
Use the [GridViewCommandEventArgs](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridviewcommandeventargs.aspx).CommandArgument property !
GridView control with two asp:Command columns using the same command
[ "", "c#", "asp.net", "gridview", "" ]
I like to change the UI of a JComboBox from the default metal look to some custom UI, see attached image. [![Sample](https://i.stack.imgur.com/9oVZi.png)](https://i.stack.imgur.com/9oVZi.png) I have tried changing all the UIDefaults for the JComboBox but to no success. How does one achieve this? jdk1.4.2
You have to write your own ComboBoxUI class. I suggest to look at either Synth or Nimbus Look and Feel to make it easier.
use WindowsLookAndFeel; this works if and only if you are running your application in winows; in your main you can do this before creating any UI: ``` try{ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); }catch(Exception ignore){ } ```
How do i change the UI of a JComboBox
[ "", "java", "swing", "user-interface", "jcombobox", "" ]
**My code** ``` import sys number=int(sys.argv[1]) if number == 0 fact=1 else fact=number for (x=1; x<number; x++) fact*=x; // mistake probably here print fact ``` I get the error ``` File "factorial.py", line 5 if number == 0 ^ SyntaxError: invalid syntax ``` **How can you make a factorial function in Python?**
Here's your code, fixed up and working: ``` import sys number = int(sys.argv[1]) fact = 1 for x in range(1, number+1): fact *= x print fact ``` (Factorial zero is one, for anyone who didn't know - I had to look it up. 8-) You need colons after `if`, `else`, `for`, etc., and the way `for` works in Python is different from C.
The line that your error is on should read ``` if number == 0: ``` Note the colon on the end. Additionally, you would need to add the same colon after the else and the for. The colons work similarly to {} in other languages. Finally, thats not how for loops work in Python. The code you want to use that list would be ``` for x in range(1,number): ``` Which would have the same effect of what you wrote, if you put that in a C style language. EDIT: Oops, the for loop I gave was wrong, it would have included 0. I updated the code to correct this.
Unable to make a factorial function in Python
[ "", "python", "factorial", "" ]
I've been tasked to figure out how to find the centerline of a polygon. My google searches led me to believe that what I need is called the 'Medial Axis'. Like this: [![alt text](https://i.stack.imgur.com/xGIlo.png)](https://i.stack.imgur.com/xGIlo.png) (source: [kiev.ua](http://www.ndl.kiev.ua/downloads/center_line.png)) According to what I've read, what I need can be produced by using a 2D Voronoi diagram construction algorithm for segments. I've found a C# version of the Voronoi algorithm on codeplex (FortuneVoronoi) and after applying my polygon to it, I end up with this: [alt text http://www.carbonatlas.com/geonotes/gaia\_voronoi.png](http://www.carbonatlas.com/geonotes/gaia_voronoi.png) The green is the original polygon. The orange are the Voronoi vertices and the black lines are the voronoi edges. I can see the makings of what I need in those vertices, but I'm unsure of the next step required to filter out all the stuff I don't need. I'd appreciate any help you can offer.
One simple solution would be as suggested in the comments: 1. Build the Delaunay triangulation of the polygon vertices. 2. Identify the Voronoi vertices inside the polygon (see <http://en.wikipedia.org/wiki/Point_in_polygon>) 3. Output the Voronoi edges connecting two interior Voronoi vertices. If you have huge data the intersections might be quite costly. Then you could do a similar approach like in the [question](https://stackoverflow.com/questions/996620/how-to-determine-if-a-delaunay-triangle-is-internal-or-external), and [this solution](https://stackoverflow.com/questions/996620/how-to-determine-if-a-delaunay-triangle-is-internal-or-external/1002775#1002775) could work for you, as well. The way I would do it: 1. Build the Delaunay triangulation of the polygon vertices. 2. Insert the midpoint of every polygon edge that is not covered by a delaunay edge. Do this recursively until all polygon edges are covered by Delaunay edges. 3. Mark all Delaunay edges which correspond to a polygon edge. 4. Extract the medial axis using steps 3.-5. in [this solution](https://stackoverflow.com/questions/996620/how-to-determine-if-a-delaunay-triangle-is-internal-or-external/1002775#1002775) PS. Note that both solutions give some *approximation* of the medial axis, computing it exactly is much more costly but as a teaser... you can get results like this for the black input sample points: ![medial axis](https://farm2.static.flickr.com/1223/989123527_75b3ec98a6.jpg?v=0)
A similar construct is the [Straight skeleton](http://en.wikipedia.org/wiki/Straight_skeleton), which can be constructed by shrinking the polygon into itself and tracing the vertices as they approach the center. This may be a little easier to construct, though it's not quite the same curve as the medial axis.
Find medial axis of a polygon using C#
[ "", "c#", "geometry", "computational-geometry", "medial-axis", "" ]
[This question has been asked in a C++ context](https://stackoverflow.com/questions/551263/method-chaining-inheritance-dont-play-well-together) but I'm curious about Java. The concerns about virtual methods don't apply (I think), but if you have this situation: ``` abstract class Pet { private String name; public Pet setName(String name) { this.name = name; return this; } } class Cat extends Pet { public Cat catchMice() { System.out.println("I caught a mouse!"); return this; } } class Dog extends Pet { public Dog catchFrisbee() { System.out.println("I caught a frisbee!"); return this; } } class Bird extends Pet { public Bird layEgg() { ... return this; } } { Cat c = new Cat(); c.setName("Morris").catchMice(); // error! setName returns Pet, not Cat Dog d = new Dog(); d.setName("Snoopy").catchFrisbee(); // error! setName returns Pet, not Dog Bird b = new Bird(); b.setName("Tweety").layEgg(); // error! setName returns Pet, not Bird } ``` In this sort of class hierarchy, is there any way to return `this` in a way that doesn't (effectively) upcast the the object type?
If you want to avoid unchecked cast warnings from your compiler (and don't want to @SuppressWarnings("unchecked")), then you need to do a little more: First of all, your definition of Pet must be self-referential, because Pet is always a generic type: ``` abstract class Pet <T extends Pet<T>> ``` Secondly, the `(T) this` cast in setName is also unchecked. To avoid this, use the "getThis" technique in the excellent [Generics FAQ by Angelika Langer](http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ206): > The "getThis" trick provides a way to > recover the exact type of the this > reference. This results in the code below, which compiles and runs without warnings. If you want to extend your subclasses, then the technique still holds (though you'll probably need to genericise your intermediate classes). The resulting code is: ``` public class TestClass { static abstract class Pet <T extends Pet<T>> { private String name; protected abstract T getThis(); public T setName(String name) { this.name = name; return getThis(); } } static class Cat extends Pet<Cat> { @Override protected Cat getThis() { return this; } public Cat catchMice() { System.out.println("I caught a mouse!"); return getThis(); } } static class Dog extends Pet<Dog> { @Override protected Dog getThis() { return this; } public Dog catchFrisbee() { System.out.println("I caught a frisbee!"); return getThis(); } } public static void main(String[] args) { Cat c = new Cat(); c.setName("Morris").catchMice(); Dog d = new Dog(); d.setName("Snoopy").catchFrisbee(); } } ```
How about this old trick: ``` abstract class Pet<T extends Pet> { private String name; public T setName(String name) { this.name = name; return (T) this; } } class Cat extends Pet<Cat> { /* ... */ } class Dog extends Pet<Dog> { /* ... */ } ```
Method chaining + inheritance don’t play well together?
[ "", "java", "inheritance", "method-chaining", "" ]
I have some contract text that may change. It is currently (non live system) stored in a database field (we determine which contract text to get by using other fields in table). I, however need to display a specific date (based on individual contract) within this text. IE (but Jan 12, changes depending on the individual contract): > blah blah blah... on Jan 12, 2009... blah blah blah but everything else in the contract text is the same. I'm looking for a way to inject the date into this text. Similar to .NET's ``` Console.Write("Some text here {0} and some more here", "My text to inject"); ``` Is there something like this? Or am I going to need to split the text into two fields and just concatenate? I am always displaying this information using Crystal Reports so if I can inject the data in through Crystal then that's fine. I am using Crystal Reports, SqlServer 2005, and VB.net.
You could use some "reserved string" (such as the "{0}") as part of the contract, and then perform a replace after reading from the database. If there's no option for this reserved string (for instance, if the contract may contain any type of string characters in any sequence, which I find unlikely), then you'll probably need to split into 2 text fields
Have you tried putting a text marker like the {0} above that can be replaced in the crystal reports code?
Injecting a value into text
[ "", "sql", "sql-server", "crystal-reports", "" ]
I have added the following custom loop in my Wordpress template: ``` $args = array( 'category__not_in' => array($featured_cat->term_id), 'posts_per_page' => 10, 'post__not_in' => array($recent_post) ); query_posts($args); ``` For pagination to work, I guess I need to pass another arg `paged` with the current page number. What is the way to get the current page number in Wordpress?
Not near a wordpress system to test this out at the mo, but you should be able to use: ``` $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; ``` (obviously defaulting to 1, if it has not been sent through).
using variable $paged. ``` global $paged; echo $paged; ```
Finding current page number in Wordpress
[ "", "php", "wordpress", "" ]
`Delete`s on sql server are sometimes slow and I've been often in need to optimize them in order to diminish the needed time. I've been googleing a bit looking for tips on how to do that, and I've found diverse suggestions. I'd like to know your favorite and most effective techinques to tame the delete beast, and how and why they work. until now: * be sure foreign keys have indexes * be sure the where conditions are indexed * use of `WITH ROWLOCK` * destroy unused indexes, delete, rebuild the indexes now, your turn.
The following article, *Fast Ordered Delete Operations* may be of interest to you. [Performing fast SQL Server delete operations](http://www.johnsansom.com/fast-sql-server-delete) The solution focuses on utilising a view in order to simplify the execution plan produced for a batched delete operation. This is achieved by referencing the given table once, rather than twice which in turn reduces the amount of I/O required.
I have much more experience with Oracle, but very likely the same applies to SQL Server as well: * when deleting a large number of rows, issue a table lock, so the database doesn't have to do lots of row locks * if the table you delete from is referenced by other tables, make sure those other tables have indexes on the foreign key column(s) (otherwise the database will do a full table scan *for each deleted row* on the other table to ensure that deleting the row doesn't violate the foreign key constraint)
Optimizing Delete on SQL Server
[ "", "sql", "sql-server", "" ]
Suppose we have a (toy) C++ class such as the following: ``` class Foo { public: Foo(); private: int t; }; ``` Since no destructor is defined, a C++ compiler should create one automatically for class `Foo`. If the destructor does not need to clean up any dynamically allocated memory (that is, we could reasonably rely on the destructor the compiler gives us), will defining an empty destructor, ie. ``` Foo::~Foo() { } ``` do the same thing as the compiler-generated one? What about an empty constructor -- that is, `Foo::Foo() { }`? If there are differences, where do they exist? If not, is one method preferred over the other?
It will do the same thing (nothing, in essence). But it's not the same as if you didn't write it. Because writing the destructor will require a working base-class destructor. If the base class destructor is private or if there is any other reason it can't be invoked, then your program is faulty. Consider this ``` struct A { private: ~A(); }; struct B : A { }; ``` That is OK, as long as your don't require to destruct an object of type B (and thus, implicitly of type A) - like if you never call delete on a dynamically created object, or you never create an object of it in the first place. If you do, then the compiler will display an appropriate diagnostic. Now if you provide one explicitly ``` struct A { private: ~A(); }; struct B : A { ~B() { /* ... */ } }; ``` That one will try to implicitly call the destructor of the base-class, and will cause a diagnostic already at definition time of `~B`. There is another difference that centers around the definition of the destructor and implicit calls to member destructors. Consider this smart pointer member ``` struct C; struct A { auto_ptr<C> a; A(); }; ``` Let's assume the object of type `C` is created in the definition of A's constructor in the `.cpp` file, which also contains the definition of struct `C`. Now, if you use struct `A`, and require destruction of an `A` object, the compiler will provide an implicit definition of the destructor, just like in the case above. That destructor will also implicitly call the destructor of the auto\_ptr object. And that will delete the pointer it holds, that points to the `C` object - without knowing the definition of `C`! That appeared in the `.cpp` file where struct A's constructor is defined. This actually is a common problem in implementing the pimpl idiom. The solution here is to add a destructor and provide an empty definition of it in the `.cpp` file, where the struct `C` is defined. At the time it invokes the destructor of its member, it will then know the definition of struct `C`, and can correctly call its destructor. ``` struct C; struct A { auto_ptr<C> a; A(); ~A(); // defined as ~A() { } in .cpp file, too }; ``` Note that `boost::shared_ptr` does not have that problem: It instead requires a complete type when its constructor is invoked in certain ways. Another point where it makes a difference in current C++ is when you want to use `memset` and friends on such an object that has a user declared destructor. Such types are not PODs anymore (plain old data), and these are not allowed to be bit-copied. Note that this restriction isn't really needed - and the next C++ version has improved the situation on this, so that it allows you to still bit-copy such types, as long as other more important changes are not made. --- Since you asked for constructors: Well, for these much the same things are true. Note that constructors also contain implicit calls to destructors. On things like auto\_ptr, these calls (even if not actually done at runtime - the pure possibility already matters here) will do the same harm as for destructors, and happen when something in the constructor throws - the compiler is then required to call the destructor of the members. [This answer](https://stackoverflow.com/questions/401621/best-way-to-build-a-list-of-per-type-data/401801#401801) makes some use of implicit definition of default constructors. Also, the same is true for visibility and PODness that i said about the destructor above. There is one important difference regarding initialization. If you put a user declared constructor, your type does not receive value initialization of members anymore, and it is up to your constructor to do any initialization that's needed. Example: ``` struct A { int a; }; struct B { int b; B() { } }; ``` In this case, the following is always true ``` assert(A().a == 0); ``` While the following is undefined behavior, because `b` was never initialized (your constructor omitted that). The value may be zero, but may aswell be any other weird value. Trying to read from such an uninitialized object causes undefined behavior. ``` assert(B().b == 0); ``` This is also true for using this syntax in `new`, like `new A()` (note the parentheses at the end - if they are omitted value initialization is not done, and since there is no user declared constructor that could initialize it, `a` will be left uninitialized).
I know I'm late in the discussion, nevertheless my experience says that the compiler behaves differently when facing an empty destructor compared to a compiler generated one. At least this is the case with MSVC++ 8.0 (2005) and MSVC++ 9.0 (2008). When looking at the generated assembly for some code making use of expression templates, I realized that in release mode, the call to my `BinaryVectorExpression operator + (const Vector& lhs, const Vector& rhs)` was never inlined. (please don't pay attention to the exact types and operator signature). To further diagnose the problem, I enabled the various [Compiler Warnings That Are Off by Default](http://msdn.microsoft.com/en-us/library/23k5d385.aspx). The [C4714](http://msdn.microsoft.com/en-us/library/a98sb923.aspx) warning is particularly interesting. It is emitted by the compiler when a function marked with `__forceinline` **doesn't get inlined nonetheless**. I enabled the C4714 warning and I marked the operator with `__forceinline` and I could verify the compiler reports it was unable to inline the call to the operator. Among the reasons described in the documentation, the compiler fails to inline a function marked with `__forceinline` for: > Functions returning an unwindable object by value when -GX/EHs/EHa is on This is the case of my `BinaryVectorExpression operator + (const Vector& lhs, const Vector& rhs)`. `BinaryVectorExpression` is returned by value and even though its destructor is empty, it makes this return value being considered as an unwindable object. Adding `throw ()` to the destructor didn't help the compiler and [I avoid using exception specifications anyway](http://www.boost.org/development/requirements.html#Exception-specification). Commenting out the empty destructor let the compiler fully inline the code. The take-away is that from now, in every class, I write commented out empty destructors to let humans know the destructor does nothing on purpose, the very same way people comment out the empty exception specification `/\* throw() \*/ to indicate that the destructor cannot throw. ``` //~Foo() /* throw() */ {} ``` Hope that helps.
Will an 'empty' constructor or destructor do the same thing as the generated one?
[ "", "c++", "class", "oop", "constructor", "destructor", "" ]
I have an event handler in code that I see is getting called multiple times when I am expecting it to only be called once. In the past this has been because I have defined the delegation in the wrong place (so more that one delegate is added to the event handling list), but on this occastion this is only being set once (in the class constructor). Rather than continuing to manually search through my code looking for errors, is there a (simple) pragmatic approach I can take to figuring out where event handlers are being assigned?
You can replace the default: ``` public event EventHandler MyEvent; ``` ...with ``` private EventHandler _myEvent; public event EventHandler MyEvent { add { _myEvent += value; } remove { _myEvent -= value; } } ``` Then you could put logging or breakpoints inside the add/remove functions and look at the call stack.
if you are using vb.net then are you sure that you are not adding the handler in a method and also using the handles keyword? this causes an event to be handled twice.
.NET Eventhandler Management
[ "", "c#", "event-handling", "" ]
I cannot get the following code to generate any output. The MySQL user has "all" grant level, /tmp is writable, the query returns a results set. ``` mysql> SELECT field FROM test_table WHERE condition='test' -> INTO OUTFILE '/tmp/test.csv' -> FIELDS TERMINATED BY ',' -> ENCLOSED BY '"' -> LINES TERMINATED BY '\n'; Query OK, 1 row affected (0.00 sec) mysql> [1]+ Stopped mysql [root@web1 ~]# cat /tmp/test.csv cat: /tmp/test.csv: No such file or directory ``` Should I be seeing different output from MySQL in case of failure? Can I verify the result further than "1 row affected"?
The files generate by the outfile clause are created on the mysql server host. Please make sure you are looking on the mysql server host as it seems you are on the client host which most likely isn't the mysql server host. See <http://dev.mysql.com/doc/refman/5.0/en/select.html> in the section about outfile for documentation regarding this.
I came across this problem in Fedora 17 and it was caused by systemd. I think it's good to share. ``` mysql> select * into outfile '/tmp/z1' from t1; Query OK, 673 rows affected (0.01 sec) mysql> select * into outfile '/tmp/z2' from t1; Query OK, 673 rows affected (0.01 sec) mysql> select * into outfile '/tmp/z1' from t1; ERROR 1086 (HY000): File '/tmp/z1' already exists mysql> Bye # cat /tmp/z1 cat: /tmp/z1: No such file or directory # ls -d systemd-* /tmp/systemd-private-AQEueG /tmp/systemd-private-AuCNDY /tmp/systemd-private-TOMNxZ /tmp/systemd-private-UacrpE /tmp/systemd-private-yal7lQ /tmp/systemd-private-ZlRJeN # ls /tmp/systemd-private-TOMNxZ z1 z2 ``` The culprit was in /usr/lib/systemd/system/mysqld.service. ``` # Place temp files in a secure directory, not /tmp PrivateTmp=true ``` Thanks to [this blog](http://jamesmcdonald.id.au/it-tips/mysql-cannot-find-outfile), I found the clue.
MySQL select into outfile /tmp no output
[ "", "mysql", "sql", "into-outfile", "" ]
I'm working on an app in CodeIgniter, and I'm trying to make a field on a form dynamically generate the **URL slug**. What I'd like to do is remove the punctuation, convert it to lowercase, and replace the spaces with hyphens. So for example, Shane's Rib Shack would become shanes-rib-shack. Here's what I have so far. The lowercase part was easy, but the replace doesn't seem to be working at all, and I have no idea to remove the punctuation: ``` $("#Restaurant_Name").keyup(function() { var Text = $(this).val(); Text = Text.toLowerCase(); Text = Text.replace('/\s/g','-'); $("#Restaurant_Slug").val(Text); }); ```
I have no idea where the 'slug' term came from, but here we go: ``` function convertToSlug(Text) { return Text.toLowerCase() .replace(/ /g, "-") .replace(/[^\w-]+/g, ""); } console.log(convertToSlug("hello world!")); console.log(convertToSlug("hello - world!")); ``` The first `replace` method will change spaces to hyphens, second, replace removes anything not alphanumeric, underscore, or hyphen. If you don't want things "like - this" turning into "like---this" then you can instead use this one: ``` function convertToSlug(Text) { return Text.toLowerCase() .replace(/[^\w ]+/g, "") .replace(/ +/g, "-"); } console.log(convertToSlug("hello world!")); console.log(convertToSlug("hello - world!")); ``` That will remove hyphens (but no spaces) on the first replace, and in the second replace it will condense consecutive spaces into a single hyphen. So "like - this" comes out as "like-this".
``` var slug = function(str) { str = str.replace(/^\s+|\s+$/g, ''); // trim str = str.toLowerCase(); // remove accents, swap ñ for n, etc var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;"; var to = "aaaaaeeeeeiiiiooooouuuunc------"; for (var i = 0, l = from.length; i < l; i++) { str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i)); } str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars .replace(/\s+/g, '-') // collapse whitespace and replace by - .replace(/-+/g, '-'); // collapse dashes return str; }; ``` and try ``` slug($('#field').val()) ``` original by: <http://dense13.com/blog/2009/05/03/converting-string-to-slug-javascript/> --- EDIT: extended for more language specific chars: ``` var from = "ÁÄÂÀÃÅČÇĆĎÉĚËÈÊẼĔȆĞÍÌÎÏİŇÑÓÖÒÔÕØŘŔŠŞŤÚŮÜÙÛÝŸŽáäâàãåčçćďéěëèêẽĕȇğíìîïıňñóöòôõøðřŕšşťúůüùûýÿžþÞĐđ߯a·/_,:;"; var to = "AAAAAACCCDEEEEEEEEGIIIIINNOOOOOORRSSTUUUUUYYZaaaaaacccdeeeeeeeegiiiiinnooooooorrsstuuuuuyyzbBDdBAa------"; ```
How to convert a Title to a URL slug in jQuery?
[ "", "javascript", "jquery", "regex", "slug", "slugify", "" ]
This is my first post on stackoverflow, I hope one of many! My question is this: I'm using CTE in a query to detect and remove duplicate records in a table. This query works just fine in SQL Server 2005 / 2008, but in Compact it throws an exception: > There was an error parsing the query. > [ Token line number = 1,Token line > offset = 1,Token in error = WITH ] This is my query: ``` SqlCeConnection con = new SqlCeConnection(ConfigurationManager.ConnectionStrings["ADSLConnectionString"].ConnectionString); SqlCeCommand command = new SqlCeCommand(); command.Connection = con; command.CommandType = CommandType.Text; command.CommandText = "WITH Dublicates_CTE(Username, accountid)" + " AS" + " (" + " SELECT UserName,min(accountid)" + " FROM Accounts" + " GROUP BY username" + " HAVING Count(*) > 1" + " )" + " DELETE FROM Accounts" + " WHERE accountid IN (" + " SELECT Accounts.accountid" + " FROM Accounts" + " INNER JOIN Dublicates_CTE" + " ON Accounts.Username = Dublicates_CTE.Username" + " AND Accounts.accountid <> Dublicates_CTE.accountid" + " ) "; con.Open(); command.ExecuteNonQuery(); ``` Am I missing something, or does CTE not work on SQL Server Compact?
You can probably just nest the query, something like this (may have some syntax problems): ``` DELETE FROM Accounts WHERE accountid IN ( SELECT Accounts.accountid FROM Accounts INNER JOIN ( SELECT UserName,min(accountid) accountid FROM Accounts GROUP BY username HAVING Count(*) > 1 ) Dublicates_CTE ON Accounts.Username = Dublicates_CTE.Username AND Accounts.accountid <> Dublicates_CTE.accountid ) ```
some things are not supported by the mobile version CTE and store procs for example will not work on the mobile version. You could use the express version which is also free
Using CTE on SQL Server Compact 3.5
[ "", "c#", "sql-server", "" ]
I'm writing an equipment rental application where clients are charged a fee for renting equipment based on the duration (in days) of the rental. So, basically, (daily fee \* number of days) = total charge. For instant feedback on the client side, I'm trying to use Javascript to figure out the difference in two calendar dates. I've searched around, but nothing I've found is quite what I'm looking for. Most solutions I've seen are of the form: ``` function dateDiff1(startDate, endDate) { return ((endDate.getTime() - startDate.getTime()) / 1000*60*60*24); } ``` My problem is that equipment can be checked out and returned at *any time of day* during those two dates with no additional charge. The above code is calculating the number of 24 hour periods between the two dates, when I'm really interested in the number of calendar days. For example, if someone checked out equipment at 6am on July 6th and returned it at 10pm on July 7th, the above code would calculate that more than one 24 hour period had passed, and would return 2. The desired result is 1, since only one calendar date has elapsed (i.e. the 6th to the 7th). The closest solution I've found is this function: ``` function dateDiff2(startDate, endDate) { return endDate.getDate() - startDate.getDate(); } ``` which does exactly what I want, as long as the two dates are within the same month. However, since getDate() only returns the day of month (i.e. 1-31), it doesn't work when the dates span multiple months (e.g. July 31 to August 1 is 1 day, but the above calcuates 1 - 31, or -29). On the backend, in PHP, I'm using gregoriantojd(), which seems to work just fine (see [this post](http://no.php.net/manual/en/function.date.php#84942) for an example). I just can't find an equivalent solution in Javascript. Anyone have any ideas?
If you want whole days for your student camera rental example ... ``` function daysBetween(first, second) { // Copy date parts of the timestamps, discarding the time parts. var one = new Date(first.getFullYear(), first.getMonth(), first.getDate()); var two = new Date(second.getFullYear(), second.getMonth(), second.getDate()); // Do the math. var millisecondsPerDay = 1000 * 60 * 60 * 24; var millisBetween = two.getTime() - one.getTime(); var days = millisBetween / millisecondsPerDay; // Round down. return Math.floor(days); } ```
I just had this problem and solved it after finding this question, so I came back to post this. This will get the total days regardless of time. And DST doesn't mess it up: ``` date1 = Date.UTC(date1.getFullYear(), date1.getMonth(), date1.getDate()); date2 = Date.UTC(date2.getFullYear(), date2.getMonth(), date2.getDate()); var ms = Math.abs(date1-date2); return Math.floor(ms/1000/60/60/24); //floor should be unnecessary, but just in case ``` The trick is converting to a UTC date that doesn't even know about the times of the original dates.
Date difference in Javascript (ignoring time of day)
[ "", "javascript", "date", "" ]
I have the following dynamic query which is working fine without the `WHERE` clause, which is expecting `UNIQUEIDENTIFIER`. When I pass it in, I don't get a result. I tried `CAST` and `CONVERT`, but no result. I might be doing it wrong, can anybody help? ``` CREATE PROCEDURE [dbo].[sp_Test1] /* 'b0da56dc-fc73-4c0e-85f7-541e3e8f249d' */ ( @p_CreatedBy UNIQUEIDENTIFIER ) AS DECLARE @sql NVARCHAR(4000) SET @sql =' DECLARE @p_CreatedBY UNIQUEIDENTIFIER SELECT DateTime, Subject, CreatedBy FROM ( SELECT DateTime, Subject, CreatedBy, ROW_NUMBER() OVER(ORDER BY DateTime ) AS Indexing FROM ComposeMail WHERE CreatedBy = @p_CreatedBy /* <--- the problem is in this condition */ ) AS NewDataTable ' EXEC sp_executesql @sql ```
You must pass in the parameters to sp\_executesql. [See MSDN for details](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-executesql-transact-sql). ``` ... WHERE CreatedBy = @p ... EXECUTE sp_executesql @sql, N'@p UNIQUEIDENTIFIER', @p = @p_CreatedBY ```
Multiple parameter syntax. Maybe this will save someone an extra Google Search: ``` exec sp_executesql @qry, N'@value1 int, @value2 int, @currentValue int', @value1 = @value1, @value2 = @value2, @currentValue = @currentValue ```
T-SQL: How to use parameters in dynamic SQL?
[ "", "sql", "sql-server", "t-sql", "dynamic-sql", "" ]
What are the advantages of [NumPy](http://en.wikipedia.org/wiki/NumPy) over regular Python lists? I have approximately 100 financial markets series, and I am going to create a cube array of 100x100x100 = 1 million cells. I will be regressing (3-variable) each x with each y and z, to fill the array with standard errors. I have heard that for "large matrices" I should use NumPy as opposed to Python lists, for performance and scalability reasons. Thing is, I know Python lists and they seem to work for me. What will the benefits be if I move to NumPy? What if I had 1000 series (that is, 1 billion floating point cells in the cube)?
NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy. Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware! The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!
NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented. For example, you could read your cube directly from a file into an array: ``` x = numpy.fromfile(file=open("data"), dtype=float).reshape((100, 100, 100)) ``` Sum along the second dimension: ``` s = x.sum(axis=1) ``` Find which cells are above a threshold: ``` (x > 0.5).nonzero() ``` Remove every even-indexed slice along the third dimension: ``` x[:, :, ::2] ``` Also, many useful libraries work with NumPy arrays. For example, statistical analysis and visualization libraries. Even if you don't have performance problems, learning NumPy is worth the effort.
What are the advantages of NumPy over regular Python lists?
[ "", "python", "arrays", "list", "numpy", "numpy-ndarray", "" ]
I'm considering allowing users to input JavaScript in web pages and letting them share those pages with other users. What's the worst that can happen? Is there any way I can make it 'safe'?
As mentioned by others, if the javascript is only displayed to other users and not run, it would be perfectly safe (not taking into account users manually running the code of course). If, however, the code is run, then some bad things can happen. One pretty bad thing that can happen is that your site is used to form a so called puppetnet. Puppetnets are similar to botnets but utilize browsers instead, and single puppets may therefore be relatively shortlived (which distinguishes puppetnets from botnets). Puppetnets can be used for distributed denial of service attacks, worm propagation, spamming and more. More about puppetnets can be found at <http://www.cs.ucsd.edu/groups/sysnet/miscpapers/puppetnets-ccs06.pdf>.
What can happen has a name - [Cross Site Scripting](http://en.wikipedia.org/wiki/Cross-site_scripting). Basically, you are allowing a (malicious) user Mallory to run a piece of code in the context of another (victimized) user Alice. [Here](http://msdn.microsoft.com/en-us/library/ms998274.aspx)'s a paper for preventing that from happening in ASP.Net. If you want to share the content, not the behavior, of those js snippets, that's another story. In that case, you should make sure that, when sending the response to Alice containing code posted by Mallory, it is appropriately enclosed as a text NOT to be parsed and executed. [Here's](http://ha.ckers.org/xss.html) is another paper that goes through the many twists this issue has.
Allowing users to input JavaScript in a page and sharing it with other users?
[ "", "javascript", "" ]
I have a dictionary object `IDictionary<string, string>` which only has the following items: Item1, Items2 and Item3. Each item only has a maximum length of 50 characters. I then have a list of words `List<string>`. I need a loop that will go through the words and add them to the dictionary starting at Item1, but before adding it to the dictionary the length needs to be checked. If the new item and the current item's length added together is greater than 50 characters then the word needs to move down to the next line (in this case Item2). What is the best way to do this?
I'm not sure why this question got voted down so much, but perhaps the reason is you have a very clear algorithm already, so it should be trivial to get the C# code. As it stands, either you're either really inexperienced or really lazy. I'm going to assume the former. Anyways, lets walk through the requirements. 1) "I then have a list of words List." you have this line in some form already. ``` List<string> words = GetListOfWords(); ``` 2) "go through the words and add them to the dictionary starting at Item1" -- I'd recommend a List instead of a dictionary, if you're going for a sequence of strings. Also, you'll need a temporary variable to store the contents of the current line, because you're really after adding a full line at a time. ``` var lines = new List<string>(); string currentLine = ""; ``` 3) "I need a loop that will go through the words" ``` foreach(var word in words) { ``` 4) " If the new item and the current item's length added together is greater than 50 characters" -- +1 for the space. ``` if (currentLine.Length + word.Length + 1 > 50) { ``` 5) "then the word needs to move down to the next line " ``` lines.Add(currentLine); currentLine = word; } ``` 6) " go through the words and add them to the dictionary starting at Item1 " -- you didn't phrase this very clearly. What you meant was you want to join each word to the last line unless it would make the line exceed 50 characters. ``` else { currentLine += " " + word; } } lines.Add(currentLine); // the last unfinished line ``` and there you go. --- If you absolutely need it as an IDictionary with 3 lines, just do ``` var dict = new Dictionary<string,string>(); for(int lineNum = 0; lineNum < 3; lineNum ++) dict["Address"+lineNum] = lineNume < lines.Length ? lines[lineNum] : ""; ```
I currently have this and was wondering if there was perhaps a better solution: ``` public IDictionary AddWordsToDictionary(IList words) { IDictionary addressParts = new Dictionary(); addressParts.Add("Address1", string.Empty); addressParts.Add("Address2", string.Empty); addressParts.Add("Address3", string.Empty); int currentIndex = 1; foreach (string word in words) { if (!string.IsNullOrEmpty(word)) { string key = string.Concat("Address", currentIndex); int space = 0; string spaceChar = string.Empty; if (!string.IsNullOrEmpty(addressParts[key])) { space = 1; spaceChar = " "; } if (word.Length + space + addressParts[key].Length > MaxAddressLineLength) { currentIndex++; key = string.Concat("Address", currentIndex); space = 0; spaceChar = string.Empty; if (currentIndex > addressParts.Count) { break; // To big for all 3 elements so discard } } addressParts[key] = string.Concat(addressParts[key], spaceChar, word); } } return addressParts; } ```
How to split long strings into fixed array items
[ "", "c#", "algorithm", "" ]
What is the difference between a `wait()` and `sleep()` in Threads? Is my understanding that a `wait()`-ing Thread is still in running mode and uses CPU cycles but a `sleep()`-ing does not consume any CPU cycles correct? Why do we have *both* `wait()` and `sleep()`? How does their implementation vary at a lower level?
A [`wait`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#wait%28%29) can be "woken up" by another thread calling [`notify`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#notify%28%29) on the monitor which is being waited on whereas a [`sleep`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html#sleep%28long%29) cannot. Also a `wait` (and `notify`) must happen in a block `synchronized` on the monitor object whereas `sleep` does not: ``` Object mon = ...; synchronized (mon) { mon.wait(); } ``` At this point the currently executing thread waits *and releases the monitor*. Another thread may do ``` synchronized (mon) { mon.notify(); } ``` (on the same `mon` object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up. You can also call [`notifyAll`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html#notifyAll%28%29) if more than one thread is waiting on the monitor – this will wake *all of them up*. However, only one of the threads will be able to grab the monitor (remember that the `wait` is in a `synchronized` block) and carry on – the others will then be blocked until they can acquire the monitor's lock. Another point is that you call `wait` on [`Object`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Object.html) itself (i.e. you wait on an object's monitor) whereas you call `sleep` on [`Thread`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Thread.html). Yet another point is that you can get *spurious wakeups* from `wait` (i.e. the thread which is waiting resumes for no apparent reason). You should **always `wait` whilst spinning on some condition** as follows: ``` synchronized { while (!condition) { mon.wait(); } } ```
One key difference not yet mentioned is that: * `sleep()` does ***not*** release the lock it holds on the Thread, ``` synchronized(LOCK) { Thread.sleep(1000); // LOCK is held } ``` * `wait()` **releases** the lock it holds on the object. ``` synchronized(LOCK) { LOCK.wait(); // LOCK is not held } ```
Difference between "wait()" vs "sleep()" in Java
[ "", "java", "multithreading", "wait", "sleep", "java-threads", "" ]
I currently have a report with pagination, that displays 20 records at a time. In total, there are 600 records. Within this report, I also have a checkbox column for every record. Based on this, my queries are as follows: 1. I want to incorporate a "Check All" feature, so based on my scenario which displays 20 records (total of 600 records overall), when I press the "Check All" checkbox, I would actually like to check all 600 records and not just the 20 per pagination. Is this possible with JavaScript, as the total number of records will vary? 2. Same concept as point (1), if I have a "Submit" button, I actually want to validate that all 600 records have been checked, even though I am only looking at 20 records at a time Is this possible?
If you want javascript to do this kind of feature then all your checkboxes have to be rendered to the screen.
If you really want your "Check All" box to mean check all across pages, then 'd recommend checking for that on the server side. e.g. ``` <ul> <li><input type='checkbox' name='item_ids[]' value='1'/>Item 1</li> <li><input type='checkbox' name='item_ids[]' value='2'/>Item 2</li> <li><input type='checkbox' name='item_ids[]' value='3'/>Item 3</li> <li><input type='checkbox' name='check_all' value='check_all'/></li> </ul> ``` Be aware of course, that "checking" boxes that the user can't see means they can't select all and then deselect individual ones. It's also somewhat counter-intuitive to check all across pages. Most implementations of this sort of thing only affect the page you are currently viewing. I would perhaps use a different control (a separate button) for this kind of functionality.
Check all checkbox with pagination
[ "", "javascript", "" ]
I am spawning external console application and use async output redirect. [as shown in this SO post](https://stackoverflow.com/questions/442680/best-way-to-interact-with-command-line-application) My problem is it seems that the spawned process needs to produce certain amount of output before I get the **OutputDataReceived** event notification. I want to receive the **OutputDataReceived** event as soon as possible. I have a bare-bones redirecting application, and here are some observations: 1. When I call a simple 'while(true) print("X");' console application (C#) I receive output event immediately. 2. When I call a 3d party app I am trying to wrap **from the command line** I see the line-by-line output. 3. When I call that 3d party app from my bare-bone wrapper (see 1) - the output comes in chunks (about one page size). What happens inside that app? FYI: The app in question is a "USBee DX Data Exctarctor (Async bus) v1.0".
I did some more research and have a fix to microsofts Process class. But as my last answer was deleted without a reason, I have had to create a new one. So take this example... Create a windows app and stick a rich textbox on the main form, then add this to the form load... ``` Process p = new Process() { StartInfo = new ProcessStartInfo() { FileName = "cmd.exe", CreateNoWindow = true, UseShellExecute = false, ErrorDialog = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, }, EnableRaisingEvents = true, SynchronizingObject = this }; p.OutputDataReceived += (s, ea) => this.richTextBox1.AppendText(ea.Data); p.Start(); p.BeginOutputReadLine(); ``` This will output something like this... ``` Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. ``` The OutputDataReceived event is not fired for the last line. After some ILSpying it appears that this is deliberate because the last line does not end with a crlf, it assumes there is more comming and appends it to the start of the next event. To correct this, I have written a wrapper for the Process class and taken some of the required internal classes out with it so that it all works neatly. Here is the FixedProcess class... ``` using System; using System.Collections; using System.IO; using System.Text; using System.Threading; namespace System.Diagnostics { internal delegate void UserCallBack(string data); public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e); public class FixedProcess : Process { internal AsyncStreamReader output; internal AsyncStreamReader error; public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; public new void BeginOutputReadLine() { Stream baseStream = StandardOutput.BaseStream; this.output = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedOutputReadNotifyUser), StandardOutput.CurrentEncoding); this.output.BeginReadLine(); } public void BeginErrorReadLine() { Stream baseStream = StandardError.BaseStream; this.error = new AsyncStreamReader(this, baseStream, new UserCallBack(this.FixedErrorReadNotifyUser), StandardError.CurrentEncoding); this.error.BeginReadLine(); } internal void FixedOutputReadNotifyUser(string data) { DataReceivedEventHandler outputDataReceived = this.OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) { this.SynchronizingObject.Invoke(outputDataReceived, new object[] { this, dataReceivedEventArgs }); return; } outputDataReceived(this, dataReceivedEventArgs); } } internal void FixedErrorReadNotifyUser(string data) { DataReceivedEventHandler errorDataReceived = this.ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs dataReceivedEventArgs = new DataReceivedEventArgs(data); if (this.SynchronizingObject != null && this.SynchronizingObject.InvokeRequired) { this.SynchronizingObject.Invoke(errorDataReceived, new object[] { this, dataReceivedEventArgs }); return; } errorDataReceived(this, dataReceivedEventArgs); } } } internal class AsyncStreamReader : IDisposable { internal const int DefaultBufferSize = 1024; private const int MinBufferSize = 128; private Stream stream; private Encoding encoding; private Decoder decoder; private byte[] byteBuffer; private char[] charBuffer; private int _maxCharsPerBuffer; private Process process; private UserCallBack userCallBack; private bool cancelOperation; private ManualResetEvent eofEvent; private Queue messageQueue; private StringBuilder sb; private bool bLastCarriageReturn; public virtual Encoding CurrentEncoding { get { return this.encoding; } } public virtual Stream BaseStream { get { return this.stream; } } internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding) : this(process, stream, callback, encoding, 1024) { } internal AsyncStreamReader(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize) { this.Init(process, stream, callback, encoding, bufferSize); this.messageQueue = new Queue(); } private void Init(Process process, Stream stream, UserCallBack callback, Encoding encoding, int bufferSize) { this.process = process; this.stream = stream; this.encoding = encoding; this.userCallBack = callback; this.decoder = encoding.GetDecoder(); if (bufferSize < 128) { bufferSize = 128; } this.byteBuffer = new byte[bufferSize]; this._maxCharsPerBuffer = encoding.GetMaxCharCount(bufferSize); this.charBuffer = new char[this._maxCharsPerBuffer]; this.cancelOperation = false; this.eofEvent = new ManualResetEvent(false); this.sb = null; this.bLastCarriageReturn = false; } public virtual void Close() { this.Dispose(true); } void IDisposable.Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing && this.stream != null) { this.stream.Close(); } if (this.stream != null) { this.stream = null; this.encoding = null; this.decoder = null; this.byteBuffer = null; this.charBuffer = null; } if (this.eofEvent != null) { this.eofEvent.Close(); this.eofEvent = null; } } internal void BeginReadLine() { if (this.cancelOperation) { this.cancelOperation = false; } if (this.sb == null) { this.sb = new StringBuilder(1024); this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null); return; } this.FlushMessageQueue(); } internal void CancelOperation() { this.cancelOperation = true; } private void ReadBuffer(IAsyncResult ar) { int num; try { num = this.stream.EndRead(ar); } catch (IOException) { num = 0; } catch (OperationCanceledException) { num = 0; } if (num == 0) { lock (this.messageQueue) { if (this.sb.Length != 0) { this.messageQueue.Enqueue(this.sb.ToString()); this.sb.Length = 0; } this.messageQueue.Enqueue(null); } try { this.FlushMessageQueue(); return; } finally { this.eofEvent.Set(); } } int chars = this.decoder.GetChars(this.byteBuffer, 0, num, this.charBuffer, 0); this.sb.Append(this.charBuffer, 0, chars); this.GetLinesFromStringBuilder(); this.stream.BeginRead(this.byteBuffer, 0, this.byteBuffer.Length, new AsyncCallback(this.ReadBuffer), null); } private void GetLinesFromStringBuilder() { int i = 0; int num = 0; int length = this.sb.Length; if (this.bLastCarriageReturn && length > 0 && this.sb[0] == '\n') { i = 1; num = 1; this.bLastCarriageReturn = false; } while (i < length) { char c = this.sb[i]; if (c == '\r' || c == '\n') { if (c == '\r' && i + 1 < length && this.sb[i + 1] == '\n') { i++; } string obj = this.sb.ToString(num, i + 1 - num); num = i + 1; lock (this.messageQueue) { this.messageQueue.Enqueue(obj); } } i++; } // Flush Fix: Send Whatever is left in the buffer string endOfBuffer = this.sb.ToString(num, length - num); lock (this.messageQueue) { this.messageQueue.Enqueue(endOfBuffer); num = length; } // End Flush Fix if (this.sb[length - 1] == '\r') { this.bLastCarriageReturn = true; } if (num < length) { this.sb.Remove(0, num); } else { this.sb.Length = 0; } this.FlushMessageQueue(); } private void FlushMessageQueue() { while (this.messageQueue.Count > 0) { lock (this.messageQueue) { if (this.messageQueue.Count > 0) { string data = (string)this.messageQueue.Dequeue(); if (!this.cancelOperation) { this.userCallBack(data); } } continue; } break; } } internal void WaitUtilEOF() { if (this.eofEvent != null) { this.eofEvent.WaitOne(); this.eofEvent.Close(); this.eofEvent = null; } } } public class DataReceivedEventArgs : EventArgs { internal string _data; /// <summary>Gets the line of characters that was written to a redirected <see cref="T:System.Diagnostics.Process" /> output stream.</summary> /// <returns>The line that was written by an associated <see cref="T:System.Diagnostics.Process" /> to its redirected <see cref="P:System.Diagnostics.Process.StandardOutput" /> or <see cref="P:System.Diagnostics.Process.StandardError" /> stream.</returns> /// <filterpriority>2</filterpriority> public string Data { get { return this._data; } } internal DataReceivedEventArgs(string data) { this._data = data; } } } ``` Stick that in your project and then change ... ``` Process p = new Process() { .... ``` to ``` FixedProcess p = new FixedProcess() { .... ``` Now your application should display something like this... ``` Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. C:\Projects\FixedProcess\bin\Debug> ``` without needing to make any other changes to your existing code. It is also still async and wrapped up nicely. The one caveat is that now you will get multiple events for large output with potential breaks in-between, so you will need to handle this scenario yourself. Other than that, it should be all good.
It seems as the problem was that the dummy app was written in c# which flushes the output automatically one every println while the 3rd party app was written in c/c++ and therefore only wrote when the stdoutbuffer was full. The only solution which ive found is to make sure the c/c++ app flushes after every print or to set its buffer to 0.
C# : Redirect console application output : How to flush the output?
[ "", "c#", "console", "external-process", "output-redirect", "" ]
I'm unable to figure out how to select an item programmatically in a ListView. I'm attempting to use the listview's ItemContainerGenerator, but it just doesn't seem to work. For example, obj is null after the following operation: ``` //VariableList is derived from BindingList m_VariableList = getVariableList(); lstVariable_Selected.ItemsSource = m_VariableList; var obj = lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]); ``` I've tried (based on suggestions seen here and other places) to use the ItemContainerGenerator's StatusChanged event, but to no avail. The event never fires. For example: ``` m_VariableList = getVariableList(); lstVariable_Selected.ItemContainerGenerator.StatusChanged += new EventHandler(ItemContainerGenerator_StatusChanged); lstVariable_Selected.ItemsSource = m_VariableList; ... void ItemContainerGenerator_StatusChanged(object sender, EventArgs e) { //This code never gets called var obj = lstVariable_Selected.ItemContainerGenerator.ContainerFromItem(m_VariableList[0]); } ``` The crux of this whole thing is that I simply want to pre-select a few of the items in my ListView. In the interest of not leaving anything out, the ListView uses some templating and Drag/Drop functionality, so I'm including the XAML here. Essentially, this template makes each item a textbox with some text - and when any item is selected, the checkbox is checked. And each item also gets a little glyph underneath it to insert new items (and this all works fine): ``` <DataTemplate x:Key="ItemDataTemplate_Variable"> <StackPanel> <CheckBox x:Name="checkbox" Content="{Binding Path=ListBoxDisplayName}" IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}, Path=IsSelected}" /> <Image ToolTip="Insert Custom Variable" Source="..\..\Resources\Arrow_Right.gif" HorizontalAlignment="Left" MouseLeftButtonDown="OnInsertCustomVariable" Cursor="Hand" Margin="1, 0, 0, 2" Uid="{Binding Path=CmiOrder}" /> </StackPanel> </DataTemplate> ... <ListView Name="lstVariable_All" MinWidth="300" Margin="5" SelectionMode="Multiple" ItemTemplate="{StaticResource ItemDataTemplate_Variable}" SelectionChanged="lstVariable_All_SelectionChanged" wpfui:DragDropHelper.IsDropTarget="True" wpfui:DragDropHelper.IsDragSource="True" wpfui:DragDropHelper.DragDropTemplate="{StaticResource ItemDataTemplate_Variable}" wpfui:DragDropHelper.ItemDropped="OnItemDropped"/> ``` So what am I missing? How do I programmatically select one or more of the items in the ListView?
Bind the `IsSelected` property of the `ListViewItem` to a property on your model. Then, you need only work with your model rather than worrying about the intricacies of the UI, which includes potential hazards around container virtualization. For example: ``` <ListView> <ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Setter Property="IsSelected" Value="{Binding IsGroovy}"/> </Style> </ListView.ItemContainerStyle> </ListView> ``` Now, just work with your model's `IsGroovy` property to select/deselect items in the `ListView`.
Where 'this' is the ListView instance. This will not only change the selection, but also set the focus on the newly selected item. ``` private void MoveSelection(int level) { var newIndex = this.SelectedIndex + level; if (newIndex >= 0 && newIndex < this.Items.Count) { this.SelectedItem = this.Items[newIndex]; this.UpdateLayout(); ((ListViewItem)this.ItemContainerGenerator.ContainerFromIndex(newIndex)).Focus(); } } ```
Select item programmatically in WPF ListView
[ "", "c#", ".net", "wpf", "listview", "selecteditem", "" ]
So I have a program that serves as a sort of 'shell' for other programs. At its core, it gets passed a class, a method name, and some args, and handles the execution of the function, with the idea of allowing other programmers to basically schedule their processes to run on this shell service. Everything works fine except for one issue. Frequently, these processes that are scheduled for execution are very CPU heavy. At times, the processes called start using so much of the CPU, that the threads that I have which are responsible for checking schedules and firing off other jobs don't get a chance to run for quite some time, resulting in scheduling issues and a lack of sufficient responsiveness. Unfortunately, I can't insert Thread.Sleep() calls in the actual running code, as I don't really 'own' it. So my question is: Is it possible to force an arbitrary thread (that I started) to sleep (yield) every so often, without modifying the actual code running in that thread? Barring that, is there some way to 'inject' Thread.Sleep() calls into code that I'm about to run dynamically, at run-time?
Not really. You could try changing the priority of the other thread with the [`Priority`](http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx) property, but you can't really inject a "sleep" call. There's [`Thread.Suspend()`](http://msdn.microsoft.com/en-us/library/system.threading.thread.suspend.aspx) but I *strongly* recommend you don't use it. You don't really *want* to get another thread to suspend at arbitrary times, as it might hold important resources. (That's why the method is marked as obsolete and has all kinds of warnings around it :) Reducing the priority of the other tasks and potentially boosting the priority of your own tasks is probably the best approach.
No there is not (to my knowledge), you can however change the scheduling priority of a thread - <http://msdn.microsoft.com/en-us/library/system.threading.thread.priority.aspx>. Lower the priority of the thread that is running the problem code as you start the thread (or raise the priority of your scheduling threads)
Force a Different Thread to Sleep
[ "", "c#", ".net", "multithreading", "sleep", "" ]
Do I really need to switch from VARCHAR to VARBINARY and TEXT to BLOB for UTF-8 in Mysql & PHP? Or can I stick with CHAR/TEXT fields in MySQL?
Maybe. As [jason](https://stackoverflow.com/questions/1030234/do-i-really-need-to-switch-from-varchar-to-varbinary-for-utf-8-in-mysql-php/1030261#1030261) pointed out and I failed to notice, MySQL UTF-8 does only map the Basic Multilingual Plane. The manual does point out however, that "They [utf8 and ucs2] are sufficient for almost all characters in major languages" So, it is probably safe but you might want to check out what is in the Basic Multilingual Plane just to be sure. **Orignal Answer** As long as your database is using UTF-8 you should be able to stick with VARCHAR and TEXT. (As a side note, the [MySQL manual](http://dev.mysql.com/doc/refman/5.0/en/charset-unicode.html) recommends using VARCHAR over CHAR with UTF-8 to save space. As this is the case, it should be safe to use VARCHAR and TEXT.)
Not necessarily. MySQL's UTF-8 support is limited to only 3 byte UTF8, which includes everything upto and including the [Basic Multilingual Plane](http://en.wikipedia.org/wiki/Mapping_of_Unicode_character_planes). It is only if you need characters which are in the 4 byte range that you need to use BLOB storage; this is rare, but not totally uncommon. See the Wikipedia article for a breakdown of what you'll be missing, and decide if there's anything there that is a must have.
Do I really need to switch from VARCHAR to VARBINARY for UTF-8 in Mysql & PHP?
[ "", "php", "mysql", "utf-8", "character-encoding", "" ]
I have a html table that I reorder based on a CSV list of custom attribute values that I have for each table row. I am using the following function to do it: ``` for (var i = 0; i < arrCSV.length; i++) { $('#' + tableId) .find('[fname = ' + arrCSV[i] + ']') .eq(0) .parents('tr') .eq(0) .appendTo('#' + tableId); } ``` The table structure is: ``` <table> <tr> <td fname='f1'>something here</td> </tr> <tr> <td fname='f2'>something here</td> </tr> </table> ``` The CSV could be something like this "f2, f1" I find this is very very slow performing function. Any help in optimizing it is really appreciated. **EDIT: Based on the article at <http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly>, one can achieve the greatest boost in performance by calling append only once with the html concatenated string. Can someone help in using this technique to my problem? I am not sure how to go about getting the s HTML in the for loop and appending it once.**
I would suggest finding the elements as few times as possible. Store all the matching rows into a "hash" using the attribute value of interest as the key. Go through your CSV, pick the corresponding row out of the hash, push it into an array, then finally append the elements of the array to the table using the jQuery object previously found. ``` var table = $('#' + tableId); var rowHash = {}; table.find('[fname]').each( function() { rowHash[$(this).attr('fname')] = $(this).closest('tr'); }); var rows = []; for (var i = 0; i < arrCSV.length; ++i) { var row = rowHash[arrCSV[i]]; if (row) { rows.push(row); } } $(rows).appendTo(table); ``` **EDIT**: This seems like a slight improvement to my previous code where I was appending each row to the table as it was found. I tested on a table with 1000 rows and it seems to take about 1sec to sort a table that needs to be completely inverted.
If you want to append html only once (like that learningjquery.com article), try following: ``` $(document).ready( function() { var arrCSV = ['f2', 'f1']; var tableId = 'mainTable'; var newTable = []; for (var i = 0; i < arrCSV.length; i++) { var row = $('#' + tableId) .find('[fname = ' + arrCSV[i] + ']') .eq(0) .parents('tr') .eq(0); newTable.push(row.html()); } $('#' + tableId).html(newTable.join('')); }; }); ``` Live version: <http://jsbin.com/uwipo> Code: <http://jsbin.com/uwipo/edit> Though I personally feel that you should profile your code first and see if it's append which is slow OR that 'find' method call. I am thinking that for a huge table, using 'find method' to find a custom attribute could be slow. But again, there is no point in any guesswork, profile the code and find it out. If the 'find' method is slow, will it be possible to use id attribute on td instead of giving custom attribute. e.g. ``` <table> <tr> <td id='f1'>something here</td> </tr> <tr> <td id='f2'>something here</td> </tr> </table> ``` Then your code to find the parent row could be as simple as: ``` ('#' + arrCsv[i]).parent('tr') ``` **EDIT:** As pointed out by tvanfosson, this code assumes that arrCSV contains attribute for all the rows. The final table will only contain those rows which are present in arrCSV. Also, this code does not copy 'thead', 'tfoot' section from the original table, though it should be easy to write code which does.
JQuery's appendTo is very slow!
[ "", "javascript", "jquery", "client", "" ]
Do you see any problem with using a byte array as Map key? I could also do `new String(byte[])` and hash by `String` but it is more straightforward to use `byte[]`.
The problem is that `byte[]` uses object identity for `equals` and `hashCode`, so that ``` byte[] b1 = {1, 2, 3} byte[] b2 = {1, 2, 3} ``` will not match in a `HashMap`. I see three options: 1. Wrapping in a `String`, but then you have to be careful about encoding issues (you need to make certain that the byte -> String -> byte gives you the same bytes). 2. Use `List<Byte>` (can be expensive in memory). 3. Do your own wrapping class, writing `hashCode` and `equals` to use the contents of the byte array.
It's okay so long as you only want reference equality for your key - arrays don't implement "value equality" in the way that you'd probably want. For example: ``` byte[] array1 = new byte[1]; byte[] array2 = new byte[1]; System.out.println(array1.equals(array2)); System.out.println(array1.hashCode()); System.out.println(array2.hashCode()); ``` prints something like: ``` false 1671711 11394033 ``` (The actual numbers are irrelevant; the fact that they're different is important.) Assuming you *actually* want equality, I suggest you create your own wrapper which contains a `byte[]` and implements equality and hash code generation appropriately: ``` public final class ByteArrayWrapper { private final byte[] data; public ByteArrayWrapper(byte[] data) { if (data == null) { throw new NullPointerException(); } this.data = data; } @Override public boolean equals(Object other) { if (!(other instanceof ByteArrayWrapper)) { return false; } return Arrays.equals(data, ((ByteArrayWrapper)other).data); } @Override public int hashCode() { return Arrays.hashCode(data); } } ``` Note that if you change the values within the byte array after using the `ByteArrayWrapper`, as a key in a `HashMap` (etc) you'll have problems looking up the key again... you could take a copy of the data in the `ByteArrayWrapper` constructor if you want, but obviously that will be a waste of performance if you know you *won't* be changing the contents of the byte array. EDIT: As mentioned in the comments, you could also use `ByteBuffer` for this (in particular, its [`ByteBuffer#wrap(byte[])`](http://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html#wrap%28byte%5B%5D%29) method). I don't know whether it's really the right thing, given all the extra abilities that `ByteBuffer`s have which you don't need, but it's an option.
Using a byte array as Map key
[ "", "java", "hashmap", "arrays", "" ]
I trying clojure i am trying to figure out how to implement the following algorithm, I am reading from an input stream i want to continue reading until it is not a delimiter character. i can do this in java with a while loop but i can't seem to figure out how to do it in clojure? ``` while read readChar != delimiter do some processing.... end while ```
I don't know Clojure, but it looks that, like Scheme, it supports "let loops": ``` (loop [char (readChar)] (if (= char delimiter) '() (do (some-processing) (recur (readChar))))) ``` Hope this is enough to get you started. I referred to <http://clojure.org/special_forms#toc9> to answer this question. NOTE: I know that Clojure discourages side-effects, so presumably you want to return something useful instead of '().
Working on Clojure 1.3.0, and for what it's worth, you can write while loops in Clojure now by doing something akin to ``` (while truth-expression (call-some-function)) ```
Clojure While Loop
[ "", "java", "clojure", "loops", "while-loop", "" ]
I have an application for which I do not have the code, and a dll for which I do have the code. I need to be able to debug into the dll, but lacking the source for the exe, how do I do this? The dll code is mfc c++; I believe that the main app is the same thing as well. I've tried doing a 'set target application' deal, where I set the application that the dll will be called from, and the application crashes a horrible, horrible death when called that way. I don't know if the fault lies with this dll or with the executable for that behavior, and it's just one of the myriad things I'd like to solve. I'm thinking that there should be some call to allow the dll to spin indefinitely until a debugger is attached to the process, at which point I should be able to debug the dll by attaching to the process. Does that make sense? Is there a better way to do this?
If the application is linked against a non-debug DLL and does not have debug symbols itself, this isn't really likely to be fruitful. You might want to look [here](http://www.microsoft.com/whdc/DevTools/Debugging/debugstart.mspx) for information on using windows symbol packages to help you if you're curious about what's going in inside windows DLL's, but by and large, an application which does not have debug info and which you can't compile isn't debuggable in any meaningful way.
I used to use the [DebugBreak](http://msdn.microsoft.com/en-us/library/ms679297(VS.85).aspx) function for this. You could have it called conditionally based on the presence of a particular file, perhaps. ``` #ifdef DEBUG if (... file exists...) { DebugBreak(); } #endif ``` This will halt application execution until you attach a debugger or terminate the app.
how do I stop a C++ application during execution to debug into a dll?
[ "", "c++", "visual-studio", "debugging", "dll", "" ]
I have developed a script for checking that user has selected a valid month and year for credit card. ``` function validatemonth() { var dt = new Date(); var mth = dt.getMonth(); var yr = dt.getYear(); //this seems to return different data in different browsers yr = yr + 1900; if(eval(document.PurchaseCredit.cc_expire_month.value) < mth && eval(document.PurchaseCredit.cc_expire_year.value) == yr) { document.getElementById('error').innerHTML = "Expiry Date cannot be less than current date."; document.forms['PurchaseCredit'].submit.disabled = true; } else { document.getElementById('error').innerHTML = ""; document.forms['PurchaseCredit'].submit.disabled = false; } } ``` This script works well in FireFox but does not work in IE7. Why?
Its not working because getYear() return different results for different browsers. > Internet Explorer: > > ``` > * Returns four digits for years before 1900 and after 1999. > ``` > > Firefox: > > ``` > * Returns a value less than 0 for years before 1900. For example, the > ``` > > year 1800 returns -100. > \* Returns a value 100 or greater for years greater than or equal to > 2000. For example, the year 2008 returns 108. Your addition of 1900 is relevant only for Firefox. Easy Solution : Try using getFullYear()
Date.getYear() is browser dependent. In Firefox it returns the number of years after 1900, in IE it returns the full 4 digit year. Date.getFullYear() returns the 4 digit year in all browsers, so you should always use it instead.
There is something wrong with this JavaScript
[ "", "javascript", "" ]
Is there any init method provided for struts 2 action class that can be called before every method of that action class? For example, I have an action class for struts 2 as given below ``` import com.opensymphony.xwork2.ActionSupport; public class EmployeeAction extends ActionSupport{ private DepartmentDaoService deptService = new DepartmentDaoService() ; private EmployeeDaoService empService = new EmployeeDaoService(); private Employee employee; private List<Employee> employees; private List<Department> departments; public void init() { //Do initialization stuff here } public String getAllEmployees(){ employees = empService.getAllEmployees(); return "success"; } public String deleteEmployee(){ empService.deleteEmployee(employee.getEmployeeId()); return "success"; } } ``` Now in above code when struts action for `getAllEmployees()` and `deleteEmplyee()` is called I want `init()` method to execute first. We can run it by calling it from both functions. But is there any provision given in struts 2 that will run init method automatically on each call or struts 2 provides any such method for action clases? Please tell me if anyone knows. Thanks.
Yes there is: First of all, your action class must implement the [Preparable interface](https://struts.apache.org/getting-started/preperable-interface.html). Then, your action must implement Preparable.prepare() method. Struts 2 will execute prepare() everytime before it invokes your action method. Cheers.
Take a look at the [Preparable interface and the Prepare Interceptor](https://struts.apache.org/getting-started/preperable-interface.html).
Is there any init method given for struts2 action class?
[ "", "java", "struts2", "" ]
I have this library called [BASS](http://www.un4seen.com/) which is an audio library which I'm going to use to record with the microphone. I have all the files needed to use it, but I don't know how to install the library. I tried taking the example files and putting them in the same directory as the bass.h file. But I got a bunch of errors saying there are function calls that doesn't exist. So my question is, how do I install it to be able to use it?
Installing a C++ library means specifying to interested software (eg. a compiler) the location of two kinds of files: headers (typical extensions \*.h or *.hpp) and compiled objects (*.dll or \*.lib for instance). The headers will contain the declarations exposed to the developer by the library authors, and your program will #include them in its source code, the dll will contain the compiled code which will be or linked together and used by your program, and they will be found by the linker (or loaded dynamically, but this is another step). So you need to 1. Put the header files in a location which your compiler is aware of (typically IDE allows to set so-called include directories, otherwise you specify a flag like `-I<path-to-headers>` when invoking the compiler) 2. Put the dll files in a location which your linker is aware of (surely your IDE will allow that, otherwise you speficy a flag like `-L<path-to-libraries> -l<name-of-libraries>` Last but not least, since I see that BASS library is a commercial product, probably they will have made available some installation instructions?
Run this command in a terminal or console. ``` cpp -v ``` Notice at the end of the output, you'll see a line like this: ``` #include<...> search starts here: ``` There will be a list of directories below that line. Move the package folder to one of those directories. Then try importing the module with <>.
How do I install a c++ library so I can use it?
[ "", "c++", "windows", "installation", "mingw", "" ]
I have a database view that yields a result set that has no true primary key. I want to use Hibernate/Persistence to map this result set onto Java objects. Of course, because there is no PK, I cannot decorate any field with `@Id`. When deploying, Hibernate complains about the missing `@Id`. How can I work around this?
If there's a combination of columns that makes a row unique, model a primary key class around the combination of columns. If there isn't, you're basically out of luck -- but you should reexamine the design of the view since it probably doesn't make sense. There are a couple different approaches: ``` @Entity public class RegionalArticle implements Serializable { @Id public RegionalArticlePk getPk() { ... } } @Embeddable public class RegionalArticlePk implements Serializable { ... } ``` Or: ``` @Entity public class RegionalArticle implements Serializable { @EmbeddedId public RegionalArticlePk getPk() { ... } } public class RegionalArticlePk implements Serializable { ... } ``` The details are here: <https://docs.jboss.org/ejb3/app-server/HibernateAnnotations/reference/en/html_single/index.html#d0e1517> Here's a posting that describes a similar issue: <http://www.theserverside.com/discussions/thread.tss?thread_id=22638>
Instead of searching for workarounds in Hibernate, it might be easier to add dummy id in your database view. Let's assume that we have PostgreSQL view with two columns and none of them is unique (and there is no primary key as Postgres doesn't allow to make PK or any other constraints on views) ex. ``` | employee_id | project_name | |:------------|:-------------| | 1 | Stack01 | | 1 | Jira01 | | 1 | Github01 | | 2 | Stack01 | | 2 | Jira01 | | 3 | Jira01 | ------------------------------ ``` Which is represented by the following query: ``` CREATE OR REPLACE VIEW someschema.vw_emp_proj_his AS SELECT DISTINCT e.employee_id, pinf.project_name FROM someschema.project_info pinf JOIN someschema.project_employee pe ON pe.proj_id = pinf.proj_id JOIN someschema.employees e ON e.employee_id = pe.emloyee_id ``` We can add dummy id using row\_number(): ``` SELECT row_number() OVER (ORDER BY subquery.employee_id) AS row_id ``` like in this example: ``` CREATE OR REPLACE VIEW someschema.vw_emp_proj_his AS SELECT row_number() OVER (ORDER BY subquery.employee_id) AS row_id, subquery.employee_id, subquery.project_name FROM (SELECT DISTINCT e.employee_id, pinf.project_name FROM someschema.project_info pinf JOIN someschema.project_employee pe ON pe.proj_id = pinf.proj_id JOIN someschema.employees e ON e.employee_id = pe.emloyee_id ) subquery; ``` And the table will look like this: ``` | row_id | employee_id | project_name | |:------------|:------------|:-------------| | 1 | 1 | Stack01 | | 2 | 1 | Jira01 | | 3 | 1 | Github01 | | 4 | 2 | Stack01 | | 5 | 2 | Jira01 | | 6 | 3 | Jira01 | ------------------------------------------- ``` Now we can use row\_id as @Id in JPA/Hibernate/Spring Data: ``` @Id @Column(name = "row_id") private Integer id; ``` Like in the example: ``` @Entity @Table(schema = "someschema", name = "vw_emp_proj_his") public class EmployeeProjectHistory { @Id @Column(name = "row_id") private Integer id; @Column(name = "employee_id") private Integer employeeId; @Column(name = "project_name") private String projectName; //Getters, setters etc. } ```
Hibernate/persistence without @Id
[ "", "java", "hibernate", "primary-key", "hibernate-annotations", "" ]
I'm about to begin building a huge clinical healthcare application with PHP, and I'm looking for some advice on a framework. I need to be able to come up with a quick prototype, so it's important that the framework takes care of many mundane tasks; therefore, I've narrowed it down to CakePHP or Symfony. I'm hoping to get a few developers opinions that have worked with both frameworks. Thanks, Pete
IBM published an article here on both those frameworks along with Zend in a comparisson, see: <http://www.ibm.com/developerworks/opensource/library/os-php-fwk1/?S_TACT=105AGX44&S_CMP=ART> I personally use CakePHP, it's pretty awesome compared to just straight out PHP. Easy to build things in, very MVC focused, reasonable integration with third party components. I did have some issues with the lack of any sort of discernable upgrade path between versions though. I can't speak for Symfony, but I believe it's more heavyweight than CakePHP. Take a look at the screencasts for CakePHP as well, they give a good overview: <http://cakephp.org/screencasts>
I'd like to counter some of the arguments presented above. I've worked extensively with Zend Framework and symfony, and I've had a brief look at CakePHP. First of all, compared to symfony, the ZF documentation is not "extensive" - its on the other hand quite superficial. Second, I think that the symfony community is much more available and helpful than the ZF framework in general, and the development process is much more transparent. However, I agree that Zend Framework enjoys the advantage of being supported by Zend, which might be a powerful argument for enterprise projects. In my experience symfony is more of a framework than ZF. In symfony you use the whole package - or the whole frame, while you in ZF is able to use tools to your liking, making it more like a "toolbox" than a framework. Also remember that if you like some of the tools in ZF, you'll be able to use these in symfony (and probably also CakePHP) projects, alongside symfony/CakePHP. This is not really an answer but more like a general comment to the answers given above.
Which PHP MVC Framework for the enterprise; CakePHP or Symfony?
[ "", "php", "cakephp", "symfony1", "" ]
I have a PHP script that runs database queries. Now, if a query fails, should I trigger an error or throw an exception? I noticed that if I do the latter, the script execution will stop after facing the exception. My code is as follows: ``` if (!$this->connection[0]->query($this->query)) throw new Exception($this->connection[0]->error); ``` What are the pros and cons of using exceptions for this kind of cases (failed queries)?
depends on your general error handling strategy and the queries passed to this function. Throwing Exceptions itself is a very good idea, IMHO, **if** they are caught somewhere and processed.
> *What are the pros and cons of using exceptions for this kind of cases (failed queries)?* Simply: * **Pros**: your application can handle the failed query gracefully, log it if need be, and move on. * **Cons**: performance. That said, I think you may be focusing on the wrong question. **You *should* be handling exceptions whenever they might happen, but they should happen very, very rarely.** If your query has a reasonable chance of failing, then the query itself should be your focus rather than any error-handling mechanism. By this I mean improving the *validation* of any input to your query that could cause it to choke, and not the *speed* of the query as a means to offset any performance hit due to error handling. In other words, find out what would make your query fail and ensure that such a state is not achieved. Consider this analogy: if you're heading out onto the lake in a potentially leaky boat (your query), you shouldn't be worrying so much about wearing a wetsuit (error handling) as you should be about making sure the boat is watertight.
Would I want to throw an exception or an error in this PHP script?
[ "", "php", "exception", "" ]
I have this `struct`: ``` struct Snapshot { double x; int y; }; ``` I want `x` and `y` to be 0. Will they be 0 by default or do I have to do: ``` Snapshot s = {0,0}; ``` What are the other ways to zero out the structure?
They are not null if you don't initialize the struct. ``` Snapshot s; // receives no initialization Snapshot s = {}; // value initializes all members ``` The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive: ``` struct Parent { Snapshot s; }; Parent p; // receives no initialization Parent p = {}; // value initializes all members ``` The second will make `p.s.{x,y}` zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors ``` struct Snapshot { int x; double y; Snapshot():x(0),y(0) { } // other ctors / functions... }; ``` Will initialize both x and y to 0. Note that you can use `x(), y()` to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template.
No, they are not 0 by default. The simplest way to ensure that all values or defaulted to 0 is to define a constructor ``` Snapshot() : x(0), y(0) { } ``` This ensures that all uses of Snapshot will have initialized values.
Are members of a C++ struct initialized to 0 by default?
[ "", "c++", "" ]
Hey I was wondering... I am using the pydev with eclipse and I'm really enjoying the powerful debugging features, but I was wondering: **Is it possible to set a breakpoint in eclipse and jump into the interactive python interpreter during execution?** I think that would be pretty handy ;) **edit**: I want to emphasize that my goal is not to jump into a debugger. pydev/eclipse have a great debugger, and I can just look at the traceback and set break points. What I want is to execute a script and jump into an interactive python interpreter during execution so I can do things like... * poke around * check the values of things * manipulate variables * figure out some code before I add it to the app I know you can do this all with a debugger, but I can do it faster in the interactive interpreter because I can try something, see that it didn't work, and try something else without having get the app back to the point of executing that code again.
So roughly a year on from the OP's question, PyDev has this capability built in. I am not sure when this feature was introduced, but all I know is I've spent the last ~2hrs Googling... configuring iPython and whatever (which was looking like it would have done the job), but only to realise Eclipse/PyDev has what I want ootb. As soon as you hit a breakpoint in debug mode, the console is right there ready and waiting! I only didn't notice this as there is no prompt or blinking cursor; I had wrongly assumed it was a standard, output-only, console... but it's not. It even has code-completion. Great stuff, see <http://pydev.org/manual_adv_debug_console.html> for more details.
This is from an old project, and I didn't write it, but it does something similar to what you want using ipython. ``` '''Start an IPython shell (for debugging) with current environment. Runs Call db() to start a shell, e.g. def foo(bar): for x in bar: if baz(x): import ipydb; ipydb.db() # <-- start IPython here, with current value of x (ipydb is the name of this module). . ''' import inspect,IPython def db(): '''Start IPython shell with callers environment.''' # find callers __up_frame = inspect.currentframe().f_back eval('IPython.Shell.IPShellEmbed([])()', # Empty list arg is # ipythons argv later args to dict take precedence, so # f_globals() shadows globals(). Need globals() for IPython # module. dict(globals().items() + __up_frame.f_globals.items()), __up_frame.f_locals) ``` **edit by Jim Robert (question owner)**: If you place the above code into a file called `my_debug.py` for the sake of this example. Then place that file in your python path, and you can insert the following lines anywhere in your code to jump into a debugger (as long as you execute from a shell): ``` import my_debug my_debug.db() ```
Jump into a Python Interactive Session mid-program?
[ "", "python", "eclipse", "debugging", "breakpoints", "pydev", "" ]
Firstly, what is the best/simplest way to detect if X11 is running and available for a python script. parent process? session leader? X environment variables? other? Secondly, I would like to have a utility (python script) to present a gui if available, otherwise use a command line backed tool. Off the top of my head I thought of this -main python script (detects if gui is available and launches appropriate script) -gui or command line python script starts -both use a generic module to do actual work I am very open to suggestions to simplify this.
You could simply launch the gui part, and catch the exception it raises when X (or any other platform dependent graphics system is not available. Make sure you really have an interactive terminal before running the text based part. Your process might have been started without a visible terminal, as is common in graphical user environments like KDE, gnome or windows.
Check the return code of `xset -q`: ``` def X_is_running(): from subprocess import Popen, PIPE p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE) p.communicate() return p.returncode == 0 ``` As for the second part of your question, I suggest the following `main.py` structure: ``` import common_lib def gui_main(): ... def cli_main(): ... def X_is_running(): ... if __name__ == '__main__': if X_is_running(): gui_main() else: cli_main() ```
Detect if X11 is available (python)
[ "", "python", "user-interface", "" ]
How come dividing two 32 bit int numbers as ( int / int ) returns to me `0`, but if I use `Decimal.Divide()` I get the correct answer? I'm by no means a c# guy.
`int` is an integer type; dividing two ints performs an *integer* division, i.e. the fractional part is truncated since it can't be stored in the result type (also `int`!). `Decimal`, by contrast, has got a fractional part. By invoking `Decimal.Divide`, your `int` arguments get implicitly converted to `Decimal`s. You can enforce non-integer division on `int` arguments by explicitly casting at least one of the arguments to a floating-point type, e.g.: ``` int a = 42; int b = 23; double result = (double)a / b; ```
In the first case, you're doing integer division, so the result is truncated (the decimal part is chopped off) and an integer is returned. In the second case, the ints are converted to decimals first, and the result is a decimal. Hence they are not truncated and you get the correct result.
Why does Decimal.Divide(int, int) work, but not (int / int)?
[ "", "c#", "math", "int", "divide", "" ]
This is an example of a pattern I've encountered a lot recently. I have a method to be tested that takes a List and may invoke some other method(s) for each item in the list. To test this I define an Iterator with the expected call parameters and a loop in the JMock expectations to check the call is made against each item of the iterator (see trivial example below). I've had a look at the Hamcrest matchers but haven't found something that tests for this (or have misunderstood how the available matchers work). Does anyone have a more elegant approach? ``` package com.hsbc.maven.versionupdater; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.jmock.Expectations; import org.jmock.Mockery; import org.jmock.Sequence; import org.jmock.internal.NamedSequence; public class FooTest extends AbstractMojoTestCase { public interface Bar { void doIt(String arg); } public class Foo { private Bar bar; public void executeEven(final List<String> allParameters) { for (int i = 0; i < allParameters.size(); i++) { if (i % 2 == 0) { bar.doIt(allParameters.get(i)); } } } public Bar getBar() { return bar; } public void setBar(final Bar bar) { this.bar = bar; } } public void testExecuteEven() { Mockery mockery = new Mockery(); final Bar bar = mockery.mock(Bar.class); final Sequence sequence = new NamedSequence("sequence"); final List<String> allParameters = new ArrayList<String>(); final List<String> expectedParameters = new ArrayList<String>(); for (int i = 0; i < 3; i++) { allParameters.add("param" + i); if (i % 2 == 0) { expectedParameters.add("param" + i); } } final Iterator<String> iter = expectedParameters.iterator(); mockery.checking(new Expectations() { { while (iter.hasNext()) { one(bar).doIt(iter.next()); inSequence(sequence); } } }); Foo subject = new Foo(); subject.setBar(bar); subject.executeEven(allParameters); mockery.assertIsSatisfied(); } } ```
I think your current test implementation is pretty close to ideal. Any further compaction risks either changing the semantics of the test or obscuring the intent of the test to a reader (or both). However, if you're looking for a way to expect a specific number of calls to a method, you can use `exactly(n).of()`: ``` mockery.checking(new Expectations() {{ exactly(expectedParameters.length()).of(bar).doIt(with(anyOf(expectedParameters))); }}); ``` (I left out the evenness check, but you get the idea). This is similar to the jmockit example in a different answer. Be aware that this does not test the same thing as your original test. In particular it does not check: 1. The order of the calls to `doIt` 2. That each element of the parameter list is passed exactly once For example, this test would pass if your method iterated over the list in reverse order, or if it just called the `doIt` method `n` times but passed the first element of the list each time. If you want to ensure that each element in the list is passed, you pretty much have to iterate over it setting an individual expectation for each. If you don't care about the order of the invocations, you can omit the use of the Sequence (in that case you may want to change your original method to accept a Collection instead of a List).
Perhaps the following (using JMockit instead of jMock)? ``` import java.util.*; import org.junit.*; import org.junit.runner.*; import org.hamcrest.*; import static org.hamcrest.core.AnyOf.*; import static org.hamcrest.core.Is.*; import org.hamcrest.core.*; import mockit.*; import mockit.integration.junit4.*; @RunWith(JMockit.class) public class FooTest { public interface Bar { void doIt(String arg); } public class Foo { private Bar bar; public void executeEven(final List<String> allParameters) { for (int i = 0; i < allParameters.size(); i++) { if (i % 2 == 0) { bar.doIt(allParameters.get(i)); } } } public void setBar(final Bar bar) { this.bar = bar; } } @Test public void testExecuteEven(final Bar bar) { final List<String> allParameters = new ArrayList<String>(); final List<Matcher<? extends String>> expectedParameters = new ArrayList<Matcher<? extends String>>(); for (int i = 0; i < 3; i++) { allParameters.add("param" + i); if (i % 2 == 0) { expectedParameters.add(new IsEqual<String>("param" + i)); } } new Expectations() { { bar.doIt(with(anyOf(expectedParameters))); repeats(expectedParameters.size()); } }; Foo subject = new Foo(); subject.setBar(bar); subject.executeEven(allParameters); } @Test // a shorter version of the same test public void testExecuteEven2(final Bar bar) { final List<String> allParameters = Arrays.asList("param0", "param1", "param2"); new Expectations() { { bar.doIt(with(anyOf(is("param0"), is("param2")))); repeats(2); } }; Foo subject = new Foo(); subject.setBar(bar); subject.executeEven(allParameters); } } ```
Is there a neater way of testing calls to mocked methods for each item in a list
[ "", "java", "unit-testing", "jmock", "jmockit", "" ]
which one of the 2 have the best performance? In javascript I was heard douglas crockford say that you shouldn't use str += if you are concatenating a large string but use array.push instead. I've seen lots of code where developers use $str .= to concatenate a large string in PHP as well, but since "everything" in PHP is based on arrays (try dumping an object), my thought was that the same rule applies for PHP. Can anyone confirm this?
Strings are mutable in PHP so using .= does not have the same affect in php as using += in javascript. That is, you will not not end up with two different strings every time you use the operator. See: [php String Concatenation, Performance](https://stackoverflow.com/questions/124067/php-string-concatenation-performance) [Are php strings immutable?](https://stackoverflow.com/questions/496669/are-php-strings-immutable)
`.=` is for strings. [`array_push()`](https://www.php.net/manual/en/function.array-push.php) is for arrays. They aren't the same thing in PHP. Using one on the other will generate an error.
array_push vs $str .= in PHP
[ "", "php", "" ]
Seeing various locking related question and (almost) always finding the 'loop because of spurious wakeups' terms1 I wonder, has anyone experienced such kind of a wakeup (assuming a decent hardware/software environment for example)? I know the term 'spurious' means no apparent reason but what can be the reasons for such kind of an event? (1 Note: I'm not questioning the looping practice.) **Edit:** A helper question (for those who like code samples): If I have the following program, and I run it: ``` public class Spurious { public static void main(String[] args) { Lock lock = new ReentrantLock(); Condition cond = lock.newCondition(); lock.lock(); try { try { cond.await(); System.out.println("Spurious wakeup!"); } catch (InterruptedException ex) { System.out.println("Just a regular interrupt."); } } finally { lock.unlock(); } } } ``` What can I do to wake this `await` up spuriously without waiting forever for a random event?
The Wikipedia [article on spurious wakeups](http://en.wikipedia.org/wiki/Spurious_wakeup) has this tidbit: > The `pthread_cond_wait()` function in Linux is implemented using the `futex` system call. Each blocking system call on Linux returns abruptly with `EINTR` when the process receives a signal. ... `pthread_cond_wait()` can't restart the waiting because it may miss a real wakeup in the little time it was outside the `futex` system call. This race condition can only be avoided by the caller checking for an invariant. A POSIX signal will therefore generate a spurious wakeup. **Summary**: If a Linux process is signaled its waiting threads will each enjoy a nice, hot *spurious wakeup*. I buy it. That's an easier pill to swallow than the typically vague "it's for performance" reason often given.
I have a production system that exhibits this behaviour. A thread waits on a signal that there is a message in the queue. In busy periods, up to 20% of the wakeups are spurious (ie when it wakes there is nothing in the queue). This thread is the only consumer of the messages. It runs on a Linux SLES-10 8-processor box and is built with GCC 4.1.2. The messages come from an external source and are processed asynchronously because there are problems if my system does not read them fast enough.
Do spurious wakeups in Java actually happen?
[ "", "java", "multithreading", "locking", "spurious-wakeup", "" ]
I have two regular expressions that I use to validate Colorado driver's license formats. ``` [0-9]{2}[-][0-9]{3}[-][0-9]{4} ``` and ``` [0-9]{9} ``` We have to allow for only 9 digits but the user is free to enter it in as 123456789 or 12-345-6789. Is there a way I can combine these into one? Like a regex conditional statement of sorts? Right now I am simply enumerating through all the available formats and breaking out once one is matched. I could always strip the hyphens out before I do the compare and only use `[0-9]{9}`, but then I won't be learning anything new.
For a straight combine, ``` (?:[0-9]{2}[-][0-9]{3}[-][0-9]{4}|[0-9]{9}) ``` or to merge the logic (allowing dashes in one position without the other, which may not be desired), ``` [0-9]{2}-?[0-9]{3}-?[0-9]{4} ``` (The brackets around the hyphens in your first regex aren't doing anything.) Or merging the logic so that both hyphens are required if one is present, ``` (?:\d{2}-\d{3}-|\d{5})\d{4} ``` (Your `[0-9]`s can also be replaced with `\d`s.)
How about using a backreference to match the second hyphen only if the first is given: ``` \d{2}(-?)\d{3}\1\d{4} ``` Although I've never used regexes in Java so if it's supported the syntax might be different. I've just tried this out in Ruby.
two regex patterns, can they be one?
[ "", "java", "regex", "" ]
I'm using a [`WriteableBitmap`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.writeablebitmap.aspx) to display images I process myself at around 20 frames per second. This question ([WPF: More efficient way of displaying quickly-changing images?](https://stackoverflow.com/questions/893324/wpf-more-efficient-way-of-displaying-quickly-changing-images)) and this question ([How to display quick-updating images without large memory allocation?](https://stackoverflow.com/questions/812288/how-to-display-quick-updating-images-without-large-memory-allocation)) indicate that the best way to do this is by using a `WriteableBitmap`. The documentation for `WriteableBitmap` indicates that calling `WritePixels()` on the UI thread will cause the rendering thread to redraw the image: **MSDN documentation:** *The UI thread writes content to the back buffer. The render thread reads content from the front buffer and copies it to video memory. Changes to the back buffer are tracked with changed rectangular regions.* *< snip / >* *When updates are sent to the rendering thread, the rendering thread copies the changed rectangles from the back buffer to the front buffer. The rendering system controls this exchange to avoid deadlocks and redraw artifacts, such as "tearing".* I process my images on a background thread, then use `Dispatcher.BeginInvoke()` to call `WritePixels()`, to ensure that `WritePixels()` is called on the UI thread. I'm finding that tearing still occurs with `WriteableBitmap`, and in the application I'm working on, it looks awful (its a medical imaging application). Is there anything I can do?
There was a lot of work put into WriteableBitmap to avoid tearing, but on some system configurations this is unavoidable. This mostly will happen on Windows XP or Vista w/ Aero (DWM) turned off.
While you are calling WritePixels() you may be overwriting your bitmap. Using Dispatcher.Invoke() rather then BeginInvoke() might help.
WPF: How do I prevent tearing with WriteableBitmap?
[ "", "c#", "wpf", ".net-3.5", "artifacts", "tearing", "" ]
Is it possible to use NIO to process the stdout from a Process? I have it working with java.io, but this is something of an exercise to learn a bit more about NIO and to explore the possibility of performance improvements. Basically I want to stream a large volume of text from stdout into a buffer as fast as possible without blocking, and then process the contents of that buffer later. The trouble is, I can't seem to figure out the right voodoo to make it work with NIO. This is where I am right now: ``` ProcessBuilder pb = new ProcessBuilder( ... ); Process p = pb.start(); stdout = new StreamConsumer(p.getInputStream()); new Thread(stdout).start(); // other stuff omitted for brevity ``` The class StreamConsumer looks like this: ``` class StreamConsumer implements Runnable { private InputStream is; public StreamConsumer(InputStream is) { this.is = is; } public void run() { try { ReadableByteChannel source = Channels.newChannel(is); // Is it possible get a channel to a ByteBuffer // or MappedByteBuffer here? WritableByteChannel destination = ??; ByteBuffer buffer = ByteBuffer.allocateDirect(128 * 1024); while (source.read(buffer) != -1) { buffer.flip(); while (buffer.hasRemaining()) { destination.write(buffer); } buffer.clear(); } source.close(); destination.close(); } catch (IOException e) { e.printStackTrace(); } } } ```
Believe it or not, I think the writable byte channel you want is ``` ByteArrayOutputStream ostream = new ByteArrayOutputStream(<some large number>); WritableByteChannel destination = Channels.newChannel(ostream); ``` Then when done ``` ostream.toByteArray() ``` contains the bytes to process. Or, if you want a byte buffer, ``` ByteBuffer.wrap(ostream.toByteArray()) ``` I don't see here how you get the output outside the runnable, but I suspect your original code had that. Otherwise you might want the `StreamConsumer` to be a `Callable<ByteBuffer>`.
I have created an open source library that allows non-blocking I/O between java and your child processes. The library provides an event-driven callback model. It depends on the JNA library to use platform-specific native APIs, such as epoll on Linux, kqueue/kevent on MacOS X, or IO Completion Ports on Windows. The project is called [NuProcess](https://github.com/brettwooldridge/NuProcess) and can be found here: <https://github.com/brettwooldridge/NuProcess>
Is it possible to read the Process stdout InputStream into an NIO ByteBuffer?
[ "", "java", "inputstream", "nio", "bytebuffer", "" ]
Is it possible to introduce ClickOnce functionality to an existing application? The scenario is: Version 1.0 is already installed on client premises. I would like to send them a new setup package which will upgrade to 1.1, which has ClickOnce functionality, thereby making future upgrades "effortless". Barring that, are there any other solutions to this sort of problem? P.S.: The original application was developed with [Visual Studio 2005](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005) (that is, .NET 2.0). I'm using [Visual Studio 2008](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008) now.
No, it is not possible with a standard ClickOnce deployment scenario. ClickOnce is a sandboxed installation on the client side. It will not know about version 1.0 that's already installed. It is simply going to check to see whether its [GUID](http://en.wikipedia.org/wiki/Globally_unique_identifier) has already been installed via ClickOnce and if so update it, but only if the previous version was deployed via ClickOnce. In your case, if the user installed Version 1.1, both versions will be installed side by side. Version 1.0 will not be updated, because ClickOnce doesn't know there's an association since it was deployed via a different method. If they don't want version 1.0 anymore, they'll need to remove it manually. Once you've got version 1.1 deployed via ClickOnce, subsequent updates will work correctly. Don't think of ClickOnce as something you're "including", think of it as a method of deployment. **Alternatively:** I should clarify that what you're looking for is not possible with standard ClickOnce deployment. However, you mentioned you're going to send them an initial setup file. In that case you may have a workaround that's possible: 1. Script the setup file to remove the version 1.0 installation automatically 2. Script the setup file to launch the ClickOnce installation. For subsequent updates, simply point the user to the "pure" ClickOnce setup package, and your updates should work fine.
Make sure to test out your ClickOnce deployment very thoroughly in your client's environment. I am omitting details here, but there are many problems with ClickOnce. I have been supporting a ClickOnce application for 3.5 years now and have run into many problems with manifests, having to manually delete the sandbox storage folders so the updates install correctly, etc. - if you search online for ClickOnce problems you'll find quite a few issues in the MSDN forums and elsewhere, many of which MS does not appear to want to resolve as they've been open since Visual Studio 2005. Also, be aware of a potential gotcha in ClickOnce prior to .NET 3.5 SP1. If you do not have your own software deployment certificate from a [CA](https://en.wikipedia.org/wiki/Certificate_authority) recognized by the client machines, Visual Studio uses a "temporary" certificate (\*.pfx) which expires one year from creation. After that time, subsequent update releases will probably not install, and will show users scary messages about certificate expiration. Microsoft fixed this in .NET 3.5 SP1, but you had to dig through the release notes to find the comments that temporary or permanent certificates were no longer required. So - if you don't have a public CA certificate, and you'll be supporting this application for some time, then make sure you're on .NET 3.5 SP1. Depending on the complexity of your scenario, since you ask about other solutions, we wound up using a "roll your own" approach that goes something like this. Each updated release increments the assembly version as needed. Build contains a custom step to auto-generate a file with the new assembly version. The deployment project copies the version file to the output directory with MSI. Each time the installed application runs, it compares its own version to the version in the version file in the deploy folder. If they differ, quit the application and launch the MSI, which we set to automatically remove older application versions. This is a "poor man's ClickOnce" for an environment where there are no application deployment tools whatsoever avl (not even AD application advertising) so we made do. Again, this approach may not be sophisticated enough for you, but it works fine for us. Best of luck.
Upgrade an existing application to include ClickOnce
[ "", "c#", "visual-studio-2008", "deployment", "clickonce", "automated-deploy", "" ]
Suppose I have a set of column definitions: ``` Col1: value11 value12 value13 Col2: value21 value22 Col3: value31 value32 value33 ... ``` Given some subset of columns -- 2 or more -- I want to find all possible values for those columns. Suppose I choose columns 1 and 2, above: ``` (value11 value21) (value11 value22) (value12 value21) (value12 value22) (value13 value21) (value13 value22) ``` If I'd chosen 2:3: ``` (value21 value31) (value21 value32) (value21 value33) (value22 value31) (value22 value32) (value22 value33) ``` If I'd chosen all three: ``` (value11 value21 value31) (value11 value21 value32) ... ``` I'm implementing this in python, and I'd like a *fast* algorithm to do this. My input is a list of tuples: (columnName, columnValueList) Any suggestions?
The best way to get this is going to be using itertools.product(). For example: ``` import itertools group1 = ['a', 'b'] group2 = ['c', 'd'] print list(itertools.product(group1, group2)) #==> [('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd')] ``` This function accepts multiple arguments (i.e. multiple columns). For more help on iterools.product() see [this](http://docs.python.org/library/itertools.html#itertools.product).
more general solutions that Jeremy's would be: ``` import itertools full = [[value11, value12, value13], [value21, value22], [value31, value32, value33]] ids = 0, 2 ``` or if it is a dict (as it should be): ``` full = {'col1': [value11, value12, value13], 'col2': [value21, value22], 'col3': [value31, value32, value33]} ids = 'col1', 'col3' selected = (full[i] for i in ids) list(itertools.product(*selected)) ```
How do I build a list of all possible tuples from this table?
[ "", "python", "algorithm", "" ]
I have an array of java objects. * Each object stores two longs that define a number range. * I already have a guarantee that for all the objects in the range, the number ranges don't overlap. I want a quick of finding a particular object in the array, given a number which may (or may not) fall within one of the number ranges defined by the objects. I was hoping to do this using Array.binarySearch but that doesn't look appropriate. Any thoughts on the best way to do this?
Use a TreeMap. The key is the lower of the two Long range bounds; the value is the object. ``` private TreeMap<Long, T> map = new TreeMap<Long, T>(); void insertObject(T object) { map.put(object, object.getLowerRangeBoundary()); } T getObjectByKeyInRange(Long query) { // Get the first Object in the tree that corresponds with the query Map.Entry<Long, T> e = map.floorEntry(query); // If there's no entry, then the query value is lower than all ranges in the tree if (e == null) { return null; } T target = e.getValue(); // "target" is the only object that can contain the query value // If the query value is within the range of "target", then it is our object if (query < target.getUpperRangeBoundary()) { return target; } // Nobody has the query value in their range; return null return null; } ```
Have the items in the array implement the Comparable interface, by letting item a be bigger than the other item b if a.start > b.end. Then sort the array using this comparison. Then to find if a number x is in a range in a item in the array, do a search in the array for the first item k with k.end >= x, and check if k.start <= x. If so, k is the range. Else, x is not in any range in the array.
How to find if a number is contained in an array of number ranges in java
[ "", "java", "arrays", "search", "" ]
I came across this problem in javabat(<http://www.javabat.com/prob/p183562>): > We want to make a row of bricks that > is goal inches long. We have a number > of small bricks (1 inch each) and big > bricks (5 inches each). Return true if > it is possible to make the goal by > choosing from the given bricks. This > is a little harder than it looks and > can be done without any loops. > > makeBricks(3, 1, 8) → true > makeBricks(3, 1, 9) → false > makeBricks(3, 2, 10) → true I came up with this solution: ``` public boolean makeBricks(int small, int big, int goal) { if (goal > small + big * 5) return false; else if (goal % 5 == 0) return goal / 5 <= big; else return goal % 5 <= small; } ``` This passed the test. But I found a counter-example myself: makeBricks(10, 0, 10) -> true. My logic will return false. How should I fix my logic? Or is there a better way to do this?
I think you can just remove your second test. I would try this: ``` public boolean makeBricks(int small, int big, int goal) { if (goal > small + big * 5) return false; else return goal % 5 <= small; } ``` The first test just checks how long the row would be if we just put *all* the bricks in a row. If that's not as long as the goal, then we know that it's impossible. Next, we calculate the minimum number of small bricks: `goal % 5`. For example, if the goal is 8 and we have 1000 large bricks, how many small bricks do we need? `8 % 5` is 3, so we need 3 small bricks at the end of the row. If we have enough small bricks, and the total length of all the bricks is enough, then we can meet the goal.
Your logic is incorrect. This should do it: ``` public boolean makeBricks(int small, int big, int goal) { if (goal < 0 || big < 0 || small < 0) { throw new IllegalArgumentException(); } else if (goal > big * 5 + small) { return false; } else if (goal % 5 <= small) { return true; } else { return false; } } ``` is sufficient. This can be simplified to: ``` public boolean makeBricks(int small, int big, int goal) { if (goal < 0 || big < 0 || small < 0) { throw new IllegalArgumentException(); } else { return goal <= big * 5 + small && goal % 5 <= small; } } ``` Of course, the sanity check on negative goal, small or big is not strictly required but recommended. Without those checks, the result can simply be obtained by: ``` public boolean makeBricks(int small, int big, int goal) { return goal <= big * 5 + small && goal % 5 <= small; } ```
A java practice problem
[ "", "java", "logic", "" ]
If I have a JavaScript object such as: ``` var list = { "you": 100, "me": 75, "foo": 116, "bar": 15 }; ``` Is there a way to sort the properties based on value? So that I end up with ``` list = { "bar": 15, "me": 75, "you": 100, "foo": 116 }; ```
Move them to an array, sort that array, and then use that array for your purposes. Here's a solution: ``` let maxSpeed = { car: 300, bike: 60, motorbike: 200, airplane: 1000, helicopter: 400, rocket: 8 * 60 * 60 }; let sortable = []; for (var vehicle in maxSpeed) { sortable.push([vehicle, maxSpeed[vehicle]]); } sortable.sort(function(a, b) { return a[1] - b[1]; }); // [["bike", 60], ["motorbike", 200], ["car", 300], // ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]] ``` --- Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object. ``` let objSorted = {} sortable.forEach(function(item){ objSorted[item[0]]=item[1] }) ``` --- In ES8, you can use [`Object.entries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) to convert the object into an array: ``` const maxSpeed = { car: 300, bike: 60, motorbike: 200, airplane: 1000, helicopter: 400, rocket: 8 * 60 * 60 }; const sortable = Object.entries(maxSpeed) .sort(([,a],[,b]) => a-b) .reduce((r, [k, v]) => ({ ...r, [k]: v }), {}); console.log(sortable); ``` --- In ES10, you can use [`Object.fromEntries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) to convert array to object. Then the code can be simplified to this: ``` const maxSpeed = { car: 300, bike: 60, motorbike: 200, airplane: 1000, helicopter: 400, rocket: 8 * 60 * 60 }; const sortable = Object.fromEntries( Object.entries(maxSpeed).sort(([,a],[,b]) => a-b) ); console.log(sortable); ```
We don't want to duplicate the entire data structure, or use an array where we need an associative array. Here's another way to do the same thing as bonna: ``` var list = {"you": 100, "me": 75, "foo": 116, "bar": 15}; keysSorted = Object.keys(list).sort(function(a,b){return list[a]-list[b]}) console.log(keysSorted); // bar,me,you,foo ```
Sorting object property by values
[ "", "javascript", "sorting", "properties", "object", "" ]
I have table A and table B, same schemas. I want to insert certain rows from table A into table B. For example, insert into table B all rows from table A with column 'abc' > 10. Couldn't figure out how to do it
Something like this ``` INSERT INTO B (supplier_id, supplier_name) SELECT supplier_id, supplier_name FROM A WHERE abc > 10; ``` Make sense?
You can use the following notation: ``` BEGIN TRAN INSERT INTO ExistingTable (Col1, Col2...) SELECT Something1, Something2... FROM Table1 WHERE ... --ROLLBACK/COMMIT ```
Insert a part of a table into another table
[ "", "sql", "" ]
We have native Win32 C++ code and a set of C# assemblies which we wish to call from the C++ code. I summaries our optios as: 1. Use COM. The C# code would need to be decorated with additional attributes (GUID, COMVisible). The C# assemblies would need to be registered regasm and would then be available to the native C++ code via COM. 2. Use a C++/CLI (formerly managed C++) wrapper class. A C++ class could be added to the native C++ project. That class would be compiled with /clr. The native C++ code would call the C++/CLI class which would then call the .Net code. No COM involved. The CLR is started by magic as required with marshalling handled by the C++/CLI extenstions. 3. Host an instance of the CLR in the native C++ code. I'm going to discount option 3 as I don't see the benefits over option 2 other than we lose the need for a wrapper class. So the question is, what are the pros/cons of option 1 versus option 2? Thanks in advance.
Option 2 will perform the best, and be the most seamless and maintainable, IMO. There is really no advantage to option 1 that I've found. Using C++/CLI seems to function much better, work faster, and be much simpler in general. You also can, btw, just use the C# assembly directly without having a wrapper class. This does require compiling any files that want to use it with /CLR, but it works quite well.
For option 1 your main pro would be not having to write a wrapper class which can get hairy depending on your project. For option 2 you won't have to modify your managed library to facilitate unmanaged use, which is sometimes not an option. For me it comes down to where you want to make your code changes.
C++ calling C# options
[ "", "c#", "com", "c++-cli", "com-interop", "managed-c++", "" ]