text
stringlengths
8
267k
meta
dict
Q: Integration Testing Http Proxy Server I have written a simple HTTP Proxy server in C# that I would like to integration/functional test. Is there a product already created that I could use to do this? If not, what is the best way to write my own tests for this (I already have unit tests)? A: To test the integration by delivering a webpage you could try one of the following: * *Selenium *WaTiN *Watir You can run Watin tests directly from xUnit in C# too - we do this for our applications. I also believe it is possible to dynamically set the proxy settings in the browser for Watin (and probably the others too). Alternatively to make HTTP requests to a given address try JMeter. A: Slightly offtopic: Having seen a share of custom HTTP proxies, the usual feature their authors forget (and later discover that they need) is the support for the CONNECT method. Without CONNECT your proxy can't be used for TLS/SSL connections. Also, software that tunnels their non-HTTP traffic via the proxy won't work either. A: There are two more products to use: * *Web Polygraph *Funkload Both are easy to find via Google. Both perform functional and load testing of web servers/proxies. A: When you're using the above, I'd also suggest running one of the latency/packet loss injection tools discussed in Best way to simulate a WAN network. It's regrettably easy to decide that your proxy is stable when you test it in a non-messy environment.
{ "language": "en", "url": "https://stackoverflow.com/questions/104097", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: When to use Windows Workflow Foundation? Some things are easier to implement just by hand (code), but some are easier through WF. It looks like WF can be used to create (almost) any kind of algorithm. So (theoretically) I can do all my logic in WF, but it's probably a bad idea to do it for all projects. In what situations is it a good idea to use WF and when will it make things harder then they have to be? What are pros and cons/cost of WF vs. coding by hand? A: Never. You will probably regret it: * *Steep learning curve *Difficult to debug *Difficult to maintain *Doesn't provide enough power, flexibility, or productivity gain to justify its use *Can and will corrupt application state that cannot be recovered The only time I could ever conceive of using WF is if I wanted to host the designer for an end-user and probably not even then. Trust me, nothing will ever be as straightforward, powerful, or flexible as the code that you write to do exactly what you need it to do. Stay away from WF. Of course, this is only my opinion, but I think it's a damn good one. :) A: The company I am currently working for set up a Windows Workflow Foundation (WF) and the reasons they chose to use it was because the rules would frequently be changing and that would force them to do a recompile of the various dll's etc and so their solution was to place the rules in the DB and call them from there. This way they could change the rules and not have to recompile and redistribute the dlls etc. A: Windows Workflows seduce non-coding IT managers, BAs and the like as does its cousin BizTalk but in practice unit testing, debugging and code coverage are just three of the many pitfalls. You can overcome some of them but you have to invest heavily in achieving that whereas with plain code you just get that. If you genuinely have a long-running requirement then you probably need something more sophisticated. I've heard the argument about being able to drop new xaml files into production without re-compiling dlls but honestly the time that Workflows will consume could be better used to improve your Continuous Integration to the point where compiled deploys aren't a problem. A: The code generated by WF is nasty. The value that WF brings is in the visual representation of the system, although I have yet to see anything (6-7 projects at work now with WF that i've been involved with) where I would not have preferred a simpler hand coded project. A: In general, if you do not need the persistence and tracking features (which in my opinion are the main features), you shouldn't use Workflow Foundation. Here are the advantages and disadvantages of Workflow Foundation I gathered from my experience: Advantages * *Persistence: If you're going to have many long running processes (think days, weeks, months), then Workflows are great for this. Idle workflow instances are persisted to the database so it doesn't use up memory. *Tracking: WF provides the mechanism to track each activity executed in a workflow **Visual Designer: I put this as a *, because I think this is really only useful for marketing purposes. As a developer, I prefer to write code rather than snapping things together visually. And when you have a non-developer making workflows, you often end up with a huge confusing mess. Disadvantages * *Programming Model: You're really limited in programming features. Think about all the great features you have in C#, then forget about them. Simple one or two line statements in C# becomes a fairly large block activities. This is particularly a pain for input validation. Having said that, if you're really careful to keep only high-level logic in workflows, and everything else in C#, then it might not be a problem. *Performance: Workflows use up a large amount of memory. If you're deploying a lot of workflows on a server, make sure you have tons of memory. Also be aware that workflows are much slower than normal C# code. *Steep learning curve, hard to debug: As mentioned above. You're going to spend a lot of time figuring out how to get things to work, and figuring out the best way to do something. *Workflow Version Incompatibility: If you deploy a workflow with persistence, and you need to make updates to the workflow, the old workflow instances are no longer compatible. Supposedly this is fixed in .NET 4.5. *You have to use VB expressions (.NET 4.5 allows for C# expressions). *Not flexible: If you need some special or specific functionality not provided by Workflow Foundation, prepare for a lot of pain. In some cases, it might not even be possible. Who knows until you try? There's a lot of risk here. *WCF XAML services without interfaces: Normally with WCF services, you develop against an interface. With WCF XAML Services, you cannot ensure a WCF XAML Service has implemented everything in an interface. You don't even need to define an interface. (as far as I know...) A: I would use it in any environment where I need to work with workflow, however when using it in conjuction with K2 or even SharePoint 2007 the power of the platform is truly useful. When developing business applications with BI specialist the use of the platform is recommended and this would normally only be relevant to streamline and improve business processes. For the record WF was developed in conjunction with K2's development team and the new K2 Blackpearl is built on top of WF, so is MOSS 2007 and WSS 3.0's workflow engines. A: The major reason I've found for using workflow foundation is how much it brings you out of the box in terms of tracking and persistence. It's very easy to get the persistence service up and running, which brings reliability and load distribution between multiple instances and hosts. On the other hand, just like forms apps, the code patterns that the workflow designer pushes you towards are bad. But you can avoid problems by writing no code in the workflow and delegating all work to other classes, which can be organized and unit tested more gracefully than the workflow. Then you get the cool visual aspect of the designer without the cruft of spaghetti code behind. A: When you don't want to manually write all those codes to maintain the visual interface, tracking and persistence, it's a wise choice to vote for WF. A: You may need WF only if any of the following are true: * *You have a long-running process. *You have a process that changes frequently. *You want a visual model of the process. For more details, see Paul Andrew's post: What to use Windows Workflow Foundation for? Please do not confuse or relate WF with visual programming of any kind. It is wrong and can lead to very bad architecture/design decisions. A: Personally, I'm not sold on WF. It's usefulness wasn't as obvious to me as other new MS technologies, like WPF or WCF. I think WF will be used heavily in business applications in the future, but I have no plans to use it because it doesn't seem like the right tool for the job for my projects. A: I have been using Windows workflow for months now to develop custom activities and a re-hosted designer that non-developers can use to build workflows. WF is very powerful but it is only as good as the custom activities that are built by developers. When it comes down to it, a developer would have to look over workflows built by non-developers to test and debug but from the point they can create draft workflows- that is fantastic. Furthermore, in cases where you have long running processes WF is a good tech stack to use when you need to update processes dynamically - without having to reinstall/download or do anything, just add the new XAML files to a directory and your architecture should be set up with versioning to scrap the old one and use the new one.
{ "language": "en", "url": "https://stackoverflow.com/questions/104099", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "155" }
Q: Lowest cost Windows VPS hosting? For a while, I thought I'd host stuff at home because I can do whatever I want. However, hurricane Ike knocked out my power for a week, and I've finally realized this situation won't work. I have extremely low traffice websites (20 visitors/day), so I don't need tons of CPU or bandwidth. What cheap options are there for VPS hosting that will give me flexiblity to do what I need to configure my server, but not cost very much. A: RapidVPS offers windows hosting. $29,99/month https://www.rapidvps.com/index.php?page=Hosting.Windows.Specs I am a customer of their linux vps hosting and have had zero problems. A: I use Applied Innovations for my .NET hosting. They seem to have cheap VPS as well. I've never noticed a downtime,and their billing and support has been reliable. A: Check out KickAssVPS I have had a Windows VPS with them for over a year now. http://www.kickassvps.com/ I have the $35 package which is 960 MB RAM 10GB Space 100GB Transfer A: http://www.ajkservers.co.uk Get high quality VPS from them :) They support linux.
{ "language": "en", "url": "https://stackoverflow.com/questions/104106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you increase the maximum heap size for the javac process in Borland JBuilder 2005/2006 In most modern IDEs there is a parameter that you can set to ensure javac gets enough heap memory to do its compilation. For reasons that are not worth going into here, we are tied for the time being to JBuilder 2005/2006, and it appears the amount of source code has exceeded what can be handled by javac. Please keep the answer specific to JBuilder 2005/2006 javac (we cannot migrate away right now, and the Borland Make compiler does not correctly support Java 1.6) I realize how and what parameters should be passed to javac, the problem is the IDE doesn't seem to allow these to be set anywhere. A lot of configuration is hidden down in the Jbuilder Install\bin*.config files, I feel the answer may be in there somewhere, but have not found it. A: did you find a good solution for that problem? I have the same problem and the only solution I found is the following: The environment variable JAVA_TOOL_OPTIONS can be used to provide parameters for the JVM. http://java.sun.com/javase/6/docs/platform/jvmti/jvmti.html#tooloptions I have created a batch file "JBuilderw.bat" with the following content: set JAVA_TOOL_OPTIONS=-Xmx256m JBuilderw.exe Each time I start JBuilder using this batch file the env.var. JAVA_TOOL_OPTIONS will be set and javac.exe will receive the setting. The JVM displays at the end the following message: "Picked up JAVA_TOOL_OPTIONS: -Xmx256m" Drawback: all virtual machines started by JBuilder will get that setting. :( Thanks, JB A: Have a look at http://javahowto.blogspot.com/2006/06/fix-javac-java-lang-outofmemoryerror.html The arguments that you need to pass to JBuilder's javac is "-J-Xms256m -J-Xmx256m". Replace the 256m with whatever is appropriate in your case. Also, remove the quotes. This should work for java 1.4, java 1.5 and forward. BR, ~A A: "I realize how and what parameters should be passed to javac, the problem is the IDE doesn't seem to allow these to be set anywhere." I realized now that you know how to pass the right arguments ONLY not where/how to pass those arguments :-( How about this : Can you locate where is the JAVA_HOME/bin directory that borland uses ? If yes, then you can rename the javac.exe(to say javacnew.exe) with a javac.bat which in turn will call the javacnew.exe (as well as pass the required arguments) ? A: I don't know if this will help since I don't use Borland but in Eclipse, this is a setting that you attach to the program you're going to run. Each program you run in the IDE has configuration specific to it, including arguments to the VM. Is there something like that? A: Do you have a jdk.config file located in JBuilder2005/bin/? You should be able to modify vm parameters in that file like: vmparam -Xms256m vmparam -Xmx256m Let me know if this works, I found it on a page talking about editing related settings in JBuilder 2005. A: Edit the jbuilder.config file. Put in comment those two lines: * *vmmemmax 75% *vmmemmin 32m has they ought to be <1Gb and with a > 1Gb PC , 75% is too big?
{ "language": "en", "url": "https://stackoverflow.com/questions/104115", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Maximum # of Results in a Sitecore Droplink field? In Sitecore 6, one of my templates contains a "Droplink" field bound to the results of a particular sitecore query. This query currently returns approximately 200 items. When I look at an item that implements this template in the content editor, I can only see the first 50 items in the field's dropdown list. How do I display all of the items returned from this query in the editor's dropdown? A: There is a setting in the web.config that controls the max number of items that can be returned by a query: <setting name="Query.MaxItems" value="100" /> By default, it's set to 100 so I'm not quite sure why your query is only returning 50, perhaps someone else changed the setting? Also, be wary of a performance hit when returning more than 100 items. Depending on your hardware and overall Sitecore architecture it may not be that noticeable, but just something to be wary of.
{ "language": "en", "url": "https://stackoverflow.com/questions/104121", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Finding GDI/User resource usage from a crash dump I have a crash dump of an application that is supposedly leaking GDI. The app is running on XP and I have no problems loading it into WinDbg to look at it. Previously we have use the Gdikdx.dll extension to look at Gdi information but this extension is not supported on XP or Vista. Does anyone have any pointers for finding GDI object usage in WinDbg. Alternatively, I do have access to the failing program (and its stress testing suite) so I can reproduce on a running system if you know of any 'live' debugging tools for XP and Vista (or Windows 2000 though this is not our target). A: I've spent the last week working on a GDI leak finder tool. We also perform regular stress testing and it never lasted longer than a day's worth w/o stopping due to user/gdi object handle overconsumption. My attempts have been pretty successful as far as I can tell. Of course, I spent some time beforehand looking for an alternative and quicker solution. It is worth mentioning, I had some previous semi-lucky experience with the GDILeaks tool from msdn article mentioned above. Not to mention that i had to solve a few problems prior to putting it to work and this time it just didn't give me what and how i wanted it. The downside of their approach is the heavyweight debugger interface (it slows down the researched target by orders of magnitude which I found unacceptable). Another downside is that it did not work all the time - on some runs I simply could not get it to report/compute anything! Its complexity (judging by the amount of code) was another scare-away factor. I'm not a big fan of GUIs, as it is my belief that I'm more productive with no windows at all ;o). I also found it hard to make it find and use my symbols. One more tool I used before setting on to write my own, was the leakbrowser. Anyways, I finally settled on an iterative approach to achieve following goals: * *minor performance penalties *implementation simplicity *non-invasiveness (used for multiple products) *relying on as much available as possible I used detours (non-commercial use) for core functionality (it is an injectible DLL). Put Javascript to use for automatic code generation (15K script to gen 100K source code - no way I code this manually and no C preprocessor involved!) plus a windbg extension for data analysis and snapshot/diff support. To tell the long story short - after I was finished, it was a matter of a few hours to collect information during another stress test and another hour to analyze and fix the leaks. I'll be more than happy to share my findings. P.S. some time did I spend on trying to improve on the previous work. My intention was minimizing false positives (I've seen just about too many of those while developing), so it will also check for allocation/release consistency as well as avoid taking into account allocations that are never leaked. Edit: Find the tool here A: There was a MSDN Magazine article from several years ago that talked about GDI leaks. This points to several different places with good information. In WinDbg, you may also try the !poolused command for some information. Finding resource leaks in from a crash dump (post-mortem) can be difficult -- if it was always the same place, using the same variable that leaks the memory, and you're lucky, you could see the last place that it will be leaked, etc. It would probably be much easier with a live program running under the debugger. You can also try using Microsoft Detours, but the license doesn't always work out. It's also a bit more invasive and advanced. A: I have created a Windbg script for that. Look at the answer of Command to get GDI handle count from a crash dump To track the allocation stack you could set a ba (Break on Access) breakpoint past the last allocated GDICell object to break just at the point when another GDI allocation happens. That could be a bit complex because the address changes but it could be enough to find pretty much any leak.
{ "language": "en", "url": "https://stackoverflow.com/questions/104122", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Using multiple web projects with different languages in Visual Studio I need to combine a VB web project and a C# web project and have them run alongside each other in the same web root. For instance, I need to be able to navigate to localhost:1234/vbProjPage.aspx and then redirect to localhost:1234/cSharpProjPage.aspx. Is this possible from within Visual Studio 2008? I know you have the ability to create a web site and throw everything into the root, but it would be best in this scenario to keep each project separate from each other. UPDATE: To answer Wes' question, it is possible but not desirable to change paths like that (/vb/vbPage.aspx & /cs/csPage.aspx) UPDATE: Travis suggested using sub-web projects. This link explains how to do it but the solution involves putting a project inside of a project, that is exactly what I am trying to avoid. I need the projects physically separated. A: You can do this using sub-web projects. This has been available in Visual Studio since 2005 and works with the Web Application Project style of web site. ScottGu has a great blog entry describing the process. You may face some interesting challenges getting pages to commingle in the same folder, but the sub-web project structure should still lend you some ideas. A: I don't think you'll be able to have two seperate projects but intermixing them within one project isn't a problem. You could always organize the files into folder to keep things seperate if you felt the need. A: Just out of curiosity, would changing your url paths be out of the question? Instead of 1234/vbpage and 1234/cspage how about something like 1234/vb/page and 1234/cs/page ? I know you said same web root, but I'm just curious :) A: you could use URL re-writting with a filter to look for "cs" or "vb" at the begining of each file and direct it to the appropriate directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/104133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is "Best Practice" For Comparing Two Instances of a Reference Type? I came across this recently, up until now I have been happily overriding the equality operator (==) and/or Equals method in order to see if two references types actually contained the same data (i.e. two different instances that look the same). I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned). While looking over some of the coding standards guidelines in MSDN I came across an article that advises against it. Now I understand why the article is saying this (because they are not the same instance) but it does not answer the question: * *What is the best way to compare two reference types? *Should we implement IComparable? (I have also seen mention that this should be reserved for value types only). *Is there some interface I don't know about? *Should we just roll our own?! Many Thanks ^_^ Update Looks like I had mis-read some of the documentation (it's been a long day) and overriding Equals may be the way to go.. If you are implementing reference types, you should consider overriding the Equals method on a reference type if your type looks like a base type such as a Point, String, BigNumber, and so on. Most reference types should not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you should override the equality operator. A: That article just recommends against overriding the equality operator (for reference types), not against overriding Equals. You should override Equals within your object (reference or value) if equality checks will mean something more than reference checks. If you want an interface, you can also implement IEquatable (used by generic collections). If you do implement IEquatable, however, you should also override equals, as the IEquatable remarks section states: If you implement IEquatable<T>, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable<T>.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals method return consistent results. In regards to whether you should implement Equals and/or the equality operator: From Implementing the Equals Method Most reference types should not overload the equality operator, even if they override Equals. From Guidelines for Implementing Equals and the Equality Operator (==) Override the Equals method whenever you implement the equality operator (==), and make them do the same thing. This only says that you need to override Equals whenever you implement the equality operator. It does not say that you need to override the equality operator when you override Equals. A: Implementing equality in .NET correctly, efficiently and without code duplication is hard. Specifically, for reference types with value semantics (i.e. immutable types that treat equvialence as equality), you should implement the System.IEquatable<T> interface, and you should implement all the different operations (Equals, GetHashCode and ==, !=). As an example, here’s a class implementing value equality: class Point : IEquatable<Point> { public int X { get; } public int Y { get; } public Point(int x = 0, int y = 0) { X = x; Y = y; } public bool Equals(Point other) { if (other is null) return false; return X.Equals(other.X) && Y.Equals(other.Y); } public override bool Equals(object obj) => Equals(obj as Point); public static bool operator ==(Point lhs, Point rhs) => object.Equals(lhs, rhs); public static bool operator !=(Point lhs, Point rhs) => ! (lhs == rhs); public override int GetHashCode() => X.GetHashCode() ^ Y.GetHashCode(); } The only movable parts in the above code are the bolded parts: the second line in Equals(Point other) and the GetHashCode() method. The other code should remain unchanged. For reference classes that do not represent immutable values, do not implement the operators == and !=. Instead, use their default meaning, which is to compare object identity. The code intentionally equates even objects of a derived class type. Often, this might not be desirable because equality between the base class and derived classes is not well-defined. Unfortunately, .NET and the coding guidelines are not very clear here. The code that Resharper creates, posted in another answer, is susceptible to undesired behaviour in such cases because Equals(object x) and Equals(SecurableResourcePermission x) will treat this case differently. In order to change this behaviour, an additional type check has to be inserted in the strongly-typed Equals method above: public bool Equals(Point other) { if (other is null) return false; if (other.GetType() != GetType()) return false; return X.Equals(other.X) && Y.Equals(other.Y); } A: It looks like you're coding in C#, which has a method called Equals that your class should implement, should you want to compare two objects using some other metric than "are these two pointers (because object handles are just that, pointers) to the same memory address?". I grabbed some sample code from here: class TwoDPoint : System.Object { public readonly int x, y; public TwoDPoint(int x, int y) //constructor { this.x = x; this.y = y; } public override bool Equals(System.Object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; if ((System.Object)p == null) { return false; } // Return true if the fields match: return (x == p.x) && (y == p.y); } public bool Equals(TwoDPoint p) { // If parameter is null return false: if ((object)p == null) { return false; } // Return true if the fields match: return (x == p.x) && (y == p.y); } public override int GetHashCode() { return x ^ y; } } Java has very similar mechanisms. The equals() method is part of the Object class, and your class overloads it if you want this type of functionality. The reason overloading '==' can be a bad idea for objects is that, usually, you still want to be able to do the "are these the same pointer" comparisons. These are usually relied upon for, for instance, inserting an element into a list where no duplicates are allowed, and some of your framework stuff may not work if this operator is overloaded in a non-standard way. A: For complex objects that will yield specific comparisons then implementing IComparable and defining the comparison in the Compare methods is a good implementation. For example we have "Vehicle" objects where the only difference may be the registration number and we use this to compare to ensure that the expected value returned in testing is the one we want. A: Below I have summed up what you need to do when implementing IEquatable and provided the justification from the various MSDN documentation pages. Summary * *When testing for value equality is desired (such as when using objects in collections) you should implement the IEquatable interface, override Object.Equals, and GetHashCode for your class. *When testing for reference equality is desired you should use operator==,operator!= and Object.ReferenceEquals. *You should only override operator== and operator!= for ValueTypes and immutable reference types. Justification IEquatable The System.IEquatable interface is used to compare two instances of an object for equality. The objects are compared based on the logic implemented in the class. The comparison results in a boolean value indicating if the objects are different. This is in contrast to the System.IComparable interface, which return an integer indicating how the object values are different. The IEquatable interface declares two methods that must be overridden. The Equals method contains the implementation to perform the actual comparison and return true if the object values are equal, or false if they are not. The GetHashCode method should return a unique hash value that may be used to uniquely identify identical objects that contain different values. The type of hashing algorithm used is implementation-specific. IEquatable.Equals Method * *You should implement IEquatable for your objects to handle the possibility that they will be stored in an array or generic collection. *If you implement IEquatable you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method Guidelines for Overriding Equals() and Operator == (C# Programming Guide) * *x.Equals(x) returns true. *x.Equals(y) returns the same value as y.Equals(x) *if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true. *Successive invocations of x. Equals (y) return the same value as long as the objects referenced by x and y are not modified. *x. Equals (null) returns false (for non-nullable value types only. For more information, see Nullable Types (C# Programming Guide).) *The new implementation of Equals should not throw exceptions. *It is recommended that any class that overrides Equals also override Object.GetHashCode. *Is is recommended that in addition to implementing Equals(object), any class also implement Equals(type) for their own type, to enhance performance. By default, the operator == tests for reference equality by determining whether two references indicate the same object. Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. It is not a good idea to override operator == in non-immutable types. * *Overloaded operator == implementations should not throw exceptions. *Any type that overloads operator == should also overload operator !=. == Operator (C# Reference) * *For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. *For reference types other than string, == returns true if its two operands refer to the same object. *For the string type, == compares the values of the strings. *When testing for null using == comparisons within your operator== overrides, make sure you use the base object class operator. If you don't, infinite recursion will occur resulting in a stackoverflow. Object.Equals Method (Object) If your programming language supports operator overloading and if you choose to overload the equality operator for a given type, that type must override the Equals method. Such implementations of the Equals method must return the same results as the equality operator The following guidelines are for implementing a value type: * *Consider overriding Equals to gain increased performance over that provided by the default implementation of Equals on ValueType. *If you override Equals and the language supports operator overloading, you must overload the equality operator for your value type. The following guidelines are for implementing a reference type: * *Consider overriding Equals on a reference type if the semantics of the type are based on the fact that the type represents some value(s). *Most reference types must not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator. Additional Gotchas * *When overriding GetHashCode() make sure you test reference types for NULL before using them in the hash code. *I ran into a problem with interface-based programming and operator overloading described here: Operator Overloading with Interface-Based Programming in C# A: I tend to use what Resharper automatically makes. for example, it autocreated this for one of my reference types: public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == typeof(SecurableResourcePermission) && Equals((SecurableResourcePermission)obj); } public bool Equals(SecurableResourcePermission obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.ResourceUid == ResourceUid && Equals(obj.ActionCode, ActionCode) && Equals(obj.AllowDeny, AllowDeny); } public override int GetHashCode() { unchecked { int result = (int)ResourceUid; result = (result * 397) ^ (ActionCode != null ? ActionCode.GetHashCode() : 0); result = (result * 397) ^ AllowDeny.GetHashCode(); return result; } } If you want to override == and still do ref checks, you can still use Object.ReferenceEquals. A: Microsoft appears to have changed their tune, or at least there is conflicting info about not overloading the equality operator. According to this Microsoft article titled How to: Define Value Equality for a Type: "The == and != operators can be used with classes even if the class does not overload them. However, the default behavior is to perform a reference equality check. In a class, if you overload the Equals method, you should overload the == and != operators, but it is not required." According to Eric Lippert in his answer to a question I asked about Minimal code for equality in C# - he says: "The danger you run into here is that you get an == operator defined for you that does reference equality by default. You could easily end up in a situation where an overloaded Equals method does value equality and == does reference equality, and then you accidentally use reference equality on not-reference-equal things that are value-equal. This is an error-prone practice that is hard to spot by human code review. A couple years ago I worked on a static analysis algorithm to statistically detect this situation, and we found a defect rate of about two instances per million lines of code across all codebases we studied. When considering just codebases which had somewhere overridden Equals, the defect rate was obviously considerably higher! Moreover, consider the costs vs the risks. If you already have implementations of IComparable then writing all the operators is trivial one-liners that will not have bugs and will never be changed. It's the cheapest code you're ever going to write. If given the choice between the fixed cost of writing and testing a dozen tiny methods vs the unbounded cost of finding and fixing a hard-to-see bug where reference equality is used instead of value equality, I know which one I would pick." The .NET Framework will not ever use == or != with any type that you write. But, the danger is what would happen if someone else does. So, if the class is for a 3rd party, then I would always provide the == and != operators. If the class is only intended to be used internally by the group, I would still probably implement the == and != operators. I would only implement the <, <=, >, and >= operators if IComparable was implemented. IComparable should only be implemented if the type needs to support ordering - like when sorting or being used in an ordered generic container like SortedSet. If the group or company had a policy in place to not ever implement the == and != operators - then I would of course follow that policy. If such a policy were in place, then it would be wise to enforce it with a Q/A code analysis tool that flags any occurrence of the == and != operators when used with a reference type. A: I believe getting something as simple as checking objects for equality correct is a bit tricky with .NET's design. For Struct 1) Implement IEquatable<T>. It improves performance noticeably. 2) Since you're having your own Equals now, override GetHashCode, and to be consistent with various equality checking override object.Equals as well. 3) Overloading == and != operators need not be religiously done since the compiler will warn if you unintentionally equate a struct with another with a == or !=, but its good to do so to be consistent with Equals methods. public struct Entity : IEquatable<Entity> { public bool Equals(Entity other) { throw new NotImplementedException("Your equality check here..."); } public override bool Equals(object obj) { if (obj == null || !(obj is Entity)) return false; return Equals((Entity)obj); } public static bool operator ==(Entity e1, Entity e2) { return e1.Equals(e2); } public static bool operator !=(Entity e1, Entity e2) { return !(e1 == e2); } public override int GetHashCode() { throw new NotImplementedException("Your lightweight hashing algorithm, consistent with Equals method, here..."); } } For Class From MS: Most reference types should not overload the equality operator, even if they override Equals. To me == feels like value equality, more like a syntactic sugar for Equals method. Writing a == b is much more intuitive than writing a.Equals(b). Rarely we'll need to check reference equality. In abstract levels dealing with logical representations of physical objects this is not something we would need to check. I think having different semantics for == and Equals can actually be confusing. I believe it should have been == for value equality and Equals for reference (or a better name like IsSameAs) equality in the first place. I would love to not take MS guideline seriously here, not just because it isn't natural to me, but also because overloading == doesn't do any major harm. That's unlike not overriding non-generic Equals or GetHashCode which can bite back, because framework doesn't use == anywhere but only if we ourself use it. The only real benefit I gain from not overloading == and != will be the consistency with design of the entire framework over which I have no control of. And that's indeed a big thing, so sadly I will stick to it. With reference semantics (mutable objects) 1) Override Equals and GetHashCode. 2) Implementing IEquatable<T> isn't a must, but will be nice if you have one. public class Entity : IEquatable<Entity> { public bool Equals(Entity other) { if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(null, other)) return false; //if your below implementation will involve objects of derived classes, then do a //GetType == other.GetType comparison throw new NotImplementedException("Your equality check here..."); } public override bool Equals(object obj) { return Equals(obj as Entity); } public override int GetHashCode() { throw new NotImplementedException("Your lightweight hashing algorithm, consistent with Equals method, here..."); } } With value semantics (immutable objects) This is the tricky part. Can get easily messed up if not taken care.. 1) Override Equals and GetHashCode. 2) Overload == and != to match Equals. Make sure it works for nulls. 2) Implementing IEquatable<T> isn't a must, but will be nice if you have one. public class Entity : IEquatable<Entity> { public bool Equals(Entity other) { if (ReferenceEquals(this, other)) return true; if (ReferenceEquals(null, other)) return false; //if your below implementation will involve objects of derived classes, then do a //GetType == other.GetType comparison throw new NotImplementedException("Your equality check here..."); } public override bool Equals(object obj) { return Equals(obj as Entity); } public static bool operator ==(Entity e1, Entity e2) { if (ReferenceEquals(e1, null)) return ReferenceEquals(e2, null); return e1.Equals(e2); } public static bool operator !=(Entity e1, Entity e2) { return !(e1 == e2); } public override int GetHashCode() { throw new NotImplementedException("Your lightweight hashing algorithm, consistent with Equals method, here..."); } } Take special care to see how it should fare if your class can be inherited, in such cases you will have to determine if a base class object can be equal to a derived class object. Ideally, if no objects of derived class is used for equality checking, then a base class instance can be equal to a derived class instance and in such cases, there is no need to check Type equality in generic Equals of base class. In general take care not to duplicate code. I could have made a generic abstract base class (IEqualizable<T> or so) as a template to allow re-use easier, but sadly in C# that stops me from deriving from additional classes. A: All the answers above do not consider polymorphism, often you want derived references to use the derived Equals even when compared via a base reference. Please see the question/ discussion/ answers here - Equality and polymorphism
{ "language": "en", "url": "https://stackoverflow.com/questions/104158", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "48" }
Q: How do I embed an image in a .NET HTML Mail Message? I have an HTML Mail template, with a place holder for the image. I am getting the image I need to send out of a database and saving it into a photo directory. I need to embed the image in the HTML Message. I have explored using an AlternateView: AlternateView htmlView = AlternateView.CreateAlternateViewFromString("<HTML> <img src=cid:VisitorImage> </HTML>"); LinkedResource VisitorImage = new LinkedResource(p_ImagePath); VisitorImage.ContentId= "VisitorImage"; htmlView.LinkedResources.Add(VisitorImage); A: Try this: LinkedResource objLinkedRes = new LinkedResource( Server.MapPath(".") + "\\fuzzydev-logo.jpg", "image/jpeg"); objLinkedRes.ContentId = "fuzzydev-logo"; AlternateView objHTLMAltView = AlternateView.CreateAlternateViewFromString( "<img src='cid:fuzzydev-logo' />", new System.Net.Mime.ContentType("text/html")); objHTLMAltView.LinkedResources.Add(objLinkedRes); objMailMessage.AlternateViews.Add(objHTLMAltView);
{ "language": "en", "url": "https://stackoverflow.com/questions/104177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "23" }
Q: Is it safe to get values from a java.util.HashMap from multiple threads (no modification)? There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a java.util.HashMap in this way? (Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice. Hence, this question is not "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?") A: One note is that under some circumstances, a get() from an unsynchronized HashMap can cause an infinite loop. This can occur if a concurrent put() causes a rehash of the Map. http://lightbody.net/blog/2005/07/hashmapget_can_cause_an_infini.html A: Jeremy Manson, the god when it comes to the Java Memory Model, has a three part blog on this topic - because in essence you are asking the question "Is it safe to access an immutable HashMap" - the answer to that is yes. But you must answer the predicate to that question which is - "Is my HashMap immutable". The answer might surprise you - Java has a relatively complicated set of rules to determine immutability. For more info on the topic, read Jeremy's blog posts: Part 1 on Immutability in Java: http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html Part 2 on Immutability in Java: http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html Part 3 on Immutability in Java: http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html A: There is an important twist though. It's safe to access the map, but in general it's not guaranteed that all threads will see exactly the same state (and thus values) of the HashMap. This might happen on multiprocessor systems where the modifications to the HashMap done by one thread (e.g., the one that populated it) can sit in that CPU's cache and won't be seen by threads running on other CPUs, until a memory fence operation is performed ensuring cache coherence. The Java Language Specification is explicit on this one: the solution is to acquire a lock (synchronized (...)) which emits a memory fence operation. So, if you are sure that after populating the HashMap each of the threads acquires ANY lock, then it's OK from that point on to access the HashMap from any thread until the HashMap is modified again. A: Your idiom is safe if and only if the reference to the HashMap is safely published. Rather than anything relating the internals of HashMap itself, safe publication deals with how the constructing thread makes the reference to the map visible to other threads. Basically, the only possible race here is between the construction of the HashMap and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the HashMap reference is published. For example, imagine you publish the map like this: class SomeClass { public static HashMap<Object, Object> MAP; public synchronized static setMap(HashMap<Object, Object> m) { MAP = m; } } ... and at some point setMap() is called with a map, and other threads are using SomeClass.MAP to access the map, and check for null like this: HashMap<Object,Object> map = SomeClass.MAP; if (map != null) { .. use the map } else { .. some default behavior } This is not safe even though it probably appears as though it is. The problem is that there is no happens-before relationship between the set of SomeObject.MAP and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do anything and even in practice it does things like put the reading thread into an infinite loop. To safely publish the map, you need to establish a happens-before relationship between the writing of the reference to the HashMap (i.e., the publication) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to accomplish that[1]: * *Exchange the reference through a properly locked field (JLS 17.4.5) *Use static initializer to do the initializing stores (JLS 12.4) *Exchange the reference via a volatile field (JLS 17.4.5), or as the consequence of this rule, via the AtomicX classes *Initialize the value into a final field (JLS 17.5). The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of MAP to: public static volatile HashMap<Object, Object> MAP; then everything is kosher: readers who see a non-null value necessarily have a happens-before relationship with the store to MAP and hence see all the stores associated with the map initialization. The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using final) imply that you cannot set MAP dynamically at runtime. If you don't need to do that, then just declare MAP as a static final HashMap<> and you are guaranteed safe publication. In practice, the rules are simple for safe access to "never-modified objects": If you are publishing an object which is not inherently immutable (as in all fields declared final) and: * *You already can create the object that will be assigned at the moment of declarationa: just use a final field (including static final for static members). *You want to assign the object later, after the reference is already visible: use a volatile fieldb. That's it! In practice, it is very efficient. The use of a static final field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a final member field allows most architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizationsc. Finally, the use of volatile does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one HashMap, you can store as many more not-modified HashMaps as you want to the same reference and be assured that all readers will see a safely published map. For more gory details, refer to Shipilev or this FAQ by Manson and Goetz. [1] Directly quoting from shipilev. a That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields). b Optionally, you can use a synchronized method to get/set, or an AtomicReference or something, but we're talking about the minimum work you can do. c Some architectures with very weak memory models (I'm looking at you, Alpha) may require some type of read barrier before a final read - but these are very rare today. A: According to http://www.ibm.com/developerworks/java/library/j-jtp03304/ # Initialization safety you can make your HashMap a final field and after the constructor finishes it would be safely published. ... Under the new memory model, there is something similar to a happens-before relationship between the write of a final field in a constructor and the initial load of a shared reference to that object in another thread. ... A: This question is addressed in Brian Goetz's "Java Concurrency in Practice" book (Listing 16.8, page 350): @ThreadSafe public class SafeStates { private final Map<String, String> states; public SafeStates() { states = new HashMap<String, String>(); states.put("alaska", "AK"); states.put("alabama", "AL"); ... states.put("wyoming", "WY"); } public String getAbbreviation(String s) { return states.get(s); } } Since states is declared as final and its initialization is accomplished within the owner's class constructor, any thread who later reads this map is guaranteed to see it as of the time the constructor finishes, provided no other thread will try to modify the contents of the map. A: The reads are safe from a synchronization standpoint but not a memory standpoint. This is something that is widely misunderstood among Java developers including here on Stackoverflow. (Observe the rating of this answer for proof.) If you have other threads running, they may not see an updated copy of the HashMap if there is no memory write out of the current thread. Memory writes occur through the use of the synchronized or volatile keywords, or through uses of some java concurrency constructs. See Brian Goetz's article on the new Java Memory Model for details. A: So the scenario you described is that you need to put a bunch of data into a Map, then when you're done populating it you treat it as immutable. One approach that is "safe" (meaning you're enforcing that it really is treated as immutable) is to replace the reference with Collections.unmodifiableMap(originalMap) when you're ready to make it immutable. For an example of how badly maps can fail if used concurrently, and the suggested workaround I mentioned, check out this bug parade entry: bug_id=6423457 A: After a bit more looking, I found this in the java doc (emphasis mine): Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This seems to imply that it will be safe, assuming the converse of the statement there is true. A: Be warned that even in single-threaded code, replacing a ConcurrentHashMap with a HashMap may not be safe. ConcurrentHashMap forbids null as a key or value. HashMap does not forbid them (don't ask). So in the unlikely situation that your existing code might add a null to the collection during setup (presumably in a failure case of some kind), replacing the collection as described will change the functional behaviour. That said, provided you do nothing else concurrent reads from a HashMap are safe. [Edit: by "concurrent reads", I mean that there are not also concurrent modifications. Other answers explain how to ensure this. One way is to make the map immutable, but it's not necessary. For example, the JSR133 memory model explicitly defines starting a thread to be a synchronised action, meaning that changes made in thread A before it starts thread B are visible in thread B. My intent is not to contradict those more detailed answers about the Java Memory Model. This answer is intended to point out that even aside from concurrency issues, there is at least one API difference between ConcurrentHashMap and HashMap, which could scupper even a single-threaded program which replaced one with the other.] A: http://www.docjar.com/html/api/java/util/HashMap.java.html here is the source for HashMap. As you can tell, there is absolutely no locking / mutex code there. This means that while its okay to read from a HashMap in a multithreaded situation, I'd definitely use a ConcurrentHashMap if there were multiple writes. Whats interesting is that both the .NET HashTable and Dictionary<K,V> have built in synchronization code. A: If the initialization and every put is synchronized you are save. Following code is save because the classloader will take care of the synchronization: public static final HashMap<String, String> map = new HashMap<>(); static { map.put("A","A"); } Following code is save because the writing of volatile will take care of the synchronization. class Foo { volatile HashMap<String, String> map; public void init() { final HashMap<String, String> tmp = new HashMap<>(); tmp.put("A","A"); // writing to volatile has to be after the modification of the map this.map = tmp; } } This will also work if the member variable is final because final is also volatile. And if the method is a constructor.
{ "language": "en", "url": "https://stackoverflow.com/questions/104184", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "167" }
Q: JPA 1 is not good enough Working in a medium size project during last 4 months - we are using JPA and Spring - I'm quite sure that JPA is not powerfull for projects that requires more than CRUD screen... Query interface is poor, Hibernate doesn't respect JPA spec all the time and lot of times I need to use hibernate classes, annotations and config. What do you guys think about JPA? Is it not good enough? A: Well I think most of the time JPA is "good enough" but I miss the Criteria API a lot (only provided by Hibernate) A: Hibernate has been a long time in the road. That's why it has many functions not avaiable in JPA yet. But with time JPA will catch up. Until then, use JPA and Hibernate specific settings where necessary. If you need to switch later, it'll be a lot easier. A: Well I can't provide specific guidance without knowing more about your particular case. It seems like you're using Hibernate's JPA implementation. You might try other JPA implementations if there is something about Hibernate's you don't like. As far as the query interface, if JPA's queries aren't doing what you want, you always have the ability to get a plain old Connection and work with that. The genius of the framework is that -- at the very least -- you don't have to write all the CRUD code ever again. I would never claim JPA is perfect, but it's better than hand-writing SQL all the time to do trivial things. A: We combine JPA 2.0, Hibernate Core, Hibernate Search and Hibernate Validator via our in-house wrapper framework. It does everything we throw at it :) Combine that with Maven and we have a database built for us too! Add DBUnit into the mix and you've got everything you need. Wickedly fast searches via Lucene, but using Hibernate Criteria/HQL queries are very cool. All this power behind a GWT suggest box is great. A: My advice would be simply to use Hibernate. Hibernate coupled with JPA annotations + Hibernate annotations is pretty powerful. You can even configure an EntityManagerFactory to autodiscover Entities on the classpath but then call getSessionFactory() to leverage the native Hibernate APIs in your application. If you are using Spring it's very easy to do this with LocalContainerEntityManagerFactoryBean and HibernateJpaVendorAdapter. A: Sure any ORM is better than hand-writting SQL for CRUD operations... the thing is: I'm think there is no reason to use JPA instead pure Hibernate because I'm mixing both a lot. If I'm not getting a hidden provider why use JPA anyway? A: One of the nice things about using JPA vs Hibernate Annotations is the automatic configuration and discovery of persistent classes. Also, it depends on how much of the time you need to break from using the JPA API, if you are only doing it 10% of the time, it would still make switching providers a lot easier than if you were to use hibernate for 100% of your queries.
{ "language": "en", "url": "https://stackoverflow.com/questions/104185", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to remove published wmi schema? I've published schema, and no longer have the dll's that contained the wmi provider that the schema was published from. How can I remove the schema? A: If you are talking about the assembly from your other question, you can simply use wbemtest.exe: * *Connect to Root namespace *Enum instances... button (Superclass name: __Namespace) *Delete instance named Test or MyTest That will delete the entire namespace including all the classes you created. If you want to delete a class and leave the namespace * *Connect to Root\Test *Enum classes... button (Recursive) *Delete the classes you want If there are multiple machines this can be automated using WMI scripting library or System.Management. With MOF you can use #pragma deleteclass. If the schema was created with #pragma autorecover you need to remove the entry from HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WBEM\CIMOM\autorecover mofs
{ "language": "en", "url": "https://stackoverflow.com/questions/104188", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Benefits of static code analysis What are the benefits of doing static code analysis on your source code? I was playing around with FxCop and I was wondering if there any benefits beyond making sure you are following the coding standards. A: Many classes of memory leaks and common logic errors can be caught statically as well. You can also look at cyclomatic complexity and such, which may be part of the "coding standards" you mentioned, but may be a separate metric you use to evaluate the algorithmic "cleanliness" of your code. In any case, only a judicious combination of profiling (dynamic or run-time analysis) and static analysis/linting will ensure a consistent, reliable code base. Oh, that, and a little luck ;-) A: It's a trade-off. For an individual developer who wants to improve his understanding of the framework and guidelines, I would definitely encourage it. FxCop generates a lot of noise / false positives, but I've also found the following benefits: * *it detects bugs (e.g. a warning about an unused argument may indicate you used the wrong argument in the method body). *understanding the guidelines FxCop is following helps you to become a better developer. However with a mixed-ability team, FxCop may well generate too many false positives to be useful. Junior developers will have difficulty appreciating whether some of the more esoteric violations thrown up by FxCop should concern them or are just noise. Bottom line: * *If you're developing reusable class libraries, such as an in-house framework, make sure you have good developers and use FxCop. *For everyday application development with mixed-ability teams, it will probably not be practicable. A: There are all kinds of benefits: * *If there are anti-patterns in your code, you can be warned about it. *There are certain metrics (such as McCabe's Cyclomatic Complexity) that tell useful things about source code. *You can also get great stuff like call-graphs, and class diagrams from static analysis. Those are wonderful if you are attacking a new code base. Take a look at SourceMonitor A: actually, fxcop doesn't particularly help you follow a coding standard. What it does help you with is designing a well-thought out framework/API. It's true that parts of the coding standard (such as casing of public members) will be caught by FxCop, but coding standards isn't the focus. coding standards can be checked with stylecop, which checks the source code instead of the MSIL like fxcop does. A: It can catch actual bugs, like forgetting to Dispose IDisposables. A: Depends on the rules, but many subtle defects can be avoided, code can be cleaned, potential performance problems can be detected etc. Put it one way...if it's cheap or free (in both time and financial costs) and doesn't break anything, why not use it? A: FxCop There is a list of all warnings in FxCop. You can see that there are warnings from the following areas: Design Warnings Warnings that support proper library design as specified by the .NET Framework Design Guidelines. Globalization Warnings Warnings that support world-ready libraries and applications. Interoperability Warnings Warnings that support interacting with COM clients. Naming Warnings Warnings that support adherence to the naming conventions of the .NET Framework Design Guidelines. Performance Warnings Warnings that support high performance libraries and applications. Security Warnings Warnings that support safer libraries and applications. Depending on your application some of those areas might not be very interesting, but if you e.g. need COM interoperability, the tests can really help you to avoid the pitfalls. Other tools Other static checking tools can help you to detect bugs like not disposing an IDisposable, memory leaks and other subtle bugs. For a extreme case see the not-yet-released NStatic tool. NStatic is used to track things such as redundant parameters, expressions that evaluate to constants, infinite loops and many other metrics. A: The benefits are that you can automatically find and quantify technical debt within your software application. I find static code analysis tools indispensable on large enterprise application development where many developers and testers come and go over the life of an application but the code quality still needs to be kept high and the technical debt managed properly. A: What are the benefits of doing static code analysis on your source code? The benefits depend on the type of static code analysis that is performed. Static code analysis can range from simple to sophisticated techniques. For example, generating metrics about your source code to identify error prone code is one technique. Other techniques actively attempt to find bugs in your code. Sophisticated techniques use formal methods to prove that your code is free of bugs. Therefore the benefit depends on the type of static code analysis being used. If the technique produces metrics (such as code complexity etc.), then a benefit is that these metrics could be used during code review to identify error prone code. If the technique detects bugs, then the benefit is that the developer can identify bugs before unit test. If formal methods based techniques are used to prove that the code does not contain bugs, then the benefit is that this information could be used to prove to the QA department (or certification authorities) that the code is free of certain types of bugs. A more detailed description of the techniques and benefits can also be found on this page: www.mathworks.com/static-analysis A: I'll try to describe the main ones: * *Static code analysis identifies detects in the program at early stage, resulting decrease in cost to fix them. *It can detect flaws in the program's inputs and outputs that cannot be seen through dynamic testing. *It automatically scans uncompiled codes and identifies vulnerabilities. *Of what I know from dealing with checkmarx is that static code analysis fixes multiple vulnerabilities at a single point, which saves a lot of time for the developer.
{ "language": "en", "url": "https://stackoverflow.com/questions/104196", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: cURL in PHP returns different data in _FILE and _RETURNTRANSFER I have noticed that cURL in PHP returns different data when told to output to a file via CURLOPT_FILE as it does when told to send the output to a string via CURLOPT_RETURNTRANSFER. _RETURNTRANSFER seems to strip newlines and extra white space as if parsing it for display as standard HTML code. _FILE on the other hand preserves the file exactly as it was intended. I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have _RETURNTRANSFER return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible. Here is the code I am using. The data in question is a CSV file with \r\n line endings. function update_roster() { $url = "http://example.com/"; $userID = "xx"; $apikey = "xxx"; $passfields = "userID=$userID&apikey=$apikey"; $file = fopen("roster.csv","w+"); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $file); $variable_in_question = curl_exec ($ch); curl_close ($ch); fclose($file); return $variable_in_question; } Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:$cresult = split("\r\n", $cresult); This does not: $cresult = split('\r\n', $cresult); A: Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:$cresult = split("\r\n", $cresult); This does not: $cresult = split('\r\n', $cresult); A: In most scripting langage (it's also true in Bash for instance), simple quotes are used to represent things as they are written, whereas double quotes are "analysed" (i don't think it's the appropriate word but i can't find better). $str = 'foo'; echo '$str'; // print “$str” to the screen echo "$str"; // print “foo” to the screen It is true for variables and escaped characters. A: I didn't try to reproduce the "bug" (I think we can consider this as a bug if it is the actual behavior), but maybe you could get over it. The PHP Doc says that the default comportement is to write the result to a file, and that the default file is STDOUT (the browser's window). What you want is to get the same result than in a file but in a variable. You could do that using ob_start(); and ob_get_clean();. $ch = curl_init(...); // ... ob_start(); curl_exec($ch); $yourResult = ob_get_clean(); curl_close($ch); I know that's not really the clean way (if there is one), but at least it sould work fine. (Please excuse me if my english is not perfect ;-)...)
{ "language": "en", "url": "https://stackoverflow.com/questions/104223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How do you troubleshoot WPF UI problems? I'm working on a WPF application that sometimes exhibits odd problems and appears to hang in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below. My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page. I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it. EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows: [Managed to Native Transition] WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C# [Native to Managed Transition] [Managed to Native Transition] mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x66 bytes mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes A: Try removing the borderless behavior of your window and see if that helps. Also, are you BeginInvoke()'ing or Invoke()'ing any long running operations? Another thing to look at: When you break into your code, try looking at threads other than your main thread. One of them may be blocking the UI thread. A: Your WPF app could be hanging due to performance issues. Try using Perforator to see if you have any parts that are software rendered or if you app is using too much video ram. A: One great tool is Snoop. Really nice for looking at what WPF objects are displayed on the visual tree at a given time. I'm not sure how much it will help, but it's possible you're jamming the UI thread with a lot of extra things it has to do. Snoop may be able to help you track down what is on the screen to give you an idea what to look for. A: I have removed the borderless behavior as suggested by Bob King. To date, that seems to have gotten rid of the problem. Now the question is, why and how can I fix the issue? The product is designed to have no border with some rounded corners and transparent parts. A: Hurrah,... it seems that the problem isn't related to borderless windows (at least in my case). There is a big performance hit when you set AllowsTransparency to true. So much of a hit it would seem, that the whole thing can hang the UI thread. Very strange behaviour. Could be related to this ticket
{ "language": "en", "url": "https://stackoverflow.com/questions/104224", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "11" }
Q: Has TRUE always had a non-zero value? I have a co-worker that maintains that TRUE used to be defined as 0 and all other values were FALSE. I could swear that every language I've worked with, if you could even get a value for a boolean, that the value for FALSE is 0. Did TRUE used to be 0? If so, when did we switch? A: If nothing else, bash shells still use 0 for true, and 1 for false. A: Several functions in the C standard library return an 'error code' integer as result. Since noErr is defined as 0, a quick check can be 'if it's 0, it's Ok'. The same convention carried to a Unix process' 'result code'; that is, an integer that gave some inidication about how a given process finished. In Unix shell scripting, the result code of a command just executed is available, and tipically used to signify if the command 'succeeded' or not, with 0 meaning success, and anything else a specific non-success condition. From that, all test-like constructs in shell scripts use 'success' (that is, a result code of 0) to mean TRUE, and anything else to mean FALSE. On a totally different plane, digital circuits frecuently use 'negative logic'. that is, even if 0 volts is called 'binary 0' and some positive value (commonly +5v or +3.3v, but nowadays it's not rare to use +1.8v) is called 'binary 1', some events are 'asserted' by a given pin going to 0. I think there's some noise-resistant advantages, but i'm not sure about the reasons. Note, however that there's nothing 'ancient' or some 'switching time' about this. Everything I know about this is based on old conventions, but are totally current and relevant today. A: The 0 / non-0 thing your coworker is confused about is probably referring to when people use numeric values as return value indicating success, not truth (i.e. in bash scripts and some styles of C/C++). Using 0 = success allows for a much greater precision in specifying causes of failure (e.g. 1 = missing file, 2 = missing limb, and so on). As a side note: in Ruby, the only false values are nil and false. 0 is true, but not as opposed to other numbers. 0 is true because it's an instance of the object 0. A: I'm not certain, but I can tell you this: tricks relying on the underlying nature of TRUE and FALSE are prone to error because the definition of these values is left up to the implementer of the language (or, at the very least, the specifier). A: It might be in reference to a result code of 0 which in most cases after a process has run, a result code of 0 meant, "Hey, everything worked fine, no problems here." A: System calls in the C standard library typically return -1 on error and 0 on success. Also the Fotran computed if statement would (and probably still does) jump to one of three line numbers depending on the condition evaluating to less than, equal to or greater than zero. eg: IF (I-15) 10,20,10 would test for the condition of I == 15 jumping to line 20 if true (evaluates to zero) and line 10 otherwise. Sam is right about the problems of relying on specific knowledge of implementation details. A: General rule: * *Shells (DOS included) use "0" as "No Error"... not necessarily true. *Programming languages use non-zero to denote true. That said, if you're in a language which lets your define TRUE of FALSE, define it and always use the constants. A: I worked at a company with a large amount of old C code. Some of the shared headers defined their own values for TRUE and FALSE, and some did indeed have TRUE as 0 and FALSE as 1. This led to "truth wars": /* like my constants better */ #undef TRUE #define TRUE 1 #undef FALSE #define FALSE 0 A: Even today, in some languages (Ruby, lisp, ...) 0 is true because everything except nil is true. More often 1 is true. That's a common gotcha and so it's sometimes considered a good practice to not rely on 0 being false, but to do an explicit test. Java requires you do this. Instead of this int x; .... x = 0; if (x) // might be ambiguous { } Make is explicit if (0 != x) { } A: I recall doing some VB programming in an access form where True was -1. A: I remember PL/1 had no boolean class. You could create a bit and assign it the result of a boolean expression. Then, to use it, you had to remember that 1 was false and 0 was true. A: It's easy to get confused when bash's true/false return statements are the other way around: $ false; echo $? 1 $ true; echo $? 0 A: For the most part, false is defined as 0, and true is non-zero. Some programming languages use 1, some use -1, and some use any non-zero value. For Unix shells though, they use the opposite convention. Most commands that run in a Unix shell are actually small programs. They pass back an exit code so that you can determine whether the command was successful (a value of 0), or whether it failed for some reason (1 or more, depending on the type of failure). This is used in the sh/ksh/bash shell interpreters within the if/while/until commands to check conditions: if command then # successful fi If the command is successful (ie, returns a zero exit code), the code within the statement is executed. Usually, the command that is used is the [ command, which is an alias for the test command. A: The funny thing is that it depends on the language your are working with. In Lua is true == zero internal for performance.. Same for many syscalls in C. A: In the C language, before C++, there was no such thing as a boolean. Conditionals were done by testing ints. Zero meant false and any non-zero meant true. So you could write if (2) { alwaysDoThis(); } else { neverDothis(); } Fortunately C++ allowed a dedicated boolean type. A: I have heard of and used older compilers where true > 0, and false <= 0. That's one reason you don't want to use if(pointer) or if(number) to check for zero, they might evaluate to false unexpectedly. Similarly, I've worked on systems where NULL wasn't zero. A: In any language I've ever worked in (going back to BASIC in the late 70s), false has been considered 0 and true has been non-zero. A: I can't recall TRUE being 0. 0 is something a C programmer would return to indicate success, though. This can be confused with TRUE. It's not always 1 either. It can be -1 or just non-zero. A: For languages without a built in boolean type, the only convention that I have seen is to define TRUE as 1 and FALSE as 0. For example, in C, the if statement will execute the if clause if the conditional expression evaluates to anything other than 0. I even once saw a coding guidelines document which specifically said not to redefine TRUE and FALSE. :) If you are using a language that has a built in boolean, like C++, then keywords true and false are part of the language, and you should not rely on how they are actually implemented. A: In languages like C there was no boolean value so you had to define your own. Could they have worked on a non-standard BOOL overrides? A: DOS and exit codes from applications generally use 0 to mean success and non-zero to mean failure of some type! DOS error codes are 0-255 and when tested using the 'errorlevel' syntax mean anything above or including the specified value, so the following matches 2 and above to the first goto, 1 to the second and 0 (success) to the final one! IF errorlevel 2 goto CRS IF errorlevel 1 goto DLR IF errorlevel 0 goto STR A: The SQL Server Database Engine optimizes storage of bit columns. If there are 8 or less bit columns in a table, the columns are stored as 1 byte. If there are from 9 up to 16 bit columns, the columns are stored as 2 bytes, and so on. The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0. Converting to bit promotes any nonzero value to 1. Every language can have 0 as true or false So stop using number use words true Lol Or t and f 1 byte storage
{ "language": "en", "url": "https://stackoverflow.com/questions/104225", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: how do I query multiple SQL tables for a specific key-value pair? Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id. Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module. A: What about? SELECT * FROM mod_a WHERE section_id=value UNION ALL SELECT * FROM mod_b WHERE section_id=value UNION ALL SELECT * FROM mod_c WHERE section_id=value A: If the tables are changing over time, you can inline code gen your solution in an SP (pseudo code - you'll have to fill in): SET @sql = '' DECLARE CURSOR FOR SELECT t.[name] AS TABLE_NAME FROM sys.tables t WHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES' -- or this DECLARE CURSOR FOR SELECT t.[name] AS TABLE_NAME FROM TABLE_OF_TABLES_TO_SEACRH t START LOOP IF @sql <> '' SET @sql = @sql + 'UNION ALL ' SET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value ' END LOOP EXEC(@sql) I've used this technique occasionally, when there just isn't any obvious way to make it future-proof without dynamic SQL. Note: In your loop, you can use the COALESCE/NULL propagation trick and leave the string as NULL before the loop, but it's not as clear if you are unfamiliar with the idiom: SET @sql = COALESCE(@sql + ' UNION ALL ', '') + 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value ' A: I have two suggestions. * *Perhaps you need to consolidate all your tables. If they all contain the same structure, then why not have one "master" module table, that just adds one new column identifying the module ("A", "B", "C", ....) If your module tables are mostly the same, but you have a few columns that are different, you might still be able to consolidate all the common information into one table, and keep smaller module-specific tables with those differences. Then you would just need to do a join on them. This suggestion assumes that your query on the column section_id you mention is super-critical to look up quickly. With one query you get all the common information, and with a second you would get any specific information if you needed it. (And you might not -- for instance if you were trying to validate the existense of the section, then finding it in the common table would be enough) *Alternatively you can add another table that maps section_id's to the modules that they are in. section_id | module -----------+------- 1 | A 2 | B 3 | A ... | ... This does mean though that you have to run two queries, one against this mapping table, and another against the module table to pull out any useful data. You can extend this table with other columns and indices on those columns if you need to look up other columns that are common to all modules. This method has the definite disadvanage that the data is duplicated. A: I was going to suggest the same think as borjab. The only problem with that is that you will have to update all of these queries if you add another table. The only other option I see is a stored procedure. I did think of another option here, or at least an easier way to present this. You can also use a view to these multiple tables to make them appear as one, and then your query would look cleaner, be easier to understand and you wouldn't have to rewrite a long union query when you wanted to do other queries on these multiple tables. A: Perhaps some additional info would help, but it sounds like you have the solution already. You will have to select from all the tables with a section_id. You could use joins instead of a table list, joining on section_id. For example select a.some_field, b.some_field.... from mod_a a inner join mod_b b on a.section_id = b.section_id ... where a.section_id = <parameter> You could also package this up as a view. Also notice the field list instead of *, which I would recommend if you were intending to actually use *. A: Well, there are only so many ways to aggregate information from multiple tables. You can join, like you mentioned in your example, or you can run multiple queries and union them together as in borjab's answer. I don't know if some idea of creating a table that intersects all the module tables would be useful to you, but if section_id was on a table like that you'd be able to get everything from a single query. Otherwise, I applaud your laziness, but am afraid to say, I don't see any way to make that job eaiser :) A: SELECT * FROM ( SELECT * FROM table1 UNION ALL SELECT * FROM table2 UNION ALL SELECT * FROM table3 ) subQry WHERE field=value A: An option from the database side would be to create a view of the UNION ALL of the various tables. When you add a table, you would need to add it to the view, but otherwise it would look like a single table. CREATE VIEW modules AS ( SELECT * FROM mod_A UNION ALL SELECT * FROM mod_B UNION ALL SELECT * FROM mod_C ); select * from modules where section_id=value;
{ "language": "en", "url": "https://stackoverflow.com/questions/104230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can I use DebugBreak() in C#? What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help. A: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.break#System_Diagnostics_Debugger_Break #if DEBUG System.Diagnostics.Debugger.Break(); #endif A: I also like to check to see if the debugger is attached - if you call Debugger.Break when there is no debugger, it will prompt the user if they want to attach one. Depending on the behavior you want, you may want to call Debugger.Break() only if (or if not) one is already attached using System.Diagnostics; //.... in the method: if( Debugger.IsAttached) //or if(!Debugger.IsAttached) { Debugger.Break(); } A: You can use System.Diagnostics.Debugger.Break() to break in a specific place. This can help in situations like debugging a service. A: The answers from @Philip Rieck and @John are subtly different. John's ... #if DEBUG System.Diagnostics.Debugger.Break(); #endif only works if you compiled with the DEBUG conditional compilation symbol set. Phillip's answer ... if( Debugger.IsAttached) //or if(!Debugger.IsAttached) { Debugger.Break(); } will work for any debugger so you will give any hackers a bit of a fright too. Also take note of SecurityException it can throw so don't let that code out into the wild. Another reason no to ... If no debugger is attached, users are asked if they want to attach a debugger. If users say yes, the debugger is started. If a debugger is attached, the debugger is signaled with a user breakpoint event, and the debugger suspends execution of the process just as if a debugger breakpoint had been hit. from https://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx A: Put the following where you need it: System.Diagnostics.Debugger.Break();
{ "language": "en", "url": "https://stackoverflow.com/questions/104235", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "31" }
Q: How do I match one letter or many in a PHP preg_split style regex I'm having an issue with my regex. I want to capture <% some stuff %> and i need what's inside the <% and the %> This regex works quite well for that. $matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); I also want to catch &amp;% some stuff %&amp;gt; so I need to capture <% or &amp;lt;% and %> or %&amp;gt; respectively. If I put in a second set of parens, it makes preg_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens. Preferably, it would only match &amp;lt; to &amp;gt; and < to > as well, but that's not completely necessary EDIT: The SUBJECT may contain multiple matches, and I need all of them A: In your case, it's better to use preg_match with its additional parameter and parenthesis: preg_match("#((?:<|&lt;)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|&gt;))#i",$markup, $out); print_r($out); Array ( [0] => <% your stuff %> [1] => <% [2] => your stuff [3] => %> ) By the way, check this online tool to debug PHP regexp, it's so useful ! http://regex.larsolavtorvik.com/ EDIT : I hacked the regexp a bit so it's faster. Tested it, it works :-) Now let's explain all that stuff : * *preg_match will store everything he captures in the var passed as third param (here $out) *if preg_match matches something, it will be store in $out[0] *anything that is inside () but not (?:) in the pattern will be stored in $out The patten in details : #((?:<|&lt;)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|&gt;))#i can be viewed as ((?:<|&lt;)%) + ([\s]*(?:[^ø]*)[\s]*?) + (%(?:>|&gt;)). ((?:<|&lt;)%) is capturing < or &lt; then % (%(?:>|&gt;)) is capturing % then < or &gt; ([\s]*(?:[^ø]*)[\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces. Why do we use [^ø] instead of . ? It's because . is very time consuming, the regexp engine will check among all the existing characters. [^ø] just check if the char is not ø. Nobody uses ø, it's an international money symbol, but if you care, you can replace it by chr(7) wich is the shell bell char that's obviously will never be typed in a web page. EDIT2 : I just read your edit about capturing all the matches. In that case, you´ll use preg_match_all the same way. A: <?php $code = 'Here is a <% test %> and &lt;% another test %&gt; for you'; preg_match_all('/(<|&lt;)%\s*(.*?)\s*%(>|&gt;)/', $code, $matches); print_r($matches[2]); ?> Result: Array ( [0] => test [1] => another test ) A: Why are you using preg_split if what you really want is what matches inside the parentheses? Seems like it would be simpler to just use preg_match. It's often an issue with regex that parens are used both for grouping your logic and for capturing patterns. According to the PHP doc on regex syntax, The fact that plain parentheses fulfil two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. A: If you want to match, give preg_match_all a shot with a regular expression like this: preg_match_all('/((\<\%)(\s)(.*?)(\s)(\%\>))/i', '<% wtf %> <% sadfdsafds %>', $result); This results in a match of just about everything under the sun. You can add/remove parens to match more/less: Array ( [0] => Array ( [0] => <% wtf %> [1] => <% sadfdsafds %> ) [1] => Array ( [0] => <% wtf %> [1] => <% sadfdsafds %> ) [2] => Array ( [0] => <% [1] => <% ) [3] => Array ( [0] => [1] => ) [4] => Array ( [0] => wtf [1] => sadfdsafds ) [5] => Array ( [0] => [1] => ) [6] => Array ( [0] => %> [1] => %> ) ) A: One possible solution is to use the extra parens, like so, but to ditch those in the results, so you actually only use 1/2 of the total restults. this regex $matches = preg_split("/(<|&lt;)%[\s]*(.*?)[\s]*%(>|&gt;)/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); for input Hi my name is <h1>Issac</h1><% some stuff %>here&lt;% more stuff %&gt; output would be Array( [0]=>Hi my name is <h1>Issac</h1> [1]=>< [2]=>some stuff [3]=>> [4]=>here [5]=>&;lt; [6]=>more stuff [7]=>&gt; ) Which would give the desired resutls, if I only used the even numbers
{ "language": "en", "url": "https://stackoverflow.com/questions/104238", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Is it possible in W3C's XML Schema language (XSD) to allow a series of elements to be in any order but still limit occurrences? I know about all and choice, but they don't account for a case where I do want some elements to be able to occur more than once, such as: <Root> <ThingA/> <ThingB/> <ThingC/> <ThingC/> <ThingC/> </Root> I could use sequence, but I'd prefer to allow these children to be in any order. I could use any, but then I couldn't have more than one ThingC. I could use choice, but then I couldn't limit ThingA and ThingB to 0 or 1. I think I may have read somewhere that this was either difficult or impossible in XSD, but might be possible with RELAX NG. I don't remember where I read that, unfortunately. Thanks for any help! A: That's right: you can't do what you want to do in XML Schema, but you can in RELAX NG with: <element name="Root"> <interleave> <element name="ThingA"><empty /></element> <element name="ThingB"><empty /></element> <oneOrMore><element name="ThingC"><empty /></element></oneOrMore> </interleave> </element> Your options in XML Schema are: * *add a preprocessing step that normalises your input XML into a particular order, and then use <xs:sequence> *use <xs:choice>, and add extra validation (for example using Schematron) to check that there's not more than one <ThingA> or <ThingB> *decide to fix the order of the elements in your markup language It turns out that the third is usually the best option; there's usually not much cost for generators of XML to output elements in a particular order, and not only does it help validation but it also aids consumption of the XML if the order can be known in advance.
{ "language": "en", "url": "https://stackoverflow.com/questions/104248", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: java.io.Console support in Eclipse IDE I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the java.io.Console class to manage output and, more importantly, user input. The problem is that System.console() returns null when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with. Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse. A: The reason this occurs is because eclipse runs your app as a background process and not as a top-level process with a system console. A: You can implement a class yourself. Following is an example: public class Console { BufferedReader br; PrintStream ps; public Console(){ br = new BufferedReader(new InputStreamReader(System.in)); ps = System.out; } public String readLine(String out){ ps.format(out); try{ return br.readLine(); }catch(IOException e) { return null; } } public PrintStream format(String format, Object...objects){ return ps.format(format, objects); } } A: I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath. java -cp workspace\p1\bin;workspace\p2\bin foo.Main You can debug using the remote debugger and taking advantage of the class files built in your project. In this example, the Eclipse project structure looks like this: workspace\project\ \.classpath \.project \debug.bat \bin\Main.class \src\Main.java 1. Start the JVM Console in Debug Mode debug.bat is a Windows batch file that should be run externally from a cmd.exe console. @ECHO OFF SET A_PORT=8787 SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y java.exe %A_DBG% -cp .\bin Main In the arguments, the debug port has been set to 8787. The suspend=y argument tells the JVM to wait until the debugger attaches. 2. Create a Debug Launch Configuration In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new Remote Java Application configuration with the following settings: * *Project: your project name *Connection Type: Standard (Socket Attach) *Host: localhost *Port: 8787 3. Debugging So, all you have to do any time you want to debug the app is: * *set a break point *launch the batch file in a console *launch the debug configuration You can track this issue in bug 122429. You can work round this issue in your application by using an abstraction layer as described here. A: Found something about this at http://www.stupidjavatricks.com/?p=43 . And sadly, since console is final, you can't extend it to create a a wrapper around system.in and system.out that does it either. Even inside the eclipse console you still have access to those. Thats probably why eclipse hasn't plugged this into their console yet... I understand why you wouldn't want to have any other way to get a console other than System.console, with no setter, but i don't understand why you wouldn't want someone to be able to override the class to make a mock/testing console... A: Another option is to create a method to wrap up both options, and "fail over" to the System.in method when Console isn't available. The below example is a fairly basic one - you can follow the same process to wrap up the other methods in Console (readPassword, format) as required. That way you can run it happily in Eclipse & when its deployed you get the Console features (e.g. password hiding) kicking in. private static String readLine(String prompt) { String line = null; Console c = System.console(); if (c != null) { line = c.readLine(prompt); } else { System.out.print(prompt); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); try { line = bufferedReader.readLine(); } catch (IOException e) { //Ignore } } return line; } A: The workaround that I use is to just use System.in/System.out instead of Console when using Eclipse. For example, instead of: String line = System.console().readLine(); You can use: BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); String line = bufferedReader.readLine(); A: As far as I can tell, there is no way to get a Console object from Eclipse. I'd just make sure that console != null, then JAR it up and run it from the command line. A: There seems to be no way to get a java.io.Console object when running an application through Eclipse. A command-line console window is not opened with the application, as it is run as a background process (background to Eclipse?). Currently, there is no Eclipse plugin to handle this issue, mainly due to the fact that java.io.Console is a final class. All you can really do is test the returned Console object for null and proceed from there. A: This link offers alternatives to using System.console(). One is to use a BufferedReader wrapped around System.in, the second is to use a Scanner wrapped around System.in. Neither are as concise as console, but both work in eclipse without having to resort to debug silliness! A: Let's say your Eclipse workspace is C:\MyWorkspace, you created your java application inside a maven project MyProject, and your Java main class is com.mydomain.mypackage.MyClass. In this case, you can run your main class that uses System.console() on the command line: java -cp C:\MyWorkspace\MyProject\target\classes com.mydomain.mypackage.MyClass NB1: if it's not in a maven project, check the output folder in project properties | Java Build Path | Source. It might not be "target/classes" NB2: if it is a maven project, but your class is in src/test/java, you'll likely have to use "target\test-classes" instead of "target\classes"
{ "language": "en", "url": "https://stackoverflow.com/questions/104254", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "107" }
Q: xul: open a local html file relative to "myapp.xul" in xul browser in short: is there any way to find the current directory full path of a xul application? long explanation: I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app) It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html" what i want to do is to open the file relative to my xul application. I found i can open the user's profile path: var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties"); var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path; var appletPath; // find directory separator type if (path.search(/\\/) != -1) { appletPath = path + "\\myApp\\content\\applet.html" } else { appletPath = path + "/myApp/content/applet.html" } // Cargar el applet en el iframe var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); appletFile.initWithPath(appletPath); var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile); var appletFrame = document.getElementById("appletFrame"); appletFrame.setAttribute("src", appletURL); is there any way to find the current directory full path of a xul application? A: I found a workaround: http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO i cannot exactly open a file using a relative path "../../index.html" but i can get the app directory and work with that. var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties"); var path = (new DIR_SERVICE()).get(resource:app, Components.interfaces.nsIFile).path; var appletPath; A: Yes, html files within your extension can be addressed using chrome URIs. An example from one of my extensions: content.document.location.href = "chrome://{appname}/content/logManager/index.html" A: In a xul application, you can access the chrome folder of the application using a chrome url. I have relatively little experience with the element , so I'm not sure if this will work exactly for you. It is the way you include javascript source files in your xul file: <script src="chrome://includes/content/XSLTemplate.js" type="application/x-javascript"/> So, perhaps if the file resides at c:\applicationFolder\chrome\content\index.html , you can access it at: chrome://content/index.html in some fashion. You may also look at jslib, a library that simplifies a lot of things, including file i/o. IIRC, I had trouble getting to a relative path using '../', though.
{ "language": "en", "url": "https://stackoverflow.com/questions/104267", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Flash vs. Silverlight We are building a training website where we need to track viewers watching videos and store detailed info about the viewing (when they paused, if they watched the whole video etc) What should we consider when deciding between the two technologies? I forgot to add. This is for an in house app. We have complete control over the environment. If it this was for a public application I would definitely go with Flash. I'm just looking for technical advantages of one over the other from someone who has used both. A: having had to make the call between silverlight and flash recently for a very intense interactive component, i had to go with flash. and for one reason: online support. If i have a problem building something in flash, chances are pretty good that I'll find help somewhere online from someone thats overcome the same issue. And with Silverlight being new and still fresh from beta iterations, finding that same volume of help is unlikely (at least right now.) In the end, my Flash app was pretty complicated and I still had quite a few issues that I was unable to find help for and just had to dig through api's and try a few things out. Had I gone with Silverlight instead, I would have been desperately idle. dont get me wrong, i'm dying to jump into silverlight and I'd love to convert my flash app to SL someday. I just need the online community/forum presence to grow. And it will. I'm excited to see where Silverlight will go. A: What do your developers know? If they already know ActionScript then use Flash, if they know C#, VB.NET, JavaScript, Ruby, or Python then use Silverlight. A: If you are looking for maintainablility, its silverlight, their programming api, is way cleaner. But, its not only not installed everywhere, its not supported by every browser or client OS. If you can, do it in both, but if you can't, do it in flash , and port it when you get a chance after the install base is larger, since silverlight is easier engineering wise. A: I'd personally use Flash due to installed base. The way I see it, if YouTube and Google Video are using Flash than just about every computer on earth has it so it wins hands down. A: I have yet to find a silverlight video that works properly in firefox. As far as I know there is also no linux viewer. Also there are more users out there that have flash already installed so not having to install another app to watch a video will have more people watch the video A: i found this blog (not mine!) very interesting on the subject. personally i would adopt a solution based on needs, if i was building say a internal app for a company on a windows network, then silverlight seems great. Otherwise, it seems you leave out the entire rest of the world by going with silverlight on a public site. I'm all for competition and both are still proprietary products. Although the flex3 compiler and framework have been released open source the actual flash player is still proprietary. That said almost every computer online has some form of the flash player, though it might not be the needed version 9 for flex apps, it can easily be upgraded through a simple click in the browser. A: Pls find some additional info here: Silverlight vs Flex A: If you need stats to support a decision for Flash, you can grab it's install stats here: http://www.adobe.com/products/player_census/flashplayer/version_penetration.html About 97% install rate. That's pretty sweet. A: It does matter how many concurrent queries you're awaiting. This was also the decision-base for the Olympics-Website, because a lot more server-ressources are needed to deliver videos via flash instead of silverlight. So silverlight might be cost-saving. A: Sounds like you have got complete control over the environement So it is better to choose Silverlight because of the ease of development and extensibility features of this new technology. It supports the best scripting language(C#, the most matured language ever). I bet the investment you can make on this new technology wont depress you in the future. A: There is a valuable blog where the author compares Silverlight and Flash from a developer and end-user point of view. Both Silverlight and Flash running the same use cases are shown, the code can be downloaded and the users can up/down about the best one. I consider this site as a great Silverlight vs Flash resource. http://www.shinedraw.com/ A: Silverlight is actually closing in in flash, and functionality flash just recently got is rapidly being implemented in silverlight, but there's still a lot more users with flash than with silverlight, so you'll reach out to more with flash. here's statistics of how many % of users have them installed. http://riastats.com/# as you can see, flash is far ahead A: I've gotta say silverlight has a much better API and with the .NET it's got a huge benefit A: I'll chime in because it seems people missed the point of the question: What are the technical advantages of Flash vs Silverlight? (as it pertains to an in-house app) Flash Pros * *The "artistic" interface is much better, in my opinion. If you have artists and designers that are used to using Illustrator or Photoshop, this is pretty straight forward. *The way their environment integrates frame-based movie timelines is pretty slick and has been for years. It makes it very easy to integrate and layer many different animated elements and sounds into your movie or animation. *All coding is done in the JavaScript-esque language ActionScript, so the learning curve for the syntax at least is pretty low for non-microsoft developers. *Online support. There are years and years worth of posts that can help you figure out what you need to do to get what you want in Flash. Silverlight Pros * *It uses .Net as a back end. If you have a lot of .Net developers, you'll be able to leverage the .Net framework which is a much more powerful set of tools, programmatically speaking. *Easier to debug. In my experience it's easier to debug than Actionscript, largely due to the superior IDE. *Bringing me to the IDE. The coding IDE is vastly superior to Flash's clunky, cobbled together, fancified textpad. It has intellisense, auto-complete, etc. Flash Cons * *In my extensive Flash experience, If you're making a highly interactive app, it can be buggy as all get out. Some of the bugs bordering on nonsense, the work arounds being hackish at best. *The IDE sucks. Period. It's notepad with some poorly implemented intellisense-esque keyword identification. *The language falls on it's face at times. I've seen instances where all of a sudden a var got all type-sensitive on me, where it wasn't just two stanzas prior. My fault? Maybe. Probably. But nonetheless I've seen some weird behavior from ActionScript, whereas C# has always done what I've told it to. *No real standard way of doing things. No "best-practice put your code here" way to do things. Flash lets you put code on anything. A frame, a MovieClip, an object, an array... sure whatever, just pop some functions on some stuff and party! This makes finding bugs in someone else's app a real chore. Silverlight Cons * *Not a lot of documentation yet, in my opinion. *Substandard "artist" interface by comparision. If you're going for a certain look, it may be harder for your designer to acheive. *If you're not used to XAML, layouts can be a real pain in the butt. If you've never used XAML, and you've got a sort timeline to get this thing done, you best be prepared to put in some extra time, or be okay with a less than stellar look and feel. It's not quite as easy to get the look that you want with XAML as it is in Flash. Again, all of this is in my own opinion and from my experiences. Other people may have different opinions. If you have a few designers and some Flash experience, go with flash. If you want to learn something new, pad your resume, and you've got nothing but .Net experience, go with Silverlight. In the end, do whatever it is that makes you like coming to work. (as long as it meets your deadlines. lol) Oh, and I should note, I wasn't talking about FLEX here, but Flash. A: Flash is more widely use but SilverLight got good press during the Olympic. Can't you have both to have the more user. Because if you stop just with SilverLight you might cut all user that doesn't bother to install the needed file. A: Both can fulfill all of your requirements, so go with the one with the higher install base - which is, hands down, Flash. A: If you have full control of environment, consider WPF/Web Browser Application. Compared to Silverlight, development is a bit easier and learning curve for typical .NET developers is practically flat.
{ "language": "en", "url": "https://stackoverflow.com/questions/104270", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Trialware/licensing strategies I wrote a utility for photographers that I plan to sell online pretty cheap ($10). I'd like to allow the user to try the software out for a week or so before asking for a license. Since this is a personal project and the software is not very expensive, I don't think that purchasing the services of professional licensing providers would be worth it and I'm rolling my own. Currently, the application checks for a registry key that contains an encrypted string that either specifies when the trial expires or that they have a valid license. If the key is not present, a trial period key is created. So all you would need to do to get another week for free is delete the registry key. I don't think many users would do that, especially when the app is only $10, but I'm curious if there's a better way to do this that is not onerous to the legitimate user. I write web apps normally and haven't dealt with this stuff before. The app is in .NET 2.0, if that matters. A: If you are hosting your homepage on a server that you control, you could have the downloadable trial-version of your software automatically compile to a new binary every night. This compile will replace a hardcoded datetime-value in your program for when the software expires. That way the only way to "cheat" is to change the date on your computer, and most people wont do that because of the problems that will create. A: Try the Shareware Starter Kit. It was developed my Microsoft and may have some other features you want. http://msdn.microsoft.com/en-us/vs2005/aa718342.aspx A: If you are planning to continue developing your software, you might consider the ransom model: http://en.wikipedia.org/wiki/Street_Performer_Protocol Essentially, you develop improvements to the software, and then ask for a certain amount of donations before you release them (without any DRM). A: One way to do it that's easy for the user but not for you is to hard-code the expiry date and make new versions of the installer every now and then... :) If I were you though, I wouldn't make it any more advanced than what you're already doing. Like you say it's only $10, and if someone really wants to crack your system they will do it no matter how complicated you make it. You could do a slightly more advanced version of your scheme by requiring a net connection and letting a server generate the trial key. If you do something along the lines of sign(hash(unique_computer_id+when_to_expire)) and let the app check with a public key that your server has signed the expiry date it should require a "real" hack to bypass. This way you can store the unique id's serverside and refuse to generate a expiry date more than once or twice. Not sure what to use as the unique id, but there should be some way to get something useful from Windows. A: I am facing the very same problem with an application I'm selling for a very low price as well. Besides obfuscating the app, I came up with a system that uses two keys in the registry, one of which is used to determine that time of installation, the other one the actual license key. The keys are named obscurely and a missing key indicates tampering with the installation. Of course deleting both keys and reinstalling the application will start the evaluation time again. I figured it doesn't matter anyway, as someone who wants to crack the app will succeed in doing so, or find a crack by someone who succeeded in doing so. So in the end I'm only achieving the goal of making it not TOO easy to crack the application, and this is what, I guess, will stop 80-90% of the customers from doing so. And afterall: as the application is sold for a very low price, there's no justification for me to invest any more time into this issue than I already have. A: just be cool about the license. explain up front that this is your passion and a child of your labor. give people a chance to do the right thing. if someone wants to pirate it, it will happen eventually. i still remember my despair seeing my books on bittorrent, but its something you have to just deal with. Don't cave to casual piracy (what you're doing now sounds great) but don't cripple the thing beyond that. I still believe that there are enough honest people out there to make a for-profit coding endeavor worth while. A: Don't have the evaluation based on "days since install", instead do number of days used, or number of times run or something similar. People tend to download shareware, run it once or twice, and then forget it for a few weeks until they need it again. By then, the trial may have expired and so they've only had a few tries to get hooked on using your app, even though they've had it installed for a while. Number of activation/days instead lets them get into a habit of using your app for a task, and also makes a stronger sell (i.e. you've used this app 30 times...). Even better, limiting the features works better than timing out. For example, perhaps your photography app could limit the user to 1 megapixel images, but let them use it for as long as they want. Also, consider pricing your app at $20 (or $19.95). Unless there's already a micropayment setup in place (like iPhone store or XBoxLive or something) people tend to have an aversion to buying things online below a certain price point (which is around $20 depending on the type of app), and people assume subconciously if something is inexpensive, it must not be very good. You can actually raise your conversion rate with a higher price (up to a point of course). A: EDIT: You can make your current licensing scheme considerable more difficult to crack by storing the registry information in the Local Security Authority (LSA). Most users will not be able to remove your key information from there. A search for LSA on MSDN should give you the information you need. Opinions on licensing schemes vary with each individual, more among developers than specific user groups (such as photographers). You should take a deep breath and try to see what your target user would accept, given the business need your application will solve. This is my personal opinion on the subject. There will be vocal individuals that disagree. The answer to this depends greatly on how you expect your application to be used. If you expect the application to be used several times every day, you will benefit the most from a very long trial period (several month), to create a lock-in situation. For this to work you will have to have a grace period where the software alerts the user that payment will be needed soon. Before the grace period you will have greater success if the software is silent about the trial period. Wether or not you choose to believe in this quite bold statement is of course entirely up to you. But if you do, you should realize that the less often your application will be used, the shorter the trial period should be. It is also very important that payment is very quick and easy for the user (as little data entry and as few clicks as possible). If you are very uncertain about the usage of the application, you should choose a very short trial period. You will, in my experience, achieve better results if the application is silent about the fact that it is in trial period in this case. Though effective for licensing purposes, "Call home" features is regarded as a privacy threat by many people. Personally I disagree with the notion that this is any way bad for a customer that is willing to pay for the software he/she is using. Therefore I suggest implementing a licensing scheme where the application checks the license status (trial, paid) on a regular basis, and helps the user pay for the software when it's time. This might be overkill for a small utility application, though. For very small, or even simple, utility applications, I argue that upfront payment without trial period is the most effective. Regarding the security of the solution, you have to make it proportional to the development effort. In my line of work, security is very critical because there are partners and dealers involved, and because the investment made in development is very high. For a small utility application, it makes more sense to price it right and rely on the honest users that will pay for the software that address their business needs. A: There's not much point to doing complicated protection schemes. Basically one of two things will happen: * *Your app is not popular enough, and nobody cracks it. *Your app becomes popular, someone cracks it and releases it, then anybody with zero knowledge can simply download that crack if they want to cheat you. In the case of #1, it's not worth putting a lot of effort into the scheme, because you might make one or two extra people buy your app. In the case of #2, it's not worth putting a lot of effort because someone will crack it anyway, and the effort will be wasted. Basically my suggestion is just do something simple, like you already are, and that's just as effective. People who don't want to cheat / steal from you will pay up, people who want to cheat you will do it regardless. A: In these sort of circumstances, I don't really think it matters what you do. If you have some kind of protection it will stop 90% of your users. The other 10% - if they don't want to pay for your software they'll pretty much find a way around protection no matter what you do. If you want something a little less obvious you can put a file in System32 that sounds like a system file that the application checks the existence of on launch. That can be a little harder to track down.
{ "language": "en", "url": "https://stackoverflow.com/questions/104291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: How do I change the build directory that MSBuild uses under Team Foundation Build? I'm getting the following error when trying to build my app using Team Foundation Build: C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(1682,9): error MSB3554: Cannot write to the output file "obj\Release\Company.Redacted.BlahBlah.Localization.Subsystems. Startup_Shutdown_Processing.StartupShutdownProcessingMessages.de.resources". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. My project builds fine on my development machine as the source is only two folders deep, but TF Build seems to use a really deep directory that is causing it to break. How do I change the folders that are used? Edit: I checked the .proj file for my build that is stored in source control and found the following: <!-- BUILD DIRECTORY This property is included only for backwards compatibility. The build directory used for a build definition is now stored in the database, as the BuildDirectory property of the definition's DefaultBuildAgent. For compatibility with V1 clients, keep this property in sync with the value in the database. --> <BuildDirectoryPath>UNKNOWN</BuildDirectoryPath> If this is stored in the database how do I change it? Edit: Found the following blog post which may be pointing me torward the solution. Now I just need to figure out how to change the setting in the Build Agent. http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx Currently my working directory is "$(Temp)\$(BuildDefinitionPath)" but now I don't know what wildcards are available to specify a different folder. A: You need to edit the build working directory of your Build Agent so that the begging path is a little smaller. To edit the build agent, right click on the "Builds" node and select "Manage Build Agents..." I personally use something like c:\bw\$(BuildDefinitionId). $(BuildDefinitionId) translates into the id of the build definition (hence the name :-) ), which means you get a build path starting with something like c:\bw\36 rather than c:\Documents and Settings\tfsbuild\Local Settings\Temp\BuildDefinitionName Good luck, Martin. A: you have to checkout the build script file, from the source control explorer, and get your elbows dirty replacing the path.
{ "language": "en", "url": "https://stackoverflow.com/questions/104292", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: How do I run another web site or web service side by side with Sharepoint? I'm getting a 404 error when trying to run another web service on an IIS 6 server which is also running Sharepoint 2003. I'm pretty sure this is an issue with sharepoint taking over IIS configuration. Is there a way to make a certain web service or web site be ignored by whatever Sharepoint is doing? A: I found the command line solution. STSADM.EXE -o addpath -url http://localhost/<your web service/app> -type exclusion A: I depends on what you mean by side by side, if you are trying to make something inside the same URL path as sharepoint then the above answers about managed paths should do it for you, but there is also nothing stopping you from just creating another Web Site inside of IIS, sharepoint will only take over the requests coming to its specific web. A: you'll have to go into the SharePoint admin console and explicitely allow that web application to run on on the same web site as SharePoint. I believe it is under defined managed paths. Central Administration > Application Management > Define Managed Paths A: Hasn't this change from 2003 to 2007? There's no longer an excluded paths option.
{ "language": "en", "url": "https://stackoverflow.com/questions/104293", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Apache module FORM handling in C I'm implementing an Apache 2.0.x module in C, to interface with an existing product we have. I need to handle FORM data, most likely using POST but I want to handle the GET case as well. Nick Kew's Apache Modules book has a section on handling form data. It provides code examples for POST and GET, which return an apr_hash_t of the key+value pairs in the form. parse_form_from_POST marshalls the bucket brigade and flattens it into a buffer, while parse_form_from_GET can simply reference the URL. Both routines rely on a parse_form_from_string routine to walk through each delimited field and extract the information into the hash table. That would be fine, but it seems like there should be an easier way to do this than adding a couple hundred lines of code to my module. Is there an existing module or routines within apache, apr, or apr-util to extract the field names and associated data from a GET or POST FORM into a structure which C code can more easily access? I cannot find anything relevant, but this seems like a common need for which there should be a solution. A: I switched to G-WAN which offers a transparent ANSI C scripts interface for GET and POST forms (and many other goodies like charts, GIF I/O, etc.). A couple of AJAX examples are available at the GWAN developer page Hope it helps! A: While, on it's surface, this may seem common, cgi-style content handlers in C on apache are pretty rare. Most people just use CGI, FastCGI, or the myriad of frameworks such as mod_perl. Most of the C apache modules that I've written are targeted at modifying the particular behavior of the web server in specific, targeted ways that are applicable to every request. If it's at all possible to write your handler outside of an apache module, I would encourage you to pursue that strategy. A: I have not yet tried any solution, since I found this SO question as a result of my own frustration with the example in the "Apache Modules" book as well. But here's what I've found, so far. I will update this answer when I have researched more. Luckily it looks like this is now a solved problem in Apache 2.4 using the ap_parse_form_data funciton. No idea how well this works compared to your example, but here is a much more concise read_post function. It is also possible that mod_form could be of value.
{ "language": "en", "url": "https://stackoverflow.com/questions/104313", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do you install Boost on MacOS? How do you install Boost on MacOS? Right now I can't find bjam for the Mac. A: Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of Getting Started Guide for Unix Variants. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile. A: Install both of them using homebrew separately. brew install boost brew install bjam A: Fink appears to have a full set of Boost packages... With fink installed and running just do fink install boost1.35.nopython at the terminal and accept the dependencies it insists on. Or use fink list boost to get a list of different packages that are availible. A: Install Xcode from the mac app store. Then use the command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" the above will install homebrew and allow you to use brew in terminal then just use command : brew install boost which would then install the boost libraries to <your macusername>/usr/local/Cellar/boost A: In order to avoid troubles compiling third party libraries that need boost installed in your system, run this: sudo port install boost +universal A: Try +universal One thing to note: in order for that to make a difference you need to have built python with +universal, if you haven't or you're not sure you can just rebuild python +universal. This applies to both brew as well as macports. $ brew reinstall python $ brew install boost OR $ sudo port -f uninstall python $ sudo port install python +universal $ sudo port install boost +universal A: You can get the latest version of Boost by using Homebrew. brew install boost. A: you can download bjam for OSX (or any other OS) here A: If you are too lazy like me: conda install -c conda-forge boost A: Download MacPorts, and run the following command: sudo port install boost A: Just get the source, and compile Boost yourself; it has become very easy. Here is an example for the current version of Boost on the current macOS as of this writing: * *Download the the .tar.gz from https://www.boost.org/users/download/#live *Unpack and go into the directory:tar -xzf boost_1_50_0.tar.gz cd boost_1_50_0 *Configure (and build bjam): ./bootstrap.sh --prefix=/some/dir/you/would/like/to/prefix *Build: ./b2 *Install:./b2 install Depending on the prefix you choose in Step 3, you might need to sudo Step 5, if the script tries copy files to a protected location.
{ "language": "en", "url": "https://stackoverflow.com/questions/104322", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "204" }
Q: Use jQuery to replace XMLHttpRequest I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this: var req; function createRequest() { var key = document.getElementById("key"); var keypressed = document.getElementById("keypressed"); keypressed.value = key.value; var url = "/My_Servlet/response?key=" + escape(key.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("Get", url, true); req.onreadystatechange = callback; req.send(null); } function callback() { if (req.readyState == 4) { if (req.status == 200) { var decimal = document.getElementById('decimal'); decimal.value = req.responseText; } } clear(); } I wanted to replace my code with something a little friendlier like jQuery's $.get(url, callback); However it doesn't call my callback function. Also I would like to call a function called createRequest continuously. Does jQuery have a nice way of doing that? ­­­­­­­­­­­­­­­­­­­­­­­ A: Take out the readyState and status checks. jQuery only calls your callback upon success. Your callback is supplied the arguments (data, textStatus), so you should use data instead of req.responseText. window.setTimeout() as suggested by another answer won't do what you want - that only waits and then calls your function once. You need to use window.setInterval() instead, which will call your function periodically until you cancel it. So, in summary: var interval = 500; /* Milliseconds between requests. */ window.setInterval(function() { var val = $("#key").val(); $("#keypressed").val(val); $.get("/My_Servlet/response", { "key": val }, function(data, textStatus) { $("#decimal").val(data); }); }), interval); A: I don't think jQuery implements a timeout function, but plain old javascript does it rather nicely :) A: According to the docs, jQuery.get's arguments are url, data, callback, not url, callback. A call to JavaScript's setTimeout function at the end of your callback function should suffice to get this to continually execute. A: There's no need to set the GET parameters on the URL, jQuery will set them automatically. Try this code: var key = document.getElementById("key"); [...] var url = "/My_Servlet/response"; $.get (url, {'key': key}, function (responseText) { var decimal = document.getElementById ('decimal'); decimal.value = responseText; }); A: $.get(url, {}, callback); should do the trick. Your callback could be simplified like this: function callback(content){ $('#decimal').val(content); } Or even shorter: $.get(url, {}, function(content){ $('#decimal').val(content); }); And all in all I think this should work: function createRequest() { var keyValue = $('#key').val(); $('#keypressed').val(keyValue); var url = "/My_Servlet/response"; $.get(url, {key: keyValue}, function(content){ $('#decimal').val(content); }); } A: In the end I guess it was added the type. This seems to work for me. function convertToDecimal(){ var key = document.getElementById("key"); var keypressed = document.getElementById("keypressed"); keypressed.value = key.value; var url = "/My_Servlet/response?key="+ escape(key.value); jQuery.get(url, {}, function(data){ callback(data);} , "text" ); } function callback(data){ var decimal = document.getElementById('decimal'); decimal.value = data; clear(); } Thanks Everyone for the help. I'll vote you up.
{ "language": "en", "url": "https://stackoverflow.com/questions/104323", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Performance of try-catch in php What kind of performance implications are there to consider when using try-catch statements in php 5? I've read some old and seemingly conflicting information on this subject on the web before. A lot of the framework I currently have to work with was created on php 4 and lacks many of the niceties of php 5. So, I don't have much experience myself in using try-catchs with php. A: Generally, use an exception to guard against unexpected failures, and use error checking in your code against failures that are part of normal program state. To illustrate: * *Record not found in database - valid state, you should be checking the query results and messaging the user appropriately. *SQL error when trying to fetch record - unexpected failure, the record may or may not be there, but you have a program error - this is good place for an exception - log error in error log, email the administrator the stack trace, and display a polite error message to the user advising him that something went wrong and you're working on it. Exceptions are expensive, but unless you handle your whole program flow using them, any performance difference should not be human-noticeable. A: One thing to consider is that the cost of a try block where no exception is thrown is a different question from the cost of actually throwing and catching an exception. If exceptions are only thrown in failure cases, you almost certainly don't care about performance, since you won't fail very many times per execution of your program. If you're failing in a tight loop (a.k.a: banging your head against a brick wall), your application likely has worse problems than being slow. So don't worry about the cost of throwing an exception unless you're somehow forced to use them for regular control flow. Someone posted an answer talking about profiling code which throws an exception. I've never tested it myself, but I confidently predict that this will show a much bigger performance hit than just going in and out of a try block without throwing anything. Another thing to consider is that where you nest calls a lot of levels deep, it can even be faster to have a single try...catch right at the top than it is to check return values and propagate errors on every call. In the opposite of that situation, where you find that you're wrapping every call in its own try...catch block, your code will be slower. And uglier. A: I was bored and profiled the following (I left the timing code out): function no_except($a, $b) { $a += $b; return $a; } function except($a, $b) { try { $a += $b; } catch (Exception $e) {} return $a; } using two different loops: echo 'no except with no surrounding try'; for ($i = 0; $i < NUM_TESTS; ++$i) { no_except(5, 7); } echo 'no except with surrounding try'; for ($i = 0; $i < NUM_TESTS; ++$i) { try { no_except(5, 7); } catch (Exception $e) {} } echo 'except with no surrounding try'; for ($i = 0; $i < NUM_TESTS; ++$i) { except(5, 7); } echo 'except with surrounding try'; for ($i = 0; $i < NUM_TESTS; ++$i) { try { except(5, 7); } catch (Exception $e) {} } With 1000000 runs on my WinXP box run apache and PHP 5.2.6: no except with no surrounding try = 3.3296 no except with surrounding try = 3.4246 except with no surrounding try = 3.2548 except with surrounding try = 3.2913 These results were consistent and remained in similar proportion no matter which order the tests ran. Conclusion: Adding code to handle rare exceptions is no slower than code the ignores exceptions. A: I have not found anything on Try/Catch performance on Google but a simple test with a loop throwing error instead of a IF statement produce 329ms vs 6ms in a loop of 5000. A: Sorry to post to a very old message, but I read the comments and I somewhat disagree, the difference might be minimal with simple piece of codes, or it could be neglectable where the Try/Catch are used for specific parts of code that are not always predictable, but I also believe (not tested) that a simple: if(isset($var) && is_array($var)){ foreach($var as $k=>$v){ $var[$k] = $v+1; } } is faster than try{ foreach($var as $k=>$v){ $var[$k] = $v+1; } }catch(Exception($e)){ } I also believe (not tested) that a: <?php //beginning code try{ //some more code foreach($var as $k=>$v){ $var[$k] = $v+1; } //more code }catch(Exception($e)){ } //output everything ?> is more expensive than have extra IFs in the code A: Try-catch blocks are not a performance problem - the real performance bottleneck comes from creating exception objects. Test code: function shuffle_assoc($array) { $keys = array_keys($array); shuffle($keys); return array_merge(array_flip($keys), $array); } $c_e = new Exception('n'); function no_try($a, $b) { $a = new stdclass; return $a; } function no_except($a, $b) { try { $a = new Exception('k'); } catch (Exception $e) { return $a + $b; } return $a; } function except($a, $b) { try { throw new Exception('k'); } catch (Exception $e) { return $a + $b; } return $a; } function constant_except($a, $b) { global $c_e; try { throw $c_e; } catch (Exception $e) { return $a + $b; } return $a; } $tests = array( 'no try with no surrounding try'=>function() { no_try(5, 7); }, 'no try with surrounding try'=>function() { try { no_try(5, 7); } catch (Exception $e) {} }, 'no except with no surrounding try'=>function() { no_except(5, 7); }, 'no except with surrounding try'=>function() { try { no_except(5, 7); } catch (Exception $e) {} }, 'except with no surrounding try'=>function() { except(5, 7); }, 'except with surrounding try'=>function() { try { except(5, 7); } catch (Exception $e) {} }, 'constant except with no surrounding try'=>function() { constant_except(5, 7); }, 'constant except with surrounding try'=>function() { try { constant_except(5, 7); } catch (Exception $e) {} }, ); $tests = shuffle_assoc($tests); foreach($tests as $k=>$f) { echo $k; $start = microtime(true); for ($i = 0; $i < 1000000; ++$i) { $f(); } echo ' = '.number_format((microtime(true) - $start), 4)."<br>\n"; } Results: no try with no surrounding try = 0.5130 no try with surrounding try = 0.5665 no except with no surrounding try = 3.6469 no except with surrounding try = 3.6979 except with no surrounding try = 3.8729 except with surrounding try = 3.8978 constant except with no surrounding try = 0.5741 constant except with surrounding try = 0.6234 A: I updated Brilliand's test code to make it's report more understandable and also statitistically truthfully by adding more randomness. Since I changed some of its tests to make them more fair the results will be different, therefore I write it as different answer. My tests executed by: PHP 7.4.4 (cli) (built: Mar 20 2020 13:47:45) ( NTS ) <?php function shuffle_assoc($array) { $keys = array_keys($array); shuffle($keys); return array_merge(array_flip($keys), $array); } $c_e = new Exception('n'); function do_nothing($a, $b) { return $a + $b; } function new_exception_but_not_throw($a, $b) { try { new Exception('k'); } catch (Exception $e) { return $a + $b; } return $a + $b; } function new_exception_and_throw($a, $b) { try { throw new Exception('k'); } catch (Exception $e) { return $a + $b; } return $a + $b; } function constant_exception_and_throw($a, $b) { global $c_e; try { throw $c_e; } catch (Exception $e) { return $a + $b; } return $a + $b; } $tests = array( 'do_nothing with no surrounding try'=>function() { do_nothing(5, 7); }, 'do_nothing with surrounding try'=>function() { try { do_nothing(5, 7); } catch (Exception $e) {} }, 'new_exception_but_not_throw with no surrounding try'=>function() { new_exception_but_not_throw(5, 7); }, 'new_exception_but_not_throw with surrounding try'=>function() { try { new_exception_but_not_throw(5, 7); } catch (Exception $e) {} }, 'new_exception_and_throw with no surrounding try'=>function() { new_exception_and_throw(5, 7); }, 'new_exception_and_throw with surrounding try'=>function() { try { new_exception_and_throw(5, 7); } catch (Exception $e) {} }, 'constant_exception_and_throw with no surrounding try'=>function() { constant_exception_and_throw(5, 7); }, 'constant_exception_and_throw with surrounding try'=>function() { try { constant_exception_and_throw(5, 7); } catch (Exception $e) {} }, ); $results = array_fill_keys(array_keys($tests), 0); $testCount = 30; const LINE_SEPARATOR = PHP_EOL; //"<br>"; for ($x = 0; $x < $testCount; ++$x) { if (($testCount-$x) % 5 === 0) { echo "$x test cycles done so far".LINE_SEPARATOR; } $tests = shuffle_assoc($tests); foreach ($tests as $k => $f) { $start = microtime(true); for ($i = 0; $i < 1000000; ++$i) { $f(); } $results[$k] += microtime(true) - $start; } } echo LINE_SEPARATOR; foreach ($results as $type => $result) { echo $type.' = '.number_format($result/$testCount, 4).LINE_SEPARATOR; } The results are following: do_nothing with no surrounding try = 0.1873 do_nothing with surrounding try = 0.1990 new_exception_but_not_throw with no surrounding try = 1.1046 new_exception_but_not_throw with surrounding try = 1.1079 new_exception_and_throw with no surrounding try = 1.2114 new_exception_and_throw with surrounding try = 1.2208 constant_exception_and_throw with no surrounding try = 0.3214 constant_exception_and_throw with surrounding try = 0.3312 Conclusions are: * *adding extra try-catch adds ~0.01 microsecond per 1000000 iterations *exception throwing and catching adds ~0.12 microsecond (x12 compared to previous when nothing were thrown and nothing were catched) *exception creation adds ~0.91 microsecond (x7.6 compared to execution of try-catch mechanism calculated in previous line) So the most expensive part is exception creation - not the throw-catch mechanism, however latter made this simple routine 2 times slower compared to do_nothing scenarion. * all measurements in conclusions are rounded and are not pretends to be scientifically accurate. A: Thats a very good question! I have tested it many times and never saw any performance issue ;-) It was true 10 years ago in C++ but I think today they have improved it a lot since its so usefull and cleaner. But I am still afraid to surround my first entry point with it: try {Controller::run();}catch(...) I didnt test with plenty of functions call and big include .... Is anyone has fully test it already? A: Generally speaking, they're expensive and not worthwhile in PHP. Since it is a checked expressions language, you MUST catch anything that throws an exception. When dealing with legacy code that doesn't throw, and new code that does, it only leads to confusion. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/104329", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "66" }
Q: SQL Query Help: Transforming Dates In A Non-Trivial Way I have a table with a "Date" column, and I would like to do a query that does the following: If the date is a Monday, Tuesday, Wednesday, or Thursday, the displayed date should be shifted up by 1 day, as in DATEADD(day, 1, [Date]) On the other hand, if it is a Friday, the displayed date should be incremented by 3 days (i.e. so it becomes the following Monday). How do I do this in my SELECT statement? As in, SELECT somewayofdoingthis([Date]) FROM myTable (This is SQL Server 2000.) A: Here is how I would do it. I do recommend a function like above if you will be using this in other places. CASE WHEN DATEPART(dw, [Date]) IN (2,3,4,5) THEN DATEADD(d, 1, [Date]) WHEN DATEPART(dw, [Date]) = 6 THEN DATEADD(d, 3, [Date]) ELSE [Date] END AS [ConvertedDate] A: CREATE FUNCTION dbo.GetNextWDay(@Day datetime) RETURNS DATETIME AS BEGIN DECLARE @ReturnDate DateTime set @ReturnDate = dateadd(dd, 1, @Day) if (select datename(@ReturnDate))) = 'Saturday' set @ReturnDate = dateadd(dd, 2, @ReturnDate) if (select datename(@ReturnDate) = 'Sunday' set @ReturnDate = dateadd(dd, 1, @ReturnDate) RETURN @ReturnDate END A: Try select case when datepart(dw,[Date]) between 2 and 5 then DATEADD(dd, 1, [Date]) when datepart(dw,[Date]) = 6 then DATEADD(dd, 3, [Date]) else [Date] end as [Date] A: I'm assuming that you also want Saturday and Sunday to shift forward to the following Monday. If that is not the case, take the 1 out of (1,2,3,4,5) and remove the last when clause. case --Sunday thru Thursday are shifted forward 1 day when datepart(weekday, [Date]) in (1,2,3,4,5) then dateadd(day, 1, [Date]) --Friday is shifted forward to Monday when datepart(weekday, [Date]) = 6 then dateadd(day, 3, [Date]) --Saturday is shifted forward to Monday when datepart(weekday, [Date]) = 7 then dateadd(day, 2, [Date]) end You can also do it in one line: select dateadd(day, 1 + (datepart(weekday, [Date])/6) * (8-datepart(weekday, [Date])), [Date]) A: Sounds like a CASE expression. I don't know the proper data manipulations for SQL Server, but basically it would look like this: CASE WHEN [Date] is a Friday THEN DATEADD( day, 3, [Date] ) ELSE DATEADD( day, 1, [Date] ) END If you wanted to check for weekend days you could add additional WHEN clauses before the ELSE. A: This is off the top of my head and can be clearly cleaned up but use it as a starting point: select case when DATENAME(dw, [date]) = 'Monday' then DATEADD(dw, 1, [Date]) when DATENAME(dw, [date]) = 'Tuesday' then DATEADD(dw, 1, [Date]) when DATENAME(dw, [date]) = 'Wednesday' then DATEADD(dw, 1, [Date]) when DATENAME(dw, [date]) = 'Thursday' then DATEADD(dw, 1, [Date]) when DATENAME(dw, [date]) = 'Friday' then DATEADD(dw, 3, [Date]) end as nextDay ... A: you could use this: select dayname,newdayname = CASE dayname WHEN 'Monday' THEN 'Tuesday' WHEN 'Tuesday' THEN 'Wednesday' WHEN 'Wednesday' THEN 'Thursday' WHEN 'Thursday' THEN 'Friday' WHEN 'Friday' THEN 'Monday' WHEN 'Saturday' THEN 'Monday' WHEN 'Sunday' THEN 'Monday' END FROM UDO_DAYS results: Monday Tuesday Tuesday Wednesday Wednesday Thursday Thursday Friday Friday Monday Saturday Monday Sunday Monday table data: Monday Tuesday Wednesday Thursday Friday Saturday Sunday A: Look up the CASE statement and the DATEPART statement. You will want to use the dw argument with DATEPART to get back an integer that represents the day of week. A: How about taking a page from the Data Warehouse guys and make a table. In DW terms, this would be a date dimension. A standard date dimension would have things like various names for a date ("MON", "Monday", "August 22, 1998"), or indicators like end-of-month and start-of-month. However, you can also have columns that only make sense in your environment. For instance, based on the question, yours might have a next-work-day column that would point to the key for the day in question. That way you can customize it further to take into account holidays or other non-working days. The DW folks are adamant about using meaningless keys (that is, don't just use a truncated date as the key, use a generated key), but you can decide that for yourself. The Date Dimension Toolkit has code to generate your own tables in various DBMS and it has CSV data for several years worth of dates. A: you need to create a SQL Function that does this transformation for you. A: This is mostly like Brian's except it didn't compile due to mismatched parens and I changed the IF to not have the select in it. It is important to note that we use DateNAME here rather than datePART because datePART is dependent on the value set by SET DATEFIRST, which sets the first day of the week. CREATE FUNCTION dbo.GetNextWDay(@Day datetime) RETURNS DATETIME AS BEGIN DECLARE @ReturnDate DateTime set @ReturnDate = dateadd(dd, 1, @Day) if datename(dw, @ReturnDate) = 'Saturday' set @ReturnDate = dateadd(dd, 2, @ReturnDate) if datename(dw, @ReturnDate) = 'Sunday' set @ReturnDate = dateadd(dd, 1, @ReturnDate) RETURN @ReturnDate END A: create table #dates (dt datetime) insert into #dates (dt) values ('1/1/2001') insert into #dates (dt) values ('1/2/2001') insert into #dates (dt) values ('1/3/2001') insert into #dates (dt) values ('1/4/2001') insert into #dates (dt) values ('1/5/2001') select dt, day(dt), dateadd(dd,1,dt) from #dates where day(dt) between 1 and 4 union all select dt, day(dt), dateadd(dd,3,dt) from #dates where day(dt) = 5 drop table #dates
{ "language": "en", "url": "https://stackoverflow.com/questions/104330", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Objective-C switch using objects? I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result. First version looked like this: if([elementName compare:@"companyName"] == 0) [character setCorporationName:currentElementText]; else if([elementName compare:@"corporationID"] == 0) [character setCorporationID:currentElementText]; else if([elementName compare:@"name"] == 0) ... But I don't like the if-else-if-else pattern this produces. Looking at the switch statement I see that i can only handle ints, chars etc and not objects... so is there a better implementation pattern I'm not aware of? BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the if-else vs switch pattern in Objective-C A: Dare I suggest using a macro? #define TEST( _name, _method ) \ if ([elementName isEqualToString:@ _name] ) \ [character _method:currentElementText]; else #define ENDTEST { /* empty */ } TEST( "companyName", setCorporationName ) TEST( "setCorporationID", setCorporationID ) TEST( "name", setName ) : : ENDTEST A: If you want to use as little code as possible, and your element names and setters are all named so that if elementName is @"foo" then setter is setFoo:, you could do something like: SEL selector = NSSelectorFromString([NSString stringWithFormat:@"set%@:", [elementName capitalizedString]]); [character performSelector:selector withObject:currentElementText]; or possibly even: [character setValue:currentElementText forKey:elementName]; // KVC-style Though these will of course be a bit slower than using a bunch of if statements. [Edit: The second option was already mentioned by someone; oops!] A: One way I've done this with NSStrings is by using an NSDictionary and enums. It may not be the most elegant, but I think it makes the code a little more readable. The following pseudocode is extracted from one of my projects: typedef enum { UNKNOWNRESIDUE, DEOXYADENINE, DEOXYCYTOSINE, DEOXYGUANINE, DEOXYTHYMINE } SLSResidueType; static NSDictionary *pdbResidueLookupTable; ... if (pdbResidueLookupTable == nil) { pdbResidueLookupTable = [[NSDictionary alloc] initWithObjectsAndKeys: [NSNumber numberWithInteger:DEOXYADENINE], @"DA", [NSNumber numberWithInteger:DEOXYCYTOSINE], @"DC", [NSNumber numberWithInteger:DEOXYGUANINE], @"DG", [NSNumber numberWithInteger:DEOXYTHYMINE], @"DT", nil]; } SLSResidueType residueIdentifier = [[pdbResidueLookupTable objectForKey:residueType] intValue]; switch (residueIdentifier) { case DEOXYADENINE: do something; break; case DEOXYCYTOSINE: do something; break; case DEOXYGUANINE: do something; break; case DEOXYTHYMINE: do something; break; } A: The if-else implementation you have is the right way to do this, since switch won't work with objects. Apart from maybe being a bit harder to read (which is subjective), there is no real downside in using if-else statements this way. A: Although there's not necessarily a better way to do something like that for one time use, why use "compare" when you can use "isEqualToString"? That would seem to be more performant since the comparison would halt at the first non-matching character, rather than going through the whole thing to calculate a valid comparison result (though come to think of it the comparison might be clear at the same point) - also though it would look a little cleaner because that call returns a BOOL. if([elementName isEqualToString:@"companyName"] ) [character setCorporationName:currentElementText]; else if([elementName isEqualToString:@"corporationID"] ) [character setCorporationID:currentElementText]; else if([elementName isEqualToString:@"name"] ) A: There is actually a fairly simple way to deal with cascading if-else statements in a language like Objective-C. Yes, you can use subclassing and overriding, creating a group of subclasses that implement the same method differently, invoking the correct implementation at runtime using a common message. This works well if you wish to choose one of a few implementations, but it can result in a needless proliferation of subclasses if you have many small, slightly different implementations like you tend to have in long if-else or switch statements. Instead, factor out the body of each if/else-if clause into its own method, all in the same class. Name the messages that invoke them in a similar fashion. Now create an NSArray containing the selectors of those messages (obtained using @selector()). Coerce the string you were testing in the conditionals into a selector using NSSelectorFromString() (you may need to concatenate additional words or colons to it first depending on how you named those messages, and whether or not they take arguments). Now have self perform the selector using performSelector:. This approach has the downside that it can clutter-up the class with many new messages, but it's probably better to clutter-up a single class than the entire class hierarchy with new subclasses. A: Posting this as a response to Wevah's answer above -- I would've edited, but I don't have high enough reputation yet: unfortunately the first method breaks for fields with more than one word in them -- like xPosition. capitalizedString will convert that to Xposition, which when combined with the format give you setXposition: . Definitely not what was wanted here. Here is what I'm using in my code: NSString *capName = [elementName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[elementName substringToIndex:1] uppercaseString]]; SEL selector = NSSelectorFromString([NSString stringWithFormat:@"set%@:", capName]); Not as pretty as the first method, but it works. A: I have come up with a solution that uses blocks to create a switch-like structure for objects. There it goes: BOOL switch_object(id aObject, ...) { va_list args; va_start(args, aObject); id value = nil; BOOL matchFound = NO; while ( (value = va_arg(args,id)) ) { void (^block)(void) = va_arg(args,id); if ( [aObject isEqual:value] ) { block(); matchFound = YES; break; } } va_end(args); return matchFound; } As you can see, this is an oldschool C function with variable argument list. I pass the object to be tested in the first argument, followed by the case_value-case_block pairs. (Recall that Objective-C blocks are just objects.) The while loop keeps extracting these pairs until the object value is matched or there are no cases left (see notes below). Usage: NSString* str = @"stuff"; switch_object(str, @"blah", ^{ NSLog(@"blah"); }, @"foobar", ^{ NSLog(@"foobar"); }, @"stuff", ^{ NSLog(@"stuff"); }, @"poing", ^{ NSLog(@"poing"); }, nil); // <-- sentinel // will print "stuff" Notes: * *this is a first approximation without any error checking *the fact that the case handlers are blocks, requires additional care when it comes to visibility, scope and memory management of variables referenced from within *if you forget the sentinel, you are doomed :P *you can use the boolean return value to trigger a "default" case when none of the cases have been matched A: The most common refactoring suggested for eliminating if-else or switch statements is introducing polymorphism (see http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html). Eliminating such conditionals is most important when they are duplicated. In the case of XML parsing like your sample you are essentially moving the data to a more natural structure so that you won't have to duplicate the conditional elsewhere. In this case the if-else or switch statement is probably good enough. A: You should take advantage of Key-Value Coding: [character setValue:currentElementText forKey:elementName]; If the data is untrusted, you might want to check that the key is valid: if (![validKeysCollection containsObject:elementName]) // Exception or error A: I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following. <xmlroot> <corporationID> <stockSymbol>EXAM</stockSymbol> <uuid>31337</uuid> </corporationID> <companyName>Example Inc.</companyName> </xmlroot> There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one. NSXMLElement* root = [xmlDocument rootElement]; // Assuming that we only have one of each element. [character setCorperationName:[[[root elementsForName:@"companyName"] objectAtIndex:0] stringValue]]; NSXMLElement* corperationId = [root elementsForName:@"corporationID"]; [character setCorperationStockSymbol:[[[corperationId elementsForName:@"stockSymbol"] objectAtIndex:0] stringValue]]; [character setCorperationUUID:[[[corperationId elementsForName:@"uuid"] objectAtIndex:0] stringValue]]; The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure. // The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){ if([[aNode name] isEqualToString:@"companyName"]){ [character setCorperationName:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"corporationID"]){ NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){ if([[aNode name] isEqualToString:@"stockSymbol"]){ [character setCorperationStockSymbol:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"uuid"]){ [character setCorperationUUID:[aNode stringValue]]; } } } } This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element. - (NSNode*)parse_companyName:(NSNode*)aNode { [character setCorperationName:[aNode stringValue]]; return aNode; } - (NSNode*)parse_corporationID:(NSNode*)aNode { NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){ [self invokeMethodForNode:aNode prefix:@"parse_corporationID_"]; } return [aNode previousNode]; } - (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode { [character setCorperationStockSymbol:[aNode stringValue]]; return aNode; } - (NSNode*)parse_corporationID_uuid:(NSNode*)aNode { [character setCorperationUUID:[aNode stringValue]]; return aNode; } The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method. - (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix { NSNode* ret = nil; NSString* methodName = [NSString stringWithFormat:@"%@%@:", prefix, [aNode name]]; SEL selector = NSSelectorFromString(methodName); if([self respondsToSelector:selector]) ret = [self performSelector:selector withObject:aNode]; return ret; } Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){ aNode = [self invokeMethodForNode:aNode prefix:@"parse_"]; } Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer. However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement. A: In this case, I'm not sure if you can easily refactor the class to introduce polymorphism as Bradley suggests, since it's a Cocoa-native class. Instead, the Objective-C way to do it is to use a class category to add an elementNameCode method to NSSting: typedef enum { companyName = 0, companyID, ..., Unknown } ElementCode; @interface NSString (ElementNameCodeAdditions) - (ElementCode)elementNameCode; @end @implementation NSString (ElementNameCodeAdditions) - (ElementCode)elementNameCode { if([self compare:@"companyName"]==0) { return companyName; } else if([self compare:@"companyID"]==0) { return companyID; } ... { } return Unknown; } @end In your code, you could now use a switch on [elementName elementNameCode] (and gain the associated compiler warnings if you forget to test for one of the enum members etc.). As Bradley points out, this may not be worth it if the logic is only used in one place. A: What we've done in our projects where we need to so this sort of thing over and over, is to set up a static CFDictionary mapping the strings/objects to check against to a simple integer value. It leads to code that looks like this: static CFDictionaryRef map = NULL; int count = 3; const void *keys[count] = { @"key1", @"key2", @"key3" }; const void *values[count] = { (uintptr_t)1, (uintptr_t)2, (uintptr_t)3 }; if (map == NULL) map = CFDictionaryCreate(NULL,keys,values,count,&kCFTypeDictionaryKeyCallBacks,NULL); switch((uintptr_t)CFDictionaryGetValue(map,[node name])) { case 1: // do something break; case 2: // do something else break; case 3: // this other thing too break; } If you're targeting Leopard only, you could use an NSMapTable instead of a CFDictionary. A: Similar to Lvsti I am using blocks to perform a switching pattern on objects. I wrote a very simple filter block based chain, that takes n filter blocks and performs each filter on the object. Each filter can alter the object, but must return it. No matter what. NSObject+Functional.h #import <Foundation/Foundation.h> typedef id(^FilterBlock)(id element, NSUInteger idx, BOOL *stop); @interface NSObject (Functional) -(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks; @end NSObject+Functional.m @implementation NSObject (Functional) -(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks { __block id blockSelf = self; [filterBlocks enumerateObjectsUsingBlock:^( id (^block)(id,NSUInteger idx, BOOL*) , NSUInteger idx, BOOL *stop) { blockSelf = block(blockSelf, idx, stop); }]; return blockSelf; } @end Now we can set up n FilterBlocks to test for the different cases. FilterBlock caseYES = ^id(id element, NSUInteger idx, BOOL *breakAfter){ if ([element isEqualToString:@"YES"]) { NSLog(@"You did it"); *breakAfter = YES; } return element; }; FilterBlock caseNO = ^id(id element, NSUInteger idx, BOOL *breakAfter){ if ([element isEqualToString:@"NO"] ) { NSLog(@"Nope"); *breakAfter = YES; } return element; }; Now we stick those block we want to test as a filter chain in an array: NSArray *filters = @[caseYES, caseNO]; and can perform it on an object id obj1 = @"YES"; id obj2 = @"NO"; [obj1 processByPerformingFilterBlocks:filters]; [obj2 processByPerformingFilterBlocks:filters]; This approach can be used for switching but also for any (conditional) filter chain application, as the blocks can edit the element and pass it on.
{ "language": "en", "url": "https://stackoverflow.com/questions/104339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: URLSCAN question I have uriscan installed on my Win2003 server and it is blocking an older ColdFusion script. The log entry has the following-- 2008-09-19 00:16:57 66.82.162.13 1416208729 GET /Admin/Uploads/Mountain/Wolf%2520Creek%2520gazeebo.jpg Rejected URL+is+double+escaped URL - - How do I get uriscan to allow submissions like this without turning off the double-escaped url feature? A: To quote another post on the subject, some aspect of your process for submitting URIs is doing some bad encoding. http://www.usenet-forums.com/archive/index.php/t-39111.html I recommend changing the name of the JPG to not have spaces in it as a good practice, then later try to figure out with a non-production page why you're not interpreting the %20 as an encoded space, but as a percent sign and two digits. A: How do I get uriscan to allow submissions like this without turning off the double-escaped url feature? How do you get it to allow double-escaped URLs without turning off the double-escaped url feature? I think there's something wrong with what you're trying to do. My question is this: does your HTML source literally show image requests with "%2520" in them? Is that the correct name for your file? If so, you really have only two options: rename the file or turn off the feature disallowing double escapes.
{ "language": "en", "url": "https://stackoverflow.com/questions/104341", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Any Metadata driven UI sample code? I am in the process of designing a .net windows forms application that uses metadata to drive the UI. Apart from finding http://msdn.microsoft.com/en-us/library/ms954610.aspx, I have nothing much to look forward to. Anyone here worked on metadata driven User interfaces? What are the implications of following this methodology and any pointers would be greatly helpful. A: The most obvious answer would be that Microsoft have themselves embraced this concept through their use of Xaml in Windows Presentation Foundation which replaces WinForms (to an extent). If you want to stick to a WinForms, you may want to consider MyXaml which is kind of a homage to Xaml for WinForms! A: You may want to check out Evolutility CRUD framework. It is an open source metadata driven framework for CRUD generating all UI at run-time. It comes w/ source code (in C# and JS) and many samples. http://www.evolutility.org A: You may try this with HTA. Sometime back I created a metadata driven application using HTA and XML. I created XAML like structure and HTA-VBScript code to parse this structure and render diffent types of UI elements along with validations. A: Check the Andromeda project out, which does so extensively. Too bad the stack isn´t .NET friendly (PHP, Postgres, Perl).
{ "language": "en", "url": "https://stackoverflow.com/questions/104348", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why won't my package upgrade with yum? I'm trying to upgrade a package using yum on Fedora 8. The package is elfutils. Here's what I have installed locally: $ yum info elfutils Installed Packages Name : elfutils Arch : x86_64 Version: 0.130 Release: 3.fc8 Size : 436 k Repo : installed Summary: A collection of utilities and DSOs to handle compiled objects There's a bug in this version, and according to the bug report, a newer version has been pushed to the Fedora 8 stable repository. But, if I try to update: $ yum update elfutils Setting up Update Process Could not find update match for elfutils No Packages marked for Update Here are my repositories: $ yum repolist enabled repo id repo name status InstallMedia Fedora 8 enabled fedora Fedora 8 - x86_64 enabled updates Fedora 8 - x86_64 - Updates enabled What am I missing? A: OK, I figured it out. I needed to upgrade the fedora-release package. That allowed me to see all of the updated packages. Thanks to ethyreal for pointing me to the Yum upgrade FAQ. A: i know this seems silly but did you try removing it and reinstalling? yum remove elfutils then yum install elfutils alternatively you could try updating everything: yum update ...if their is no update marked in the repository you might try: yum upgrade A: If you look at the listing of the repository packages directory at Link to Fedora Repository You will see that you have the latest version in that directory, which is why yum is not upgrading your package. This is the same in both the i386 and x86_64 package directories. So the reason that you are not seeing an update is that there is not a more current version in the repository yet. The notification in the bug report that a new version is in the repository is incorrect.
{ "language": "en", "url": "https://stackoverflow.com/questions/104363", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Mac OS X Java Swing Buttons are Disabled for no aparent reason I wrote an application in Java and when it runs on one customer's computer running OS X The Save and Export buttons are disabled. (Everything else works in the application.) Both of these buttons open up a standard save file dialog. Any ideas? A: The fact that these buttons open a file dialog probably has nothing to do with it being disabled. Buttons can end up being disabled for a number of reasons, * *its setEnabled can be called with false, *when using an action, its setEnabled can be called with false, and *when using an action, it can have a property "enabled" that potentially disables it; see Action for more information, there's a list of properties there. Could you post how you 'implemented the JButtons'? A: A stab in the dark, but most macs are still running Java 1.5; check if your current code misbehaves with Java 1.5 on your end. Maybe that's where you problem lies. A: This was caused by misinformation recieved from the customer. Turns out the customer was trying to save to a location where files can't be saved on his/her hard drive.
{ "language": "en", "url": "https://stackoverflow.com/questions/104373", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Tips on refactoring an outdated database schema Being stuck with a legacy database schema that no longer reflects your data model is every developer's nightmare. Yet with all the talk of refactoring code for maintainability I have not heard much of refactoring outdated database schemas. What are some tips on how to transition to a better schema without breaking all the code that relies on the old one? I will propose a specific problem I am having to illustrate my point but feel free to give advice on other techniques that have proven helpful - those will likely come in handy as well. My example: My company receives and ships products. Now a product receipt and a product shipment have some very different data associated with them so the original database designers created a separate table for receipts and for shipments. In my one year working with this system I have come to the realization that the current schema doesn't make a lick of sense. After all, both a receipt and a shipment are basically a transaction, they each involve changing the amount of a product, at heart only the +/- sign is different. Indeed, we frequently need to find the total amount that the product has changed over a period of time, a problem for which this design is downright intractable. Obviously the appropriate design would be to have a single Transactions table with the Id being a foreign key of either a ReceiptInfo or a ShipmentInfo table. Unfortunately, the wrong schema has already been in production for some years and has hundreds of stored procedures, and thousands of lines of code written off of it. How then can I transition the schema to work correctly? A: Here's a whole catalogue of database refactorings: http://databaserefactoring.com/ A: That's a very difficult thing to work around; A couple quick options after refactoring the database are: *Create views that match the original schema but pull from the new schema; You may need triggers here so any updates to the views can be handled. *Create the new schema and put in triggers on each side to maintain the other side. A: This book (Refactoring Databases) has been a God-send to me when dealing with legacy database schemas, including when I had to deal with almost the exact same issue for our inventory database. Also, having a system in place to track changes to the database schema (like a series of alter scripts that is stored int he source control repository) helps immensely in figuring out code-to-database dependencies. A: Stored procedures and views are your friend here. Even if the system doesn't use them, change it to use them, then refactor the database underneath. Your receipts and shipments then become views. Beware, receipts and shipments are actually two very different beasts in most systems I have worked with. Receipts are linked to suppliers, while shipments are linked to customers (or customer/ship-to locations). At the inventory level, they are often represented the same. A: Is all data access limited to stored procedures? If not, the task could be nearly impossible. If so, you just have to make sure your data migration scripts work well transitioning from the old to the new schema, and then make sure your stored procedures honor theur inputs and outputs. Hopefully none of them have "select *" queries. If they do, use 'sp_help tablename' to get the complete list of columns, copy that out and replace each * with the complete column list, just to make sure you don't break client code. I would recommend making the changes gradually, and do lots of integration testing. It's hard to do a significant remodel without introducing a few bugs. A: The first thing is to create the table schema. I already did that for a Legacy database using Enterprise Architect. You can select the DB and it will create you every tables/fields. Then, you will need to split everything in categories. Exemple all your receives and ships products together, client stuff in an other category. Once everything is clear up, you will be able to refactor field by creating new table, new releashionship and new fields. Of course, this will need lot of change if all is accessed without Stored Procedure. A: I don't think its obvious that the id of the transactions table should be a foreign key to either ReceiptInfo or a ShipmentInfo. Think the other way around. In an object oriented model you should have a transaction table and the ReceiptInfo or a ShipmentInfo should have a foreign key to the transaction table. If you are lucky, there will be only 1 or 2 points in code where new records in ReceiptInfo or a ShipmentInfo are made. There you should add code where you add an entry in the Transaction table and after that create the entry in ReceiptInfo or ShipmentInfo with the foreign key to Transaction. A: Sometimes you can create new tables that have better structures and then create views with the names of your old tables but are based on the data in the new tables. That way, you code doesnt break while you start to move to a better structure. Be careful with thsi though as sometimes you move from a non-relational table to a relational structure where you have multiple records while the code will be expecting only one. This is particulalry true if you have developers who use subqueries. Then as each thing is changed, it will move away from the views to the real table. Eventually you can drop the views. This at least allows you to work incrementally to keep things working as you move stuff, but start to fix things to use a better design.
{ "language": "en", "url": "https://stackoverflow.com/questions/104380", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Error accessing Project > References window? In Visual Basic 6, when I attempt to access Project > References, it throws an error: Error accessing system registry I am: * *Logged in as the local computer administrator *running Windows XP Professional and *I can execute regedt32.exe and access all the registry keys just fine. VB6 was installed as the local administrator. Any idea why this happens? I'm running crystal reports 8.5 and it supposed to already have fixed that issue but apparently I still have the issue with 8.5 installed. I have also made the attempt of reinstalling crystal reports with no luck on the issue. A: If you're running Office 2010 (Beta) Word (apparently) writes a restricted registry key. VB throws the error when scanning the registry. The key I have is: HKCR\TypeLib\{00020905-0000-0000-C000-000000000046}\8.5 For Regmon - Filter for Process Name -> "vb6.exe" and Result -> ACCESS DENIED. Helps find it very quickly. Fixed it with PSToosl (PSEXEC) to run registry editor. The command line is, psexec -i -d -s c:\windows\regedit.exe psexec needs to be run with elevated-permissions. Edit by Jim: I'm on a Windows 7 (x64) box. Elevated permissions require the PSTools solution. XP can get away with a little less. A: Depending on the Windows OS you have (I have Windows 7 Enterprise), you might want to try giving administrator rights to the REGTLIB.EXE (located in C:\Windws). Right click on the REGTLIB.EXE file. Select Properties from the pop-up menu. Then select the Compatiblity tab. On the Compatiblity tab, check/select the Run this program as Administrator checkbox. Click OK to save your changes. It might take take care of the problem for you. It worked for me. Good luck. A: For me this worked: * *goto C:\Program Files\Microsoft Visual Studio\VB98 *change the property of VB6.EXE by right click->Compatibility In privilege level section, check the option Run this program as Administrator A: You could try Process Monitor to see which registry keys are accessed. A: I got this on a machine that I was using for VB6 development. I had been building a lot of COM DLLs from VB6 (without binary compatibility) and the cruft that had built up in the registry eventually got too much. Have a look at what size the registry is and what limit you have set. I doubled the registry size and then went looking for a good registry hoover. A: Here is a solution from Microsoft. It references the Crystal Reports problem, but the solution just uses regedit32 to walk the HKEY_CLASSES_ROOT\TypeLib and HKEY_CLASSES_ROOT\CLSID registry branches for dimmed keys and correcting the security on those keys. There are also instructions to fix the security if regedit32 is unable to access the key. Article ID: 269383 A: In Windows 7 go to start menu then right click "Microsoft Visual Basic 6" then select properties and click Compatibility from the dialog box that appears then tick "Run this program as an administrator". A: Have you tried this? Basically, it seems that it is a crystal reports issue. Hope that helps. A: Perhaps worth a try going to the "User Account Control Settings". Regards, A: When I installed VB6 on Win7-64 (using instructions easily found by a search engine), it worked fine. UAC was off -- i.e. set to "never notify." After a few weeks I turned UAC on -- i.e. set it to its default. VB6 then couldn't compile because of the "Error accessing the system registry" problem. Unfortunately, turning it off again didn't help. Apparently the damage done by turning it on was irreversible. I can't explain why this should be, but that's my experience. Giving REGTLIB.EXE administrative privileges while leaving UAC off sounded like a great idea, but that didn't work for me either. Finally, using Process Monitor and PsTools as described in other posts here worked. However, I had to give Full Control to large parts of my registry to Everyone. This didn't apply just to isolated keys. It seems that the compiler needs to add keys to major nodes, so I had to open up these entire nodes. Aside from the fact that working through these steps took hours, I'm now much more exposed than I was before I tried to increase security via UAC, However, I need VB6 and don't see another solution short of a new computer. Lesson: Don't use UAC with VB6. Except if you've arrived here it's too late for that. A: It's VB6 installation issue. Try to re-intall VB6 on your system. Otherwise open "visual studio 6.0" with "Run as Administrator". Then open/browse your project .vbp file via - New Project -> Existing tab. A: I have fixed the problem. But none of the suggestion above worked. What I did is giving everyone full control over the SYSTEM key in the registry. This creats a security break. I am running 64bit Windows 7 with vb6 serice pack 6B. A: I'm running Windows 10 Pro (10.0.16299 Build 16299) 64 bit. I was having this error when trying to compile a VB6 DLL. I saw several answers in this post about running in compatibility mode as administrator. I thought I would first try just running in compatibility mode for Windows XP (sp2). I was able to compile my DLL after checking that box. I didn't need to run as administrator.
{ "language": "en", "url": "https://stackoverflow.com/questions/104383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Information on how to use margins I need some info on how to use margins and how exactly padding works. For example: Should I put a line to occupy the whole width of the page (no matter what resolution is used to display the web page) letting just a small border on each side, how could I achieve this? A: Have a look at this: http://redmelon.net/tstme/box_model/ Basically, an element consists of content, surrounded by its padding, then the border, then the margin. Background images only extend as far as the border. Margins are best described as 'the whitespace around this element'. But have a look at the URL above, and make yourself a test page to have a play with, it should all make sense. A: I think this should do what you want: <table width="100%" cellpadding="5"> <tr> <td> One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... One, two, three ... </td> </tr> </table> Setting width to "100%" forces the text to use the full width, and setting cellpadding to "5" sets a unvisible border of 5 pixels. A: Another way to illustrate it is in the box model, padding is the inside "margin" of a box margin is the buffer around the box.
{ "language": "en", "url": "https://stackoverflow.com/questions/104395", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I generate all permutations of a list? How do I generate all the permutations of a list? For example: permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] A: One can indeed iterate over the first element of each permutation, as in tzwenn's answer. It is however more efficient to write this solution this way: def all_perms(elements): if len(elements) <= 1: yield elements # Only permutation possible = no permutation else: # Iteration over the first element in the result permutation: for (index, first_elmt) in enumerate(elements): other_elmts = elements[:index]+elements[index+1:] for permutation in all_perms(other_elmts): yield [first_elmt] + permutation This solution is about 30 % faster, apparently thanks to the recursion ending at len(elements) <= 1 instead of 0. It is also much more memory-efficient, as it uses a generator function (through yield), like in Riccardo Reyes's solution. A: Use itertools.permutations from the standard library: import itertools list(itertools.permutations([1, 2, 3])) Adapted from here is a demonstration of how itertools.permutations might be implemented: def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] A couple of alternative approaches are listed in the documentation of itertools.permutations. Here's one: def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return And another, based on itertools.product: def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) A: This is inspired by the Haskell implementation using list comprehension: def permutation(list): if len(list) == 0: return [[]] else: return [[x] + ys for x in list for ys in permutation(delete(list, x))] def delete(list, item): lc = list[:] lc.remove(item) return lc A: def permutations(head, tail=''): if len(head) == 0: print(tail) else: for i in range(len(head)): permutations(head[:i] + head[i+1:], tail + head[i]) called as: permutations('abc') A: For performance, a numpy solution inspired by Knuth, (p22) : from numpy import empty, uint8 from math import factorial def perms(n): f = 1 p = empty((2*n-1, factorial(n)), uint8) for i in range(n): p[i, :f] = i p[i+1:2*i+1, :f] = p[:i, :f] # constitution de blocs for j in range(i): p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f] # copie de blocs f = f*(i+1) return p[:n, :] Copying large blocs of memory saves time - it's 20x faster than list(itertools.permutations(range(n)) : In [1]: %timeit -n10 list(permutations(range(10))) 10 loops, best of 3: 815 ms per loop In [2]: %timeit -n100 perms(10) 100 loops, best of 3: 40 ms per loop A: Disclaimer: shameless plug by package author. :) The trotter package is different from most implementations in that it generates pseudo lists that don't actually contain permutations but rather describe mappings between permutations and respective positions in an ordering, making it possible to work with very large 'lists' of permutations, as shown in this demo which performs pretty instantaneous operations and look-ups in a pseudo-list 'containing' all the permutations of the letters in the alphabet, without using more memory or processing than a typical web page. In any case, to generate a list of permutations, we can do the following. import trotter my_permutations = trotter.Permutations(3, [1, 2, 3]) print(my_permutations) for p in my_permutations: print(p) Output: A pseudo-list containing 6 3-permutations of [1, 2, 3]. [1, 2, 3] [1, 3, 2] [3, 1, 2] [3, 2, 1] [2, 3, 1] [2, 1, 3] A: If you don't want to use the builtin methods such as: import itertools list(itertools.permutations([1, 2, 3])) you can implement permute function yourself from collections.abc import Iterable def permute(iterable: Iterable[str]) -> set[str]: perms = set() if len(iterable) == 1: return {*iterable} for index, char in enumerate(iterable): perms.update([char + perm for perm in permute(iterable[:index] + iterable[index + 1:])]) return perms if __name__ == '__main__': print(permute('abc')) # {'bca', 'abc', 'cab', 'acb', 'cba', 'bac'} print(permute(['1', '2', '3'])) # {'123', '312', '132', '321', '213', '231'} A: The beauty of recursion: >>> import copy >>> def perm(prefix,rest): ... for e in rest: ... new_rest=copy.copy(rest) ... new_prefix=copy.copy(prefix) ... new_prefix.append(e) ... new_rest.remove(e) ... if len(new_rest) == 0: ... print new_prefix + new_rest ... continue ... perm(new_prefix,new_rest) ... >>> perm([],['a','b','c','d']) ['a', 'b', 'c', 'd'] ['a', 'b', 'd', 'c'] ['a', 'c', 'b', 'd'] ['a', 'c', 'd', 'b'] ['a', 'd', 'b', 'c'] ['a', 'd', 'c', 'b'] ['b', 'a', 'c', 'd'] ['b', 'a', 'd', 'c'] ['b', 'c', 'a', 'd'] ['b', 'c', 'd', 'a'] ['b', 'd', 'a', 'c'] ['b', 'd', 'c', 'a'] ['c', 'a', 'b', 'd'] ['c', 'a', 'd', 'b'] ['c', 'b', 'a', 'd'] ['c', 'b', 'd', 'a'] ['c', 'd', 'a', 'b'] ['c', 'd', 'b', 'a'] ['d', 'a', 'b', 'c'] ['d', 'a', 'c', 'b'] ['d', 'b', 'a', 'c'] ['d', 'b', 'c', 'a'] ['d', 'c', 'a', 'b'] ['d', 'c', 'b', 'a'] A: ANOTHER APPROACH (without libs) def permutation(input): if len(input) == 1: return input if isinstance(input, list) else [input] result = [] for i in range(len(input)): first = input[i] rest = input[:i] + input[i + 1:] rest_permutation = permutation(rest) for p in rest_permutation: result.append(first + p) return result Input can be a string or a list print(permutation('abcd')) print(permutation(['a', 'b', 'c', 'd'])) A: #!/usr/bin/env python def perm(a, k=0): if k == len(a): print a else: for i in xrange(k, len(a)): a[k], a[i] = a[i] ,a[k] perm(a, k+1) a[k], a[i] = a[i], a[k] perm([1,2,3]) Output: [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 2, 1] [3, 1, 2] As I'm swapping the content of the list it's required a mutable sequence type as input. E.g. perm(list("ball")) will work and perm("ball") won't because you can't change a string. This Python implementation is inspired by the algorithm presented in the book Computer Algorithms by Horowitz, Sahni and Rajasekeran. A: For Python 2.6 onwards: import itertools itertools.permutations([1, 2, 3]) This returns as a generator. Use list(permutations(xs)) to return as a list. A: First, import itertools: import itertools Permutation (order matters): print(list(itertools.permutations([1,2,3,4], 2))) [(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)] Combination (order does NOT matter): print(list(itertools.combinations('123', 2))) [('1', '2'), ('1', '3'), ('2', '3')] Cartesian product (with several iterables): print(list(itertools.product([1,2,3], [4,5,6]))) [(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)] Cartesian product (with one iterable and itself): print(list(itertools.product([1,2], repeat=3))) [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2), (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)] A: from __future__ import print_function def perm(n): p = [] for i in range(0,n+1): p.append(i) while True: for i in range(1,n+1): print(p[i], end=' ') print("") i = n - 1 found = 0 while (not found and i>0): if p[i]<p[i+1]: found = 1 else: i = i - 1 k = n while p[i]>p[k]: k = k - 1 aux = p[i] p[i] = p[k] p[k] = aux for j in range(1,(n-i)/2+1): aux = p[i+j] p[i+j] = p[n-j+1] p[n-j+1] = aux if not found: break perm(5) A: Here is an algorithm that works on a list without creating new intermediate lists similar to Ber's solution at https://stackoverflow.com/a/108651/184528. def permute(xs, low=0): if low + 1 >= len(xs): yield xs else: for p in permute(xs, low + 1): yield p for i in range(low + 1, len(xs)): xs[low], xs[i] = xs[i], xs[low] for p in permute(xs, low + 1): yield p xs[low], xs[i] = xs[i], xs[low] for p in permute([1, 2, 3, 4]): print p You can try the code out for yourself here: http://repl.it/J9v A: This algorithm is the most effective one, it avoids of array passing and manipulation in recursive calls, works in Python 2, 3: def permute(items): length = len(items) def inner(ix=[]): do_yield = len(ix) == length - 1 for i in range(0, length): if i in ix: #avoid duplicates continue if do_yield: yield tuple([items[y] for y in ix + [i]]) else: for p in inner(ix + [i]): yield p return inner() Usage: for p in permute((1,2,3)): print(p) (1, 2, 3) (1, 3, 2) (2, 1, 3) (2, 3, 1) (3, 1, 2) (3, 2, 1) A: def pzip(c, seq): result = [] for item in seq: for i in range(len(item)+1): result.append(item[i:]+c+item[:i]) return result def perm(line): seq = [c for c in line] if len(seq) <=1 : return seq else: return pzip(seq[0], perm(seq[1:])) A: Generate all possible permutations I'm using python3.4: def calcperm(arr, size): result = set([()]) for dummy_idx in range(size): temp = set() for dummy_lst in result: for dummy_outcome in arr: if dummy_outcome not in dummy_lst: new_seq = list(dummy_lst) new_seq.append(dummy_outcome) temp.add(tuple(new_seq)) result = temp return result Test Cases: lst = [1, 2, 3, 4] #lst = ["yellow", "magenta", "white", "blue"] seq = 2 final = calcperm(lst, seq) print(len(final)) print(final) A: This solution implements a generator, to avoid holding all the permutations on memory: def permutations (orig_list): if not isinstance(orig_list, list): orig_list = list(orig_list) yield orig_list if len(orig_list) == 1: return for n in sorted(orig_list): new_list = orig_list[:] pos = new_list.index(n) del(new_list[pos]) new_list.insert(0, n) for resto in permutations(new_list[1:]): if new_list[:1] + resto <> orig_list: yield new_list[:1] + resto A: I see a lot of iteration going on inside these recursive functions, not exactly pure recursion... so for those of you who cannot abide by even a single loop, here's a gross, totally unnecessary fully recursive solution def all_insert(x, e, i=0): return [x[0:i]+[e]+x[i:]] + all_insert(x,e,i+1) if i<len(x)+1 else [] def for_each(X, e): return all_insert(X[0], e) + for_each(X[1:],e) if X else [] def permute(x): return [x] if len(x) < 2 else for_each( permute(x[1:]) , x[0]) perms = permute([1,2,3]) A: To save you folks possible hours of searching and experimenting, here's the non-recursive permutaions solution in Python which also works with Numba (as of v. 0.41): @numba.njit() def permutations(A, k): r = [[i for i in range(0)]] for i in range(k): r = [[a] + b for a in A for b in r if (a in b)==False] return r permutations([1,2,3],3) [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] To give an impression about performance: %timeit permutations(np.arange(5),5) 243 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) time: 406 ms %timeit list(itertools.permutations(np.arange(5),5)) 15.9 µs ± 8.61 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) time: 12.9 s So use this version only if you have to call it from njitted function, otherwise prefer itertools implementation. A: Anyway we could use sympy library , also support for multiset permutations import sympy from sympy.utilities.iterables import multiset_permutations t = [1,2,3] p = list(multiset_permutations(t)) print(p) # [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] Answer is highly inspired by Get all permutations of a numpy array A: In a functional style def addperm(x,l): return [ l[0:i] + [x] + l[i:] for i in range(len(l)+1) ] def perm(l): if len(l) == 0: return [[]] return [x for y in perm(l[1:]) for x in addperm(l[0],y) ] print perm([ i for i in range(3)]) The result: [[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]] A: The following code is an in-place permutation of a given list, implemented as a generator. Since it only returns references to the list, the list should not be modified outside the generator. The solution is non-recursive, so uses low memory. Work well also with multiple copies of elements in the input list. def permute_in_place(a): a.sort() yield list(a) if len(a) <= 1: return first = 0 last = len(a) while 1: i = last - 1 while 1: i = i - 1 if a[i] < a[i+1]: j = last - 1 while not (a[i] < a[j]): j = j - 1 a[i], a[j] = a[j], a[i] # swap the values r = a[i+1:last] r.reverse() a[i+1:last] = r yield list(a) break if i == first: a.reverse() return if __name__ == '__main__': for n in range(5): for a in permute_in_place(range(1, n+1)): print a print for a in permute_in_place([0, 0, 1, 1, 1]): print a print A: A quite obvious way in my opinion might be also: def permutList(l): if not l: return [[]] res = [] for e in l: temp = l[:] temp.remove(e) res.extend([[e] + r for r in permutList(temp)]) return res A: Regular implementation (no yield - will do everything in memory): def getPermutations(array): if len(array) == 1: return [array] permutations = [] for i in range(len(array)): # get all perm's of subarray w/o current item perms = getPermutations(array[:i] + array[i+1:]) for p in perms: permutations.append([array[i], *p]) return permutations Yield implementation: def getPermutations(array): if len(array) == 1: yield array else: for i in range(len(array)): perms = getPermutations(array[:i] + array[i+1:]) for p in perms: yield [array[i], *p] The basic idea is to go over all the elements in the array for the 1st position, and then in 2nd position go over all the rest of the elements without the chosen element for the 1st, etc. You can do this with recursion, where the stop criteria is getting to an array of 1 element - in which case you return that array. A: list2Perm = [1, 2.0, 'three'] listPerm = [[a, b, c] for a in list2Perm for b in list2Perm for c in list2Perm if ( a != b and b != c and a != c ) ] print listPerm Output: [ [1, 2.0, 'three'], [1, 'three', 2.0], [2.0, 1, 'three'], [2.0, 'three', 1], ['three', 1, 2.0], ['three', 2.0, 1] ] A: I used an algorithm based on the factorial number system- For a list of length n, you can assemble each permutation item by item, selecting from the items left at each stage. You have n choices for the first item, n-1 for the second, and only one for the last, so you can use the digits of a number in the factorial number system as the indices. This way the numbers 0 through n!-1 correspond to all possible permutations in lexicographic order. from math import factorial def permutations(l): permutations=[] length=len(l) for x in xrange(factorial(length)): available=list(l) newPermutation=[] for radix in xrange(length, 0, -1): placeValue=factorial(radix-1) index=x/placeValue newPermutation.append(available.pop(index)) x-=index*placeValue permutations.append(newPermutation) return permutations permutations(range(3)) output: [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]] This method is non-recursive, but it is slightly slower on my computer and xrange raises an error when n! is too large to be converted to a C long integer (n=13 for me). It was enough when I needed it, but it's no itertools.permutations by a long shot. A: Note that this algorithm has an n factorial time complexity, where n is the length of the input list Print the results on the run: global result result = [] def permutation(li): if li == [] or li == None: return if len(li) == 1: result.append(li[0]) print result result.pop() return for i in range(0,len(li)): result.append(li[i]) permutation(li[:i] + li[i+1:]) result.pop() Example: permutation([1,2,3]) Output: [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] A: Another solution: def permutation(flag, k =1 ): N = len(flag) for i in xrange(0, N): if flag[i] != 0: continue flag[i] = k if k == N: print flag permutation(flag, k+1) flag[i] = 0 permutation([0, 0, 0]) A: This is the asymptotically optimal way O(n*n!) of generating permutations after initial sorting. There are n! permutations at most and hasNextPermutation(..) runs in O(n) time complexity In 3 steps, * *Find largest j such that a[j] can be increased *Increase a[j] by smallest feasible amount *Find lexicogrpahically least way to extend the new a[0..j] ''' Lexicographic permutation generation consider example array state of [1,5,6,4,3,2] for sorted [1,2,3,4,5,6] after 56432(treat as number) ->nothing larger than 6432(using 6,4,3,2) beginning with 5 so 6 is next larger and 2345(least using numbers other than 6) so [1, 6,2,3,4,5] ''' def hasNextPermutation(array, len): ' Base Condition ' if(len ==1): return False ''' Set j = last-2 and find first j such that a[j] < a[j+1] If no such j(j==-1) then we have visited all permutations after this step a[j+1]>=..>=a[len-1] and a[j]<a[j+1] a[j]=5 or j=1, 6>5>4>3>2 ''' j = len -2 while (j >= 0 and array[j] >= array[j + 1]): j= j-1 if(j==-1): return False # print(f"After step 2 for j {j} {array}") ''' decrease l (from n-1 to j) repeatedly until a[j]<a[l] Then swap a[j], a[l] a[l] is the smallest element > a[j] that can follow a[l]...a[j-1] in permutation before swap we have a[j+1]>=..>=a[l-1]>=a[l]>a[j]>=a[l+1]>=..>=a[len-1] after swap -> a[j+1]>=..>=a[l-1]>=a[j]>a[l]>=a[l+1]>=..>=a[len-1] a[l]=6 or l=2, j=1 just before swap [1, 5, 6, 4, 3, 2] after swap [1, 6, 5, 4, 3, 2] a[l]=5, a[j]=6 ''' l = len -1 while(array[j] >= array[l]): l = l-1 # print(f"After step 3 for l={l}, j={j} before swap {array}") array[j], array[l] = array[l], array[j] # print(f"After step 3 for l={l} j={j} after swap {array}") ''' Reverse a[j+1...len-1](both inclusive) after reversing [1, 6, 2, 3, 4, 5] ''' array[j+1:len] = reversed(array[j+1:len]) # print(f"After step 4 reversing {array}") return True array = [1,2,4,4,5] array.sort() len = len(array) count =1 print(array) ''' The algorithm visits every permutation in lexicographic order generating one by one ''' while(hasNextPermutation(array, len)): print(array) count = count +1 # The number of permutations will be n! if no duplicates are present, else less than that # [1,4,3,3,2] -> 5!/2!=60 print(f"Number of permutations: {count}") A: def permutate(l): for i, x in enumerate(l): for y in l[i + 1:]: yield x, y if __name__ == '__main__': print(list(permutate(list('abcd')))) print(list(permutate([1, 2, 3, 4]))) #[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')] #[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)] A: My Python Solution: def permutes(input,offset): if( len(input) == offset ): return [''.join(input)] result=[] for i in range( offset, len(input) ): input[offset], input[i] = input[i], input[offset] result = result + permutes(input,offset+1) input[offset], input[i] = input[i], input[offset] return result # input is a "string" # return value is a list of strings def permutations(input): return permutes( list(input), 0 ) # Main Program print( permutations("wxyz") ) A: def permutation(word, first_char=None): if word == None or len(word) == 0: return [] if len(word) == 1: return [word] result = [] first_char = word[0] for sub_word in permutation(word[1:], first_char): result += insert(first_char, sub_word) return sorted(result) def insert(ch, sub_word): arr = [ch + sub_word] for i in range(len(sub_word)): arr.append(sub_word[i:] + ch + sub_word[:i]) return arr assert permutation(None) == [] assert permutation('') == [] assert permutation('1') == ['1'] assert permutation('12') == ['12', '21'] print permutation('abc') Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba'] A: Using Counter from collections import Counter def permutations(nums): ans = [[]] cache = Counter(nums) for idx, x in enumerate(nums): result = [] for items in ans: cache1 = Counter(items) for id, n in enumerate(nums): if cache[n] != cache1[n] and items + [n] not in result: result.append(items + [n]) ans = result return ans permutations([1, 2, 2]) > [[1, 2, 2], [2, 1, 2], [2, 2, 1]] A: def permuteArray (arr): arraySize = len(arr) permutedList = [] if arraySize == 1: return [arr] i = 0 for item in arr: for elem in permuteArray(arr[:i] + arr[i + 1:]): permutedList.append([item] + elem) i = i + 1 return permutedList I intended to not exhaust every possibility in a new line to make it somewhat unique. A: from typing import List import time, random def measure_time(func): def wrapper_time(*args, **kwargs): start_time = time.perf_counter() res = func(*args, **kwargs) end_time = time.perf_counter() return res, end_time - start_time return wrapper_time class Solution: def permute(self, nums: List[int], method: int = 1) -> List[List[int]]: perms = [] perm = [] if method == 1: _, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms) elif method == 2: _, time_perm = self._permute_recur_agian(nums, perm, perms) print(perm) return perms, time_perm @measure_time def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]): # base case if l == r: perms.append(nums.copy()) for i in range(l, r + 1): nums[l], nums[i] = nums[i], nums[l] self._permute_recur(nums, l + 1, r , perms) nums[l], nums[i] = nums[i], nums[l] @measure_time def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]): """ The idea is similar to nestedForLoops visualized as a recursion tree. """ if nums: for i in range(len(nums)): # perm.append(nums[i]) mistake, perm will be filled with all nums's elements. # Method1 perm_copy = copy.deepcopy(perm) # Method2 add in the parameter list using + (not in place) # caveat: list.append is in-place , which is useful for operating on global element perms_list # Note that: # perms_list pass by reference. shallow copy # perm + [nums[i]] pass by value instead of reference. self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list) else: # Arrive at the last loop, i.e. leaf of the recursion tree. perms_list.append(perm) if __name__ == "__main__": array = [random.randint(-10, 10) for _ in range(3)] sol = Solution() # perms, time_perm = sol.permute(array, 1) perms2, time_perm2 = sol.permute(array, 2) print(perms2) # print(perms, perms2) # print(time_perm, time_perm2) ``` A: in case anyone fancies this ugly one-liner (works only for strings though): def p(a): return a if len(a) == 1 else [[a[i], *j] for i in range(len(a)) for j in p(a[:i] + a[i + 1:])] A: Solving with recursion, iterate through elements, take i'th element, and ask yourself: 'What is the permutation of rest of items` till no more element left. I explained the solution here: https://www.youtube.com/watch?v=_7GE7psS2b4 class Solution: def permute(self,nums:List[int])->List[List[int]]: res=[] def dfs(nums,path): if len(nums)==0: res.append(path) for i in range(len(nums)): dfs(nums[:i]+nums[i+1:],path+[nums[i]]) dfs(nums,[]) return res A: In case the user wants to keep all permutations in a list, the following code can be used: def get_permutations(nums, p_list=[], temp_items=[]): if not nums: return elif len(nums) == 1: new_items = temp_items+[nums[0]] p_list.append(new_items) return else: for i in range(len(nums)): temp_nums = nums[:i]+nums[i+1:] new_temp_items = temp_items + [nums[i]] get_permutations(temp_nums, p_list, new_temp_items) nums = [1,2,3] p_list = [] get_permutations(nums, p_list) A: for Python we can use itertools and import both permutations and combinations to solve your problem from itertools import product, permutations A = ([1,2,3]) print (list(permutations(sorted(A),2)))
{ "language": "en", "url": "https://stackoverflow.com/questions/104420", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "824" }
Q: How do I download the source for BIRT? The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build? A: Okay, I know the answer to this one... Eclipse has a feature named Team Project Sets which allows you to define a collection of projects, stored in various version control systems that can be downloaded as a package. I have published a collection of team project set files that can be used to get the BIRT source. The files are stored in a Subversion repository here I have a short article with a bit more detail on the BirtWorld blog. A: Go to the BIRT website and follow their Directions.
{ "language": "en", "url": "https://stackoverflow.com/questions/104439", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Memory footprint issues with JAVA, JNI, and C application I have a piece of an application that is written in C, it spawns a JVM and uses JNI to interact with a Java application. My memory footprint via Process Explorer gets upto 1GB and runs out of memory. Now as far as I know it should be able to get upto 2GB. One thing I believe is that the memory the JVM is using isn't visible in the Process Explorer. My xmx is set to 256, I added some statements to watch the java side memory and it is peaking at 256 and GC is doing its job and it is all good on that side. So my question is, where is the other 700+ MB being consumed? Anyone out there a Java/JNI/C Memory expert? A: There could be a leak in the JNI code. Remember to use (*jni)->DeleteLocalRef() for any object references you get once you are done with them. If you use any native C buffers to create new Java objects, make sure you free them off once the object is created. Check the JNI Specification for further guidelines. Depending on the VM you are using you might be able to turn on JNI checking. For example, on the IBM JDK you can specify "-Xcheck:jni". A: Try a test app in C that doesn't spawn the JVM but instead tries to allocate more and more memory. See whether the test app can reach the 2 GB barrier. A: Write a C test harness and use valgrind/alleyoop to check for leakage in your C code, and similarly use the java jvisualvm tool. A: The C and JNI code can allocate memory as well (malloc/free/new/etc), which is outside of the VM's 256m. The xMX only restricts what the VM will allocate itself. Depending on what you're allocating in the C code, and what other things are loaded in memory you may or may not be able to get up to 2GB. A: If you say that it's the Windows process that runs out of memory as opposed to the JVM, then my initial guess is that you probably invoke some (your own) native methods from the JVM and those native methods leak memory. So, I concur with @John Gardner here. A: Well thanks to all of your help especially @alexander I have discovered that all the extra memory that isn't visible via Process Explorer is being used by the Java Heap. In fact via other tests that I have run the JVM's memory consumption is included in what I see from the Process Explorer. So the heap is taking large amounts of memory, I will have to do some more research about that and maybe ask a separate question.
{ "language": "en", "url": "https://stackoverflow.com/questions/104442", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Flash - Drag Two Movieclips at Once? I'm trying to create a map application similar to this. Click the SWF Preview tab on the left of the image. Specifically, noticed how you can pan around, and the clickable buttons on the map move with it. Basically, how do they do that? My application has a map that you can click and pan around using a startDrag() function. I have a separate layer with other, clickable movie clips that I'd like to follow the pans of the map layer. Unfortunately, Flash limits you to dragging only one movie clip at a time. Somebody proposed a solution using a prototype, but I can't get that working correctly, and I'm not sure if it's because I'm using ActionScript 3.0 or not. Can anybody outline a better way for me to accomplish what I'm trying to do, or a better way to do what I'm currently doing? Appreciate it. A: Simple. Put your map and the clickable buttons into a new MovieClip, you could call it interactiveMapContainer or something similar, then call your startDrag method on interactiveMapContainer and you'll still be able to click the buttons once you've dragged it about. Jakub Kotrla's method will also work very well, although it is slightly more complicated. A: I think defmeta's method is the best one if it's possible to make everything be children of the "main" draggable object -- it's the fastest (in terms of UI response time) and most simple, and requires the least amount of code. If that is not an option, there are a couple of other methods at your disposal: * *If you're using Flex, you can have other objects move along with the map by listening to MoveEvent.MOVE events on it and moving themselves accordingly *You can implement the drag functionality yourself so that you'll have more control over it (see below). Here's an example that implements drag functionality for an object that will also move a bunch of "sibling" objects along with it. In this example, * *Any variable beginning with an underscore is a private member of the class that contains this code *_siblings is a Dictionary in which the keys are the other objects that need to be moved. . private var _dragStartCoordinates:Point = null; private var _siblingsDragStartCoordinates:Dictionary = null; private function mouseDownHandler(event:MouseEvent):void { this.startDrag(); _dragStartCoordinates = new Point(this.x, this.y); _siblingsDragStartCoordinates = new Dictionary(true); for (var sibling:DisplayObject in _siblings) { _siblingsDragStartCoordinates[sibling] = new Point(sibling.x, sibling.y); } stage.addEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler, false, 0, true); stage.addEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler, false, 0, true); } private function dragMouseUpHandler(event:MouseEvent):void { stage.removeEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler, false); stage.removeEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler, false); this.stopDrag(); moveSiblings(); _dragStartCoordinates = null; _siblingsDragStartCoordinates = null; } private function dragMouseMoveHandler(event:MouseEvent):void { moveSiblings(); } // expects _dragStartCoordinates and _siblingsDragStartCoordinates // to be set private function moveSiblings():void { var xDiff:Number = this.x - _dragStartCoordinates.x; var yDiff:Number = this.y - _dragStartCoordinates.y; for (var sibling:DisplayObject in _siblings) { sibling.x = _siblingsDragStartCoordinates[sibling].x + xDiff; sibling.y = _siblingsDragStartCoordinates[sibling].y + yDiff; } } A: I can't drag anything int SWF you linked, just zoom via mouseWheel. You can make more than one movieClip dragging at once using events mousedown, mouseMove and mouseUp. Add event handler for events via Mouse.addListener(object). * *In mouseDown set some flag and remeber current mouse position. *In mouseMove if the flag is set calculate move offset and just change .x and .y of all movieclips you want to drag. *In mouseUp set the flag to false A: Thanks hasseg for the code, saved a wee bit of time. Here's my take on it for public use... package Tools { import flash.display.MovieClip; import flash.events.*; import flash.geom.Rectangle; import flash.utils.setInterval; import flash.utils.clearInterval; import flash.display.MovieClip; import flash.display.DisplayObject; import flash.display.Sprite; import flash.geom.Point; import flash.utils.Dictionary; public class DragSync { private var _dragStartCoordinates:Point = null; private var _siblingsDragStartCoordinates:Dictionary = null; private var _primaryItem:Object = null; private var _dragWithPrimary:Array = null; public function DragSync(primaryItem:Object,dragWithPrimary:Array) { _primaryItem = primaryItem; _dragWithPrimary = dragWithPrimary; _primaryItem.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); _primaryItem.addEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler); _primaryItem.addEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler); } private function mouseDownHandler(event:MouseEvent):void { _dragStartCoordinates = new Point(_primaryItem.x, _primaryItem.y); _siblingsDragStartCoordinates = new Dictionary(true); for each (var sibling:DisplayObject in _dragWithPrimary) { _siblingsDragStartCoordinates[sibling] = new Point(sibling.x, sibling.y) } } private function dragMouseUpHandler(event:MouseEvent):void { moveSiblings(); _dragStartCoordinates = null; _siblingsDragStartCoordinates = null; } private function dragMouseMoveHandler(event:MouseEvent):void { moveSiblings(); } // expects _dragStartCoordinates and _siblingsDragStartCoordinates // to be set private function moveSiblings():void { if (!_dragStartCoordinates || !_siblingsDragStartCoordinates) return; var xDiff:Number = _primaryItem.x - _dragStartCoordinates.x; var yDiff:Number = _primaryItem.y - _dragStartCoordinates.y; for each (var sibling:DisplayObject in _dragWithPrimary) { sibling.x = _siblingsDragStartCoordinates[sibling].x + xDiff; sibling.y = _siblingsDragStartCoordinates[sibling].y + yDiff; } } } } A: Thank you very much. I have changed it as below: package { import flash.display.MovieClip; import flash.events.*; import flash.geom.Rectangle; import flash.utils.setInterval; import flash.utils.clearInterval; import flash.display.MovieClip; import flash.display.DisplayObject; import flash.display.Sprite; import flash.geom.Point; import flash.utils.Dictionary; public class DragSync { private var _dragStartCoordinates:Point = null; private var _siblingsDragStartCoordinates:Dictionary = null; private var _primaryItem:Object = null; private var _workSpace:Object = null; private var _dragWithPrimary:Array = null; public function DragSync(primaryItem:Object,workSpace:Object, dragWithPrimary:Array) { _primaryItem = primaryItem; _dragWithPrimary = dragWithPrimary; _workSpace = workSpace; _workSpace.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); _workSpace.addEventListener(MouseEvent.MOUSE_UP, dragMouseUpHandler); _workSpace.addEventListener(MouseEvent.MOUSE_MOVE, dragMouseMoveHandler); _workSpace.addEventListener(MouseEvent.MOUSE_OUT, dragOut); } private function mouseDownHandler(event:MouseEvent):void { trace("event mouse down"); _primaryItem.startDrag(); _dragStartCoordinates = new Point(_primaryItem.x, _primaryItem.y); _siblingsDragStartCoordinates = new Dictionary(true); for each (var sibling:DisplayObject in _dragWithPrimary) { _siblingsDragStartCoordinates[sibling] = new Point(sibling.x, sibling.y) } } private function dragMouseUpHandler(event:MouseEvent):void { moveSiblings(); _primaryItem.stopDrag(); _dragStartCoordinates = null; _siblingsDragStartCoordinates = null; } private function dragMouseMoveHandler(event:MouseEvent):void { trace("event mouse MOVE MOVE"); moveSiblings(); } private function dragOut(event:MouseEvent):void { _primaryItem.stopDrag(); } // expects _dragStartCoordinates and _siblingsDragStartCoordinates // to be set private function moveSiblings():void { if (!_dragStartCoordinates || !_siblingsDragStartCoordinates) return; var xDiff:Number = _primaryItem.x - _dragStartCoordinates.x; var yDiff:Number = _primaryItem.y - _dragStartCoordinates.y; for each (var sibling:DisplayObject in _dragWithPrimary) { sibling.x = _siblingsDragStartCoordinates[sibling].x + xDiff; sibling.y = _siblingsDragStartCoordinates[sibling].y + yDiff; } } } } A: can you add the movieclips to a parent clip and have the event handler drag the parent?
{ "language": "en", "url": "https://stackoverflow.com/questions/104448", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Applying Styles To ListItems in CheckBoxList How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify <ItemStyle>, you can't seem to specify a style for each individual control. Is there some sort of work around? A: In addition to Andrew's answer... Depending on what other attributes you put on a CheckBoxList or RadioButtonList, or whatever, ASP.Net will render the output using different structures. For example, if you set RepeatLayout="Flow", it won't render as a TABLE, so you have to be careful of what descendant selectors you use in your CSS file. In most cases, you can can just do a "View Source" on your rendered page, maybe on a couple of different browsers, and figure out what ASP.Net is doing. There is a danger, though, that new versions of the server controls or different browsers will render them differently. If you want to style a particular list item or set of list items differently without adding in attributes in the code-behind, you can use CSS attribute selectors. The only drawback to that is that they aren't supported in IE6. jQuery fully supports CSS 3 style attribute selectors, so you could probably also use it for wider browser support. A: You can also achieve this in the markup. <asp:ListItem Text="Good" Value="True" style="background-color:green;color:white" /> <br /> <asp:ListItem Text="Bad" Value="False" style="background-color:red;color:white" /> The word Style will be underlined with the warning that Attribute 'style' is not a valid attribute of element 'ListItem'., but the items are formatted as desired anyway. A: You can add Attributes to ListItems programmatically as follows. Say you've got a CheckBoxList and you are adding ListItems. You can add Attributes along the way. ListItem li = new ListItem("Richard Byrd", "11"); li.Selected = false; li.Attributes.Add("Style", "color: red;"); CheckBoxList1.Items.Add(li); This will make the color of the listitem text red. Experiment and have fun. A: You can even have different font styles and color for each word. <asp:ListItem Text="Other (<span style=font-weight:bold;>please </span><span>style=color:Red;font-weight:bold;>specify</span>):" Value="10"></asp:ListItem> A: It seems the best way to do this is to create a new CssClass. ASP.NET translates CheckBoxList into a table structure. Using something like Style.css .chkboxlist td { font-size:x-large; } Page.aspx <asp:CheckBoxList ID="chkboxlist1" runat="server" CssClass="chkboxlist" /> will do the trick A: public bool Repeater_Bind() { RadioButtonList objRadioButton = (RadioButtonList)eventArgs.Item.FindControl("rbList"); if (curQuestionInfo.CorrectAnswer != -1) { objRadioButton.Items[curQuestionInfo.CorrectAnswer].Attributes.Add("Style", "color: #b4fbb1;"); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/104458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: For std::map, how will insert behave if it has to resize the container and the memory is not available? For std::map, how will insert behave if it has to resize the container and the memory is not available? A: STL map does not have to "resize" container. map (just like list) is a node based container; each insert allocates memory. That said, out of memory situation is handled just like any other out-of-memory situation in C++: it throws a std::bad_alloc. STL containers with default allocators don't do anything fancy, they all end up allocating via standard new/delete operators somehow. In STL map's case, it will throw exception and will otherwise behave as if it was not called. That is, the container will remain unmodified. A: New will throw an exception. Easy as that. The insert will not happen, and neither will the content of the dictionary be modified or corrupted. A: To expand on Nils answer (yes it will throw), but what happens when it throws is sometimes confusing in the spec. In 17.2.2 of the specification (regarding maps / exceptions), if insert() throws, that function has no effect. This is a strong guarantee for map. This differs from containers using contiguous allocation like vector or deque.
{ "language": "en", "url": "https://stackoverflow.com/questions/104483", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Is there a way to force a style to a div element which already has a style="" attribute I'm trying to skin HTML output which I don't have control over. One of the elements is a div with a style="overflow: auto" attribute. Is there a way in CSS to force that div to use overflow: hidden;? A: You can add !important to the end of your style, like this: element { overflow: hidden !important; } This is something you should not rely on normally, but in your case that's the best option. Changing the value in Javascript strays from the best practice of separating markup, presentation, and behavior (html/css/javascript). A: Not sure if this would work or not, haven't tested it with overflow. overflow:hidden !important maybe? A: If the div has an inline style declaration, the only way to modify it without changing the source is with JavaScript. Inline style attributes 'win' every time in CSS. A: Magnar is correct as explained by the W3C spec pasted below. Seems the !important keyword was added to allow users to override even "baked in" style settings at the element level. Since you are in the situation where you do not have control over the html this may be your best option, though it would not be a normal design pattern. W3C CSS Specs Excerpt: 6.4.2 !important rules CSS attempts to create a balance of power between author and user style sheets. By default, rules in an author's style sheet override those in a user's style sheet (see cascade rule 3). However, for balance, an "!important" declaration (the keywords "!" and "important" follow the declaration) takes precedence over a normal declaration. Both author and user style sheets may contain "!important" declarations, and user "!important" rules override author "!important" rules. This CSS feature improves accessibility of documents by giving users with special requirements (large fonts, color combinations, etc.) control over presentation. Note. This is a semantic change since CSS1. In CSS1, author "!important" rules took precedence over user "!important" rules. Declaring a shorthand property (e.g., 'background') to be "!important" is equivalent to declaring all of its sub-properties to be "!important". Example(s): The first rule in the user's style sheet in the following example contains an "!important" declaration, which overrides the corresponding declaration in the author's styles sheet. The second declaration will also win due to being marked "!important". However, the third rule in the user's style sheet is not "!important" and will therefore lose to the second rule in the author's style sheet (which happens to set style on a shorthand property). Also, the third author rule will lose to the second author rule since the second rule is "!important". This shows that "!important" declarations have a function also within author style sheets. /* From the user's style sheet */ P { text-indent: 1em ! important } P { font-style: italic ! important } P { font-size: 18pt } /* From the author's style sheet */ P { text-indent: 1.5em !important } P { font: 12pt sans-serif !important } P { font-size: 24pt } A: Have you tried setting !important in the CSS file? Something like: #mydiv { overflow: hidden !important; } A: As far as I know, styles on the actual HTML elements override anything you can do in separate CSS style. You can, however, use Javascript to override it.
{ "language": "en", "url": "https://stackoverflow.com/questions/104485", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "34" }
Q: Mod-rewrites on apache: change all URLs Right now I'm doing something like this: RewriteRule ^/?logout(/)?$ logout.php RewriteRule ^/?config(/)?$ config.php I would much rather have one rules that would do the same thing for each url, so I don't have to keep adding them every time I add a new file. Also, I like to match things like '/config/new' to 'config_new.php' if that is possible. I am guessing some regexp would let me accomplish this? A: Try: RewriteRule ^/?(\w+)/?$ $1.php the $1 is the content of the first captured string in brackets. The brackets around the 2nd slash are not needed. edit: For the other match, try this: RewriteRule ^/?(\w+)/(\w+)/?$ $1_$2.php A: I would do something like this: RewriteRule ^/?(logout|config|foo)/?$ $1.php RewriteRule ^/?(logout|config|foo)/(new|edit|delete)$ $1_$2.php I prefer to explicitly list the url's I want to match, so that I don't have to worry about static content or adding new things later that don't need to be rewritten to php files. The above is ok if all sub url's are valid for all root url's (book/new, movie/new, user/new), but not so good if you want to have different sub url's depending on root action (logout/new doesn't make much sense). You can handle that either with a more complex regex, or by routing everything to a single php file which will determine what files to include and display based on the url. A: Mod rewrite can't do (potentially) boundless replaces like you want to do in the second part of your question. But check out the External Rewriting Engine at the bottom of the Apache URL Rewriting Guide: External Rewriting Engine Description: A FAQ: How can we solve the FOO/BAR/QUUX/etc. problem? There seems no solution by the use of mod_rewrite... Solution: Use an external RewriteMap, i.e. a program which acts like a RewriteMap. It is run once on startup of Apache receives the requested URLs on STDIN and has to put the resulting (usually rewritten) URL on STDOUT (same order!). RewriteEngine on RewriteMap quux-map prg:/path/to/map.quux.pl RewriteRule ^/~quux/(.*)$ /~quux/${quux-map:$1} #!/path/to/perl # disable buffered I/O which would lead # to deadloops for the Apache server $| = 1; # read URLs one per line from stdin and # generate substitution URL on stdout while (<>) { s|^foo/|bar/|; print $_; } This is a demonstration-only example and just rewrites all URLs /~quux/foo/... to /~quux/bar/.... Actually you can program whatever you like. But notice that while such maps can be used also by an average user, only the system administrator can define it.
{ "language": "en", "url": "https://stackoverflow.com/questions/104487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot store load test results in a TFS 2005 results store I've setup a results store and when I publish results of a load test, I can't view the published test details. From the test run section of the build report I click on the published build and when I choose View Test Results Details from the Test Runs shortcut menu I get an error that the test results details cannot be viewed because the results were not stored in a results store. I've looked for the data in the results store database and I don't anything there so the error makes sense. I've setup a connection string to the results store in the Administer Test Controller dialog. Is this the only thing that needs to be done to get test results into the store? A: The reports aren't going to be available until after the data has been copied to the data warehouse. This can typically take up to one hour to do. See http://msdn.microsoft.com/en-us/library/ms404692(VS.80).aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/104494", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flash/FLEX 3 Argument Error 2082 Has anyone else experienced this error? Sometimes it pops up at the beginning of loading the application with Argument Error 2082. The only way I can solve it is by rebooting my machine. Restarting the browser doesn't even solve it. I have read about some solutions on the web, but I am interested in knowing what others have tried using that solved the error for them? Thanks in advance. A: It's a known bug in Flash, there's a pretty long discussion about it here: http://tech.groups.yahoo.com/group/flexcoders/message/63829 The long and short of it is you should wrap your localConnection.connect() in a try catch. A: Are you talking about the Actionscript 3.0 Runtime Error 2082?
{ "language": "en", "url": "https://stackoverflow.com/questions/104500", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What's the best freely available C# wrapper for BITS? BITS, the Windows background intelligent transfer service. Looks like there are a few C# wrappers around that manage the interop to BITS, does anybody have any opinions on the best one? A: I found problems with using the Managed_BITS codeproject article and I found an even better wrapper: http://www.codeplex.com/sharpbits http://nuget.org/packages/SharpBITS Less code, a lot cleaner and unlike the codeproject, it did not hide away those parts of the BITS interface that I actually need to use. A: Check out the following: * *http://www.codeproject.com/KB/cs/Managed_BITS.aspx *http://www.simple-talk.com/dotnet/.net-tools/using-bits-to-upload-files-with-.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/104505", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Calling PHP functions within HEREDOC strings In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces. In PHP 5, it is possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example: $fn = 'testfunction'; function testfunction() { return 'ok'; } $string = <<< heredoc plain text and now a function: {$fn()} heredoc; As you can see, this is a bit more messy than just: $string = <<< heredoc plain text and now a function: {testfunction()} heredoc; There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like: ?> <!-- directly output html and only breaking into php for the function --> plain text and now a function: <?PHP print testfunction(); ?> The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want. So, the essence of my question is: is there a more elegant way to approach this? Edit based on responses: It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now. A: found nice solution with wrapping function here: http://blog.nazdrave.net/?p=626 function heredoc($param) { // just return whatever has been passed to us return $param; } $heredoc = 'heredoc'; $string = <<<HEREDOC \$heredoc is now a generic function that can be used in all sorts of ways: Output the result of a function: {$heredoc(date('r'))} Output the value of a constant: {$heredoc(__FILE__)} Static methods work just as well: {$heredoc(MyClass::getSomething())} 2 + 2 equals {$heredoc(2+2)} HEREDOC; // The same works not only with HEREDOC strings, // but with double-quoted strings as well: $string = "{$heredoc(2+2)}"; A: If you really want to do this but a bit simpler than using a class you can use: function fn($data) { return $data; } $fn = 'fn'; $my_string = <<<EOT Number of seconds since the Unix Epoch: {$fn(time())} EOT; A: This snippet will define variables with the name of your defined functions within userscope and bind them to a string which contains the same name. Let me demonstrate. function add ($int) { return $int + 1; } $f=get_defined_functions();foreach($f[user]as$v){$$v=$v;} $string = <<< heredoc plain text and now a function: {$add(1)} heredoc; Will now work. A: I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages * *No option for WYSIWYG *No code completion for HTML from IDEs *Output (HTML) locked to logic files *You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping Get a basic template engine, or just use PHP with includes - it's why the language has the <?php and ?> delimiters. template_file.php <html> <head> <title><?php echo $page_title; ?></title> </head> <body> <?php echo getPageContent(); ?> </body> index.php <?php $page_title = "This is a simple demo"; function getPageContent() { return '<p>Hello World!</p>'; } include('template_file.php'); A: I think using heredoc is great for generating HTML code. For example, I find the following almost completely unreadable. <html> <head> <title><?php echo $page_title; ?></title> </head> <body> <?php echo getPageContent(); ?> </body> However, in order to achieve the simplicity you are forced to evaluate the functions before you start. I don't believe that is such a terrible constraint, since in so doing, you end up separating your computation from display, which is usually a good idea. I think the following is quite readable: $page_content = getPageContent(); print <<<END <html> <head> <title>$page_title</title> </head> <body> $page_content </body> END; Unfortunately, even though it was a good suggestion you made in your question to bind the function to a variable, in the end, it adds a level of complexity to the code, which is not worth, and makes the code less readable, which is the major advantage of heredoc. A: I would do the following: $string = <<< heredoc plain text and now a function: %s heredoc; $string = sprintf($string, testfunction()); Not sure if you'd consider this to be more elegant ... A: you are forgetting about lambda function: $or=function($c,$t,$f){return$c?$t:$f;}; echo <<<TRUEFALSE The best color ever is {$or(rand(0,1),'green','black')} TRUEFALSE; You also could use the function create_function A: This is a little more elegant today on php 7.x <?php $test = function(){ return 'it works!'; }; echo <<<HEREDOC this is a test: {$test()} HEREDOC; A: I'd take a look at Smarty as a template engine - I haven't tried any other ones myself, but it has done me well. If you wanted to stick with your current approach sans templates, what's so bad about output buffering? It'll give you much more flexibility than having to declare variables which are the string names of the functions you want to call. A: For completeness, you can also use the !${''} black magic parser hack: echo <<<EOT One month ago was { ${!${''} = date('Y-m-d H:i:s', strtotime('-1 month'))} }. EOT; See it live on 3v4l.org. Note: PHP 8.2 deprecated bare ${} variable variables within strings, in preference to the explicit { ${} } syntax. The example above uses this explicit format to remove the deprecation notice, though it makes this method even more noisy! A: A bit late but still. This is possible in heredoc! Have a look in the php manual, section "Complex (curly) syntax" A: Here a nice example using @CJDennis proposal: function double($i) { return $i*2; } function triple($i) { return $i*3;} $tab = 'double'; echo "{$tab(5)} is $tab 5<br>"; $tab = 'triple'; echo "{$tab(5)} is $tab 5<br>"; For instance, a good use for HEREDOC syntax is generate huge forms with master-detail relationship in a Database. One can use HEREDOC feature inside a FOR control, adding a suffix after each field name. It's a typical server side task. A: Try this (either as a global variable, or instantiated when you need it): <?php class Fn { public function __call($name, $args) { if (function_exists($name)) { return call_user_func_array($name, $args); } } } $fn = new Fn(); ?> Now any function call goes through the $fn instance. So the existing function testfunction() can be called in a heredoc with {$fn->testfunction()} Basically we are wrapping all functions into a class instance, and using PHP's __call magic method to map the class method to the actual function needing to be called. A: I'm a bit late, but I randomly came across it. For any future readers, here's what I would probably do: I would just use an output buffer. So basically, you start the buffering using ob_start(), then include your "template file" with any functions, variables, etc. inside of it, get the contents of the buffer and write them to a string, and then close the buffer. Then you've used any variables you need, you can run any function, and you still have the HTML syntax highlighting available in your IDE. Here's what I mean: Template File: <?php echo "plain text and now a function: " . testfunction(); ?> Script: <?php ob_start(); include "template_file.php"; $output_string = ob_get_contents(); ob_end_clean(); echo $output_string; ?> So the script includes the template_file.php into its buffer, running any functions/methods and assigning any variables along the way. Then you simply record the buffer's contents into a variable and do what you want with it. That way if you don't want to echo it onto the page right at that second, you don't have to. You can loop and keep adding to the string before outputting it. I think that's the best way to go if you don't want to use a templating engine. A: Guys should note that it also works with double-quoted strings. http://www.php.net/manual/en/language.types.string.php Interesting tip anyway. A: <div><?=<<<heredoc Use heredoc and functions in ONE statement. Show lower case ABC=" heredoc . strtolower('ABC') . <<<heredoc ". And that is it! heredoc ?></div> A: <?php echo <<<ETO <h1>Hellow ETO</h1> ETO; you should try it . after end the ETO; command you should give an enter.
{ "language": "en", "url": "https://stackoverflow.com/questions/104516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "103" }
Q: WPF Validation for the whole form I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!! I can do this using my own ValidationEngine framework: Customer customer = new Customer(); customer.FirstName = "John"; customer.LastName = String.Empty; ValidationEngine.Validate(customer); if (customer.BrokenRules.Count > 0) { // do something display the broken rules! } A: A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the IDataErrorInfo interface on your business object, using Bindings with ValidatesOnDataErrors=true. For customizing the look of individual controls in the case of errors, set a Validation.ErrorTemplate. XAML: <Window x:Class="Example.CustomerWindow" ...> <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCanExecute" Executed="SaveExecuted" /> </Window.CommandBindings> <StackPanel> <TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> <Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button> <TextBlock Text="{Binding Error}"/> </StackPanel> </Window> This creates a Window with two TextBoxes where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The TextBlock beneath the button shows the current errors, so the user knows what's up. The default ErrorTemplate is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at Validation in Windows Presentation Foundation article on CodeProject for an in-depth look into what can be done about that. To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer. Code Behind // The CustomerWindow class receives the Customer to display // and manages the Save command public class CustomerWindow : Window { private Customer CurrentCustomer; public CustomerWindow(Customer c) { // store the customer for the bindings DataContext = CurrentCustomer = c; InitializeComponent(); } private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = ValidationEngine.Validate(CurrentCustomer); } private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) { CurrentCustomer.Save(); } } public class Customer : IDataErrorInfo, INotifyPropertyChanged { // holds the actual value of FirstName private string FirstNameBackingStore; // the accessor for FirstName. Only accepts valid values. public string FirstName { get { return FirstNameBackingStore; } set { FirstNameBackingStore = value; ValidationEngine.Validate(this); OnPropertyChanged("FirstName"); } } // similar for LastName string IDataErrorInfo.Error { get { return String.Join("\n", BrokenRules.Values); } } string IDataErrorInfo.this[string columnName] { get { return BrokenRules[columnName]; } } } An obvious improvement would be to move the IDataErrorInfo implementation up the class hierarchy, since it only depends on the ValidationEngine, but not the business object. While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data. A: I would suggest to look at the IDataErrorInfo interface on your business object. Also have a look at this article: Self Validating Text Box A: You might be interested in the BookLibrary sample application of the WPF Application Framework (WAF). It shows how to use validation in WPF and how to control the Save button when validation errors exists. A: ValidatesOnDataError is used to validate business rules against your view models, and it will validate only if the binding succeeds. ValidatesOnExceptions needs to be applied along with ValidatesOnDataError to handle those scenarios where wpf cannot perform binding because of data type mismatch, lets say you want to bind a TextBox to the Age (integer) property in your view model <TextBox Text="{Binding Age, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> If the user enters invalid entry by typing alphabets rather than numbers as age, say xyz, the wpf databinding will silently ignores the value as it cannot bind xyz to Age, and the binding error will be lost unless the binding is decorated with ValidatesOnExceptions <TextBox Text="{Binding Age, ValidatesOnDataErrors=true, ValidatesOnExceptions="True", UpdateSourceTrigger=PropertyChanged}" /> ValidatesOnException uses default exception handling for binding errors using ExceptionValidationRule, the above syntax is a short form for the following <TextBox> <TextBox.Text> <Binding Path="Age" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> </TextBox> You can defined your own rules to validate against the user input by deriving from ValidationRule and implementing Validate method, NumericRule in the following example <TextBox.Text> <Binding Path="Age" ValidatesOnDataErrors="True"> <Binding.ValidationRules> <rules:NumericRule /> </Binding.ValidationRules> </Binding> </TextBox.Text> The validation rules should be generic and not tied to business, as the later is accomplished through IDataErrorInfo and ValidatesOnDataError. The above syntax is quite messy compared to the one line binding syntax we have, by implementing the ValidationRule as an attached property the syntax can be improved and you can take a look at it here A: The description of your problem is a little vague to me. I mean, I'm not exactly sure what your difficulty is. Assuming that the DataContext is some sort of presenter or controller that has a propetry representing the customer instance, and ValidateCommand is a property of type ICommand: <StackPanel> <TextBox Text="{Binding CurrentCustomer.FirstName}" /> <TextBox Text="{Binding CurrentCustomer.LastName}" /> <Button Content="Validate" Command="{Binding ValidateCommand}" CommandParameter="{Binding CurrentCustomer}" /> <ItemsControl ItemsSource="{Binding CurrentCustomer.BrokenRules}" /> </StackPanel> This XAML is really simplified, of course, and there are other ways to do it. As a Web developer who is now heavily involved with WPF, I find most tasks like this significantly easier in WPF.
{ "language": "en", "url": "https://stackoverflow.com/questions/104520", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "15" }
Q: Warm SQL Backup We have a warm sql backup. full backup nightly, txn logs shipped every so often during the day and restored. I need to move the data files to another disk. These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '<dbname>' is in warm standby. A warm-standby database is read-only. ") and am worried about detaching and re-attaching. How do we obtain the "warm backup" status after detach/attach operations are complete? A: The only solution I know is to create a complete backup of your active database and restore this backup to a copy of the database in a 'warm backup' state. First create a backup from the active db: backup database activedb to disk='somefile' Then restore the backup on another sql server. If needed you can use the WITH REPLACE option to change the default storage directory restore database warmbackup from disk='somefile' with norecovery, replace .... Now you can create backups of the logs and restore them to the warmbackup with the restore log statement. A: It looks like you didn't complete the restore task , just do the restore task only for the TRANSACTOINAL LOG .Then it will be fine immediately when you finish that.
{ "language": "en", "url": "https://stackoverflow.com/questions/104525", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Do I have always use .css files? Are .css files always needed? Or may I have a .css "basic" file and define other style items inside the HTML page? Does padding, borders and so on always have to be defined in a .css file that is stored separately, or may I embed then into an HTML page? A: You can include CSS inside an HTML page. It goes within the <style> tag, which goes within the <head> tag: <head> <style type="text/css"> body{ background-color: blue; } </style> </head> Note, however, that it is best practice to use .css files. A: Putting rules into the HTML page gives them greater "specificity," and therefore priority, over external rules. If several CSS rules conflict, ID wins over class, and inline styles win over ID. <head> <style type="text/css"> span.reminder {color: blue;} span#themostimportant {color: red;} </style> </head> <body> <span class="reminder" id="themostimportant"> This text will be red. </span> <span class="reminder" id="themostimportant" style="color: green;"> This text will be green. </span> </body> A: It is technically possible to use inline CSS formatting exclusively and have no external stylesheet. You can also embed the stylesheet within the HTML document. The best practice in web design is to separate out the CSS into a separate stylesheet. The reason for this is that the CSS stylesheet exists for the purpose of defining the presentation style of the document. The HTML file exists to define the structure and content of the document. And perhaps you may have JavaScript files which exist to add additional behavior to the document. Keeping the presentation, markup, and behavior separate creates a cleaner design. From a practical perspective, if you have a single external CSS stylesheet the browser can cache it. If multiple pages on your site have the same look and feel, they can use the same external stylesheet which only needs to be downloaded once by the web browser. This will make your network bandwidth bills lower as well as creating a faster end user experience. A: You can define CSS at three levels, externally, embedded in the document (inside a <style> tag), or inline on the element. Depending on your needs, you might use all three, as a rule of thumb external sheets are good for overall styles as you can apply them globally. If you have specific cases that you must handle you can then use the other levels. A: You can do either. However, by shifting your CSS out to a separate file, it can be cached. This reduces the amount of data that you need to transmit for each page, cutting down on bandwidth costs, and increasing speed. A: You don't have to keep your CSS in an external file, no. What you're asking about is "inline" css: including style directives directly within the page itself via <style> blocks. There are times where that may makes sense, in moderation, but in general it's not the way you want to go. Keep your CSS isolated in an external stylesheet makes it much easier to maintain both your HTML and your styling, especially as a project scales and changes hands. A: One big advantage of having CSS in an external file is that one rule can apply to many different pages. Here is a contrast of three CSS approaches: Inline Styles - to change the color to blue, you have to find each place that the red style exists - maybe on many pages. <span style="color: red;">This is a warning.</span> Page Styles - this allows you to label what something is - in this case, a warning - rather than what it looks like. You could change all the "warnings" on the page to instead have a yellow background by changing one line of code at the top of the page. <head> <style type="text/css"> .warning {color: red;} </style> <body> <span class="warning">This is a warning.</span*> External File - same code as above, but the fact that the style info is in a separate file means that you can use the "warning" class on many pages. A: You can use anywhere, css files are not a requirement. using css files however is recommended as it makes the site easier to maintain and change in the future A: Have to? No. You can do it however you prefer. Generally it's better stype to keep your CSS out of your html whenever possible though. A: That's what i usually do. At least at the begining. When a page design gets close to final, I move most things to the 'main' style.css A: I prefer to keep styling in CSS as it separates view from presentation, allowing me to swap between presentations fairly easily. Plus it keeps all the information in one place instead of split between two places. A: Css can improve performance, because they are cached from browser, and pages are smaller! A: Use an external file for all styles that are used sitewide, document stylesheet for styles that are only used on that page and use inline styles when the style only affects that single element. External stylesheets do not always lower bandwidth. If you put every style for every page in your site into one giant css file, your users incur a large initial download even if they only visit your homepage once ever. Thoughtful division of your styles into a main.css with the most common styles and then into additional stylesheets as users drill down deeper can help to make the downloads smaller for some paths through the site.
{ "language": "en", "url": "https://stackoverflow.com/questions/104550", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's the best source to learn about database replication mechanisms? What's the widest overview and where are the deepest analysis of different replication methods and problems? A: I would start here: wikipedia's replication article, then read a couple of related papers on general replication techniques such as the replicated distributed state machine approach (Paxos (pdf)) and epidemic replication (Google 'Epidemic Algorithms for Replicated Database Maintenance'). For a practical overview, perhaps consider investigating the source code for Postgresql, which seems to have some replication technologies built in. This presentation purports to have some details. However, given that you're talking about deep analysis, the best approach is to make sure that you have a very sound understanding of fundamental distributed database systems issues. My copy of Date's Introduction to Database Systems has a few pages on distributed databases and their attendant issues. I should think a textbook dedicated to distributed databases would have much more detail - this one, for example, looks promising. You can go much deeper if you read Ken Birman's work on Virtual Synchrony, and most things that Leslie Lamport has ever written. These will attack the problem from the perspective of a general distributed systems approach. Good luck! A: In my opinion, you should pick a mainstream database (such as Oracle) and study everything it offers and go from there. Oracle offers: * *Replication *Data guard (standby database and beyond- physical, logical) *Real Application Clusters - (multiple instances, one DB) and more ! A bit of hands-on would not hurt so you can download a PC version and try various replication approaches on one PC! Enjoy ! A: Though it is MS-SQL specific, you should have a look at "Pro SQL SERVER 2005 Replication" (Sujoy P. PAUL, Apress). I owe this guy many quiet nights... I guess you can find some extracts of this book as PDF files. A: Wikipedia has some overview on the matter: http://en.wikipedia.org/wiki/Multi-master_replication http://en.wikipedia.org/wiki/Lazy_replication
{ "language": "en", "url": "https://stackoverflow.com/questions/104554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing Greasemonkey metadata from within your script? Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps GM_getValue(). That would of course involve a special name syntax. I have tried, for example: GM_getValue("@name"). The motivation here is to avoid redundant specification. If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for "// @". (That may be necessary in my case any way, since the value I'm really interested in is @version, which is an extended value read by userscripts.org.) A: This answer is out of date : As of Greasemonkey 0.9.16 (Feb 2012) please see Brock's answer regarding GM_info Yes. A very simple example is: var metadata=<> // ==UserScript== // @name Reading metadata // @namespace http://www.afunamatata.com/greasemonkey/ // @description Read in metadata from the header // @version 0.9 // @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script // ==/UserScript== </>.toString(); GM_log(metadata); See this thread on the greasemonkey-users group for more information. A more robust implementation can be found near the end. A: Use the GM_info object, which was added to Greasemonkey in version 0.9.16. For example, if You run this script: // ==UserScript== // @name _GM_info demo // @namespace Stack Overflow // @description Tell me more about me, me, ME! // @include http://stackoverflow.com/questions/* // @version 8.8 // ==/UserScript== unsafeWindow.console.clear (); unsafeWindow.console.log (GM_info); It will output this object: { version: (new String("0.9.18")), scriptWillUpdate: false, script: { description: "Tell me more about me, me, ME!", excludes: [], includes: ["http://stackoverflow.com/questions/*"], matches: [], name: "_GM_info demo", namespace: "Stack Overflow", 'run-at': "document-end", unwrap: false, version: "8.8" }, scriptMetaStr: "// @name _GM_info demo\r\n// @namespace Stack Overflow\r\n// @description Tell me more about me, me, ME!\r\n// @include http://stackoverflow.com/questions/*\r\n// @version 8.8\r\n" } A: Building on Athena's answer, here is my generalized solution that yields an object of name/value pairs, each representing a metadata property. Note that certain properties can have multiple values, (@include, @exclude, @require, @resource), therefore my parser captures those as Arrays - or in the case of @resource, as a subordinate Object of name/value pairs. var scriptMetadata = parseMetadata(.toString()); function parseMetadata(headerBlock) { // split up the lines, omitting those not containing "// @" function isAGmParm(element) { return /\/\/ @/.test(element); } var lines = headerBlock.split(/[\r\n]+/).filter(isAGmParm); // initialize the result object with empty arrays for the enumerated properties var metadata = { include: [], exclude: [], require: [], resource: {} }; for each (var line in lines) { [line, name, value] = line.match(/\/\/ @(\S+)\s*(.*)/); if (metadata[name] instanceof Array) metadata[name].push(value); else if (metadata[name] instanceof Object) { [rName, rValue] = value.split(/\s+/); // each resource is named metadata[name][rName] = rValue; } else metadata[name] = value; } return metadata; } // example usage GM_log("version: " + scriptMetadata["version"]); GM_log("res1: " + scriptMetadata["resource"]["res1"]); This is working nicely in my scripts. EDIT: Added @resource and @require, which were introduced in Greasemonkey 0.8.0. EDIT: FF5+ compatibility, Array.filter() no longer accepts a regular expression
{ "language": "en", "url": "https://stackoverflow.com/questions/104568", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: CVS and Visual Studio 2008 - integration options I'd like to increase developers' "comfort level" in our team a bit. We are using Visual Studio 2008 and TortoiseCVS + WinCVS, but no integration as of yet. In your CVS/Visual Studio experience, what is the best integration tool in terms of "supports basic CVS functionality add/diff/update/commit/annotate/etc", "works out of the box", almost "bug-free"? * *a) commercial *b) free or open source Edit: There are 2 commercial MSSCCI bridge solutions I've found so far: PushOk.com and TamTam (daveswebsite.com). Both were developed quite a long time ago and now have only minor updates. Being MSSCCI bridges, they are somewhat limited in functionality and can not provide all the nice features of vsPackage SCC provider, but are probably better than nothing. A: You might be stuck with one of those MSSCCI bridges you mentioned. As it is, not too many people still use CVS, especially those using Visual Studio (most of them seem to use Team System's revision control, or Subversion). There's always the possibility of hacking together your own macros to take care of CVS operations, but this has the disadvantage of not giving you real, in-depth integration the way a an SCC provider, or even an old brige, would. A: I don't know about CVS, but if going to SVN is an option, there's always Ankh. A: Ankh is a open source choice http://ankhsvn.open.collab.net/
{ "language": "en", "url": "https://stackoverflow.com/questions/104579", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Does the iPhone SDK allow hardware access to the dock connector? I haven't been able to find any documentation on hardware access via the iPhone SDK so far. I'd like to be able to send signals via the dock connector to an external hardware device but haven't seen any evidence that this is accessible via the SDK (not interested in possibilities on jailbroken iPhones). Anyone have any pointers to docs for this or some idea of what deep dark corner i should look? A: Available in iPhone SDK 3.0 as External Accessory framework http://developer.apple.com/iphone/program/sdk.html A: To get the Hardware specs for the Doc connector you need to be part of the made for ipod/iphone program. But if you just want to talk to an already existing piece of hardware that supports it, the 3.0 SDK will let you access it. I have tried applying to the made for ipod/iphone program as a individual/hobbyist, but have so far not heard anything past the "fill out the company information" stage. chris. A: It will with the new SDK (3.0): iPhone OS Accessories Using iPhone SDK 3.0 your application can communicate with accessories attached to iPhone or iPod touch through either the 30-pin dock connector or wirelessly using Bluetooth. A: This falls into the range of capabilities that requires working with Apple to get a special license. At, I presume, a special price. This has changed to some extent with the 3.0 version of the iPhone firmware. If PyjamaSam is correct there is still some special activity required to get the connector specifications.
{ "language": "en", "url": "https://stackoverflow.com/questions/104583", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How to configure ResourceBundleViewResolver in Spring Framework 2.0 Everywhere I look always the same explanation pop ups. Configure the view resolver. <bean id="viewMappings" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views" /> </bean> And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names). logout.class=org.springframework.web.servlet.view.JstlView logout.url=WEB-INF/jsp/logout.jsp What does logout.class and logout.url mean? How does ResourceBundleViewResolver uses the key-value pairs in the file? My goal is that when someone enters the URI myserver/myapp/logout.htm the file logout.jsp gets served. A: ResourceBundleViewResolver uses the key/vals in views.properties to create view beans (actually created in an internal application context). The name of the view bean in your example will be "logout" and it will be a bean of type JstlView. JstlView has an attribute called URL which will be set to "WEB-INF/jsp/logout.jsp". You can set any attribute on the view class in a similar way. What you appear to be missing is your controller/handler layer. If you want /myapp/logout.htm to serve logout.jsp, you must map a Controller into /myapp/logout.htm and that Controller needs to return the view name "logout". The ResourceBundleViewResolver will then be consulted for a bean of that name, and return your instance of JstlView. A: To answer your question logout is the view name obtained from the ModelAndView object returned by the controller. If your are having problems you many need the following additional configuration. You need to add a servlet mapping for *.htm in your web.xml: <web-app> <servlet> <servlet-name>htm</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <oad-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>htm</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> </web-app> And if you want to map directly to the *.jsp without creating a custom controller then you need to add the following bean to your Spring context: <bean id="urlFilenameController" class="org.springframework.web.servlet.mvc.UrlFilenameViewController" />
{ "language": "en", "url": "https://stackoverflow.com/questions/104587", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: What's a good alternative to security questions? From Wired magazine: ...the Palin hack didn't require any real skill. Instead, the hacker simply reset Palin's password using her birthdate, ZIP code and information about where she met her spouse -- the security question on her Yahoo account, which was answered (Wasilla High) by a simple Google search. We cannot trust such security questions to reset forgotten passwords. How do you design a better system? A: Having seen a lot of posters suggest email, all I can suggest is DONT use email as your line of defense. Compromising somebodys email account can be relatively easy. Many web based email services DONT provide any real security either, and even if they offer SSL, its often not default and you are still relying on the weakness of the email password to protect the user ( Which, in turn has a reset mechanism most the time ). Email is one of the most insecure technologies, and there are good reasons why its a really bad idea to send information like credit card details over them. They're usually transmitted between servers in plaintext, and equally often, between server and desktop client equally unencrypted, and all it takes is a wire sniff to get the reset url and trigger it. ( Don't say I'm paranoid, because banks use SSL encryption for a good reason. How can you trust the 20-200 physical devices on the route have good intentions? ) Once you get the reset data, you can reset the password, and then change your(their) email address, and have permanent control of their account ( it happens all the time ). And if they get your email account, all they have to do is have a browse through your inbox to find whom you're subscribed with, and then easily reset the password ON ALL OF THEM So now, using the email based security, can lead to a propogative security weakness!. I'm sure thats beneficial!. The question being asked Is one I figure is almost impossible to do with software alone. This is why we have 2-factor authentication with hardware dongles that respond to challenges with their own unique private key signature, and only if you lose that are you screwed, and you then have to deal with a human ( oh no ) to get a new one. A: It 'depends' on the 'system'. * *If you are a Bank or a credit card provider, you have already issued some physical token to your customer that you can validate against and more. *If you are an ecommerce site, you ask for some recent transactions -exact amounts, credit card number used et al.. *If you are like Yahoo, an automated approach I would use is to send an activation code via either a phone call or a text message to the cell phone along with some other basic question and answers. Jay A: Do away with the (in)security questions completely. They're such an obvious security hole that I'm actually a bit surprised that it's taken this long for them to create a serious (well, highly-publicized) incident. Until they disappear, I'm just going to keep on telling websites which use them that I went to "n4weu6vyeli4u5t" high school... A: Have the user enter 3 questions and answers. When they request a reset present them with a drop down of 5 questions, one if which is a random one from the 3 they entered. Then send a confirmation email to actually reset the password. Of course, nothing is going to be truly "hacker proof". A: When users are involved (and mostly when not, too) there is no security; there is only the illusion of security. There's not a lot you can do about it. You could have 'less common' security questions but even they are prone to exploitation since some people put everything out in the public eye. Secondary channels like email offer a reasonable solution to the problem. If the user requests a password reset you can email them a password reset token. Still not perfect, as others have said, but exploiting this would require the attacker to be somewhere in the line of sight between the website, its MTA and the users MUA. It's technically easy but I suggest that the reality is it's just too much work/risk for them to bother on anyone except very high profile individuals. Requiring the user to supply SSL or GPG public keys at account creation time will help enormously, but clueless users won't know what those things are let-alone be able to keep their private keys secure and backed up so they don't lose them. Asking the user to supply a second emergency password (kind of like PIN/PUK on mobile phone SIM cards) could help but it's likely the user would use the same password twice or forget the second password too. Short answer, you're S.O.L unless you want to educate your users on security and then hit them with a cluestick until they realise that it is necessary to be secure and the slight amount of extra work is not simply there to be a pain in the arse. A: Authenticating everything by sending emails is a reasonably effective solution. (although, that might not have been workable for Yahoo in this case :)). Rather than messing about with security questions or other means to recover passwords, simply respond to password recover requests by sending an email to a predefined email account with an authorisation link. From there you can change passwords, or whatever you need to do (never SEND the password though - you should always store it as a salted hash anyway, always change it. Then if the email account has ben compromised, at least there's some indication to the user that their other services have been accessed) A: The true answer is, there isn't a fool proof way to keep hackers out. I hate security questions, but if your going to use them, allow for user defined security questions. As a user, if I must have a security question on a site to set up an account, I really like having the ability to setup my own security question to allow me to ask something that only I know how to answer. It doesn't even have to be a real question in this case. But a users account is then as secure as the stupidity of the user, and the fact that many users will use something like "question?" and "answer!" or something equally dumb. You can't save users from their own stupidity. A: Treating these security questions as something actually being two-factor authentication is totally misleading. From spurious items read before, when certain (banks) sites were required to have "two-factor authentication" they started implementing this as a cheap way to do it. Bruce Schneier talked about this a [while back][1]. Multiple factors are best things that are not-the-same. It should not be all things you "know" but something you know and something you have, etc. This is where the hardware authentication tokens, smart cards, and other such devices come into play. [1]: http://www.schneier.com/blog/archives/2005/03/the_failure_of.html The Failure of Two-Factor Authentication A: when its not an email system, email them a link to a secure page, with a hash that must come back in the query string to reset password. Then if someone tried to reset your password, you would know, and they wouldn't be able to guess the hash potentially. We use 2 guids multiplied together, represented as hex. A: Well for one it should not directly reset the password but send an email with a link to reset the password. That way she would have got the email and known that it was not her who initiated the reset, and that her question / answer had been compromised. In the case where the email address is no longer valid, it should wait for a timeout ( few days or a week ) before allowing a new email to be attached to an account. A: Send a message to a different e-mail account, or text their cell phone, or call them, or send a snail-mail message. Anything that doesn't involve matters of public record or preferences that may change at any time. A: Good security questions are a misnomer. They actually create a vulnerability into a system. We should call them in-secure questions. However, recognizing the risk and value they provide, "good" security questions should have 4 characteristics: 1. cannot be easily guessed or researched (safe), 2. doesn't change over time (stable), 3. is memorable, 4. is definitive or simple. You can read more about this at http://www.goodsecurityquestions.com. Here's a list of good, fair, and poor security questions. A: IMO Secret questions should only be used as a very weak control with a time limit as part of a system. Ex: Password reset system. * *You are authenticated. Registrate your mobile phone number and your secret(not so secret) answer. *You forget your password. *You request to unlock it. a) Your "Not so secret" question asks you for the "not so secret answer". b) If correct, a text message is sent to the pre registrated phone. This way, if your phone gets stolen and also, controls like pin/lock on the phone is not working. You still will have a measure of obfuscation for the attacker to get to reset the password until the time it is reported the phone is lost/stolen and can be disabled. This usage is what i think the only purpose at all for the "not so secret" questions/answers. So i would argue there is a place in this world for them and that usually a system needs to be the discussion. A: The insecurity of so-called "security questions" has been known for a long time. As Bruce Schneier puts it: The result is the normal security protocol (passwords) falls back to a much less secure protocol (secret questions). And the security of the entire system suffers. What can one do? My usual technique is to type a completely random answer -- I madly slap at my keyboard for a few seconds -- and then forget about it. This ensures that some attacker can't bypass my password and try to guess the answer to my secret question, but is pretty unpleasant if I forget my password. The one time this happened to me, I had to call the company to get my password and question reset. (Honestly, I don't remember how I authenticated myself to the customer service rep at the other end of the phone line.) I think the better technique is to just send an e-mail with a link they can use to generate a new random password to the e-mail account the user originally used to register. If they didn't request a new password, they can just ignore it and keep using their old one. As others have pointed out, this wouldn't necessarily have helped Yahoo, since they were running an e-mail service, but for most other services e-mail is a decent authentication measure (in effect, you foist the authentication problem off on the user's e-mail provider). Of course, you could just use OpenID. A: Out-of-band communication is the way to go. For instance, sending a temporary password in SMS may be acceptable (depending on the system). I've seen this implemented often by telecoms, where SMS is cheap/free/part of business, and the user's cellphone number is pre-registered... Banks often require a phone call to/from a specific number, but I personally am not too crazy about that.... And of course, depending on the system, forcing the user to come in to the branch office to personally identify themselves can also work (just royally annoy the user). Bottom line, DON'T create a weaker channel to bypass the strong password requirements. A: Only provide questions that aren't on the public record. A: always send the password reset to a registered email account (which is tricky for an email account) or send a PIN number to a registerd mobile phone, or a link to a IM address, etc - basically, capture some secondary contact information on registration and use it to send a 'password reset' link. Never let anyone change their password directly, always make sure they go through an additional step. A: I prefer to keep things simple and use an honor system approach. For example I'll present the user with something like, Is this really you? Select: Yes or No. A: How about requesting the users to enter their own security question and answer, and a secondary email (not the one where the password reset link is sent). Store the security question and answer hashed in the database for that extra step of security. If the user forgets his/her password, send the password reset link to the user's primary email. User then clicks on the link which redirects and asks for the security question and answer. If this step is successful then allow the user to reset his/her password. If the user forgets the security question/answer send a link to reset the security question/answer to the user's secondary email. If the attacker gets access to one of the emails, it will still be useless without access to the other (very unlikely the attacker can get access to both). I know this process needs a lot of extra work on both the developers and users, but I think it is worth it. (Maybe we could give the users a recommended option to activate the security question/answer if they need this extra bit of security.) Bottom line is that how strong or weak this system works will depends heavily on the user. The strength of the security question/answer and how well the two emails are "untied" (that is, there is no way of gaining access to one email through the other) will decide this systems strength. I don't know if there are any problems with this way of doing it, but if any, I'd be happy if anyone could point those out :) A: Generate a hash that contains the person's username and password and send it over Https to the user as a file. The user saves the file to disk. It is their responsibility to store this file in a secure location. Alternatively you can send it to their email address but this will result in less security. If the user forgets their login credentials they must then upload this file. Once the server verifies the username and password, they are then presented with a dialog to alter their password. A: Due to the evolution of social media, security questions asked by websites are too easy to crack. Since most of the questions are personal information which is easily available on social media platforms one or another. One of the alternatives to avoid account hacking is to make password rules strict for login like adding special characters, numerical, capital letters etc. These kind of passwords are hard to decode and can enhance the security to a great extent. But there are new alternative methods like multi-factor authentication, passwordless login, SMS authentication etc. SMS authentication is part of multi-factor authentication where a user is provided with an OTP on his/her cellphone which he/she need to enter in order to log in to a website. This is a secure way since the access of mobile is limited to the user only(mostly). Another multi-factor authentication method is sending a verification link to email to complete the signing in process. There is a very well written blog on this topic on Medium that explains this concept in a detailed manner.
{ "language": "en", "url": "https://stackoverflow.com/questions/104592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: Sort on a string that may contain a number I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the string are the same, and the middle part that differs is an integer, then compare based on the numeric values of those integers. For example, I want the following strings to end up in order they're shown: * *aaa *bbb 3 ccc *bbb 12 ccc *ccc 11 *ddd *eee 3 ddd jpeg2000 eee *eee 12 ddd jpeg2000 eee As you can see, there might be other integers in the string, so I can't just use regular expressions to break out any integer. I'm thinking of just walking the strings from the beginning until I find a bit that doesn't match, then walking in from the end until I find a bit that doesn't match, and then comparing the bit in the middle to the regular expression "[0-9]+", and if it compares, then doing a numeric comparison, otherwise doing a lexical comparison. Is there a better way? Update I don't think I can guarantee that the other numbers in the string, the ones that may match, don't have spaces around them, or that the ones that differ do have spaces. A: Ian Griffiths of Microsoft has a C# implementation he calls Natural Sorting. Porting to Java should be fairly easy, easier than from C anyway! UPDATE: There seems to be a Java example on eekboom that does this, see the "compareNatural" and use that as your comparer to sorts. A: The implementation I propose here is simple and efficient. It does not allocate any extra memory, directly or indirectly by using regular expressions or methods such as substring(), split(), toCharArray(), etc. This implementation first goes across both strings to search for the first characters that are different, at maximal speed, without doing any special processing during this. Specific number comparison is triggered only when these characters are both digits. public static final int compareNatural (String s1, String s2) { // Skip all identical characters int len1 = s1.length(); int len2 = s2.length(); int i; char c1, c2; for (i = 0, c1 = 0, c2 = 0; (i < len1) && (i < len2) && (c1 = s1.charAt(i)) == (c2 = s2.charAt(i)); i++); // Check end of string if (c1 == c2) return(len1 - len2); // Check digit in first string if (Character.isDigit(c1)) { // Check digit only in first string if (!Character.isDigit(c2)) return(1); // Scan all integer digits int x1, x2; for (x1 = i + 1; (x1 < len1) && Character.isDigit(s1.charAt(x1)); x1++); for (x2 = i + 1; (x2 < len2) && Character.isDigit(s2.charAt(x2)); x2++); // Longer integer wins, first digit otherwise return(x2 == x1 ? c1 - c2 : x1 - x2); } // Check digit only in second string if (Character.isDigit(c2)) return(-1); // No digits return(c1 - c2); } A: I came up with a quite simple implementation in Java using regular expressions: public static Comparator<String> naturalOrdering() { final Pattern compile = Pattern.compile("(\\d+)|(\\D+)"); return (s1, s2) -> { final Matcher matcher1 = compile.matcher(s1); final Matcher matcher2 = compile.matcher(s2); while (true) { final boolean found1 = matcher1.find(); final boolean found2 = matcher2.find(); if (!found1 || !found2) { return Boolean.compare(found1, found2); } else if (!matcher1.group().equals(matcher2.group())) { if (matcher1.group(1) == null || matcher2.group(1) == null) { return matcher1.group().compareTo(matcher2.group()); } else { return Integer.valueOf(matcher1.group(1)).compareTo(Integer.valueOf(matcher2.group(1))); } } } }; } Here is how it works: final List<String> strings = Arrays.asList("x15", "xa", "y16", "x2a", "y11", "z", "z5", "x2b", "z"); strings.sort(naturalOrdering()); System.out.println(strings); [x2a, x2b, x15, xa, y11, y16, z, z, z5] A: I realize you're in java, but you can take a look at how StrCmpLogicalW works. It's what Explorer uses to sort filenames in Windows. You can look at the WINE implementation here. A: Split the string into runs of letters and numbers, so "foo 12 bar" becomes the list ("foo", 12, "bar"), then use the list as the sort key. This way the numbers will be ordered in numerical order, not alphabetical. A: Here is the solution with the following advantages over Alphanum Algorithm: * *3.25x times faster (tested on the data from 'Epilogue' chapter of Alphanum description) *Does not consume extra memory (no string splitting, no numbers parsing) *Processes leading zeros correctly (e.g. "0001" equals "1", "01234" is less than "4567") public class NumberAwareComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { int len1 = s1.length(); int len2 = s2.length(); int i1 = 0; int i2 = 0; while (true) { // handle the case when one string is longer than another if (i1 == len1) return i2 == len2 ? 0 : -1; if (i2 == len2) return 1; char ch1 = s1.charAt(i1); char ch2 = s2.charAt(i2); if (Character.isDigit(ch1) && Character.isDigit(ch2)) { // skip leading zeros while (i1 < len1 && s1.charAt(i1) == '0') i1++; while (i2 < len2 && s2.charAt(i2) == '0') i2++; // find the ends of the numbers int end1 = i1; int end2 = i2; while (end1 < len1 && Character.isDigit(s1.charAt(end1))) end1++; while (end2 < len2 && Character.isDigit(s2.charAt(end2))) end2++; int diglen1 = end1 - i1; int diglen2 = end2 - i2; // if the lengths are different, then the longer number is bigger if (diglen1 != diglen2) return diglen1 - diglen2; // compare numbers digit by digit while (i1 < end1) { if (s1.charAt(i1) != s2.charAt(i2)) return s1.charAt(i1) - s2.charAt(i2); i1++; i2++; } } else { // plain characters comparison if (ch1 != ch2) return ch1 - ch2; i1++; i2++; } } } } A: Instead of reinventing the wheel, I'd suggest to use a locale-aware Unicode-compliant string comparator that has built-in number sorting from the ICU4J library. import com.ibm.icu.text.Collator; import com.ibm.icu.text.RuleBasedCollator; import java.util.Arrays; import java.util.List; import java.util.Locale; public class CollatorExample { public static void main(String[] args) { // Make sure to choose correct locale: in Turkish uppercase of "i" is "İ", not "I" RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(Locale.US); collator.setNumericCollation(true); // Place "10" after "2" collator.setStrength(Collator.PRIMARY); // Case-insensitive List<String> strings = Arrays.asList("10", "20", "A20", "2", "t1ab", "01", "T010T01", "t1aB", "_2", "001", "_200", "1", "A 02", "t1Ab", "a2", "_1", "t1A", "_01", "100", "02", "T0010T01", "t1AB", "10", "A01", "010", "t1a" ); strings.sort(collator); System.out.println(String.join(", ", strings)); // Output: _1, _01, _2, _200, 01, 001, 1, // 2, 02, 10, 10, 010, 20, 100, A 02, A01, // a2, A20, t1A, t1a, t1ab, t1aB, t1Ab, t1AB, // T010T01, T0010T01 } } A: The Alphanum algrothim is nice, but it did not match requirements for a project I'm working on. I need to be able to sort negative numbers and decimals correctly. Here is the implementation I came up. Any feedback would be much appreciated. public class StringAsNumberComparator implements Comparator<String> { public static final Pattern NUMBER_PATTERN = Pattern.compile("(\\-?\\d+\\.\\d+)|(\\-?\\.\\d+)|(\\-?\\d+)"); /** * Splits strings into parts sorting each instance of a number as a number if there is * a matching number in the other String. * * For example A1B, A2B, A11B, A11B1, A11B2, A11B11 will be sorted in that order instead * of alphabetically which will sort A1B and A11B together. */ public int compare(String str1, String str2) { if(str1 == str2) return 0; else if(str1 == null) return 1; else if(str2 == null) return -1; List<String> split1 = split(str1); List<String> split2 = split(str2); int diff = 0; for(int i = 0; diff == 0 && i < split1.size() && i < split2.size(); i++) { String token1 = split1.get(i); String token2 = split2.get(i); if((NUMBER_PATTERN.matcher(token1).matches() && NUMBER_PATTERN.matcher(token2).matches()) { diff = (int) Math.signum(Double.parseDouble(token1) - Double.parseDouble(token2)); } else { diff = token1.compareToIgnoreCase(token2); } } if(diff != 0) { return diff; } else { return split1.size() - split2.size(); } } /** * Splits a string into strings and number tokens. */ private List<String> split(String s) { List<String> list = new ArrayList<String>(); try (Scanner scanner = new Scanner(s)) { int index = 0; String num = null; while ((num = scanner.findInLine(NUMBER_PATTERN)) != null) { int indexOfNumber = s.indexOf(num, index); if (indexOfNumber > index) { list.add(s.substring(index, indexOfNumber)); } list.add(num); index = indexOfNumber + num.length(); } if (index < s.length()) { list.add(s.substring(index)); } } return list; } } PS. I wanted to use the java.lang.String.split() method and use "lookahead/lookbehind" to keep the tokens, but I could not get it to work with the regular expression I was using. A: Interesting little challenge, I enjoyed solving it. Here is my take at the problem: String[] strs = { "eee 5 ddd jpeg2001 eee", "eee 123 ddd jpeg2000 eee", "ddd", "aaa 5 yy 6", "ccc 555", "bbb 3 ccc", "bbb 9 a", "", "eee 4 ddd jpeg2001 eee", "ccc 11", "bbb 12 ccc", "aaa 5 yy 22", "aaa", "eee 3 ddd jpeg2000 eee", "ccc 5", }; Pattern splitter = Pattern.compile("(\\d+|\\D+)"); public class InternalNumberComparator implements Comparator { public int compare(Object o1, Object o2) { // I deliberately use the Java 1.4 syntax, // all this can be improved with 1.5's generics String s1 = (String)o1, s2 = (String)o2; // We split each string as runs of number/non-number strings ArrayList sa1 = split(s1); ArrayList sa2 = split(s2); // Nothing or different structure if (sa1.size() == 0 || sa1.size() != sa2.size()) { // Just compare the original strings return s1.compareTo(s2); } int i = 0; String si1 = ""; String si2 = ""; // Compare beginning of string for (; i < sa1.size(); i++) { si1 = (String)sa1.get(i); si2 = (String)sa2.get(i); if (!si1.equals(si2)) break; // Until we find a difference } // No difference found? if (i == sa1.size()) return 0; // Same strings! // Try to convert the different run of characters to number int val1, val2; try { val1 = Integer.parseInt(si1); val2 = Integer.parseInt(si2); } catch (NumberFormatException e) { return s1.compareTo(s2); // Strings differ on a non-number } // Compare remainder of string for (i++; i < sa1.size(); i++) { si1 = (String)sa1.get(i); si2 = (String)sa2.get(i); if (!si1.equals(si2)) { return s1.compareTo(s2); // Strings differ } } // Here, the strings differ only on a number return val1 < val2 ? -1 : 1; } ArrayList split(String s) { ArrayList r = new ArrayList(); Matcher matcher = splitter.matcher(s); while (matcher.find()) { String m = matcher.group(1); r.add(m); } return r; } } Arrays.sort(strs, new InternalNumberComparator()); This algorithm need much more testing, but it seems to behave rather nicely. [EDIT] I added some more comments to be clearer. I see there are much more answers than when I started to code this... But I hope I provided a good starting base and/or some ideas. A: The Alphanum Algorithm From the website "People sort strings with numbers differently than software. Most sorting algorithms compare ASCII values, which produces an ordering that is inconsistent with human logic. Here's how to fix it." Edit: Here's a link to the Java Comparator Implementation from that site. A: interesting problem, and here my proposed solution: import java.util.Collections; import java.util.Vector; public class CompareToken implements Comparable<CompareToken> { int valN; String valS; String repr; public String toString() { return repr; } public CompareToken(String s) { int l = 0; char data[] = new char[s.length()]; repr = s; valN = 0; for (char c : s.toCharArray()) { if(Character.isDigit(c)) valN = valN * 10 + (c - '0'); else data[l++] = c; } valS = new String(data, 0, l); } public int compareTo(CompareToken b) { int r = valS.compareTo(b.valS); if (r != 0) return r; return valN - b.valN; } public static void main(String [] args) { String [] strings = { "aaa", "bbb3ccc", "bbb12ccc", "ccc 11", "ddd", "eee3dddjpeg2000eee", "eee12dddjpeg2000eee" }; Vector<CompareToken> data = new Vector<CompareToken>(); for(String s : strings) data.add(new CompareToken(s)); Collections.shuffle(data); Collections.sort(data); for (CompareToken c : data) System.out.println ("" + c); } } A: Prior to discovering this thread, I implemented a similar solution in javascript. Perhaps my strategy will find you well, despite different syntax. Similar to above, I parse the two strings being compared, and split them both into arrays, dividing the strings at continuous numbers. ... var regex = /(\d+)/g, str1Components = str1.split(regex), str2Components = str2.split(regex), ... I.e., 'hello22goodbye 33' => ['hello', 22, 'goodbye ', 33]; Thus, you can walk through the arrays' elements in pairs between string1 and string2, do some type coercion (such as, is this element really a number?), and compare as you walk. Working example here: http://jsfiddle.net/F46s6/3/ Note, I currently only support integer types, though handling decimal values wouldn't be too hard of a modification. A: My 2 cents.Is working well for me. I am mainly using it for filenames. private final boolean isDigit(char ch) { return ch >= 48 && ch <= 57; } private int compareNumericalString(String s1,String s2){ int s1Counter=0; int s2Counter=0; while(true){ if(s1Counter>=s1.length()){ break; } if(s2Counter>=s2.length()){ break; } char currentChar1=s1.charAt(s1Counter++); char currentChar2=s2.charAt(s2Counter++); if(isDigit(currentChar1) &&isDigit(currentChar2)){ String digitString1=""+currentChar1; String digitString2=""+currentChar2; while(true){ if(s1Counter>=s1.length()){ break; } if(s2Counter>=s2.length()){ break; } if(isDigit(s1.charAt(s1Counter))){ digitString1+=s1.charAt(s1Counter); s1Counter++; } if(isDigit(s2.charAt(s2Counter))){ digitString2+=s2.charAt(s2Counter); s2Counter++; } if((!isDigit(s1.charAt(s1Counter))) && (!isDigit(s2.charAt(s2Counter)))){ currentChar1=s1.charAt(s1Counter); currentChar2=s2.charAt(s2Counter); break; } } if(!digitString1.equals(digitString2)){ return Integer.parseInt(digitString1)-Integer.parseInt(digitString2); } } if(currentChar1!=currentChar2){ return currentChar1-currentChar2; } } return s1.compareTo(s2); } A: I created a project to compare the different implementations. It is far from complete, but it is a starting point. A: Adding on to the answer made by @stanislav. A few problems I faced while using the answer provided was: * *Capital and small letters are separated by the characters between their ASCII codes. This breaks the flow when the strings being sorted have _ or other characters which are between small letters and capital letters in ASCII. *If two strings are the same except for the leading zeroes count being different, the function returns 0 which will make the sort depend on the original positions of the string in the list. These two issues have been fixed in the new code. And I made a few function instead of a few repetitive set of code. The differentCaseCompared variable keeps track of whether if two strings are the same except for the cases being different. If so the value of the first different case characters subtracted is returned. This is done to avoid the issue of having two strings differing by case returned as 0. public class NaturalSortingComparator implements Comparator<String> { @Override public int compare(String string1, String string2) { int lengthOfString1 = string1.length(); int lengthOfString2 = string2.length(); int iteratorOfString1 = 0; int iteratorOfString2 = 0; int differentCaseCompared = 0; while (true) { if (iteratorOfString1 == lengthOfString1) { if (iteratorOfString2 == lengthOfString2) { if (lengthOfString1 == lengthOfString2) { // If both strings are the same except for the different cases, the differentCaseCompared will be returned return differentCaseCompared; } //If the characters are the same at the point, returns the difference between length of the strings else { return lengthOfString1 - lengthOfString2; } } //If String2 is bigger than String1 else return -1; } //Check if String1 is bigger than string2 if (iteratorOfString2 == lengthOfString2) { return 1; } char ch1 = string1.charAt(iteratorOfString1); char ch2 = string2.charAt(iteratorOfString2); if (Character.isDigit(ch1) && Character.isDigit(ch2)) { // skip leading zeros iteratorOfString1 = skipLeadingZeroes(string1, lengthOfString1, iteratorOfString1); iteratorOfString2 = skipLeadingZeroes(string2, lengthOfString2, iteratorOfString2); // find the ends of the numbers int endPositionOfNumbersInString1 = findEndPositionOfNumber(string1, lengthOfString1, iteratorOfString1); int endPositionOfNumbersInString2 = findEndPositionOfNumber(string2, lengthOfString2, iteratorOfString2); int lengthOfDigitsInString1 = endPositionOfNumbersInString1 - iteratorOfString1; int lengthOfDigitsInString2 = endPositionOfNumbersInString2 - iteratorOfString2; // if the lengths are different, then the longer number is bigger if (lengthOfDigitsInString1 != lengthOfDigitsInString2) return lengthOfDigitsInString1 - lengthOfDigitsInString2; // compare numbers digit by digit while (iteratorOfString1 < endPositionOfNumbersInString1) { if (string1.charAt(iteratorOfString1) != string2.charAt(iteratorOfString2)) return string1.charAt(iteratorOfString1) - string2.charAt(iteratorOfString2); iteratorOfString1++; iteratorOfString2++; } } else { // plain characters comparison if (ch1 != ch2) { if (!ignoreCharacterCaseEquals(ch1, ch2)) return Character.toLowerCase(ch1) - Character.toLowerCase(ch2); // Set a differentCaseCompared if the characters being compared are different case. // Should be done only once, hence the check with 0 if (differentCaseCompared == 0) { differentCaseCompared = ch1 - ch2; } } iteratorOfString1++; iteratorOfString2++; } } } private boolean ignoreCharacterCaseEquals(char character1, char character2) { return Character.toLowerCase(character1) == Character.toLowerCase(character2); } private int findEndPositionOfNumber(String string, int lengthOfString, int end) { while (end < lengthOfString && Character.isDigit(string.charAt(end))) end++; return end; } private int skipLeadingZeroes(String string, int lengthOfString, int iteratorOfString) { while (iteratorOfString < lengthOfString && string.charAt(iteratorOfString) == '0') iteratorOfString++; return iteratorOfString; } } The following is a unit test I used. public class NaturalSortingComparatorTest { private int NUMBER_OF_TEST_CASES = 100000; @Test public void compare() { NaturalSortingComparator naturalSortingComparator = new NaturalSortingComparator(); List<String> expectedStringList = getCorrectStringList(); List<String> testListOfStrings = createTestListOfStrings(); runTestCases(expectedStringList, testListOfStrings, NUMBER_OF_TEST_CASES, naturalSortingComparator); } private void runTestCases(List<String> expectedStringList, List<String> testListOfStrings, int numberOfTestCases, Comparator<String> comparator) { for (int testCase = 0; testCase < numberOfTestCases; testCase++) { Collections.shuffle(testListOfStrings); testListOfStrings.sort(comparator); Assert.assertEquals(expectedStringList, testListOfStrings); } } private List<String> getCorrectStringList() { return Arrays.asList( "1", "01", "001", "2", "02", "10", "10", "010", "20", "100", "_1", "_01", "_2", "_200", "A 02", "A01", "a2", "A20", "t1A", "t1a", "t1AB", "t1Ab", "t1aB", "t1ab", "T010T01", "T0010T01"); } private List<String> createTestListOfStrings() { return Arrays.asList( "10", "20", "A20", "2", "t1ab", "01", "T010T01", "t1aB", "_2", "001", "_200", "1", "A 02", "t1Ab", "a2", "_1", "t1A", "_01", "100", "02", "T0010T01", "t1AB", "10", "A01", "010", "t1a"); } } Suggestions welcome! I am not sure whether adding the functions changes anything other than the readability part of things. P.S: Sorry to add another answer to this question. But I don't have enough reps to comment on the answer which I modified for my use. A: modification of this answer * *case insensitive order (1000a is less than 1000X) *nulls handling implementation: import static java.lang.Math.pow; import java.util.Comparator; public class AlphanumComparator implements Comparator<String> { public static final AlphanumComparator ALPHANUM_COMPARATOR = new AlphanumComparator(); private static char[] upperCaseCache = new char[(int) pow(2, 16)]; private boolean nullIsLess; public AlphanumComparator() { } public AlphanumComparator(boolean nullIsLess) { this.nullIsLess = nullIsLess; } @Override public int compare(String s1, String s2) { if (s1 == s2) return 0; if (s1 == null) return nullIsLess ? -1 : 1; if (s2 == null) return nullIsLess ? 1 : -1; int i1 = 0; int i2 = 0; int len1 = s1.length(); int len2 = s2.length(); while (true) { // handle the case when one string is longer than another if (i1 == len1) return i2 == len2 ? 0 : -1; if (i2 == len2) return 1; char ch1 = s1.charAt(i1); char ch2 = s2.charAt(i2); if (isDigit(ch1) && isDigit(ch2)) { // skip leading zeros while (i1 < len1 && s1.charAt(i1) == '0') i1++; while (i2 < len2 && s2.charAt(i2) == '0') i2++; // find the ends of the numbers int end1 = i1; int end2 = i2; while (end1 < len1 && isDigit(s1.charAt(end1))) end1++; while (end2 != len2 && isDigit(s2.charAt(end2))) end2++; // if the lengths are different, then the longer number is bigger int diglen1 = end1 - i1; int diglen2 = end2 - i2; if (diglen1 != diglen2) return diglen1 - diglen2; // compare numbers digit by digit while (i1 < end1) { ch1 = s1.charAt(i1); ch2 = s2.charAt(i2); if (ch1 != ch2) return ch1 - ch2; i1++; i2++; } } else { ch1 = toUpperCase(ch1); ch2 = toUpperCase(ch2); if (ch1 != ch2) return ch1 - ch2; i1++; i2++; } } } private boolean isDigit(char ch) { return ch >= 48 && ch <= 57; } private char toUpperCase(char ch) { char cached = upperCaseCache[ch]; if (cached == 0) { cached = Character.toUpperCase(ch); upperCaseCache[ch] = cached; } return cached; } } A: I think you'll have to do the comparison on a character-by-character fashion. Grab a character, if it's a number character, keep grabbing, then reassemble to characters into a single number string and convert it into an int. Repeat on the other string, and only then do the comparison. A: Short answer: based on the context, I can't tell whether this is just some quick-and-dirty code for personal use, or a key part of Goldman Sachs' latest internal accounting software, so I'll open by saying: eww. That's a rather funky sorting algorithm; try to use something a bit less "twisty" if you can. Long answer: The two issues that immediately come to mind in your case are performance, and correctness. Informally, make sure it's fast, and make sure your algorithm is a total ordering. (Of course, if you're not sorting more than about 100 items, you can probably disregard this paragraph.) Performance matters, as the speed of the comparator will be the largest factor in the speed of your sort (assuming the sort algorithm is "ideal" to the typical list). In your case, the comparator's speed will depend mainly on the size of the string. The strings seem to be fairly short, so they probably won't dominate as much as the size of your list. Turning each string into a string-number-string tuple and then sorting this list of tuples, as suggested in another answer, will fail in some of your cases, since you apparently will have strings with multiple numbers appearing. The other problem is correctness. Specifically, if the algorithm you described will ever permit A > B > ... > A, then your sort will be non-deterministic. In your case, I fear that it might, though I can't prove it. Consider some parsing cases such as: aa 0 aa aa 23aa aa 2a3aa aa 113aa aa 113 aa a 1-2 a a 13 a a 12 a a 2-3 a a 21 a a 2.3 a A: Although the question asked a java solution, for anyone who wants a scala solution: object Alphanum { private[this] val regex = "((?<=[0-9])(?=[^0-9]))|((?<=[^0-9])(?=[0-9]))" private[this] val alphaNum: Ordering[String] = Ordering.fromLessThan((ss1: String, ss2: String) => (ss1, ss2) match { case (sss1, sss2) if sss1.matches("[0-9]+") && sss2.matches("[0-9]+") => sss1.toLong < sss2.toLong case (sss1, sss2) => sss1 < sss2 }) def ordering: Ordering[String] = Ordering.fromLessThan((s1: String, s2: String) => { import Ordering.Implicits.infixOrderingOps implicit val ord: Ordering[List[String]] = Ordering.Implicits.seqDerivedOrdering(alphaNum) s1.split(regex).toList < s2.split(regex).toList }) } A: My problem was that I have lists consisting of a combination of alpha numeric strings (eg C22, C3, C5 etc), alpha strings (eg A, H, R etc) and just digits (eg 99, 45 etc) that need sorting in the order A, C3, C5, C22, H, R, 45, 99. I also have duplicates that need removing so I only get a single entry. I'm also not just working with Strings, I'm ordering an Object and using a specific field within the Object to get the correct order. A solution that seems to work for me is : SortedSet<Code> codeSet; codeSet = new TreeSet<Code>(new Comparator<Code>() { private boolean isThereAnyNumber(String a, String b) { return isNumber(a) || isNumber(b); } private boolean isNumber(String s) { return s.matches("[-+]?\\d*\\.?\\d+"); } private String extractChars(String s) { String chars = s.replaceAll("\\d", ""); return chars; } private int extractInt(String s) { String num = s.replaceAll("\\D", ""); return num.isEmpty() ? 0 : Integer.parseInt(num); } private int compareStrings(String o1, String o2) { if (!extractChars(o1).equals(extractChars(o2))) { return o1.compareTo(o2); } else return extractInt(o1) - extractInt(o2); } @Override public int compare(Code a, Code b) { return isThereAnyNumber(a.getPrimaryCode(), b.getPrimaryCode()) ? isNumber(a.getPrimaryCode()) ? 1 : -1 : compareStrings(a.getPrimaryCode(), b.getPrimaryCode()); } }); It 'borrows' some code that I found here on Stackoverflow plus some tweaks of my own to get it working just how I needed it too. Due to trying to order Objects, needing a comparator as well as duplicate removal, one negative fudge I had to employ was I first have to write my Objects to a TreeMap before writing them to a Treeset. It may impact performance a little but given that the lists will be a max of about 80 Codes, it shouldn't be a problem. A: I had a similar problem where my strings had space-separated segments inside. I solved it in this way: public class StringWithNumberComparator implements Comparator<MyClass> { @Override public int compare(MyClass o1, MyClass o2) { if (o1.getStringToCompare().equals(o2.getStringToCompare())) { return 0; } String[] first = o1.getStringToCompare().split(" "); String[] second = o2.getStringToCompare().split(" "); if (first.length == second.length) { for (int i = 0; i < first.length; i++) { int segmentCompare = StringUtils.compare(first[i], second[i]); if (StringUtils.isNumeric(first[i]) && StringUtils.isNumeric(second[i])) { segmentCompare = NumberUtils.compare(Integer.valueOf(first[i]), Integer.valueOf(second[i])); if (0 != segmentCompare) { // return only if uneven numbers in case there are more segments to be checked return segmentCompare; } } if (0 != segmentCompare) { return segmentCompare; } } } else { return StringUtils.compare(o1.getDenominazione(), o2.getDenominazione()); } return 0; } As you can see I have used Apaches StringUtils.compare() and NumberUtils.compere() as a standard help. A: In your given example, the numbers you want to compare have spaces around them while the other numbers do not, so why would a regular expression not work? bbb 12 ccc vs. eee 12 ddd jpeg2000 eee A: If you're writing a comparator class, you should implement your own compare method that will compare two strings character by character. This compare method should check if you're dealing with alphabetic characters, numeric characters, or mixed types (including spaces). You'll have to define how you want a mixed type to act, whether numbers come before alphabetic characters or after, and where spaces fit in etc. A: On Linux glibc provides strverscmp(), it's also available from gnulib for portability. However truly "human" sorting has lots of other quirks like "The Beatles" being sorted as "Beatles, The". There is no simple solution to this generic problem.
{ "language": "en", "url": "https://stackoverflow.com/questions/104599", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "86" }
Q: Response.Redirect to new window I want to do a Response.Redirect("MyPage.aspx") but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how? A: This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page? A: popup method will give a secure question to visitor.. here is my simple solution: and working everyhere. <script type="text/javascript"> function targetMeBlank() { document.forms[0].target = "_blank"; } </script> <asp:linkbutton runat="server" ID="lnkbtn1" Text="target me to blank dude" OnClick="lnkbtn1_Click" OnClientClick="targetMeBlank();"/> A: You can use this as extension method public static class ResponseHelper { public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures) { if ((String.IsNullOrEmpty(target) || target.Equals("_self", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures)) { response.Redirect(url); } else { Page page = (Page)HttpContext.Current.Handler; if (page == null) { throw new InvalidOperationException("Cannot redirect to new window outside Page context."); } url = page.ResolveClientUrl(url); string script; if (!String.IsNullOrEmpty(windowFeatures)) { script = @"window.open(""{0}"", ""{1}"", ""{2}"");"; } else { script = @"window.open(""{0}"", ""{1}"");"; } script = String.Format(script, url, target, windowFeatures); ScriptManager.RegisterStartupScript(page, typeof(Page), "Redirect", script, true); } } } With this you get nice override on the actual Response object Response.Redirect(redirectURL, "_blank", "menubar=0,scrollbars=1,width=780,height=900,top=10"); A: <asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/> protected void btnNewEntry_Click(object sender, EventArgs e) { Response.Redirect("New.aspx"); } Source: http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/ A: If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button: protected void MyButton_OnPreRender(object sender, EventArgs e) { string URL = "~/MyPage.aspx"; URL = Page.ResolveClientUrl(URL); MyButton.OnClientClick = "window.open('" + URL + "'); return false;"; } A: You can also use the following code to open new page in new tab. <asp:Button ID="Button1" runat="server" Text="Go" OnClientClick="window.open('yourPage.aspx');return false;" onclick="Button3_Click" /> And just call Response.Redirect("yourPage.aspx"); behind button event. A: I always use this code... Use this code String clientScriptName = "ButtonClickScript"; Type clientScriptType = this.GetType (); // Get a ClientScriptManager reference from the Page class. ClientScriptManager clientScript = Page.ClientScript; // Check to see if the client script is already registered. if (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName)) { StringBuilder sb = new StringBuilder (); sb.Append ("<script type='text/javascript'>"); sb.Append ("window.open(' " + url + "')"); //URL = where you want to redirect. sb.Append ("</script>"); clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ()); } A: Contruct your url via click event handler: string strUrl = "/some/url/path" + myvar; Then: ScriptManager.RegisterStartupScript(Page, Page.GetType(), "popup", "window.open('" + strUrl + "','_blank')", true); A: Because Response.Redirect is initiated on the server you can't do it using that. If you can write directly to the Response stream you could try something like: response.write("<script>"); response.write("window.open('page.html','_blank')"); response.write("</script>"); A: The fixform trick is neat, but: * *You may not have access to the code of what loads in the new window. *Even if you do, you are depending on the fact that it always loads, error free. *And you are depending on the fact that the user won't click another button before the other page gets a chance to load and run fixform. I would suggest doing this instead: OnClientClick="aspnetForm.target ='_blank';setTimeout('fixform()', 500);" And set up fixform on the same page, looking like this: function fixform() { document.getElementById("aspnetForm").target = ''; } A: I just found the answer and it works :) You need to add the following to your server side link/button: OnClientClick="aspnetForm.target ='_blank';" My entire button code looks something like: <asp:LinkButton ID="myButton" runat="server" Text="Click Me!" OnClick="myButton_Click" OnClientClick="aspnetForm.target ='_blank';"/> In the server side OnClick I do a Response.Redirect("MyPage.aspx"); and the page is opened in a new window. The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window. <script type="text/javascript"> function fixform() { if (opener.document.getElementById("aspnetForm").target != "_blank") return; opener.document.getElementById("aspnetForm").target = ""; opener.document.getElementById("aspnetForm").action = opener.location.href; } </script> and <body onload="fixform()"> A: You can also use in code behind like this way ClientScript.RegisterStartupScript(this.Page.GetType(), "", "window.open('page.aspx','Graph','height=400,width=500');", true); A: Here's a jQuery version based on the answer by @takrl and @tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic: <asp:Button ID="btnSubmit" OnClientClick="openNewWin();" Text="Submit" OnClick="btn_OnClick" runat="server"/> Then in your js file referenced on the SAME page: function openNewWin () { $('form').attr('target','_blank'); setTimeout('resetFormTarget()', 500); } function resetFormTarget(){ $('form').attr('target',''); } A: I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it: <asp:HyperLink CssClass="hlk11" ID="hlkLink" runat="server" Text='<%# Eval("LinkText") %>' Visible='<%# !(bool)Eval("IsDocument") %>' Target="_blank" NavigateUrl='<%# Eval("WebAddress") %>'></asp:HyperLink> A: You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load. A: you can open new window from asp.net code behind using ajax like I did here http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/ protected void Page_Load(object sender, EventArgs e) { Calendar1.SelectionChanged += CalendarSelectionChanged; } private void CalendarSelectionChanged(object sender, EventArgs e) { DateTime selectedDate = ((Calendar) sender).SelectedDate; string url = "HistoryRates.aspx?date=" + HttpUtility.UrlEncode(selectedDate.ToShortDateString()); ScriptManager.RegisterClientScriptBlock(this, GetType(), "rates" + selectedDate, "openWindow('" + url + "');", true); } A: None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind. Dim URL As String = "http://www.google/?Search=" + txtExample.Text.ToString URL = Page.ResolveClientUrl(URL) btnSearch.OnClientClick = "window.open('" + URL + "'); return false;" I was having to modify someone else's response.redirect code to open in a new browser. A: I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes. $(function () { //--- setup click event for elements that use a response.redirect in code behind but should open in a new window $(".new-window").on("click", function () { //--- change the form's target $("#aspnetForm").prop("target", "_blank"); //--- change the target back after the window has opened setTimeout(function () { $("#aspnetForm").prop("target", ""); }, 1); }); }); To use, add the class "new-window" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function. A: I did this by putting target="_blank" in the linkbutton <asp:LinkButton ID="btn" runat="server" CausesValidation="false" Text="Print" Visible="false" target="_blank" /> then in the codebehind pageload just set the href attribute: btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId) A: HTML <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" OnClientClick = "SetTarget();" /> Javascript: function SetTarget() { document.forms[0].target = "_blank";} AND codebehind: Response.Redirect(URL);
{ "language": "en", "url": "https://stackoverflow.com/questions/104601", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "121" }
Q: Accessing a Collection Through Reflection Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection. At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items? A: Just get the value of the property and then cast it into an IEnumerable. Here is some (untested) code to give you an idea: ClassWithListProperty obj = new ClassWithListProperty(); obj.List.Add(1); obj.List.Add(2); obj.List.Add(3); Type type = obj.GetType(); PropertyInfo listProperty = type.GetProperty("List", BindingFlags.Public); IEnumerable listObject = (IEnumerable) listProperty.GetValue(obj, null); foreach (int i in listObject) Console.Write(i); // should print out 123 A: I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that. if (item is IEnumerable) { foreach (object o in (item as IEnumerable)) { } } else { // reflect over item } A: I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. string for instance is also IEnumerable and will iterate over the characters. Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well since ICollection is also IEnumerable). public bool isCollection(object o) { return typeof(ICollection).IsAssignableFrom(o.GetType()) || typeof(ICollection<>).IsAssignableFrom(o.GetType()); } A: Just for information may be it will be of someone's help... I had a class with nested classes and collection of some other classes. I wanted to save the property values of the class as well nested classes and collection of classes. My code is as follows: public void LogObject(object obj, int indent) { if (obj == null) return; string indentString = new string(' ', indent); Type objType = obj.GetType(); PropertyInfo[] properties = objType.GetProperties(); foreach (PropertyInfo property in properties) { Type tColl = typeof(ICollection<>); Type t = property.PropertyType; string name = property.Name; object propValue = property.GetValue(obj, null); //check for nested classes as properties if (property.PropertyType.Assembly == objType.Assembly) { string _result = string.Format("{0}{1}:", indentString, property.Name); log.Info(_result); LogObject(propValue, indent + 2); } else { string _result = string.Format("{0}{1}: {2}", indentString, property.Name, propValue); log.Info(_result); } //check for collection if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) || t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)) { //var get = property.GetGetMethod(); IEnumerable listObject = (IEnumerable)property.GetValue(obj, null); if (listObject != null) { foreach (object o in listObject) { LogObject(o, indent + 2); } } } } } An called this function LogObject(obj, 0); However, I have some structs inside my classes and I need to figure out how to get their values. Moreoevr, I have some LIst. I need to get their value as well.... I will post if I update my code. A: The best you could probably do would be to check if the object implements certain collection interfaces - probably IEnumerable would be all that you need. Then it's just a matter of calling GetEnumerator() off of the object, and using IEnumerator.MoveNext() and IEnumerator.Current to work your way through the collection. This won't help you if the collection doesn't implement those interfaces, but if that's the case it's not really much of a collection, I suppose. A: When your using reflection you aren't necessarily using an instance of that object. You would have to create an instance of that type of be able to iterate through the object's properties. So if you are using reflection use the ConstructorInfo.Invoke() (?) method to create a new instance or point to an instance of the type. A: A rather straightforward approach would be to type cast the object as the collection and directly use that. A: I would look at the Type.FindInterfaces method. This can filter out the interfaces implemented by a given type. As in PropertyInfo.PropertyType.FindInterfaces(filterMethod, filterObjects). You can filter by IEnumerable and see if any results are returned. MSDN has a great example in the method documentation. A: If you're not using an instance of the object but rather a Type, you can use the following: // type is IEnumerable if (type.GetInterface("IEnumerable") != null) { }
{ "language": "en", "url": "https://stackoverflow.com/questions/104603", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "32" }
Q: Run MySQLDump without Locking Tables I want to copy a live production database into my local development database. Is there a way to do this without locking the production database? I'm currently using: mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1 But it's locking each table as it runs. A: Does the --lock-tables=false option work? According to the man page, if you are dumping InnoDB tables you can use the --single-transaction option: --lock-tables, -l Lock all tables before dumping them. The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables. For transactional tables such as InnoDB and BDB, --single-transaction is a much better option, because it does not need to lock the tables at all. For innodb DB: mysqldump --single-transaction=TRUE -u username -p DB A: mysqldump -uuid -ppwd --skip-opt --single-transaction --max_allowed_packet=1G -q db | mysql -u root --password=xxx -h localhost db A: The answer varies depending on what storage engine you're using. The ideal scenario is if you're using InnoDB. In that case you can use the --single-transaction flag, which will give you a coherent snapshot of the database at the time that the dump begins. A: --skip-add-locks helped for me A: This is ages too late, but good for anyone that is searching the topic. If you're not innoDB, and you're not worried about locking while you dump simply use the option: --lock-tables=false A: When using MySQL Workbench, at Data Export, click in Advanced Options and uncheck the "lock-tables" options. A: To dump large tables, you should combine the --single-transaction option with --quick. http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction A: For InnoDB tables use flag --single-transaction it dumps the consistent state of the database at the time when BEGIN was issued without blocking any applications MySQL DOCS http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction A: This is about as late compared to the guy who said he was late as he was to the original answer, but in my case (MySQL via WAMP on Windows 7), I had to use: --skip-lock-tables A: Honestly, I would setup replication for this, as if you don't lock tables you will get inconsistent data out of the dump. If the dump takes longer time, tables which were already dumped might have changed along with some table which is only about to be dumped. So either lock the tables or use replication. A: Due to https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables : Some options, such as --opt (which is enabled by default), automatically enable --lock-tables. If you want to override this, use --skip-lock-tables at the end of the option list. A: If you use the Percona XtraDB Cluster - I found that adding --skip-add-locks to the mysqldump command Allows the Percona XtraDB Cluster to run the dump file without an issue about LOCK TABLES commands in the dump file. A: Another late answer: If you are trying to make a hot copy of server database (in a linux environment) and the database engine of all tables is MyISAM you should use mysqlhotcopy. Acordingly to documentation: It uses FLUSH TABLES, LOCK TABLES, and cp or scp to make a database backup. It is a fast way to make a backup of the database or single tables, but it can be run only on the same machine where the database directories are located. mysqlhotcopy works only for backing up MyISAM and ARCHIVE tables. The LOCK TABLES time depends of the time the server can copy MySQL files (it doesn't make a dump). A: As none of these approaches worked for me, I simply did a: mysqldump [...] | grep -v "LOCK TABLE" | mysql [...] It will exclude both LOCK TABLE <x> and UNLOCK TABLES commands. Note: Hopefully your data doesn't contain that string in it!
{ "language": "en", "url": "https://stackoverflow.com/questions/104612", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "507" }
Q: What is a good tutorial/howto on .net / c# socket programming I'm porting old VB6 code that uses the Winsock control to C#. I haven't done any socket programming and I wonder if anyone has a good reference/tutorial/howto that I can use to start getting up to speed. I'm appealing to the hive mind while I proceed with my generally unproductive googling. I'm using UDP, not TCP at this time. A: The August 2005 MSDN Magazine had an article about System.Net.Sockets and WinSock: http://msdn.microsoft.com/en-us/magazine/cc300760.aspx A: * *I recommend the asynchronous model for most applications, especially if you want performance or applications that don't hang as soon there is a network problem. For this the MSDN articles on Socket.BeginConnect and Socket.BeginReceive are good places to start. *The following link is not .NET, but many of the recommendations still hold: http://tangentsoft.net/wskfaq/articles/lame-list.html A: MSDN is a good place to start Are you working on: a client (TCPClient) or a server (TCPListener) A: Just a heads up: I would recommend first working with TCP rather than UDP. UDP doesn't automatically redeliver lost packets like TCP so it will add another element to the equation that will probably just confuse you as you're just starting out. Building a socket client is relatively easy using the TCPClient class available in the .Net library. TCPListener is easy enough to use for a single client but if you're hoping to develop some server type application (IE: Handling multiple connections.) the real hurdle you'll have to overcome is understanding multithreading. Once you've played around with single connection sockets I suggest you read up on multithreading.
{ "language": "en", "url": "https://stackoverflow.com/questions/104617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: What does -> mean in F#? I've been trying to get into F# on and off for a while but I keep getting put off. Why? Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator ->. However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies. I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back. Can someone please, explain it or point to a truly accessible resource that explains it? A: First question - are you familiar with lambda expressions in C#? If so the -> in F# is the same as the => in C# (I think you read it 'goes to'). The -> operator can also be found in the context of pattern matching match x with | 1 -> dosomething | _ -> dosomethingelse I'm not sure if this is also a lambda expression, or something else, but I guess the 'goes to' still holds. Maybe what you are really referring to is the F# parser's 'cryptic' responses: > let add a b = a + b val add: int -> int -> int This means (as most of the examples explain) that add is a 'val' that takes two ints and returns an int. To me this was totally opaque to start with. I mean, how do I know that add isn't a val that takes one int and returns two ints? Well, the thing is that in a sense, it does. If I give add just one int, I get back an (int -> int): > let inc = add 1 val inc: int -> int This (currying) is one of the things that makes F# so sexy, for me. For helpful info on F#, I have found that blogs are FAR more useful that any of the official 'documentation': Here are some names to check out * *Dustin Campbell (that's diditwith.net, cited in another answer) *Don Symes ('the' man) *Tomasp.net (aka Tomas Petricek) *Andrew Kennedy (for units of measure) *Fsharp.it (famous for the Project Euler solutions) *http://lorgonblog.spaces.live.com/Blog (aka Brian) *Jomo Fisher A: '->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct. Inside a type, '->' describes function types as people have described above. For example let f : int -> int = ... says that 'f' is a function that takes an int and returns an int. Inside a lambda ("thing that starts with 'fun' keyword"), '->' is syntax that separates the arguments from the body. For example fun x y -> x + y + 1 is an expression that defines a two argument function with the given implementation. Inside a "match" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in match someList with | [] -> 0 | h::t -> 1 the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched. The difficulty in understanding may be rooted in the faulty assumption that '->' is "an operator" with a single meaning. An analogy might be "." in C#, if you have never seen any code before, and try to analyze the "." operator based on looking at "obj.Method" and "3.14" and "System.Collections", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear. A: (a -> b) means "function from a to b". In type annotation, it denotes a function type. For example, f : (int -> String) means that f refers to a function that takes an integer and returns a string. It is also used as a contstructor of such values, as in val f : (int -> int) = fun n -> n * 2 which creates a value which is a function from some number n to that same number multiplied by two. A: It basically means "maps to". Read it that way or as "is transformed into" or something like that. So, from the F# in 20 minutes tutorial, > List.map (fun x -> x % 2 = 0) [1 .. 10];; val it : bool list = [false; true; false; true; false; true; false; true; false; true] The code (fun i -> i % 2 = 0) defines an anonymous function, called a lambda expression, that has a parameter x and the function returns the result of "x % 2 = 0", which is whether or not x is even. A: From Microsoft: Function types are the types given to first-class function values and are written int -> int. They are similar to .NET delegate types, except they aren't given names. All F# function identifiers can be used as first-class function values, and anonymous function values can be created using the (fun ... -> ...) expression form. A: There are plenty of great answers here already, I just want to add to the conversation another way of thinking about it. ' -> ' means function. 'a -> 'b is a function that takes an 'a and returns a 'b ('a * 'b) -> ('c * 'd) is a function that takes a tuple of type ('a, 'b) and returns a tuple of ('c, 'd). Such as int/string returns float/char. Where it gets interesting is in the cascade case of 'a -> 'b -> 'c. This is a function that takes an 'a and returns a function ('b -> 'c), or a function that takes a 'b -> 'c. So if you write: let f x y z = () The type will be f : 'a -> 'b -> 'c -> unit, so if you only applied the first parameter, the result would be a curried function 'b -> 'c -> 'unit. A: In the context of defining a function, it is similar to => from the lambda expression in C# 3.0. F#: let f = fun x -> x*x C#: Func<int, int> f = x => x * x; The -> in F# is also used in pattern matching, where it means: if the expression matches the part between | and ->, then what comes after -> should be given back as the result: let isOne x = match x with | 1 -> true | _ -> false A: Many great answers to this questions, thanks people. I'd like to put here an editable answer that brings things together. For those familiar with C# understanding -> being the same as => lamba expression is a good first step. This usage is :- fun x y -> x + y + 1 Can be understood as the equivalent to:- (x, y) => x + y + 1; However its clear that -> has a more fundemental meaning which stems from concept that a function that takes two parameters such as the above can be reduced (is that the correct term?) to a series of functions only taking one parameter. Hence when the above is described in like this:- Int -> Int -> Int It really helped to know that -> is right associative hence the above can be considered:- Int -> (Int -> Int) Aha! We have a function that takes Int and returns (Int -> Int) (a curried function?). The explaination that -> can also appear as part of type definiton also helped. (Int -> Int) is the type of any of function which takes an Int and returns an Int. Also helpful is the -> appears in other syntax such as matching but there it doesn't have the same meaning? Is that correct? I'm not sure it is. I suspect it has the same meaning but I don't have the vocabulary to express that yet. Note the purpose of this answer is not to spawn further answers but to be collaboratively edited by you people to create a more definitive answer. Utlimately it would be good that all the uncertainies and fluf (such as this paragraph) be removed and better examples added. Lets try keep this answer as accessible to the uninitiated as possible. A: The nice thing about languages such as Haskell (it's very similar in F#, but I don't know the exact syntax -- this should help you understand ->, though) is that you can apply only parts of the argument, to create curried functions: adder n x y = n + x + y In other words: "give me three things, and I'll add them together". When you throw numbers at it, the compiler will infer the types of n x and y. Say you write adder 1 2 3 The type of 1, 2 and 3 is Int. Therefore: adder :: Int -> Int -> Int -> Int That is, give me three integers, and I will become an integer, eventually, or the same thing as saying: five :: Int five = 5 But, here's the nice part! Try this: add5 = adder 5 As you remember, adder takes an int, an int, an int, and gives you back an int. However, that is not the entire truth, as you'll see shortly. In fact, add5 will have this type: add5 :: Int -> Int -> Int It will be as if you have "peeled off" of the integers (the left-most), and glued it directly to the function. Looking closer at the function signature, we notice that the -> are right-associative, i.e.: addder :: Int -> (Int -> (Int -> Int)) This should make it quite clear: when you give adder the first integer, it'll evaluate to whatever's to the right of the first arrow, or: add5andtwomore :: Int -> (Int -> Int) add5andtwomore = adder 5 Now you can use add5andtwomore instead of "adder 5". This way, you can apply another integer to get (say) "add5and7andonemore": add5and7andonemore :: Int -> Int add5and7andonemore = adder 5 7 As you see, add5and7andonemore wants exactly another argument, and when you give it one, it will suddenly become an integer! > add5and7andonemore 9 => ((add5andtwomore) 7) 9 => ((adder 5) 7) 9) <=> adder 5 7 9 Substituting the parameters to adder (n x y) for (5 7 9), we get: > adder 5 7 9 = 5 + 7 + 9 => 5 + 7 + 9 => 21 In fact, plus is also just a function that takes an int and gives you back another int, so the above is really more like: > 5 + 7 + 9 => (+ 5 (+ 7 9)) => (+ 5 16) => 21 There you go!
{ "language": "en", "url": "https://stackoverflow.com/questions/104618", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "27" }
Q: Any good SQL Anywhere database schema comparison tools? Are there any good database schema comparison tools out there that support Sybase SQL Anywhere version 10? I've seen a litany of them for SQL Server, a few for MySQL and Oracle, but nothing that supports SQL Anywhere correctly. I tried using DB Solo, but it turned all my non-unique indexes into unique ones, and I didn't see any options to change that. A: If you are willing to download SQL Anywhere Version 11, and Compare It!, check out the comparison technique shown here: http://sqlanywhere.blogspot.com/2008/08/comparing-database-schemas.html You don't have to upgrade your SQL Anywhere Version 10 database. A: The new kid on the block is Qwerybuilder. It supports SQL Server, Sybase ASE, Sybase SQL Anywhere and Oracle. I've used it successfully with SQL Anywhere to track schema changes. A: Two I've come across that support SQL Anywhere: Upscene Database Workbench - http://www.upscene.com/products.dbw.sqlanywhere.php Aquafold - http://www.aquafold.com/index-sybaseany.html Each one appears has a schema comparison tool, however I have not used either to compare schemas. A: SQLDelta is awesome. It is for SQL Server. I've used it with SQL 2000 and 2005. It will compare stored procedures, tables, views, permissions, indexes, etc. It can also compare data between tables I believe. You can sync the changes or generate SQL Scripts for later use. I use it often to script out db changes in development to production. Ah...missed the Sybase remark. Not sure if SQLDelta can talk to it..but I'd probably give it a shot since Sybase is similar. A: Try erwin (CA AllFusion ERwin Data Modeler). It supports quite a lot of different DBs, including SQL Anywhere, and is quite good in reverse/forward engineering and schema comparison. However, you may find it a bit too complex to use for the comparison... A: I use SQL Data Compare from Red Gate along with SQL Compare the data compare allows you to Compare the contents of two databases and Automatically synchronize your data. SQL compare allows you to do the same but with the database tables. Nice GUI on each and very easy setup. they also work on a remote database. There not cheap but each has a 30 trail so you can get a feel if you like it or not. A: Sybase PowerDesigner can also Compare or Merge your Database Schema. It can also Load the Schema from various Databases by ODBC if you have Schema generation Scripts you can also load them into a Model. Its an expensive tool but great to document and develop you schema changes IMHO. A: Breck Carter's idea is a good one. For quick scans, I have an old product that is called DBDelta. I have it installed on an old Windows 2000 machine because the install I have will not work on an XP machine. It's a very small app that compares two SQL Anywhere databases across an ODBC connection. I've done some searches to try and find a later copy, but have not been able to. The developer was Charles Butcher. I think he supported it for a while and then stopped back in 2002 or so. I'll continue to look for a link. If I find something I will post it here. A: QweryBuilder 5.5.0 will allow you to compare all procedures, functions, views, tables and triggers in one shot. This release is scheduled for mid May, 2010. It hasn't been finalized yet but we are also looking at adding an option to turn the diff results into a script that can be executed on a target database.
{ "language": "en", "url": "https://stackoverflow.com/questions/104620", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: How can I disable the eclipse server startup timeout? By default when using a webapp server in Eclipse Web Tools, the server startup will fail after a timeout of 45 seconds. I can increase this timeout in the server instance properties, but I don't see a way to disable the timeout entirely (useful when debugging application startup). Is there a way to do this? A: In Eclipse Indigo, you can edit the default timeout by double-clicking on the server in the "servers" view and changing the timeout for start (see graphic). Save your changes, and you're good to go! A: Just another data point. If you see in your Console "Server startup in NNN ms", but the Server view still shows that it is trying to start, and then times out eventually killing the server, it might be that you have no plain HTTP connector configured. For example, if you have only a 2-way SSL connector configured in your Tomcat, it will start fine with the scripts in "TOMCAT_HOME/bin", but if you try to start it with the Eclipse Server view, it won't be able to open a connection to the HTTP port, and will terminate when it hits the timeout. (This was with a fairly old STS 2.1.0. Don't know if it's fixed in later versions) Joe A: Julie's answer gives you a long timeout, but not unlimited. You can move the server configuration file to the workspace, and then edit the xml file directly and set a limit greater than 1800. It's an ugly hack, but should work. A: Goto Window > Preferences > Server Set 'Server timeout delay' as Unlimited from drop-down menu. or Goto $WORKSPACE/.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.wst.server.core.prefs Add/update line machine-speed= -1 here, -1 ~ Unlimited A: * *On the EclipseIDE, double click on the server *Admin panel opens up, click on the "Timeouts" tab *Put larger value in the "Start (in seconds)", may be 1800 *Restart/Start the server If everything is okay, the server should start. A: yes this works, but the maximum limit is 1800, which is 30mins. Sometimes when rebuilding our entire database (on server initial start) this can go for longer than 30mins and causes problems. A: If you still has issue after changing timeout settings, then it's best to remove the server configuration in Eclipse (in Server view tab) and re-create it again. Server --> New Server. It worked for me. A: In eclipse 2019-09 (4.13.0) there is no UI capability to set an unlimited value. It must be between 1 and 84600 seconds (a day). But if you edit the .metadata/.plugins/org.eclipse.wst.server.core/servers.xml file in the workspace and set the server's start-timeout attribute to a large number of in my case -1 it will not abort the server startup until such time is reached. I had to restart eclipse for the change to be read. NOTE: using the UI to edit other values will coalesce your value to a value within the allowable range.
{ "language": "en", "url": "https://stackoverflow.com/questions/104640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "62" }
Q: What was the first version of MS Office to officially support Unicode? I am doing some research on Unicode for a white-paper I am writing. Does anyone remember the first version of MS Office on the Windows platform that was fully Unicode compliant? Not having much luck Googling this answer out of the net. A: office 97: "The universal character set provided by Unicode overcomes this problem. Office 97 was the first version of Office to support Unicode in all applications except Microsoft Access and Microsoft Outlook®. In Office 2000, Access and Microsoft Publisher gain Unicode support. Microsoft FrontPage® 2000 also supports Unicode on Web pages, but text typed into dialog boxes and other elements of the user interface are limited to characters defined by the user’s code page." - Microsoft url: http://office.microsoft.com/en-us/ork2000/HA011382921033.aspx A: Further to DanWoolston's answer, Microsoft Outlook 2003 was the first Outlook version to offer full Unicode support, so depending on your definition of 'Office' (seeing as there are so many different editions), your answer might be Microsoft Office 2003. URL: http://office.microsoft.com/en-us/ork2003/HA011402611033.aspx
{ "language": "en", "url": "https://stackoverflow.com/questions/104661", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Specific Client Detection based on headers. Firefox extension? I have a website in which I want to be able to detect a certain user based upon a permanent attribute of a specific user. My original plan was to use an ip address but those are difficult to maintain since they can change frequently. Cookie's and Sessions are almost out of question because they expire and tend to be difficult to manipulate. Basically what i want to be able to do is detect if the current client visiting the website is a special user without having to deal with logins / passwords. To use something more permanent. The user agent plugin could work but then, if i ever upgrade firefox or whatever i would have to go in and manually update the user agent string. I found this script: https://addons.mozilla.org/en-US/firefox/addon/6895 but it doesn't work for newest version of firefox 3. It would be a perfect solution because it sends special headers at specific websites. Short of writing my own extension does anyone have ideas of what to do? Do i need an extension? Should i try to write my own? A: You could generate a SSL client certificate, and have your users install it. From then on, their browser would identify them using their certificate. * *HOWTO: Securing A Website With Client SSL Certificates *SSL and Certificats (IIS 6.0)
{ "language": "en", "url": "https://stackoverflow.com/questions/104665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why should events in C# take (sender, EventArgs)? It's known that you should declare events that take as parameters (object sender, EventArgs args). Why? A: Because it's a good pattern for any callback mechanism, regardless of language. You want to know who sent the event (the sender) and data that is pertinent to the event (EventArgs). A: Using a single parameter, EventArgs, for the data passed by an event allows you to add data to your event in future versions of your software without breaking existing consumers. You simply add new members to an existing EventArgs-derived class, or create a derived class with the new members. Otherwise consistency and the principle of least surprise justify using EventArgs for passing data. As for sender, in some (but not all) cases it's useful to know what type sent the event. Using a type other than object for the sender argument is too restrictive: it would mean that other senders couldn't reuse the same event signature. A: This allows the consuming developer the ability to write a single event handler for multiple events, regardless of sender or event. Edit: Why would you need a different pattern? You can inherit EventArgs to provide any amount of data, and changing the pattern is only going to serve to confuse and frustrate any developer that is forced to consume this new pattern. A: It is a good pattern to use, that way what ever implements the event can find what was sending it. Also overriding the EventArgs and passing data through them is the best method. The EventArgs are a base class. If you look at various controls that call events, they have overridden EventArgs which gives you more information about the event. Even if you don't need the arguments to do the event, if you do not include them with the first run of the framework and want to add them later, you break all previous implementations, and have to re-write them. Plus if you a creating a framework and going to distribute that it becomes worse because everybody that uses your framework will need to refactor. A: Chris Anderson says in the Framework Design Guidelines book: [T]his is just about a pattern. By having event arguments packaged in a class you get better versioning semantics. By having a common pattern (sender, e) it is easily learned as the signature for all events. There are situations mostly involving interop that would require deviation from this pattern. A: Actually this is debatable whether or not this is the best practice way to do events. There is the school of thought that as events are intended to decouple two segments of code, the fact that the event handler gets the sender, and has to know what type to cast the sender into in order to do anything with it is an anti-pattern. A: It seemed that this was Microsoft's way to evolve the event model over time. It also seems that they are also allowing another way to do it with the "new" Action delegate and it's variations. A: Sometimes you would like to force all of your event consumers to use a particular event parameter, for example, a security event which passes a boolean parameter, true for good, false for bad. In this case you want your consumer to be painfully aware of the new parameter, i.e. you want your consumers to be coupled with that parameter. Take note, your consumers are still decoupled from your event firing class, but not from your event. I suspect that this scenario applies to a large number of cases and in those cases the value of EventArgs is greatly reduced. A: "Object sender" allows to reuse one method for multiple objects when the handler method is supposed to do something with the object that raised the event, for example 3 textbox can have one single handler that will reset the text of the firing textbox. EventArgs's main advantage is that it allows to refactor event information without the need to change signatures of all handlers in all projects that are subscribed to this kind of event. I can't think of a smarter way to deal with events. A: The EventArgs class alone is useless since it must be derived to instantiate with any content. This would indicate a subclass should be used, and many already exist in .NET. Sadly, I can't find any good generic ones. Let's say you want to delegate logging to a generic event... WITHOUT WRITING YOUR OWN EventArgs SUBCLASS. It may seem a pointless exercise, but I like using existing features. You can pass your string through the Object argument, but that goes against it's intended use. Try to find a good reference of EventArgs subclasses on Google, and you'll come up dry. (At least I did.) ReSharper helps a bit, since when you type "EventArgs" you'll see a list of all classes (within your using/imports scope) that CONTAIN the string "EventArgs". Perusing the list you'll see many classes with no string members. When you get to ControlEventArgs, you see that the Text property might be used, but with all of the overhead of a windows control. ConvertEventArgs might be useful, since you pass the type along with the data, but this still requires tight coupling that's neither well-documented nor inherently type-safe. DataReceivedEventArgs has no implementation. EntryWrittenEventArgs requires an EventLogEntry with a byte array or StreamingContext for data. ErrorEventArgs is closer, with an Exception message, if you don't mind calling all of your log events Exception ErrorEvents internally. FileSystemEventArgs is probably the closest yet, with two strings and a required WatcherChangeTypes enum argument that CAN be set to 0, if you know what you're doing. LabelEditEventArgs uses an int and a string, if you don't mind requiring the Windows.Forms namespace. RenamedEventArgs is similar to FileSystemEventArgs with an extra string. Finally, ResolveEventArgs in System.Runtime.InteropServices passes a single string. There are other libraries, but I stuck to some of the most common ones. So, depending on the implementation I can use ErrorEventArgs, FileSystemEventArgs or ResolveEventArgs for logging.
{ "language": "en", "url": "https://stackoverflow.com/questions/104674", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Are there native compilers for functional programming languages Joel Spolsky praised native-code versions of programs that have no dependencies on runtimes. What native-code compilers are available for functional languages? A: Yeah, also: ocamlc is the bytecode compiler, and ocamlopt is the native code compiler. GCL compiles Common Lisp to native binaries. There isn't anything for F# since, for what I am aware of, .NET doesn't have a native compiler, like Joel mentions. Actually, CSML can be used to call C# from ocaml, uhh, not sure if you can compile this down to native code --it doesn't seem likely-- although the documentation alludes to it, yet it is very incomplete. A: A lot of functional languages are compiled just like any other language. For example in Clojure: * *The reader translates the source code text into a data structure that represents the program (an s-expression) *If required, macros are then applied to transform the code *The Clojure compiler then translates the code into Java bytecode - this is the same machine-portable format used by Java, Scala and other JVM languages *Finally, the JIT compiler in the JVM converts the bytecode to native machine code, possibly performing various optimisations on the fly. This is the code that then gets directly executed on whatever platform it is running. One interesting point is that all this happens dynamically, i.e. at any point during program execution you can write new source code, pass it through the reader and various compilation steps and run the new compiled native code without having to restart the program. This is important as it enables interactive development at the REPL while still providing the benefits of fully compiled code. A: This post is really quite unclear. The question appears to be "Are there compilers for functional languages which can produce native executables without the need to install additional software?" The answer, generally, is yes. For example, Haskell has a compiler that produces native binaries. Many other functional languages have similar compilers. A: PLT Scheme has got a JIT compiler. Stalin is a Scheme compiler which does ridiculously aggressive optimisation. All Common Lisp implementations that I know of except CLISP compile to native code. (Whether one ought to consider CL a functional language depends on what is meant by the term “functional”, however.) MLton is a highly optimising compiler for Standard ML. Functional languages can be and have for some time been compiled very effectively. There is no difference to imperative languages in this regard.
{ "language": "en", "url": "https://stackoverflow.com/questions/104725", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Web application to user instant messaging What options are available for receiving instant alerts from web applications? I have a time sensitive web application I need to tend to (approving expediated purchase order requests). I have thought of being notified by e-mail and SMS. Are there any programs to let my website send a popup window directly to my screen? Or any other instant notification options? A: Include instant messenger fields in your account details. When your application processes an expedited order, stick the notification in a queue. If their instant messenger field is blank, prompt them. Write an XMPP (Jabber) bot that consumes items in that queue and send them out. Use transports to enable functionality for other networks, for MSN Messenger users, etc. A: You could always have it send messages via Jabber (or whatever IM network you choose). A: If you have your application open and you want a popup to appear, you could have a javascript timer that does an ajax style poll of your server every so often to see if there is a notification it needs to post. You could then throw up a pop up with the notification? A: You could also have an RSS feed tying into the application that would publish an update as soon as something occurred. Granted that would require you to have an RSS reader constantly pinging the application. Similarly, if you use the log4j/log4net framework, you can log a "fatal" or other special event for these actions and configure the appender to notify you via SMS, e-mail, etc. ...ooh, come to think of it. If you are using a .NET based app, log4net has a NetSendAppender that "Writes logging events to the Windows Messenger service. These messages are displayed in a dialog on a users terminal." A: The question isn't really specific enough to answer. From a high level point of view, presumably this notification would be sent from the server process and not client side via JavaScript. Without knowing the server side development language I can't say what specific libraries might be available, however there is the PhpTocLib PHP library available on SourceForge although I'm not sure how current that is. Another option would be to sign up for twitter or a similar service and send yourself a direct message when you have an update of interest. This could be accomplished with a simple HTTP POST from your application and you could receive notification using whatever methods the various microblogging services offer, including SMS.
{ "language": "en", "url": "https://stackoverflow.com/questions/104733", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to determine order for new item? I have a members table in MySQL CREATE TABLE `members` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(65) collate utf8_unicode_ci NOT NULL, `order` tinyint(3) unsigned NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB; And I would like to let users order the members how they like. I'm storing the order in order column. I'm wondering how to insert new user to be added to the bottom of the list. This is what I have today: $db->query('insert into members VALUES (0, "new member", 0)'); $lastId = $db->lastInsertId(); $maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members'); $db->query('update members SET `order` = ? WHERE id = ?', array( $maxOrder[0]['max_order'] + 1, $lastId )); But that's not really precise while when there are several users adding new members at the same time, it might happen the MAX(order) will return the same values. How do you handle such cases? A: You can do the SELECT as part of the INSERT, such as: INSERT INTO members SELECT 0, "new member", max(`order`)+1 FROM members; Keep in mind that you are going to want to have an index on the order column to make the SELECT part optimized. In addition, you might want to reconsider the tinyint for order, unless you only expect to only have 255 orders ever. Also order is a reserved word and you will always need to write it as `order`, so you might consider renaming that column as well. A: Since you already automatically increment the id for each new member, you can order by id. A: I am not sure I understand. If each user wants a different order how will you store individual user preferences in one single field in the "members" table? Usually you just let users to order based on the natural order of the fields. What is the purpose of the order field? A: Usually I make all my select statements order by "order, name"; Then I always insert the same value for Order (either 0 or 9999999 depending on if I want them first or last). Then the user can reorder however they like. A: InnoDB supports transactions. Before the insert do a 'begin' statement and when your finished do a commit. See this article for an explanation of transactions in mySql. A: What you could do is create a table with keys (member_id,position) that maps to another member_id. Then you can store the ordering in that table separate from the member list itself. (Each member retains their own list ordering, which is what I assume you want...?) Supposing that you have a member table like this: +-----------+--------------+ | member_id | name | +-----------+--------------+ | 1 | John Smith | | 2 | John Doe | | 3 | John Johnson | | 4 | Sue Someone | +-----------+--------------+ Then, you could have an ordering table like this: +---------------+----------+-----------------+ | member_id_key | position | member_id_value | +---------------+----------+-----------------+ | 1 | 1 | 4 | | 1 | 2 | 1 | | 1 | 3 | 3 | | 1 | 4 | 2 | | 2 | 2 | 1 | | 2 | 3 | 2 | +---------------+----------+-----------------+ You can select the member list given the stored order by using an inner join. For example: SELECT name FROM members inner join orderings ON members.member_id = orderings.member_id_value WHERE orderings.member_id_key = <ID for member you want to lookup> ORDER BY position; As an example, the result of running this query for John Smith's list (ie, WHERE member_id_key = 1) would be: +--------------+ | name | +--------------+ | Sue Someone | | John Smith | | John Johnson | | John Doe | +--------------+ You can calculate position for adding to the bottom of the list by adding one to the max position value for a given id.
{ "language": "en", "url": "https://stackoverflow.com/questions/104747", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net c# and logging ip access on every page and frequency Are there any prebuilt modules for this? Is there an event thats called everytime a page is loaded? I'm just trying to secure one of my more important admin sections. A: As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also. If you want to restrict the site or even a folder of the site to specific IP's, just go to the IIS Site or Folder properties that you want to protect in the IIS Manager, right click and select Properties. Choose the Directory Security tab. In the middle you should see the "IP Addresses and domain name restrictions. This will be where you can setup which IP's to block or allow. If you want to do this programatically in the code-behind of ASP.Net, you could use the page preinit event. A: A little more information please; do you want to log IPs or lock access via IP? Both those functions are built into IIS rather than ASP.NET; so are you looking for how to limit access via IP programatically? A: You can use the following to get a user's IP address: Request.ServerVariables["REMOTE_ADDR"] Once you have the IP you will have to write something custom to log it or block by IP. There isn't something built in to asp.net to do this for you. A: Is there an event that's called everytime a page is loaded? Page_Load might be what you're looking for. However, and I'm really not trying to be mean here, if you don't know that, you probably shouldn't be trying to secure the app. You're just not experienced enough in .Net I'm sure you're great at what you do, in whatever platform you're experienced in. But .Net WebForms isn't your forte. This is one of those times when you should back off and let someone else handle it.
{ "language": "en", "url": "https://stackoverflow.com/questions/104764", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Direct Path Load of TimeStamp Data With SQL*LDR The SQL-LDR documentation states that you need to do a convetional Path Load: When you want to apply SQL functions to data fields. SQL functions are not available during a direct path load I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such: STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')", COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')" So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data? A: From this OTN Forum thread: you just need to set the environment variable NLS_TIMESTAMP_FORMAT to tell SQL*Loader what format to expect the timestamp to be in: set NLS_TIMESTAMP_FORMAT=YYYY-MM-DD HH24:MI:SS.FF ..and remove the reference to the to_timestamp function completely from the controlfile. A: Here is an example of someone successfully direct loading timestamp data: Loading Data (Part 4): sqlldr (direct, skip_index_maintainance) A: As a side note most of us have discontinued using “sql loader” for the more advance version “External Tables” assuming you’re on a newer version of Oracle.
{ "language": "en", "url": "https://stackoverflow.com/questions/104791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: WCF service for receiving image What is the best way to create a webservice for accepting an image. The image might be quite big and I do not want to change the default receive size for the web application. I have written one that accepts a binary image but that I feel that there has to be a better alternative. A: Where does this image "live?" Is it accessible in the local file system or on the web? If so, I would suggest having your WebService accepting a URI (can be a URL or a local file) and opening it as a Stream, then using a StreamReader to read the contents of it. Example (but wrap the exceptions in FaultExceptions, and add FaultContractAttributes): using System.Drawing; using System.IO; using System.Net; using System.Net.Sockets; [OperationContract] public void FetchImage(Uri url) { // Validate url if (url == null) { throw new ArgumentNullException(url); } // If the service doesn't know how to resolve relative URI paths /*if (!uri.IsAbsoluteUri) { throw new ArgumentException("Must be absolute.", url); }*/ // Download and load the image Image image = new Func<Bitmap>(() => { try { using (WebClient downloader = new WebClient()) { return new Bitmap(downloader.OpenRead(url)); } } catch (ArgumentException exception) { throw new ResourceNotImageException(url, exception); } catch (WebException exception) { throw new ImageDownloadFailedException(url, exception); } // IOException and SocketException are not wrapped by WebException :( catch (IOException exception) { throw new ImageDownloadFailedException(url, exception); } catch (SocketException exception) { throw new ImageDownloadFailedException(url, exception); } })(); // Do something with image } A: Can't you upload the image to the server using FTP, then when that's done the server (and thus WCF service) van easily access it? That way you don't need to thinker with the receive size settings etc. At least, that's how I did it.
{ "language": "en", "url": "https://stackoverflow.com/questions/104797", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why aren't Java Collections remove methods generic? Why isn't Collection.remove(Object o) generic? Seems like Collection<E> could have boolean remove(E o); Then, when you accidentally try to remove (for example) Set<String> instead of each individual String from a Collection<String>, it would be a compile time error instead of a debugging problem later. A: remove() (in Map as well as in Collection) is not generic because you should be able to pass in any type of object to remove(). The object removed does not have to be the same type as the object that you pass in to remove(); it only requires that they be equal. From the specification of remove(), remove(o) removes the object e such that (o==null ? e==null : o.equals(e)) is true. Note that there is nothing requiring o and e to be the same type. This follows from the fact that the equals() method takes in an Object as parameter, not just the same type as the object. Although, it may be commonly true that many classes have equals() defined so that its objects can only be equal to objects of its own class, that is certainly not always the case. For example, the specification for List.equals() says that two List objects are equal if they are both Lists and have the same contents, even if they are different implementations of List. So coming back to the example in this question, it is possible to have a Map<ArrayList, Something> and for me to call remove() with a LinkedList as argument, and it should remove the key which is a list with the same contents. This would not be possible if remove() were generic and restricted its argument type. A: Josh Bloch and Bill Pugh refer to this issue in Java Puzzlers IV: The Phantom Reference Menace, Attack of the Clone, and Revenge of The Shift. Josh Bloch says (6:41) that they attempted to generify the get method of Map, remove method and some other, but "it simply didn't work". There are too many reasonable programs that could not be generified if you only allow the generic type of the collection as parameter type. The example given by him is an intersection of a List of Numbers and a List of Longs. A: In addition to the other answers, there is another reason why the method should accept an Object, which is predicates. Consider the following sample: class Person { public String name; // override equals() } class Employee extends Person { public String company; // override equals() } class Developer extends Employee { public int yearsOfExperience; // override equals() } class Test { public static void main(String[] args) { Collection<? extends Person> people = new ArrayList<Employee>(); // ... // to remove the first employee with a specific name: people.remove(new Person(someName1)); // to remove the first developer that matches some criteria: people.remove(new Developer(someName2, someCompany, 10)); // to remove the first employee who is either // a developer or an employee of someCompany: people.remove(new Object() { public boolean equals(Object employee) { return employee instanceof Developer || ((Employee) employee).company.equals(someCompany); }}); } } The point is that the object being passed to the remove method is responsible for defining the equals method. Building predicates becomes very simple this way. A: Assume one has a collection of Cat, and some object references of types Animal, Cat, SiameseCat, and Dog. Asking the collection whether it contains the object referred to by the Cat or SiameseCat reference seems reasonable. Asking whether it contains the object referred to by the Animal reference may seem dodgy, but it's still perfectly reasonable. The object in question might, after all, be a Cat, and might appear in the collection. Further, even if the object happens to be something other than a Cat, there's no problem saying whether it appears in the collection--simply answer "no, it doesn't". A "lookup-style" collection of some type should be able to meaningfully accept reference of any supertype and determine whether the object exists within the collection. If the passed-in object reference is of an unrelated type, there's no way the collection could possibly contain it, so the query is in some sense not meaningful (it will always answer "no"). Nonetheless, since there isn't any way to restrict parameters to being subtypes or supertypes, it's most practical to simply accept any type and answer "no" for any objects whose type is unrelated to that of the collection. A: I always figured this was because remove() has no reason to care what type of object you give it. It's easy enough, regardless, to check if that object is one of the ones the Collection contains, since it can call equals() on anything. It's necessary to check type on add() to ensure that it only contains objects of that type. A: It was a compromise. Both approaches have their advantage: * *remove(Object o) * *is more flexible. For example it allows to iterate through a list of numbers and remove them from a list of longs. *code that uses this flexibility can be more easily generified *remove(E e) brings more type safety to what most programs want to do by detecting subtle bugs at compile time, like mistakenly trying to remove an integer from a list of shorts. Backwards compatibility was always a major goal when evolving the Java API, therefore remove(Object o) was chosen because it made generifying existing code easier. If backwards compatibility had NOT been an issue, I'm guessing the designers would have chosen remove(E e). A: Because if your type parameter is a wildcard, you can't use a generic remove method. I seem to recall running into this question with Map's get(Object) method. The get method in this case isn't generic, though it should reasonably expect to be passed an object of the same type as the first type parameter. I realized that if you're passing around Maps with a wildcard as the first type parameter, then there's no way to get an element out of the Map with that method, if that argument was generic. Wildcard arguments can't really be satisfied, because the compiler can't guarantee that the type is correct. I speculate that the reason add is generic is that you're expected to guarantee that the type is correct before adding it to the collection. However, when removing an object, if the type is incorrect then it won't match anything anyway. If the argument were a wildcard the method would simply be unusable, even though you may have an object which you can GUARANTEE belongs to that collection, because you just got a reference to it in the previous line.... I probably didn't explain it very well, but it seems logical enough to me. A: Because it would break existing (pre-Java5) code. e.g., Set stringSet = new HashSet(); // do some stuff... Object o = "foobar"; stringSet.remove(o); Now you might say the above code is wrong, but suppose that o came from a heterogeneous set of objects (i.e., it contained strings, number, objects, etc.). You want to remove all the matches, which was legal because remove would just ignore the non-strings because they were non-equal. But if you make it remove(String o), that no longer works. A: Another reason is because of interfaces. Here is an example to show it : public interface A {} public interface B {} public class MyClass implements A, B {} public static void main(String[] args) { Collection<A> collection = new ArrayList<>(); MyClass item = new MyClass(); collection.add(item); // works fine B b = item; // valid collection.remove(b); /* It works because the remove method accepts an Object. If it was generic, this would not work */ } A: Remove is not a generic method so that existing code using a non-generic collection will still compile and still have the same behavior. See http://www.ibm.com/developerworks/java/library/j-jtp01255.html for details. Edit: A commenter asks why the add method is generic. [...removed my explanation...] Second commenter answered the question from firebird84 much better than me.
{ "language": "en", "url": "https://stackoverflow.com/questions/104799", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "151" }
Q: How do you create automated tests of a Maven plugin using JUnit? I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data. Anyone with better ideas? A: You need to use the maven-plugin-testing-harness, <dependency> <groupId>org.apache.maven.shared</groupId> <artifactId>maven-plugin-testing-harness</artifactId> <version>1.1</version> <scope>test</scope> </dependency> You derive your unit test classes from AbstractMojoTestCase. You need to create a bare bones POM, usually in the src/test/resources folder. <project> <build> <plugins> <plugin> <groupId>com.mydomain,mytools</groupId> <artifactId>mytool-maven-plugin</artifactId> <configuration> <!-- Insert configuration settings here --> </configuration> <executions> <execution> <goals> <goal>mygoal</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> Use the AbstractMojoTest.lookupMojo(String,File) (or one of the other variations) to load the Mojo for a specific goal and execute it. final File testPom = new File(PlexusTestCase.getBasedir(), "/target/test-classes/mytools-plugin-config.xml"); Mojo mojo = this.lookupMojo("mygoal", testPom); // Insert assertions to validate that your plugin was initialised correctly mojo.execute(); // Insert assertions to validate that your plugin behaved as expected I created my a plugin of my own that you can refer to for clarification http://ldap-plugin.btmatthews.com, A: If you'd like to see some real-world examples, the Terracotta Maven plugin (tc-maven-plugin) has some tests with it that you can peruse in the open source forge. The plugin is at: http://forge.terracotta.org/releases/projects/tc-maven-plugin/ And the source is in svn at: http://svn.terracotta.org/svn/forge/projects/tc-maven-plugin/trunk/ And in that source you can find some actual Maven plugin tests at: src/test/java/org/terracotta/maven/plugins/tc/
{ "language": "en", "url": "https://stackoverflow.com/questions/104803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Reduce startup time of .NET windows form app running off of a networked drive I have a simple .NET 2.0 windows form app that runs off of a networked drive (e.g. \MyServer\MyShare\app.exe). It's very basic, and only loads the bare minimum .NET libraries. However, it still takes ~6-10 seconds to load. People think something must be wrong that app so small takes so long to load. Are there any suggestions for improving the startup speed? A: Try out Sysinternals Process Explorer. It has an column of "% time in JIT". If that number is large you could run ngen on your application. If it's not it's likely to be a slow network connection. CodeGuru has a tutorial on usage of ngen. A: To speed up load time, you can compile a tiny start application and let that application do the loading of assemblies in runtime from a library outside bin folder. http://support.microsoft.com/kb/837908 A: Determining JIT time for weighing NGEN feasibility is certainly a good starting point. I also would agree with those who look to fudge the load time by using another entry point to then load the assemblies. Often it's the appearance of speed versus actual speed that improves the user experience. A: Setup Clickonce for the app so it's deployed to the local machine. A: You could cheat like Microsoft Office (and Adobe I think) and add an app in the Startup group that tells the app to load and then immediately unload. That way the DLL's are pre-cached in memory for when the user tries to start the app. Only catch: I'm not completely sure if it works this way with networked files -- and if it doesn't, this might be the cause of the slow start (ie you're always doing a cold start vs a possible warm start if running from the local machine).
{ "language": "en", "url": "https://stackoverflow.com/questions/104815", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Winform application profiling CPU usage / spikes . I have a winforms application that normally is at about 2-4% CPU. We are seeing some spikes up to 27% of CPU for limited number of times. What is the best profiling tool to determine what is actually causing this spike. We use dottrace but i dont see how to map that to exactly the CPU spikes? Appreciate the help A: I've used 2 profiling tools before - RedGate's ANTS profiler, and the built in profiler found in Visual Studio Team System. It's been some time since I used RedGate's (http://www.red-gate.com/products/ants_profiler/index.htm) profiler, though I used the built in in Visual Studio 2008 fairly recently. That being said, I felt that the RedGate product felt more intuitive to use. One thing that frustrated me back when I used the RedGate product was that I couldn't instruct the profiler to only profile my code starting at a certain point - I had a performance hit that couldn't be reached until a fair amount of code had already executed and therefore polluted my results. They may have added that feature since then. The built in version for Visual Studio is only available in their very-high end versions of the product. Someone correct me if I am wrong, but I don't think even the "Professional" version has the profiler. I am currently using Team System Developer Edition, which does have the code analysis tools. One thing the VS version does do though, is enable you to pause the profiling, and even start your app with profiling paused, so you can really focus on the performance of something very specific. This can be exceedingly helpful when you are trying to understand the analysis results. EDIT: Both tools will show you memory usage, and the number of times a specific method was called, and how much time was spent in each method. What they do not do, to the best of my knowledge, is show you CPU usage at any given point in time. However, there are likely strong correlations between CPU usage and the amount of time spent in a given block of code. If you can duplicate the CPU spikes consistently by invoking certain actions in the APP, then what I would do is try and get my hands on the VS profiler, start the app with profiling pause, enable profiling right before you do whatever typically results in the spike, and examine those results. This assumes of course that you have some sort of deterministic behavior to recreate the spikes. If not ... you might considering threaded processes or garbage collection a candidate for your performance hit. A: I’ve found DevPartner from Compuware http://www.compuware.com/ to be an excellent profiling tool. Unfortunately it looks like at the present time they don’t support VS 2008. A: Also, is this spike actually worrisome? And on what kind of hardware are you seeing this? A spike to 27% on a quad-core CPU might be cause for worry, but not on an 800Mhz P3. How long does it stay spiked? @Matt has a great point that garbage collection could be at fault. Or potentially swapping to disk. Is it affecting overall system performance for a long time, or just a couple seconds now and then? Not that finding a solution to this shouldn't be of concern, but how important is it? A: You can also learn a lot about your application with Sysinternal Process Explorer and Perfmon (like does the spike occur on a GC). A: If your app is single thread, the best profiling tool is your IDE. Added: Maybe it's obvious, but percent CPU usage is not a very clear concept. When your program is running at all, it's at 100%. When it's not, it's at 0%. So partial percents have to be based on some sort of smoothing integral over time. However, whatever it is, you are seeing a spike. Some profilers let you home in on such a spike and analyze just that interval. A: The best one that will show you the spikes and allows you to drill down to see what is causing it is Xperf/Xperfview tools. Check out http://msdn.microsoft.com/en-us/performance/cc825801.aspx and http://msdn.microsoft.com/en-us/library/cc305221.aspx these tools are based on ETW technology ( Event Tracing For Windows ), which gives you super accurate view of what is going on for your process and for the whole system. These tools also allows you to capture traces for postmortem analysis, and also attach/detach feature. Hope this helps.
{ "language": "en", "url": "https://stackoverflow.com/questions/104831", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Rails Sessions over servers I'd like to have some rails apps over different servers sharing the same session. I can do it within the same server but don't know if it is possible to share over different servers. Anyone already did or knows how to do it? Thanks A: Use the Database Session store. The short of it is this: To generate the table, at the console, run rake db:sessions:create in your environment.rb, include this line config.action_controller.session_store = :active_record_store A: Depending on how your app is set up, you can easily share cookies from sites in the same domain (foo.domain, bar.domain, domain) by setting your apps up to use the same secret: http://www.russellquinn.com/2008/01/30/multiple-rails-applications/ Now, if you have disparate sites, such as sdfsf.com, dsfsadfsdafdsaf.com, etc. you'll have to do a lot more tricks because the very nature of cookies restricts them to the specific domain. Essentially what you're trying to do is use cross-site scripting to, instead of hijack your session, read it from the other ones. In that case, a combination of using the same cookie secret etc and then some cross-site scripting you can manually extract the session info and re-create it on each site (or if you use ActiveRecord session {or NFS session dir}, link up with the existing one). It's not easy, but it can be done. Or, the low-tech way (which I've done before) is simply have the login page visit a specially crafted login page on each site that sets an app cookie on it and bounces you to the next one. It isn't pretty. A: Try using database-backed sessions. A: In Rails 2.0 there is now a CookieStore that stores all session data in an encrypted cookie on the client's machine. http://izumi.plan99.net/blog/index.php/2007/11/25/rails-20-cookie-session-store-and-security/
{ "language": "en", "url": "https://stackoverflow.com/questions/104837", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Default Printer in Unmanaged C++ I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks. A: Here is how to get a list of current printers and the default one if there is one set as the default. Also note: getting zero for the default printer name length is valid if the user has no printers or has not set one as default. Also being able to handle long printer names should be supported so calling GetDefaultPrinter with NULL as a buffer pointer first will return the name length and then you can allocate a name buffer big enough to hold the name. DWORD numprinters; DWORD defprinter=0; DWORD dwSizeNeeded=0; DWORD dwItem; LPPRINTER_INFO_2 printerinfo = NULL; // Get buffer size EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, 2, NULL, 0, &dwSizeNeeded, &numprinters ); // allocate memory //printerinfo = (LPPRINTER_INFO_2)HeapAlloc ( GetProcessHeap (), HEAP_ZERO_MEMORY, dwSizeNeeded ); printerinfo = (LPPRINTER_INFO_2)new char[dwSizeNeeded]; if ( EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, // what to enumerate NULL, // printer name (NULL for all) 2, // level (LPBYTE)printerinfo, // buffer dwSizeNeeded, // size of buffer &dwSizeNeeded, // returns size &numprinters // return num. items ) == 0 ) { numprinters=0; } { DWORD size=0; // Get the size of the default printer name. GetDefaultPrinter(NULL, &size); if(size) { // Allocate a buffer large enough to hold the printer name. TCHAR* buffer = new TCHAR[size]; // Get the printer name. GetDefaultPrinter(buffer, &size); for ( dwItem = 0; dwItem < numprinters; dwItem++ ) { if(!strcmp(buffer,printerinfo[dwItem].pPrinterName)) defprinter=dwItem; } delete buffer; } } A: The following works great for printing with the win32api from C++ char szPrinterName[255]; unsigned long lPrinterNameLength; GetDefaultPrinter( szPrinterName, &lPrinterNameLength ); HDC hPrinterDC; hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL); In the future instead of googling "unmanaged" try googling "win32 /subject/" or "win32 api /subject/" A: How to retrieve and set the default printer in Windows: http://support.microsoft.com/default.aspx?scid=kb;EN-US;246772 Code from now-unavailable article: // You are explicitly linking to GetDefaultPrinter because linking // implicitly on Windows 95/98 or NT4 results in a runtime error. // This block specifies which text version you explicitly link to. #ifdef UNICODE #define GETDEFAULTPRINTER "GetDefaultPrinterW" #else #define GETDEFAULTPRINTER "GetDefaultPrinterA" #endif // Size of internal buffer used to hold "printername,drivername,portname" // string. You may have to increase this for huge strings. #define MAXBUFFERSIZE 250 /*----------------------------------------------------------------*/ /* DPGetDefaultPrinter */ /* */ /* Parameters: */ /* pPrinterName: Buffer alloc'd by caller to hold printer name. */ /* pdwBufferSize: On input, ptr to size of pPrinterName. */ /* On output, min required size of pPrinterName. */ /* */ /* NOTE: You must include enough space for the NULL terminator! */ /* */ /* Returns: TRUE for success, FALSE for failure. */ /*----------------------------------------------------------------*/ BOOL DPGetDefaultPrinter(LPTSTR pPrinterName, LPDWORD pdwBufferSize) { BOOL bFlag; OSVERSIONINFO osv; TCHAR cBuffer[MAXBUFFERSIZE]; PRINTER_INFO_2 *ppi2 = NULL; DWORD dwNeeded = 0; DWORD dwReturned = 0; HMODULE hWinSpool = NULL; PROC fnGetDefaultPrinter = NULL; // What version of Windows are you running? osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osv); // If Windows 95 or 98, use EnumPrinters. if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { // The first EnumPrinters() tells you how big our buffer must // be to hold ALL of PRINTER_INFO_2. Note that this will // typically return FALSE. This only means that the buffer (the 4th // parameter) was not filled in. You do not want it filled in here. SetLastError(0); bFlag = EnumPrinters(PRINTER_ENUM_DEFAULT, NULL, 2, NULL, 0, &dwNeeded, &dwReturned); { if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0)) return FALSE; } // Allocate enough space for PRINTER_INFO_2. ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded); if (!ppi2) return FALSE; // The second EnumPrinters() will fill in all the current information. bFlag = EnumPrinters(PRINTER_ENUM_DEFAULT, NULL, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded, &dwReturned); if (!bFlag) { GlobalFree(ppi2); return FALSE; } // If specified buffer is too small, set required size and fail. if ((DWORD)lstrlen(ppi2->pPrinterName) >= *pdwBufferSize) { *pdwBufferSize = (DWORD)lstrlen(ppi2->pPrinterName) + 1; GlobalFree(ppi2); return FALSE; } // Copy printer name into passed-in buffer. lstrcpy(pPrinterName, ppi2->pPrinterName); // Set buffer size parameter to minimum required buffer size. *pdwBufferSize = (DWORD)lstrlen(ppi2->pPrinterName) + 1; } // If Windows NT, use the GetDefaultPrinter API for Windows 2000, // or GetProfileString for version 4.0 and earlier. else if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) { if (osv.dwMajorVersion >= 5) // Windows 2000 or later (use explicit call) { hWinSpool = LoadLibrary("winspool.drv"); if (!hWinSpool) return FALSE; fnGetDefaultPrinter = GetProcAddress(hWinSpool, GETDEFAULTPRINTER); if (!fnGetDefaultPrinter) { FreeLibrary(hWinSpool); return FALSE; } bFlag = fnGetDefaultPrinter(pPrinterName, pdwBufferSize); FreeLibrary(hWinSpool); if (!bFlag) return FALSE; } else // NT4.0 or earlier { // Retrieve the default string from Win.ini (the registry). // String will be in form "printername,drivername,portname". if (GetProfileString("windows", "device", ",,,", cBuffer, MAXBUFFERSIZE) <= 0) return FALSE; // Printer name precedes first "," character. strtok(cBuffer, ","); // If specified buffer is too small, set required size and fail. if ((DWORD)lstrlen(cBuffer) >= *pdwBufferSize) { *pdwBufferSize = (DWORD)lstrlen(cBuffer) + 1; return FALSE; } // Copy printer name into passed-in buffer. lstrcpy(pPrinterName, cBuffer); // Set buffer size parameter to minimum required buffer size. *pdwBufferSize = (DWORD)lstrlen(cBuffer) + 1; } } // Clean up. if (ppi2) GlobalFree(ppi2); return TRUE; } #undef MAXBUFFERSIZE #undef GETDEFAULTPRINTER // You are explicitly linking to SetDefaultPrinter because implicitly // linking on Windows 95/98 or NT4 results in a runtime error. // This block specifies which text version you explicitly link to. #ifdef UNICODE #define SETDEFAULTPRINTER "SetDefaultPrinterW" #else #define SETDEFAULTPRINTER "SetDefaultPrinterA" #endif /*-----------------------------------------------------------------*/ /* DPSetDefaultPrinter */ /* */ /* Parameters: */ /* pPrinterName: Valid name of existing printer to make default. */ /* */ /* Returns: TRUE for success, FALSE for failure. */ /*-----------------------------------------------------------------*/ BOOL DPSetDefaultPrinter(LPTSTR pPrinterName) { BOOL bFlag; OSVERSIONINFO osv; DWORD dwNeeded = 0; HANDLE hPrinter = NULL; PRINTER_INFO_2 *ppi2 = NULL; LPTSTR pBuffer = NULL; LONG lResult; HMODULE hWinSpool = NULL; PROC fnSetDefaultPrinter = NULL; // What version of Windows are you running? osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx(&osv); if (!pPrinterName) return FALSE; // If Windows 95 or 98, use SetPrinter. if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) { // Open this printer so you can get information about it. bFlag = OpenPrinter(pPrinterName, &hPrinter, NULL); if (!bFlag || !hPrinter) return FALSE; // The first GetPrinter() tells you how big our buffer must // be to hold ALL of PRINTER_INFO_2. Note that this will // typically return FALSE. This only means that the buffer (the 3rd // parameter) was not filled in. You do not want it filled in here. SetLastError(0); bFlag = GetPrinter(hPrinter, 2, 0, 0, &dwNeeded); if (!bFlag) { if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0)) { ClosePrinter(hPrinter); return FALSE; } } // Allocate enough space for PRINTER_INFO_2. ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded); if (!ppi2) { ClosePrinter(hPrinter); return FALSE; } // The second GetPrinter() will fill in all the current information // so that all you have to do is modify what you are interested in. bFlag = GetPrinter(hPrinter, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded); if (!bFlag) { ClosePrinter(hPrinter); GlobalFree(ppi2); return FALSE; } // Set default printer attribute for this printer. ppi2->Attributes |= PRINTER_ATTRIBUTE_DEFAULT; bFlag = SetPrinter(hPrinter, 2, (LPBYTE)ppi2, 0); if (!bFlag) { ClosePrinter(hPrinter); GlobalFree(ppi2); return FALSE; } // Tell all open programs that this change occurred. // Allow each program 1 second to handle this message. lResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0L, (LPARAM)(LPCTSTR)"windows", SMTO_NORMAL, 1000, NULL); } // If Windows NT, use the SetDefaultPrinter API for Windows 2000, // or WriteProfileString for version 4.0 and earlier. else if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT) { if (osv.dwMajorVersion >= 5) // Windows 2000 or later (use explicit call) { hWinSpool = LoadLibrary("winspool.drv"); if (!hWinSpool) return FALSE; fnSetDefaultPrinter = GetProcAddress(hWinSpool, SETDEFAULTPRINTER); if (!fnSetDefaultPrinter) { FreeLibrary(hWinSpool); return FALSE; } bFlag = fnSetDefaultPrinter(pPrinterName); FreeLibrary(hWinSpool); if (!bFlag) return FALSE; } else // NT4.0 or earlier { // Open this printer so you can get information about it. bFlag = OpenPrinter(pPrinterName, &hPrinter, NULL); if (!bFlag || !hPrinter) return FALSE; // The first GetPrinter() tells you how big our buffer must // be to hold ALL of PRINTER_INFO_2. Note that this will // typically return FALSE. This only means that the buffer (the 3rd // parameter) was not filled in. You do not want it filled in here. SetLastError(0); bFlag = GetPrinter(hPrinter, 2, 0, 0, &dwNeeded); if (!bFlag) { if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0)) { ClosePrinter(hPrinter); return FALSE; } } // Allocate enough space for PRINTER_INFO_2. ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded); if (!ppi2) { ClosePrinter(hPrinter); return FALSE; } // The second GetPrinter() fills in all the current<BR/> // information. bFlag = GetPrinter(hPrinter, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded); if ((!bFlag) || (!ppi2->pDriverName) || (!ppi2->pPortName)) { ClosePrinter(hPrinter); GlobalFree(ppi2); return FALSE; } // Allocate buffer big enough for concatenated string. // String will be in form "printername,drivername,portname". pBuffer = (LPTSTR)GlobalAlloc(GPTR, lstrlen(pPrinterName) + lstrlen(ppi2->pDriverName) + lstrlen(ppi2->pPortName) + 3); if (!pBuffer) { ClosePrinter(hPrinter); GlobalFree(ppi2); return FALSE; } // Build string in form "printername,drivername,portname". lstrcpy(pBuffer, pPrinterName); lstrcat(pBuffer, ","); lstrcat(pBuffer, ppi2->pDriverName); lstrcat(pBuffer, ","); lstrcat(pBuffer, ppi2->pPortName); // Set the default printer in Win.ini and registry. bFlag = WriteProfileString("windows", "device", pBuffer); if (!bFlag) { ClosePrinter(hPrinter); GlobalFree(ppi2); GlobalFree(pBuffer); return FALSE; } } // Tell all open programs that this change occurred. // Allow each app 1 second to handle this message. lResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0L, 0L, SMTO_NORMAL, 1000, NULL); } // Clean up. if (hPrinter) ClosePrinter(hPrinter); if (ppi2) GlobalFree(ppi2); if (pBuffer) GlobalFree(pBuffer); return TRUE; } #undef SETDEFAULTPRINTER A: GetDefaultPrinter (MSDN) ought to do the trick. That will get you the name to pass to CreateDC for printing. A: Unmanaged C++ doesn't exist (and managed C++ is now C++/CLI), if you are referring to C++, using unmanaged as a tag is just sad...
{ "language": "en", "url": "https://stackoverflow.com/questions/104844", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Test if string is a guid without throwing exceptions? I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions ( * *for performance reasons - exceptions are expensive *for usability reasons - the debugger pops up *for design reasons - the expected is not exceptional In other words the code: public static Boolean TryStrToGuid(String s, out Guid value) { try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; } } is not suitable. I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. Additionally, I thought certain Guid values are invalid(?) Update 1 ChristianK had a good idea to catch only FormatException, rather than all. Changed the question's code sample to include suggestion. Update 2 Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? The answer is yes. That is why I am using TryStrToGuid - I am expecting bad data. Example 1 Namespace extensions can be specified by appending a GUID to a folder name. I might be parsing folder names, checking to see if the text after the final . is a GUID. c:\Program Files c:\Program Files.old c:\Users c:\Users.old c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666} c:\Windows c:\Windows.old Example 2 I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be. Example 3 I might be parsing a search expression entered by a user. If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.) Update 3 - Performance benchmarks Test converting 10,000 good Guids, and 10,000 bad Guids. Catch FormatException: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen with try-catch: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks p.s. I shouldn't have to justify a question. A: Once .net 4.0 is available you can use Guid.TryParse(). A: You're not going to like this but what makes you think that catching the exception is going to be slower? How many failed attempts to parse a GUID are you expecting in comparison with successful ones? My advice is use the function you've just created and profile your code. If you find that this function is truely a hotspot then fix it but not before. A: for usability reasons - the debugger pops up If you're going for the try/catch approach you can add the [System.Diagnostics.DebuggerHidden] attribute to make sure the debugger doesn’t break even if you've set it to break on throw. A: While it is true that using errors is more expensive, most people believe that a majority of their GUIDs are going to be computer generated so a TRY-CATCH isn't too expensive since it only generates cost on the CATCH. You can prove this to yourself with a simple test of the two (user public, no password). Here you go: using System.Text.RegularExpressions; /// <summary> /// Validate that a string is a valid GUID /// </summary> /// <param name="GUIDCheck"></param> /// <returns></returns> private bool IsValidGUID(string GUIDCheck) { if (!string.IsNullOrEmpty(GUIDCheck)) { return new Regex(@"^(\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\}{0,1})$").IsMatch(GUIDCheck); } return false; } A: I had a similar situation and I noticed that almost never was the invalid string 36 characters long. So based on this fact, I changed your code a little to get better performance while still keeping it simple. public static Boolean TryStrToGuid(String s, out Guid value) { // this is before the overhead of setting up the try/catch block. if(value == null || value.Length != 36) { value = Guid.Empty; return false; } try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; } } A: In .NET 4.0 you can write as following: public static bool IsValidGuid(string str) { Guid guid; return Guid.TryParse(str, out guid); } A: I would at least rewrite it as: try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; } You don't want to say "invalid GUID" on SEHException, ThreadAbortException or other fatal or non-related stuff. Update: Starting with .NET 4.0, there is a new set of methods available for Guid: * *Guid.TryParse *Guid.TryParseExact Really, those should be used (if only for the fact, that they are not "naively" implemented using try-catch internally). A: Run the potential GUID though a RegEx or some custom code that does a sanity check to ensure the strig at least looks like a GUID and consists only of valid characters (and maybe that it seems to fit the overall format). If it doesn't pass the sanity check return an error - that'll probably weed out the vast majority of invalid strings. Then convert the string as you have above, still catching the exception for the few invalid strings that get through the sanity check. Jon Skeet did an analysis for something similar for parsing Ints (before TryParse was in the Framework): Checking if a string can be converted to Int32 However, as AnthonyWJones indicated you probably shouldn't be worrying about this. A: As far as I know, there is no something like Guid.TryParse in mscrolib. According to Reference Source, Guid type has mega-complex constructor which checks all kinds of guid formats and tries to parse them. There is no helper method you can call, even via reflection. I think you have to search for 3rd party Guid parsers, or write your own. A: Interop is slower than just catching the exception: In the happy path, with 10,000 Guids: Exception: 26ms Interop: 1,201ms In the unhappy path: Exception: 1,150ms Interop: 1,201ms It's more consistent, but it's also consistently slower. Seems to me you'd be better off configuring your debugger to only break on unhandled exceptions. A: Performance Benchmarks Catch exception: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks COM Intertop (Fastest) Answer: /// <summary> /// Attempts to convert a string to a guid. /// </summary> /// <param name="s">The string to try to convert</param> /// <param name="value">Upon return will contain the Guid</param> /// <returns>Returns true if successful, otherwise false</returns> public static Boolean TryStrToGuid(String s, out Guid value) { //ClsidFromString returns the empty guid for null strings if ((s == null) || (s == "")) { value = Guid.Empty; return false; } int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value); if (hresult >= 0) { return true; } else { value = Guid.Empty; return false; } } namespace PInvoke { class ObjBase { /// <summary> /// This function converts a string generated by the StringFromCLSID function back into the original class identifier. /// </summary> /// <param name="sz">String that represents the class identifier</param> /// <param name="clsid">On return will contain the class identifier</param> /// <returns> /// Positive or zero if class identifier was obtained successfully /// Negative if the call failed /// </returns> [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)] public static extern int CLSIDFromString(string sz, out Guid clsid); } } Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop. If you need to convert a guid in String representation to a Guid, use new Guid(someString); A: Well, here is the regex you will need... ^[A-Fa-f0-9]{32}$|^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$ But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. I can't imagine this being any faster than the try/catch method that you have already outlined. Hopefully you aren't receiving that many invalid GUIDs to warrant this type of check! A: bool IsProbablyGuid(string s) { int hexchars = 0; foreach(character c in string s) { if(IsValidHexChar(c)) hexchars++; } return hexchars==32; } A: * *Get Reflector *copy'n'paste Guid's .ctor(String) *replace every occurance of "throw new ..." with "return false". Guid's ctor is pretty much a compiled regex, that way you'll get exactly the same behavior without overhead of the exception. * *Does this constitute a reverse engineering? I think it does, and as such might be illegal. *Will break if GUID form changes. Even cooler solution would be to dynamically instrument a method, by replacing "throw new" on the fly. A: I vote for the GuidTryParse link posted above by Jon or a similar solution (IsProbablyGuid). I will be writing one like those for my Conversion library. I think it is totally lame that this question has to be so complicated. The "is" or "as" keyword would be just fine IF a Guid could be null. But for some reason, even though SQL Server is OK with that, .NET is not. Why? What is the value of Guid.Empty? This is just a silly problem created by the design of .NET, and it really bugs me when the conventions of a language step on itself. The best-performing answer so far has been using COM Interop because the Framework doesn't handle it gracefully? "Can this string be a GUID?" should be a question that is easy to answer. Relying on the exception being thrown is OK, until the app goes on the internet. At that point I just set myself up for a denial of service attack. Even if I don't get "attacked", I know some yahoo is going to monkey with the URL, or maybe my marketing department will send out a malformed link, and then my application has to suffer a fairly hefty performance hit that COULD bring down the server because I didn't write my code to handle a problem that SHOULDN'T happen, but we all know WILL HAPPEN. This blurs the line a bit on "Exception" - but bottom line, even if the problem is infrequent, if it can happen enough times in a short timespan that your application crashes servicing the catches from it all, then I think throwing an exception is bad form. TheRage3K A: if TypeOf ctype(myvar,Object) Is Guid then ..... A: Private Function IsGuidWithOptionalBraces(ByRef strValue As String) As Boolean If String.IsNullOrEmpty(strValue) Then Return False End If Return System.Text.RegularExpressions.Regex.IsMatch(strValue, "^[\{]?[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}[\}]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) End Function Private Function IsGuidWithoutBraces(ByRef strValue As String) As Boolean If String.IsNullOrEmpty(strValue) Then Return False End If Return System.Text.RegularExpressions.Regex.IsMatch(strValue, "^[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) End Function Private Function IsGuidWithBraces(ByRef strValue As String) As Boolean If String.IsNullOrEmpty(strValue) Then Return False End If Return System.Text.RegularExpressions.Regex.IsMatch(strValue, "^\{[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}\}$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) End Function A: With an extension method in C# public static bool IsGUID(this string text) { return Guid.TryParse(text, out Guid guid); } A: Returns Guid value from string. If invalid Guid value then return Guid.Empty. Null value can't be returned because Guid is a struct type /// <summary> /// Gets the GUID from string. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public static Guid GetGuidFromString(string guid) { try { if (Guid.TryParse(guid, out Guid value)) { return value; } else { return Guid.Empty; } } catch (Exception) { return Guid.Empty; } }
{ "language": "en", "url": "https://stackoverflow.com/questions/104850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "187" }
Q: "SetPropertiesRule" warning message when starting Tomcat from Eclipse When I start Tomcat (6.0.18) from Eclipse (3.4), I receive this message (first in the log): WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property. Seems this message does not have any severe impact, however, does anyone know how to get rid of it? A: Servers tab --> doubleclick servername --> Server Options: tick "Publish module contexts to separate XML files" restart your server A: I am using Eclipse. I have resolved this problem by the following: * *Open servers tab. *Double click on the server you are using. *On the server configuration page go to server options page. *Check Serve module without publishing. *Then save the page and configurations. *Restart the server by rebuild all the applications. You will not get any this kind of error. A: From Eclipse Newsgroup: The warning about the source property is new with Tomcat 6.0.16 and may be ignored. WTP adds a "source" attribute to identify which project in the workspace is associated with the context. The fact that the Context object in Tomcat has no corresponding source property doesn't cause any problems. I realize that this doesn't answer how to get rid of the warning, but I hope it helps. A: Delete the server instance from Eclipse and create a new one. A: The solution to this problem is very simple. Double click on your tomcat server. It will open the server configuration. Under server options check ‘Publish module contents to separate XML files’ checkbox. Restart your server. This time your page will come without any issues. A: I had the same problem with Eclipse 3.4(Ganymede) and dynamic web project. The message didn't influence successfull deploy.But I had to delete row <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/> from org.eclipse.wst.common.component file in .settings folder of Eclipse A: I copied the dynamic Webproject before the issue came up. So, changing the org.eclipse.wst.common.component file in the .settings directory solved the issue for me. The other solutions did not work. A: The separate XML solution never worked for me and other's recently ... I usually follow this process and something helps: * *Stop the server (Make sure its stopped via Task Manager, I killed javaw.exe as many times Eclipse doesn't really shut down properly) *Right click the Server->'Add and Remove'. Remove the project. Finish. *Right click the Server->'Add and Remove'. Add the project. Finish. *Restart see if works, if not continue *Double click the Server... See where its getting published (Server Path: which I think goes to a tmp# directory for me since I use an already-installed Tomcat instance I re-use, not sure if would be different if use Eclipse's internal/bundled tomcat server) *Right click on Server and 'Clean' ... Last one worked for me last time (so may want to try this first), Adding/Removing project worked for me other times. If doesn't work, continue ... *Delete all files from the Server Path and see if all files actually get built and published there (/WEB-INF/classes and other regular files in / webroot). *Restart Eclipse and/or machine (not sure I ever needed to get to this point) A: I am posting my answer because I suspect there might be someone out there for whom the above solutions might not have worked. So, you are getting a warning, WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server: (project name)' did not find a matching property. Rather than disabling this warning by checking that option in Server configuration (I did try that) I would suggest you do this: * *First close all the existing projects by right clicking in Project explorer. *Remove all the projects already synchronized with the server. *Remove the server and redeploy it. *Create a new dynamic project, do nothing yet just try running this on the server. *Check the console, do you get the warning now. (My case I didn't get any). This means that something is wrong with your project not with eclipse or the server. *Now restart the server. Don't run any app yet. You probably know that the Tomcat container loads up context of all the synchronized apps at the start. *It will load context of any already synchronized app. *Here is the catch, if there is really something wrong in your project it will show the stack trace of the exceptions.Look carefully and you will find where is the bug in your app. Now if you successfully found that there is a bug in your app, the probable place would be look for a web.xml file which the container uses for loading the app. In my case I had misspelled a name in servlet mapping which made me debug meaninglessly for 3 hours. Your problem might be someplace else. And another thing, if you have many apps synchronized with the server,there is a possibility some other app's context might be the source of problem. Try debugging one by one. A: I respect all the solutions given here. But what I came to know after reading all these, we haven't observed that on which folder the struts.xml file or any configuration file which is necessary for the web application. My SOULUTION IS: * *copy the struts.xml file to the src folder of our project. *click "file-->save all" in eclipse and go click "project-->clean". *restart the server. Hope the problem solved. A: Make sure you have correct jsp file name in web.xml file. By replacing default .jsp filename in web.xml with my current filename solved the problem A: I'm finding that Tomcat can't seem to find classes defined in other projects, maybe even in the main project. It's failing on the filter definition which is the first definition in web.xml. If I add the project and its dependencies to the server's launch configuration then I just move on to a new error, all of which seems to point to it not setting up the project properly. Our setup is quite complex. We have multiple components as projects in Eclipse with separate output projects. We have a separate webapp directory which contains the static HTML and images, as well as our WEB-INF. Eclipse is "Europa Winter release". Tomcat is 6.0.18. I tried version 2.4 and 2.5 of the "Dynamic Web Module" facet. Thanks for any help! * *Richard
{ "language": "en", "url": "https://stackoverflow.com/questions/104854", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "111" }
Q: Looking for C# registry class Looking for C# class which wraps calls to do the following: read and write a key value read & write a key entry enumerate the entries in a key. This is important. For example, need to list all entries in: HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\ODBC Data Sources (I scanned through some codeproject.com registry classes and they didn't enumerate) A: Use the standard C# / .NET registry classes and enumerate over the result of GetSubKeyNames(). See here for an example. A: Look in the "Microsoft.Win32" namespace. There you'll find functions for creating and reading registry entries. Registry.CurrentUser.OpenSubKey() Registry.CurrentUser.CreateSubKey() etc.. A: Microsoft.Win32.Registry A: I hope this code will help you a lot have a look on this post Registry Iteration in C# Code is also included in it.
{ "language": "en", "url": "https://stackoverflow.com/questions/104866", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: PHP :: Emulate , forwarding user to page I'm working on a PHP application that links into the Protx VSP Direct payment gateway. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the cURL libraries, but seem to have hit a problem. My code is the following: <?php $ch = curl_init(); // Set the URL curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/'); // Perform a POST curl_setopt($ch, CURLOPT_POST, 1); // If not set, curl prints output to the browser curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // Set the "form fields" curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $output = curl_exec($ch); curl_close($ch); ?> All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it. Thanks for any help :-) A: The 3D Secure API doesn't allow you to do the request in the background. You need to forward the user to the 3D secure site. Use javascript to automatically submit your form. Here's what our provider suggests: <html> <head> <title>Processing your request...</title> </head> <body OnLoad="OnLoadEvent();"> <form name="downloadForm" action="<%=RedirURL%>" method="POST"> <noscript> <br> <br> <div align="center"> <h1>Processing your 3-D Secure Transaction</h1> <h2>JavaScript is currently disabled or is not supported by your browser.</h2><BR> <h3>Please click Submit to continue the processing of your 3-D Secure transaction.</h3><BR> <input type="submit" value="Submit"> </div> </noscript> <input type="hidden" name="PaReq" value="<%=PAREQ%>"> <input type="hidden" name="MD" value="<%=TransactionID%>"> <input type="hidden" name="TermUrl" value="<%=TermUrl%>"> </form> <SCRIPT LANGUAGE="Javascript"> <!-- function OnLoadEvent() { document.downloadForm.submit(); } //--> </SCRIPT> </body> </html> A: I think you are a bit confused as to what curl does. It does exactly what you explained, it acts sort of like a browser and makes the call to the site and returns the content of that post. I don't know of any way you can actually redirect the browser server side and represent a post. I would actually create a Javascript solution to do such a thing. A: To redirect a user to another page in PHP you can send a header("Location: http://example.com/newpage");. However, unfortunately for your program redirection cause all POST variables to be removed (for security reasons). If you want to cause the user's browser to send a POST request to a different URL, you would have to create a form that submits itself. :( A: I'd much rather use something behind the scenes like cURL, as I can't guarantee my users will have JS enabled, and displaying a form causes some other problems I'd rather avoid. It's my plan B though ;-) A: You can use fsockopen() to redirect to the new web site while preserving your POST variables. There is a good tutorial on how to accomplish this here. In case that web site gets eaten by the Internet monster, I've copied and pasted the function but I suggest checking out the original web site for the context. function sendToHost($host,$method,$path,$data,$useragent=0) { // Supply a default method of GET if the one passed was empty if (empty($method)) { $method = 'GET'; } $method = strtoupper($method); $fp = fsockopen($host, 80); if ($method == 'GET') { $path .= '?' . $data; } fputs($fp, "$method $path HTTP/1.1\r\n"); fputs($fp, "Host: $host\r\n"); fputs($fp,"Content-type: application/x-www-form- urlencoded\r\n"); fputs($fp, "Content-length: " . strlen($data) . "\r\n"); if ($useragent) { fputs($fp, "User-Agent: MSIE\r\n"); } fputs($fp, "Connection: close\r\n\r\n"); if ($method == 'POST') { fputs($fp, $data); } while (!feof($fp)) { $buf .= fgets($fp,128); } fclose($fp); return $buf; } A: Ah, if I've misunderstood what cURL does, I guess i'll settle for a HTML form with JS auto-submit. Creates quite a bit more work for me, but if it's the only way, i'll have to do it. Thanks for the help all. A: I think in this case you need to use a form. The card payment companies web site needs to be visited by the user's browser, not your server-side code. Yes, 3dsecure etc, are quite annoying to integrate with, but they do provide a real security boost - use it as it's intended. A: Maybe I'm missing something; it looks like you're trying to receive the user's data, forward it via cURL to the payment processor, and then redirect the user somewhere. Right? If so, all you need to do is just put this at the end of your code: header("Location: http://www.yoursite.com/yoururl"); However, for this to work, the script CANNOT send anything to the client while it is processing; that means that the script should not be executed in the middle of a template, and another gotcha is whitespace at the beginning of the file before the opening tag. If you need to save the data from the original POST transaction, use a session to save it. That should work for a JS-free solution. A: I may be utterly wrong but it sounds like you're trying to do something similar to the Proxy Pattern. I have implemented similar patterns for other sites I've worked with and it does require a bit of tinkering around to get right. I'd set the RETURN_TRANSFER to TRUE so that you can analyse the retrieved response and make application level actions depending on it. http://en.wikipedia.org/wiki/Proxy_pattern Good luck. A: I found the sendToHost() function above very useful, but there is a typo in the source that took some time to debug: the Content-type header value contains a space between 'form-' and 'urlencoded' - should be 'application/x-www-form-urlencoded'
{ "language": "en", "url": "https://stackoverflow.com/questions/104872", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Automating interaction with a HTML game using C#? There are some HTML based games (ie bootleggers.us) that have a simple login form and after that your entire game experience revolves around submitting various forms and reading information from the website itself. My Question is, what is the best way to go about writing a bot / automate the html-based game using C#? My initial thought is to use the System.Net.HttpRequest and WebRequest classes to get the source html and parse using regexs to get the desired information. However, I would like to avoid this if it is at all possible. Are there any solutions that abstract away some of this and make automating website interaction easier? Ie filling out forms, submitting forms, reading values from the website, etc? Some library? A: You could use Watin: http://watin.sourceforge.net/ A: No, you're pretty much going to have to "screen scrape" every page. You might consider writing most this in JavaScript instead of C#. Depending on the HTML of the game site, this could be more or less difficult depending on whether they provide good id attributes on the page elements, etc...
{ "language": "en", "url": "https://stackoverflow.com/questions/104878", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Dealing with the rate of change in software development I am primarily a .NET developer, and in that sphere alone there are at any given time probably close to a dozen fascinating emerging technologies, some of them real game-changers, that I would love to delve into. Sadly, this appears to be beyond the limits of human capacity. I read an article by Rocky Lhotka (.NET legend, inventor of CSLA, etc) where he mentioned, almost in passing, that last year he felt very terribly overwheled by the rate of change. He made it sound like maybe it wasn't possible to stay on the bleeding edge anymore, that maybe he wasn't going to try so hard because it was futile. It was a surprise to me that true geniuses like Lhotka (who are probably expected to devote a great deal of their time to playing with the latest technology and should be able to pick things up quickly) also feel the burn! So, how do you guys deal with this? Do you just chalk it up to the fact that development is vast, and it's more important to be able to find things quickly than to learn it all? Or do you have a continuing education strategy that actually allows you to stay close to the cutting edge? A: I have been in IT for 30 years now, so perhaps I can offer some perspective. Yes, there is an increasing amount of material to keep abreast of. But the rate of change (as in "progress") is not increasing - if anything, it is decreasing. What we are seeing is a widening of the field. Take a simple example: Once upon a time there was HTML/1. Then came HTML/2 and that was progress. Now we have HTML/4, HTML/5, XHTML/1, Flash, Silverlight, and on and on. Any one of these is progress, but each is progress in a different direction and all are in active use. Stay on top of this? Forget it - it's not possible. On the other hand, good IT folks can pick up a new language or a new technology in a few weeks at most - no big deal. Try to pick out the genuinely new ideas and learn about them. Ignore all the specific technologies (IIS 7, SQL Server 2008, etc.) unless and until you need them. Continuing the Internet as an example, the last real innovation were the ideas behind Web 2.0. I took the opportunity to learn Ruby at the same time - did a couple of small, throw-away projects in Ruby on Rails. If a project in this area comes along, the ideas will be the same in whatever environment. One does occasionally get frustrated. It's not always easy to pick out the truly new ideas amidst all the marketing hype. All the best... Brad A: Attend conferences and local user group meetings, get on twitter and start following a bunch of folks. Join or start up a mailing list (google groups is my favorite provider, Yahoo groups aren't half bad either) in your area to discuss issues. Propose a talk at your local DNUG to have someone do a quick overview of all these new technologies or maybe have an open discussion/lightning talk where people stand up and give 5-10 minutes on their favorite new technology. In short: Get out there and talk and share with people. It's the only way you'll stay on top of everything. You can't do it by yourself unless you don't sleep and don't work. A: I find myself worrying about missing the boat on something from time to time but when I actually sit down and learn some hot new technology I find that it's primarily a new combination of fundamental technologies I've already seen. My appoach is to make sure I have a good grasp of algorithms, data structures, communication protocols, some hardware knowledge and general engineering skills. A: It is tough not to be tempted to want to learn it all, but I try not to jump into anything that is 'too new' I seem to end up with a lot of frustration with not a lot of sources out there to help. While someone does have to take the dive head first and I respect those people (I guess that's the life of a beta tester) I just do not think that responsibility falls on everyone. But if you have the time, and patience then diving into something new can be a lot of fun. I guess its not a direct answer to your question but I hope it gives you something to think about. A: I say just pick a facet of the development landscape that fascinates you and delve into that. For example, if you enjoy dealing with distributed systems, start reading up on WCF and becoming an expert on it. I don't think it's possible to be familiar with everything aside from a casual understanding of the technology. Far better to specialize instead of becoming a jack of all trades, but master of none. A: Since I can never find time to go and dabble or play with new technologies, typically I choose one based on some small amount of information - maybe an article, maybe a recommendation of a friend - and then I force myself to use the new technology in a project that I'm working on. That how got into the current process I'm in of learning SCSF and CAB. It can be painful, and even slow at the start since you have to run up the curve, in the end it typically works in your favor (provided the technology you chose gives benefits). That's how I learned LINQ, Generics and just about everything else. Choose a technology that purports to solve the problem you have better than the way you know and then force yourself to implement it that way.
{ "language": "en", "url": "https://stackoverflow.com/questions/104890", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How do I remove loadbalancer pollution from my access logs I have a pair of Sun web servers (iws6) sitting behind a load balancer. It likes to know if the web servers are up and continually asks for /alive.html. That is fine but how do I not log that in my access log? Failing that, how could I have the archiver strip out that accesses when it roles the file over? I would prefer something more elegant that cron calling grep -v alive.html A: You can give Apache rules about what logs to suppress. Maybe IWS has something similar? http://httpd.apache.org/docs/1.3/logs.html#conditional A: Logs are usually one line per entry so that you can grep for what you want. The idea is to have everything in the file, but to use grep in order to read the parts you care about. Grep for everything but load balancer stuff when you read them.
{ "language": "en", "url": "https://stackoverflow.com/questions/104892", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Sharing binary folders in Visual Studio For a long time i have tried to work out the best way to access certain site files which i don't wish to be apart of a project or to ease integration with multiple developers (and talents, e.g. designers) on a single project. A lot of sites i have created have had folders with large amounts of images and other binary files which i have not wanted to include in a visual studio project and/or source control mainly due to the constant updating of their contents. I have seen some people use virtual directories however there is no way to use virtual directories if you are using visual studio's built in web server. As far as i see it, ideally, folders containing binaries could be located on a central server and mapped to a project. Alernatively i have considered creating separate sub-domains for each project with which all images / binaries can be refereced via, e.g. http://project.client.customer.com/images Any thoughts? A: They should really be source controlled like everything else. If you use Subversion you could have them stored in a different repository and included as an svn-external on your main project repository if you didn't want them cluttering up your main repo. I'm sure other source control solutions offer similar functionality. A: You really ought to keep them in source control. If you're using Subversion, as Beepcake says, you can use svn:externals to share the files between different projects. Alternatively, you could have a custom build action that fetches the latest copy of the shared files from wherever you keep them. We do this in a variety of ways -- either we issue an "svn checkout" for a subdirectory (but svn:externals would work for this), or we do a "wget ..." to grab the output from the last successful build of another project (we use TeamCity for continuous integration, and it makes "artifacts" available over HTTP). A: Images and other binaries should be in source control just like your code files. Especially since they are changing often. That said, there is absolutely no harm in setting up a different project that only contains your binary files; and having it on a different deployment schedule.
{ "language": "en", "url": "https://stackoverflow.com/questions/104901", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Command Pattern : How to pass parameters to a command? My question is related to the command pattern, where we have the following abstraction (C# code) : public interface ICommand { void Execute(); } Let's take a simple concrete command, which aims to delete an entity from our application. A Person instance, for example. I'll have a DeletePersonCommand, which implements ICommand. This command needs the Person to delete as a parameter, in order to delete it when Execute method is called. What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ? A: My implementation would be this (using the ICommand proposed by Juanma): public class DeletePersonCommand: ICommand<Person> { public DeletePersonCommand(IPersonService personService) { this.personService = personService; } public void Execute(Person person) { this.personService.DeletePerson(person); } } IPersonService could be an IPersonRepository, it depends in what "layer" your command is. A: You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this: public class DeletePersonCommand: ICommand { private Person personToDelete; public DeletePersonCommand(Person personToDelete) { this.personToDelete = personToDelete; } public void Execute() { doSomethingWith(personToDelete); } } A: Pass the person when you create the command object: ICommand command = new DeletePersonCommand(person); so that when you execute the command, it already knows everything that it needs to know. class DeletePersonCommand : ICommand { private Person person; public DeletePersonCommand(Person person) { this.person = person; } public void Execute() { RealDelete(person); } } A: In this case, what we've done with our Command objects is to create a Context object which is essentially a map. The map contains name value pairs where the keys are constants and the values are parameters that are used by the Command implementations. Especially useful if you have a Chain of Commands where later commands depend on context changes from earlier commands. So the actual method becomes void execute(Context ctx); A: In the constructor and stored as fields. You will also want to eventually make your ICommands serializable for the undo stack or file persistence. A: Already mentioned code from Blair Conrad(don't know how to tag him) works perfectly fine if you know what person you want to delete when you instantiate the class and his method would suffice.But,if you don't know who you gonna delete until you press the button you can instantiate the command using a method reference that returns the person. class DeletePersonCommand implements ICommand { private Supplier<Person> personSupplier; public DeletePersonCommand(Supplier<Person> personSupplier) { this.personSupplier = personSupplier; } public void Execute() { personSupplier.get().delete(); } } That way when the command is executed the supplier fetches the person you want to delete,doing so at the point of execution. Up until that time the command had no information of who to delete. Usefull link on the supplier. NOTE:code writen in java . Someone with c# knowledge can tune that. A: Based on the pattern in C#/WPF the ICommand Interface (System.Windows.Input.ICommand) is defined to take an object as a parameter on the Execute, as well as the CanExecute method. interface ICommand { bool CanExecute(object parameter); void Execute(object parameter); } This allows you to define your command as a static public field which is an instance of your custom command object that implements ICommand. public static ICommand DeleteCommand = new DeleteCommandInstance(); In this way the relevant object, in your case a person, is passed in when execute is called. The Execute method can then cast the object and call the Delete() method. public void Execute(object parameter) { person target = (person)parameter; target.Delete(); } A: Passing the data in via a constructor or setter works, but requires the creator of the command to know the data the command needs... The "context" idea is really good, and I was working on (an internal) framework that leveraged it a while back. If you set up your controller (UI components that interact with the user, CLI interpreting user commands, servlet interpreting incoming parameters and session data, etc) to provide named access to the available data, commands can directly ask for the data they want. I really like the separation a setup like this allows. Think about layering as follows: User Interface (GUI controls, CLI, etc) | [syncs with/gets data] V Controller / Presentation Model | ^ [executes] | V | Commands --------> [gets data by name] | [updates] V Domain Model If you do this "right", the same commands and presentation model can be used with any type of user interface. Taking this a step further, the "controller" in the above is pretty generic. The UI controls only need to know the name of the command they'll invoke -- they (or the controller) don't need to have any knowledge of how to create that command or what data that command needs. That's the real advantage here. For example, you could hold the name of the command to execute in a Map. Whenever the component is "triggered" (usually an actionPerformed), the controller looks up the command name, instantiates it, calls execute, and pushes it on the undo stack (if you use one). A: You should create a CommandArgs object to contain the parameters you want to use. Inject the CommandArgs object using the constructor of the Command object. A: There are some options: You could pass parameters by properties or constructor. Other option could be: interface ICommand<T> { void Execute(T args); } And encapsulate all command parameters in a value object. A: DeletePersonCommand can have parameter in its constructor or methods . DeletePersonCommand will have the Execute() and in the execute can check attribute that will be passed by Getter/Setter previously the call of the Execute(). A: I would add any necessary arguments to the constructor of DeletePersonCommand. Then, when Execute() is called, those parameters passed into the object at construction time are used. A: Have "Person" implement some sort of IDeletable interface, then make the command take whatever base class or interface your entities use. That way, you can make a DeleteCommand, which tries to cast the entity to an IDeletable, and if that works, call .Delete public class DeleteCommand : ICommand { public void Execute(Entity entity) { IDeletable del = entity as IDeletable; if (del != null) del.Delete(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/104918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "70" }
Q: Is there a .NET performance counter to show the rate of p/invoke calls being made? Is there a .NET performance counter to show the rate of p/invoke calls made? I've just noticed that the application I'm debugging was making a call into native code from managed land within a tight loop. The intended implementation was for a p/invoke call to be made once and then cached. I'm wondering if I could have noticed this mistake via a CLR Interop or Remoting .NET performance counter. Any ideas? A: Try the ".NET CLR Interop" for "# of marshalling" performance counter. See this article for more http://msdn.microsoft.com/en-us/library/ms998551.aspx.
{ "language": "en", "url": "https://stackoverflow.com/questions/104920", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Web designer for VS.NET ReportViewer Is there any designer for rdl files (visual studio .net reports) that can be used on a web browser? A: The best that I've seen is RsInteract: http://www.rsinteract.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/104951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: I want tell the VC++ Compiler to compile all code. Can it be done? I am using VS2005 VC++ for unmanaged C++. I have VSTS and am trying to use the code coverage tool to accomplish two things with regards to unit tests: * *See how much of my referenced code under test is getting executed *See how many methods of my code under test (if any) are not unit tested at all Setting up the VSTS code coverage tool (see the link text) and accomplishing task #1 was straightforward. However #2 has been a surprising challenge for me. Here is my test code. class CodeCoverageTarget { public: std::string ThisMethodRuns() { return "Running"; } std::string ThisMethodDoesNotRun() { return "Not Running"; } }; #include <iostream> #include "CodeCoverageTarget.h" using namespace std; int main() { CodeCoverageTarget cct; cout<<cct.ThisMethodRuns()<<endl; } When both methods are defined within the class as above the compiler automatically eliminates the ThisMethodDoesNotRun() from the obj file. If I move it's definition outside the class then it is included in the obj file and the code coverage tool shows it has not been exercised at all. Under most circumstances I want the compiler to do this elimination for me but for the code coverage tool it defeats a significant portion of the value (e.g. finding untested methods). I have tried a number of things to tell the compiler to stop being smart for me and compile everything but I am stumped. It would be nice if the code coverage tool compensated for this (I suppose by scanning the source and matching it up with the linker output) but I didn't find anything to suggest it has a special mode to be turned on. Am I totally missing something simple here or is this not possible with the VC++ compiler + VSTS code coverage tool? Thanks in advance, KGB A: You could try adding a line of code to call the function only if some condition is true, and guarantee that that condition will never be true. Just make sure the compiler can't figure that out. For example, int main(int argc, char **argv) { if(argv == NULL) // C runtime says this won't happen someMethodWhichIsntReallyEverCalled(); } A: One way to ensure your functions are not discarded is to export them. You can do this by adding __declspec(dllexport) to your function declarations. It is best to wrap this in a C preprocessor macro so that you can turn it off, since it is compiler-specific and you might not want all of your builds to export symbols. Another way to export functions is to create a .DEF file. If inlining is the problem, you might also have success with __declspec(noinline). Is your code in a static library which is then compiled into a test EXE/DLL? The linker will automatically discard unreferenced object files that are in static libraries. Example: if the static library contains a.obj and b.obj and the EXE/DLL that you're linking it into references symbols from b.obj but not a.obj, then the contents of a.obj will not be linked into the executable or DLL. However, after re-reading your description it doesn't sound like that's what's happening here. A: Turn off inlining of functions. The easiest way to do this is to just compile in Debug mode. Edit: after seeing your clarification, I find my answer is in error. Perhaps if you moved the body of the function into another section of the .h file, using the "inline" keyword? A: Sorry I should have clarified that I am building debug mode with inlining and all optimization off. Besides, the code is getting removed before inlining even occurs since it's never referenced to even be considered for inlining. A: Another option is to switch between inline and non inline functions based on your build, using .inl files, like this: in foo.inl file: inline std::string Foo::ThisMethodDoesNotRun() { return "Not Running"; } in foo.h: #if !COVERAGE_BUILD #include "foo.inl" #endif in foo.cpp: #if COVERAGE_BUILD #define inline #include "foo.inl" #endif
{ "language": "en", "url": "https://stackoverflow.com/questions/104952", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Position an element relative to its container I'm trying to create a horizontal 100% stacked bar graph using HTML and CSS. I'd like to create the bars using DIVs with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph. In my experimentation, I've already gotten the bars to stack horizontally by assigning the CSS property float: left. However, I'd like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don't seem to work very well when the bars are floated. I think that CSS positioning should be able to handle this, but I don't yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I'd like a method that's: * *Cross-browser (ideally without too many browser hacks) *Runs in Quirks mode *As clear/clean as possible, to facilitate customizations *Done without JavaScript if possible. A: You are right that CSS positioning is the way to go. Here's a quick run down: position: relative will layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It's important to note that because it's removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour). However, you're most likely interested in position: absolute which will position an element relative to a container. By default, the container is the browser window, but if a parent element either has position: relative or position: absolute set on it, then it will act as the parent for positioning coordinates for its children. To demonstrate: #container { position: relative; border: 1px solid red; height: 100px; } #box { position: absolute; top: 50px; left: 20px; } <div id="container"> <div id="box">absolute</div> </div> In that example, the top left corner of #box would be 100px down and 50px left of the top left corner of #container. If #container did not have position: relative set, the coordinates of #box would be relative to the top left corner of the browser view port. A: Absolute positioning positions an element relative to its nearest positioned ancestor. So put position: relative on the container, then for child elements, top and left will be relative to the top-left of the container so long as the child elements have position: absolute. More information is available in the CSS 2.1 specification. A: You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this: div.parent{ position: relative; left: 0px; /* stick it wherever it was positioned by default */ top: 0px; } div.child{ position: absolute; left: 10px; top: 10px; } A: I know I am late but hope this helps. Following are the values for the position property. * *static *fixed *relative *absolute position : static This is default. It means the element will occur at a position that it normally would. #myelem { position : static; } position : fixed This will set the position of an element with respect to the browser window (viewport). A fixed positioned element will remain in its position even when the page scrolls. (Ideal if you want scroll-to-top button at the bottom right corner of the page). #myelem { position : fixed; bottom : 30px; right : 30px; } position : relative To place an element at a new location relative to its original position. #myelem { position : relative; left : 30px; top : 30px; } The above CSS will move the #myelem element 30px to the left and 30px from the top of its actual location. position : absolute If we want an element to be placed at an exact position in the page. #myelem { position : absolute; top : 30px; left : 300px; } The above CSS will position #myelem element at a position 30px from top and 300px from the left in the page and it will scroll with the page. And finally... position relative + absolute We can set the position property of a parent element to relative and then set the position property of the child element to absolute. This way we can position the child relative to the parent at an absolute position. #container { position : relative; } #div-2 { position : absolute; top : 0; right : 0; } We can see in the above image the #div-2 element is positioned at the top-right corner inside the #container element. GitHub: You can find the HTML of the above image here and CSS here. Hope this tutorial helps. A: If you need to position an element relative to its containing element first you need to add position: relative to the container element. The child element you want to position relatively to the parent has to have position: absolute. The way that absolute positioning works is that it is done relative to the first relatively (or absolutely) positioned parent element. In case there is no relatively positioned parent, the element will be positioned relative to the root element (directly to the HTML element). So if you want to position your child element to the top left of the parent container, you should do this: .parent { position: relative; } .child { position: absolute; top: 0; left: 0; } You will benefit greatly from reading this article. Hope this helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/104953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "197" }
Q: Testing Abstract Class Concrete Methods How would I design and organize tests for the concrete methods of an abstract class? Specifically in .NET. A: You have to create a subclass that implements the abstract methods (with empty methods), but none of the concrete ones. This subclass should be for testing only (it should never go into your production code). Just ignore the overridden abstract methods in your unit tests and concentrate on the concrete methods. A: Use Rhino Mocks, it can generate implementations of the abstract class at runtime and you can call the non-abstract methods. A: The first thing that comes to mind is to test those methods in a concrete child class. A: Any reason not to just include that in the testing of one of the instances? If that doesn't work, you could probably create a subclass just for testing with no unique functionality of its own. A: I Always use Stub/Mock object A: You have to define and create a concrete test class that inhereits from the abstract. Typically it will be a light shim that does nothing but pass through calls.
{ "language": "en", "url": "https://stackoverflow.com/questions/104958", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Inspecting STL containers in Visual Studio debugging If I have a std::vector or std::map variable, and I want to see the contents, it's a big pain to see the nth element while debugging. Is there a plugin, or some trick to making it easier to watch STL container variables while debugging (VS2003/2005/2008)? A: To view the nth element of a container in the Visual Studio debugger, use: container.operator[](n) A: You could create a custom visualiser Check this out: http://www.virtualdub.org/blog/pivot/entry.php?id=120 A: Most simply method is you have to ready a pointer to watch variable like this. vector<int> a = { 0,1,2,3,4,5 }; int* ptr = &a[0]; // watch this ptr in VisualStudio Watch window like this "ptr,6". I tried "a._Myfirst[0]" in VisualStudio2015, But It wasn't display array data. If you can use "natvis", it will resolve your problems. This is "sample.natvis" for display std::vector data for Visual studio 2015. <?xml version="1.0" encoding="utf-8"?> <AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010"> <Type Name="std::vector&lt;*&gt;"> <DisplayString>{{ size={_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst} }}</DisplayString> <Expand> <Item Name="[size]" ExcludeView="simple">_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst</Item> <Item Name="[capacity]" ExcludeView="simple">_Mypair._Myval2._Myend - _Mypair._Myval2._Myfirst</Item> <ArrayItems> <Size>_Mypair._Myval2._Mylast - _Mypair._Myval2._Myfirst</Size> <ValuePointer>_Mypair._Myval2._Myfirst</ValuePointer> </ArrayItems> </Expand> </Type> </AutoVisualizer> Before After A: Visual Studio 2008, at least for me, displays the contents of STL containers in the standard mouseover contents box. A: If you want to watch more than one element at the same time, you can append a comma and the number of elements as so: (v._Myfirst)[startIndex], count However, note that count must be a constant, it cannot be the result of another expression. A: For vectors, this thread on the msdn forums has a code snippet for setting a watch on a vector index that might help. A: In VS2005 and VS 2008 you can see the contents of STL containers. The rules for getting at the data are in autoexp.dat "c:\Program Files\Microsoft Visual Studio 9\Common7\Packages\Debugger\autoexp.dat". AutoExp.dat is meant to be customized. However, the STL defs are under a section called [Visualizer]. If you can figure out the language used in that section, more power to you, however I'd recommend just leaving that part alone. Autoexp.dat existed in VS2003, but there was no support for STL containers ([Visualizer] didn't exist). In VS2003 you have to manually navigate the underlying data representation. By modifying autoexp.dat it is possible to add rules for navigating the data representation of your own types so they are easier to debug. If you do this, you should only add to the stuff under [AutoExp]. Be careful and keep a back up of this file before you modify it. A: You can also right-click any value in your watch, and choose 'add watch'. This can be useful if you only need to look at one element of a map or set. It also leads to the solution that christopher_f posted for vectors - ((v)._Myfirst)[index] A: Above discussed method [((v)._Myfirst)[index]] will work only for specific container(std::vector) not for all possible STL containers. For example if you want to see the content of std::deque then you have to look for some other method to browse through the content in std::deque. Maybe you can try the following similar setting to solve your issue [I tested this setting only for Visual Studio 2010 Professional version installed with Microsoft Visual studio 2010 Service pack 1] Step 1: Uninstall the Microsoft Visual studio 2010 Service pack 1 - for my project work I don't really need the Service pack 1 so uninstalling service pack 1 will not cause any issue for my case. Step 2: Restart your system. Step 3: This step is not necessary if you are not getting Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt'. Otherwise browse through Project Property -> Linker (General) -> Change Enable Incremental Linking to No (/INCREMENTAL:NO) A: In vs 2015, I could not get any of these working so, i wrote a bit of code 1: I had vector of vector of long long elements std::vector<std::string> vs(M_coins + 1); for (unsigned long long i = 0; i <= M_coins; i++) { std::for_each(memo[i].begin(), memo[i].end(), [i, &vs](long long &n) { vs[i].append(std::to_string(n)); }); } // now vs is ready for use as vs[0], vs[1].. so on, for your debugger basically what i did was converted vector into string. i had vector of vector so i had string vector to fill. 2: if you have just a vector of long long elements, then just convert as below: std::vector<std::string> s; std::for_each(v1.begin(), v1.end(), [&s](long long &n) { s.append(std::to_string(n)); }); // now s is ready for use, for your debugger hope it helped. A: This is old but since I regularly stumble on this post because it is still referenced high on google, as of Visual Studio 2019, one can simply write in the debugger's Watch: vectorName.data() (replace vectorName by your variable name) to get a pointer to the content. Then, knowing the current size of the vector, you can tell the debugger to show you the first N cells: vectorName.data(),N (N being the size of your vector) And if like me, you have a lot of vectors of bytes that actually store another data structure, you can even tell the debugger to interpret the pointer as an array of something else : (float*)vectorName.data(),4 For example, I have a std::vector of 16 bytes and using that I can tell the debugger to show me an array of 4 floats instead (which is more useful to me than the bytes alone).
{ "language": "en", "url": "https://stackoverflow.com/questions/104959", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "35" }
Q: Are there any ORM tools for Haskell? What is the best way to interact with a database using Haskell? I'm accustomed to using some sort of ORM (Django's ORM, hibernate, etc.) and something similar would be nice when creating apps with HAppS. Edit: I'd like to be free to choose from Postgresql MySql and SQLite as far as the actual databases go. A: I personally used only Database.HDBC which is recommended by "Real World Haskell": http://book.realworldhaskell.org/read/using-databases.html But I agree that it definitely makes sense to use a higher-level DB access layer, and I'll probably try to move to such a model for future projects. On this topic, I found this post from 2012 which provides a history and comparison of such solutions for Haskell: http://www.yesodweb.com/blog/2012/03/history-of-persistence From it, I gather that Persistent (documentation) and Groundhog (some documentation, examples) are the most promising libraries in this area. Both libraries support the databases you mention; for Groundhog it's not written in this post but in this announcement you can see that it supports exactly the DBs you are interested in. Also note this thread on Haskell-beginners in which Esqueletto is mentioned as a better choice for update operations. Note that Persistent ships with Yesod and as such may have a greater following. A: I actually very much like the approach of HAppS (HAppS-State) which allows you to forget about going through the marshalling/unmarshalling cludge of ORM and let's you simply use Haskell's data types. A: The library I have in mind is not an ORM, but it may still do what you want. If you want something that makes your database accesses safe while integrating things into your program nicely then try out HaskellDB. It basically looks at your schema, generates some data structures, and then gives you type safe ways to query. It's been around for quite a while and the community opinion is that it's good and stable. To use it, you'll need some underlying Haskell DB library like HSQL. Good luck! A: The reason that ORM libraries exist is that there is relative big difference between Objects in C# or Java and what you store in a database. This is not so much an issue in Haskell because: * *It does not have Objects *Both databases and Haskell list have their inspiration in mathematical set theory, so the friction between them is a lot less than between databases and Objects. A: Persistent is rather nice to use, and lets you rely on type inference to determine the table your query relates to. For example, if I have the following in my "models" file: User name Text age Int Login user UserId login Text passwd Text Then I could do this: Just (Entity uid _) <- selectFirst [ UserName ==. "exampleUser" ] [] Just (Entity lid Login {..}) <- selectFirst [ LoginUser ==. uid ] [] And it would know which tables I meant. Of course, you probably don't want to be writing partial code like this, but I wanted to emphasize just the queries. A: Have you looked through the database mapping and access packages at http://hackage.haskell.org/packages/archive/pkg-list.html#cat:Database I haven't used them, so can't recommend any particular one. I also don't know what databases you are planning on using.
{ "language": "en", "url": "https://stackoverflow.com/questions/104960", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "37" }
Q: How do I implement a two-pass scanner using Flex? As a pet-project, I'd like to attempt to implement a basic language of my own design that can be used as a web-scripting language. It's trivial to run a C++ program as an Apache CGI, so the real work lies in how to parse an input file containing non-code (HTML/CSS markup) and server-side code. In my undergrad compiler course, we used Flex and Bison to generate a scanner and a parser for a simple language. We were given a copy of the grammar and wrote a parser that translated the simple language to a simple assembly for a virtual machine. The flex scanner tokenizes the input, and passes the tokens to the Bison parser. The difference between that and what I'd like to do is that like PHP, this language could have plain HTML markup and the scripting language interspersed like the following: <p>Hello, <? echo "World ?> </p> Am I incorrect in assuming that it would be efficient to parse the input file as follows: * *Scan input until a script start tag is found (' *Second scanner tokenizes the server-side script section of the input file (from the open tag: '') and passes the token to the parser, which has no need to know about the markup in the file. *Control is returned to the first scanner that continues this general pattern. Basically, the first scanner only differentiates between Markup (which is returned directly to the browser unmodified) and code, which is passed to the second scanner, which in turn tokenizes the code and passes the tokens to the parser. If this is not a solid design pattern, how do languages such as PHP handle scanning input and parsing code efficiently? A: You want to look at start conditions. For example: "<?" { BEGIN (PHP); } <PHP>[a-zA-Z]* { return PHP_TOKEN; } <PHP>">?" { BEGIN (0); } [a-zA-Z]* { return HTML_TOKEN; } You start off in state 0, use the BEGIN macro to change states. To match a RE only while in a particular state, prefix the RE with the state name surrounded by angle-brackets. In the example above, "PHP" is state. "PHP_TOKEN" and "HTML_TOKEN" are _%token_s defined by your yacc file. A: PHP doesn't differentiate between the scanning and the Markup. It simply outputs to buffer when in Markup mode, and then switches to parsing when in code mode. You don't need a two pass scanner, and you can do this with just a single flex lexer. If you are interested in how PHP itself works, download the source (try the PHP4 source it is a lot easier to understand). What you want to look at is in the Zend Directory, zend_language_scanner.l. Having written something similar myself, I would really recommend rethinking going the Flex and Bison route, and go with something modern like Antlr. It is a lot easier, easier to understand (the macros employed in a lex grammar get very confusing and hard to read) and it has a built in debugger (AntlrWorks) so you don't have to spend hours looking at 3 Meg debug files. It also supports many languages (Java, c#, C, Python, Actionscript) and has an excellent book and a very good website that should be able to get you up and running in no time.
{ "language": "en", "url": "https://stackoverflow.com/questions/104967", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }