Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
> **Possible Duplicate:** > [What is the difference between String.Empty and “”](https://stackoverflow.com/questions/151472/what-is-the-difference-between-string-empty-and) Is `""` equivalent to `String.Empty`? Which is preferred for initializing string values?
``` public sealed class String { //... public static readonly String Empty = ""; //... } ``` Use `null` when you want to represent that there is no value; Use `String.Empty` when you want to represent that there is a value, but the value is a blank string.
String.Empty because it is a static variable, rather than "" which has to create a new string, and null means that you must then set the string equal to a new instance of a string. (thanks for the correction)
What is the difference between String.Empty and “” and null?
[ "", "c#", ".net", "" ]
If you had an array of Strings, what is the quickest way to sort this array in ascending order ?
See [java.util.Arrays.sort(Object[])](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#sort(java.lang.Object[])) ``` import java.util.*; Arrays.sort(stringarray) ```
Arrays.sort() for now. Also I heard that Josh Bloch is working on a much faster sort algorithm than the current mergesort. (I can't remember where, maybe in [this interview](http://parleys.com/display/PARLEYS/Home#title=Joshua%20Bloch%20Devoxx%20Interview;slide=1;talk=29098015). The new algorithm will perform better for partially sorted arrays and originates from a Python? sort implementation). Also see [this](https://stackoverflow.com/questions/220044/which-sort-algorithm-works-best-on-mostly-sorted-data) question.
If you had an array of Strings, what is the quickest way to sort this array in ascending order?
[ "", "java", "algorithm", "sorting", "" ]
I have a large number of classes in a project, and I would like to compile all of them from a script. The thing is, the classes should be compiled in a certain order, for example: I have a class named **A** which depends on a class named **B**. Let's say class **B** depends on a class named **C**. In order for me to compile class A, I would have to compile first B and C. Is there some tool I could use to establish the compile order of the classes, so that I don't have to parse each class and determine this myself? I would preffer that the tool can save a file with the order of the files to be compiled, so that I could parse that from my script. Thanks !
If you compile all of them at the same time (in the same `javac` invocation), you do not need to do anything of the sort you are describing. `javac` is smart enough to compile all files you give to it at the same time, so it doesn't have any problem with out-of-order compilation.
The Java compiler (Javac) already builds up a dependency list of all the class files you need to compile. The real dependency here is between ***packages*** - not individual java files ***in the same package*** (this is automatically taken care of by the compiler). Use a tool like **Ant** or **Maven** to specify and compile all the files in various packages and produce your final distribution. If you are using an IDE like NetBeans, it automatically does this for you. Alternatively, if use a tool like **[JDepend](http://clarkware.com/software/JDepend.html)**
How can I build a compile graph for Java files?
[ "", "java", "dependencies", "compilation", "" ]
I have a function that allows users to edit a row in a table by opening the data in a modal. Right now the whole row will fire the modal. What I want is to isolate the last td that contains a link that fires a function that readies the data for processing. What happens is that when that last td is clicked the modal opens AND the ready function fires. I'm trying to stop the modal from opening. I also have a mouseover row highlighting on each row of the table. This is how I associate the table rows with the modal function: ``` $("#table").find("tr").click(function(e) { //code to open model } ``` This is how I fire the ready function: ``` $("#table tr td:last-child a").click(function(e) { //code to open model } ```
i believe you need to call e.stopPropogation() to prevent the event from propogating: ``` $("#table tr td:last-child a").click(function(e) { //code to open model e.stopPropagation(); return false; } ``` **Explanation**: Events propagate from the most "specific" element up to their parents. This is called bubbling, and in this case, your second modal is being fired because the click event is bubbling up from the A element to the TR element. I believe all events propagate and bubble. Return false simply cancels the default action of the A element, which is to follow the link... it doesn't stop the event object. Here's a [good explanation](http://www.quirksmode.org/js/events_order.html) of the whole thing.
Simply add "`return false;`": ``` $("#table tr td:last-child a").click(function(e) { // whatever should happen when clicking the anchor return false; } ``` This prevents the event from propagating to the surrounding `tr`.
jquery tablerow click function
[ "", "javascript", "jquery", "event-handling", "" ]
I have a list of msgs (it could be 24 or 100+). I would need to remove many of these messages. I was wondering, what is the best way? I dont like the idea of building names for 100+ elements and doing something like doRemove = Request["msgId" + i]; I prefer receive a array such as long[] and do something like ``` long[] removeThese = Request["remove"]; foreach .... //DELETE msgId WHERE userId=@userId ``` However i dont know if creating an array and POSTing it is possible with HTML (and basic javascript?) or if its the best solution. How should i do this?
I would slap a `<asp:CheckBoxList />` on there and when you need to submit changes, just take the .SelectedValue and pass it through into your SQL parameter (wherever that is done). If you are on SQL 2008, you can take advantage of "Table-Valued Paramaters" (just google it) which you just pass any IEnumerable (pretty much any collection) in the variable and you can just JOIN to it in your UPDATE/DELETE/etc query. Previous versions of SQL, the approach I use is very similar except just the string/VARCHAR is passed in to the query and you have to create a table variable or temp table to hold the values inserted from a split procedure. There are many ways to create the split procedure, but I've found the numbers-table approach works in all versions of SQL and has pretty good performance. See <http://www.sommarskog.se/arrays-in-sql-2005.html> for exhaustive reference of the possible performance implications of each approach. Just say no to `' IN (' + @MyValuesCSV + ')'` :-)
You could create checkbox with same name ``` <input... name="mycheckbox" value="hello"></input> <input... name="mycheckbox" value="world"></input> ``` On the server side, you could use Request("mycheckbox") & this should be an array of selected Items. Alternatively, you could use asp.net checkboxlist. link - <http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkboxlist(VS.71).aspx>
How should I post/process 100 checkboxes? HTML+C#/ASP.NET
[ "", "c#", "html", "post", "" ]
i was working with a small routine that is used to create a database connection: ## Before ``` public DbConnection GetConnection(String connectionName) { ConnectionStringSettings cs= ConfigurationManager.ConnectionStrings[connectionName]; DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName); DbConnection conn = factory.CreateConnection(); conn.ConnectionString = cs.ConnectionString; conn.Open(); return conn; } ``` Then i began looking into the .NET framework documentation, to see what the **documented** behaviour of various things are, and seeing if i can handle them. For example: ``` ConfigurationManager.ConnectionStrings... ``` The [documentation](http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings.aspx) says that calling **ConnectionStrings** throws a [ConfigurationErrorException](http://msdn.microsoft.com/en-us/library/system.configuration.configurationerrorsexception.aspx) if it could not retrieve the collection. In this case there is nothing i can do to handle this exception, so i will let it go. --- Next part is the actual indexing of the **ConnectionStrings** to find *connectionName*: ``` ...ConnectionStrings[connectionName]; ``` In this instance the [ConnectionStrings documentation](http://msdn.microsoft.com/en-us/library/c6t3b6f3.aspx) says that the property will return **null** if the connection name could not be found. i can check for this happening, and throw an exception to let someone high up that they gave an invalid connectionName: ``` ConnectionStringSettings cs= ConfigurationManager.ConnectionStrings[connectionName]; if (cs == null) throw new ArgumentException("Could not find connection string \""+connectionName+"\""); ``` --- i repeat the same excercise with: ``` DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName); ``` The [GetFactory](http://msdn.microsoft.com/en-us/library/h508h681.aspx) method has no documentation on what happens if a factory for the specified `ProviderName` couldn't be found. It's not documented to return `null`, but i can still be defensive, and ***check*** for null: ``` DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName); if (factory == null) throw new Exception("Could not obtain factory for provider \""+cs.ProviderName+"\""); ``` --- Next is construction of the DbConnection object: ``` DbConnection conn = factory.CreateConnection() ``` Again the [documentation](http://msdn.microsoft.com/en-us/library/system.data.common.dbproviderfactory.createconnection.aspx) doesn't say what happens if it couldn't create a connection, but again i can check for a null return object: ``` DbConnection conn = factory.CreateConnection() if (conn == null) throw new Exception.Create("Connection factory did not return a connection object"); ``` --- Next is setting a property of the Connection object: ``` conn.ConnectionString = cs.ConnectionString; ``` The docs don't say what happens if it could not set the connection string. Does it throw an exception? Does it ignore it? As with most exception, if there was an error while trying to set the ConnectionString of a connection, there's nothing i can do to recover from it. So i'll do nothing. --- And finally, opening the database connection: ``` conn.Open(); ``` The [Open method](http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.open.aspx) of DbConnection is abstract, so it's up to whatever provider is descending from DbConnection to decide what exceptions they throw. There is also no guidance in the abstract Open methods documentation about what i can expect to happen if there's an error. If there was an error connecting, i know i cannot handle it - i'll have to let it bubble up where the caller can show some UI to the user, and let them try again. --- ## After ``` public DbConnection GetConnection(String connectionName) { //Get the connection string info from web.config ConnectionStringSettings cs= ConfigurationManager.ConnectionStrings[connectionName]; //documented to return null if it couldn't be found if (cs == null) throw new ArgumentException("Could not find connection string \""+connectionName+"\""); //Get the factory for the given provider (e.g. "System.Data.SqlClient") DbProviderFactory factory = DbProviderFactories.GetFactory(cs.ProviderName); //Undefined behaviour if GetFactory couldn't find a provider. //Defensive test for null factory anyway if (factory == null) throw new Exception("Could not obtain factory for provider \""+cs.ProviderName+"\""); //Have the factory give us the right connection object DbConnection conn = factory.CreateConnection(); //Undefined behaviour if CreateConnection failed //Defensive test for null connection anyway if (conn == null) throw new Exception("Could not obtain connection from factory"); //Knowing the connection string, open the connection conn.ConnectionString = cs.ConnectionString; conn.Open() return conn; } ``` ## Summary So my four line function, became 12 lines, and required 5 mintues of documentation lookup. In the end i did catch one case where a method is allowed to return null. But in practice all i did was convert an access violation exception (if i attempts to call methods on a null reference) into an **InvalidArgumentException**. i also catch two possible cases where there could be **null** return objects; but again i only traded one exception for another. On the positive side, it did catch two problems, and explain what happened in the exception message, rather than bad things happening down the road (i.e. the buck stops here) But is it worth it? Is this overkill? Is this defensive programming gone awry?
Manually checking for a configuration and throwing an exception is no better than just letting the framework throw the exception if the configuration is missing. You are just duplicating precondition checks which happens inside the framework methods anyway, and it makes you code verbose with no benefit. (Actually you might be *removing* information by throwing everything as the base Exception class. The exceptions thrown by the framework are typically more specific.) Edit: This answer seem to be somewhat controversial, so a bit of elaboration: Defensive programming means "prepare for the unexpected" (or "be paranoid") and one of the ways to do that is to make lots of precondition checks. In many cases this is good practice, however as with all practices cost should be weighed against benefits. For example it does not provide any benefit to throw a "Could not obtain connection from factory" exception, since it doesn't say anything about *why* the provider couldn't be obtained - and the very next line will throw an exception anyway if the provider is null. So the cost of the precondition check (in development time and code complexity) is not justified. On the other hand the check to verify that the connection string configuration is present *may* be justified, since the exception can help tell the developer how to resolve the problem. The null-exception you will get in the next line anyway does not tell the name of the connection string that is missing, so your precondition check does provide some value. If your code is part of a component for example, the value is quite big, since the user of the component might not know which configurations the component requires. A different interpretation of defensive programming is that you should not just detect error conditions, you should also try to recover from any error or exception that may occur. I don't believe this is a good idea in general. Basically you should only handle exceptions that you can *do* something about. Exceptions that you cannot recover from anyway, should just be passed upwards to the top level handler. In a web application the top level handler probably just shows a generic error page. But there is not really much to do in most cases, if the database is off-line or some crucial configuration is missing. Some cases where that kind of defensive programming makes sense, is if you accept user input, and that input can lead to errors. If for example the user provides an URL as input, and the application tries to fetch something from that URL, then it is quite important that you check that the URL looks correct, and you handle any exception that may result from the request. This allows you to provide valuable feedback to the user.
Well, it depends who your audience is. If you're writing library code that you expect to be used by a lot of other people, who won't be talking to you about how to use it, then it's not overkill. They'll appreciate your effort. (That said, if you're doing that, I suggest you define better exceptions than just System.Exception, to make it easier for people who want to catch some of your exceptions but not others.) But if you're just going to use it yourself (or you and your buddy), then obviously it's overkill, and probably hurts you in the end by making your code less readable.
How defensively should I program?
[ "", "c#", "exception", "defensive-programming", "" ]
Would anyone be able to tell me how to pull the server name out of a UNC? ex. //servername/directory/directory Edit : I apologize but it looks like I need to clarify a mistake: the path actually is more like: **//servername/d$/directory** I know this might change things a little
How about `Uri`: ``` Uri uri = new Uri(@"\\servername\d$\directory"); string[] segs = uri.Segments; string s = "http://" + uri.Host + "/" + string.Join("/", segs, 2, segs.Length - 2) + "/"; ```
Just another option, for the sake of showing different options: ``` (?<=^//)[^/]++ ``` The server name will be in `\0` or `$0` or simply the result of the function, depending on how you call it and what your language offers. Explanation in regex comment mode: ``` (?x) # flag to enable regex comments (?<= # begin positive lookbehind ^ # start of line // # literal forwardslashes (may need escaping as \/\/ in some languages) ) # end positive lookbehind [^/]++ # match any non-/ and keep matching possessively until a / or end of string found. # not sure .NET supports the possessive quantifier (++) - a greedy (+) is good enough here. ```
How to pull the server name from a UNC
[ "", "c#", "regex", "uri", "" ]
I have a few IPython scripts which have redundant functionality. I would like to refactor the common functionality into one module and include that modules in the existing script. The problem is it cannot be made a python module as the code uses Ipython's language extensions (!, $ etc). Is it possible to make a module having IPython code and include it in another IPython scripts?
You should not be saving the IPython extension stuff (`?`, `!`, `%run`) in files. Ever. Those are interactive tools and they are something you type with your hands but never save to a file. 1. Find the common features among your files. You have exactly four kinds of things that are candidates for this. * Imports (`import`) * Function definitions (`def`) * Class definitions (`class`) * Global variable assignments You must remove all IPython interactive features from this code. All of it. 2. Rewrite your scripts so they (1) import your common stuff, (2) do the useful work they're supposed to do. You must remove all IPython interactive features from this code. All of it. Now you can run your scripts and they're do their work like proper Python scripts are supposed. You can still use IPython extension features like `!`, `?` and `%run` when you're typing, but you should not save these into files.
technically if you save a script with the `.ipy` extension, ipython will see that and use all it's fancy stuff rather than passing directly to the python interpreter. however, i would generally recommend against this, and go the route of S.Lott above.
IPython Modules
[ "", "python", "module", "ipython", "" ]
So I have a few tabs in the form, and i want it to work like that: When you click on the tab's name, it becomes editable, and when i stop editing it remains with the new name. How would i do that with C# and winforms?
You can dynamically create a text box and place it over the tab area to make the user think they are editing the tab directly. When the text box loses focus you can then put the typed in value into the tabs property.
I agree with [Eric](https://stackoverflow.com/questions/1038328/how-to-make-a-tabs-name-editable-in-c/1038351#1038351), regarding how you could do this with the standard [`TabControl`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tabcontrol.aspx). You could also provide a dialog to do the name change (a slight variation on [Eric's suggestion](https://stackoverflow.com/questions/1038328/how-to-make-a-tabs-name-editable-in-c/1038351#1038351)). However, I would also recommend that you consider rolling your own tabbed control. They're not difficult to create and by rolling your own, you will be able to put in the exact functionality you need in a robust way rather than trying to piece it together from existing components that may not play nicely together.
How to make a tab's name editable in C#?
[ "", "c#", "winforms", "" ]
My project contains a large number of classes with properties whose backing field is marked readonly as they are only set at construction. As a matter of style, I like using auto-properties as it eliminates a lot of boilerplate code and encourages use of the property member rather than the backing field. However, when using an auto-property I lose the "readonly-ness" of my backing field. I understand the compiler/runtime is able to take advantage of some performance enhancements when a field is marked this way, so I would like to be able to mark my auto-property as readonly, something like this: ``` [ReadOnly] public string LastName { get; } ``` rather than ``` private readonly string _LastName; public string LastName { get { return _LastName; } } ``` Is there some mechanism already available to do this? If not, is the performance gain from the custom backing field being readonly really worthwhile? Exposing the field as public is another option, I suppose, it just seems wrong to expose a field that way. i.e. ``` public readonly string LastName; ```
I'm afraid not, but you can do this: ``` public string LastName { get; private set; } ``` Not quite as good as `readonly`, but not too bad.
No, unfortunately there's no way of doing this. Personally there are two things that I think are missing from automatically implemented properties in C# - a default value (which I believe will be in VB10) and readonly properties which can only be set in the constructor. In other words, I'd like to be able to do: ``` public class Foo { public string Tag { get; internal set; } = "Default value"; // The "readonly" would imply "private" as it could only // be set from a constructor in the same class public int Value { get; readonly set; } public Foo() { // Valid to set property here, but nowhere else Value = 20; } } ``` As Jared mentioned, this would mean changing compiler calls to the property setter into simple field assignments, and making sure they only occurred in the constructor. This would make writing immutable types simpler. Unfortunately the situation won't improve in C# 4. Let's hope we get something like this for C# 5...
Is it possible to force an auto-property to use a readonly backing field?
[ "", "c#", ".net", "" ]
I need to create a slide show of some images that can go full screen so it can be displayed via S-Video out. The software is delivered via the web so a web-based option is needed. The list of images is dynamic, and I would like to show them in order. The list of photos can change while the slideshow is running, and I would like to add the new photos to the slideshow. I see two options: 1. Build it using JavaScript and then use a browser plugin to go full screen. I have a prototype of this, however it displays photos in random order. 2. Build it using Flash. I know nothing about Flash so I am looking for slideshows that can go full screen. What would be best? Are there any good, customizable Flash slideshows?
For those interested, I ended up making an Adobe AIR application using HTML and JavaScript. Adobe AIR can go full screen and I was able to leverage the knowledge of HTML and JavaScript I already have. It has worked out pretty well, though there was a rather steep learning curve for the native AIR classes and how to use them.
If you're using Flash, [SlideShowPro](http://slideshowpro.net/) is a good option that you may recognize from sites like ESPN.
Best tool to create a full screen slide show from the web
[ "", "javascript", "flash", "image", "slideshow", "" ]
When I run the following code: ``` private void button1_Click(object sender, EventArgs e) { Bitmap b = new Bitmap(300, 400); using (Graphics g = Graphics.FromImage(b)) { g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 300, 400)); } b.RotateFlip(RotateFlipType.Rotate90FlipNone); using (Graphics g2 = Graphics.FromImage(b)) { g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 150, 100); } using (Graphics g3 = this.panel1.CreateGraphics()) { g3.DrawImage(b, 0, 0); } } ``` I get the following: [alt text http://www.freeimagehosting.net/uploads/2c309ec21c.png](http://www.freeimagehosting.net/uploads/2c309ec21c.png) Notes: * It only happens when I rotate an image, then draw a rectangle that extends past the *original* dimensions of the image. * The rectangle is not truncated to the original image width - just the right edge of the rectangle is not drawn. * This happens in a variety of scenarios. I first noticed it in a much more complicated app - I just wrote this app to make a simple illustration of the issue. Can anyone see what I'm doing wrong?
This appears to be a GDI+ bug Microsoft has been aware of since at least 2005 (<http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=96328>). I was able to repro the problem you describe. One possible solution would be to create a second bitmap off the first one, and draw on that. The following code seems to draw correctly: ``` private void button1_Click(object sender, EventArgs e) { Bitmap b = new Bitmap(300, 400); using (Graphics g = Graphics.FromImage(b)) { g.FillRectangle(Brushes.Black, new Rectangle(0, 0, 300, 400)); } b.RotateFlip(RotateFlipType.Rotate90FlipNone); Bitmap b2 = new Bitmap(b); using (Graphics g2 = Graphics.FromImage(b2)) { g2.DrawRectangle(new Pen(Color.White, 7.2f), 200, 100, 150, 100); } using (Graphics g3 = this.panel1.CreateGraphics()) { g3.DrawImage(b2, 0, 0); } } ``` [alt text http://www.freeimagehosting.net/uploads/f6ae684547.png](http://www.freeimagehosting.net/uploads/f6ae684547.png)
Your problem is DrawRectangle. The starting location of your rectangle reaches the end of your initial bitmap. If you change the location of your rectangle you will be able to see it completely. ``` using (Graphics g2 = Graphics.FromImage(b)) { g2.DrawRectangle(new Pen(Color.White, 7.2f), 50, 50, 150, 100); } ```
C#, GDI+ - Why are my rectangles truncated?
[ "", "c#", "gdi+", "rotation", "drawrectangle", "" ]
Let's say I have the following table in SQL Server 2005: ``` id | Date | Letter ----------------------------- 01 | 5/1/2009 | W 02 | 5/1/2009 | X 03 | 5/1/2009 | Y 04 | 5/1/2009 | Z 05 | 5/1/2009 | A 06 | 5/1/2009 | B 07 | 5/1/2009 | D 08 | 5/1/2009 | E 09 | 5/2/2009 | W 10 | 5/2/2009 | X 11 | 5/2/2009 | Y 12 | 5/2/2009 | Z 13 | 5/2/2009 | A 14 | 5/2/2009 | B 15 | 5/2/2009 | C 16 | 5/2/2009 | D 17 | 5/3/2009 | W 18 | 5/3/2009 | X ``` In my [previous question](https://stackoverflow.com/questions/938357/using-tsql-can-i-increment-a-char1-column-by-one-and-use-it-in-a-left-outer-jo/938371#938371), I asked how to figure out which letter sequence was missing. In my example it would letter C between row 6 and 7. I got the following answer and it works for the most part: ``` SELECT * from TABLE1 t1 LEFT OUTER JOIN TABLE2 t2 ON ASCII(t2.INTCol) - 1 = ASCII(t2.INTCol) AND t1.date = t2.date WHERE t2.id IS NULL ``` However, this solution does have two problems. It will return false positives in two cases. 1. The letter sequence starts over at 'W' everyday. So, I get a false positive result for the last record of every day. That would be row 8 and 16 in my example data. 2. Since the sequence starts over at 'W' everyday, I get a false positive for the 'Z' record because ('Z' + 1) gives me a '[', not an 'A'. For #2 I believe I can put in an "IF" statement that says: "If this is a Z, look for an A" but I'm open to any 'cleaner' solutions. I really have no idea how to do #1, so I'm really looking for help on that one. **EDIT:** Something I left out, doing a MAX(t1.id) isn't going to work, as the rows aren't always inserted in sequence. In fact, looking at my data, it's always inserted in [a-z] order even though the first record is the 'w'. I know it's lame, but I'm dealing with log files from dozens of million dollar phone switches. Not much I can do about it.
Rollover: use mod. Days: add a predicate that excludes the final entry of each day. ``` create view missing_letter as SELECT * from TABLE1 t1 LEFT OUTER JOIN TABLE2 t2 ON t1.id = t2.id AND t1.date = t2.date and mod( ascii(t1.letter) - ascii('A'), ascii('Z') + 1 ) <> mod( ascii(t2.letter) - ascii('A'), ascii('Z') + 1 ) - 1 and t1.id < (select max(t3.id) from table t3 where t3.date = t1.date) ; ``` A better solution would be to come up with an auxiliary table of ordered allowed letters, and find all the letters in that auxiliary table that are missing ("... where not exists ...") where any of those letters comes before the highest letter in your table.
How's this? ``` SELECT * FROM ( SELECT CASE WHEN t1.date = t2.date AND (ASCII(t2.IntCol) = 90 AND ASCII(t1.IntCol) <> 65) THEN 1 WHEN t1.date = t2.date AND ASCII(t2.IntCol) <> ASCII(t1.IntCol) + 1 THEN 1 ELSE 0 END AS IsMissing, t1.* from TABLE1 t1 LEFT OUTER JOIN TABLE1 t2 ON t1.id +1 = t2.id ) as a WHERE a.IsMissing = 1 ```
Using TSQL, how can I tell if my CHAR is last one in a sequence? Also, what if the letter sequences "rolls over" from 'z' to 'a'?
[ "", "sql", "database", "algorithm", "t-sql", "" ]
I'm trying to write a simple utility method for adding aninteger number of days to a Joda time [instant](http://www.joda.org/joda-time/apidocs/org/joda/time/Instant.html). Here is my first stab. ``` /** * Adds a number of days specified to the instant in time specified. * * @param instant - the date to be added to * @param numberOfDaysToAdd - the number of days to be added to the instant specified * @return an instant that has been incremented by the number of days specified */ public static Instant addNumberOfDaysToInstant(final Instant instant, final int numberOfDaysToAdd) { Days days = Days.days(numberOfDaysToAdd); Interval interval = new Interval(instant, days); return interval.getEnd().toInstant(); } ``` This works fine for the most part except when you consider the example when the number of days added takes you across the BST / GMT boundary. Here is a small example. ``` public class DateAddTest { ``` /\*\* \* Zone to use for input and output \*/ private static final DateTimeZone ZONE = DateTimeZone.forId("Europe/London"); ``` /** * Formatter used to translate Instant objects to & from strings. */ private static final DateTimeFormatter FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT).withZone(ZONE); /** * Date format to be used */ private static final String DATE_FORMAT = "dd/MM/yyyy"; public static void main(String[] args) { DateTime dateTime = FORMATTER.parseDateTime("24/10/2009"); Instant toAdd = dateTime.toInstant(); Instant answer = JodaTimeUtils.addNumberOfDaysToInstant(toAdd, 2); System.out.println(answer.toString(FORMATTER)); //25/10/2009 } ``` } I think this problem is because the interval does not take into acount the fact that it has crossing the bst boundary. Any ideas of a better way to implement this would be appreciated.
This is the solution that was chosen. ``` /** * Zone to use for input and output */ private static final DateTimeZone ZONE = DateTimeZone.forId("Europe/London"); /** * Adds a number of days specified to the instant in time specified. * * @param instant - the date to be added to * @param numberOfDaysToAdd - the number of days to be added to the instant specified * @return an instant that has been incremented by the number of days specified */ public static Instant addNumberOfDaysToInstant(final Instant instant, final int numberOfDaysToAdd) { return instant.toDateTime(ZONE).withFieldAdded(DurationFieldType.days(), numberOfDaysToAdd).toInstant(); } ```
If you want to deal with *dates*, don't use instants. I suspect it's correctly adding 48 hours to the instant. Use a `LocalDate` instead, and then the `plusDays` method. If you want to know the instant that occurs n days after the specified instant, at the same time of day, we could no doubt work out a way of doing that (split the instant into a `LocalDate` and a `LocalTime`, advance the `LocalDate` and then reassemble, or check whether `LocalDateTime` does what you want) but you need to work out what you want to happen if the original time occurs twice on the new day, or doesn't occur at all. EDIT: Okay, so you need to work with an instant. Does that have to be in an original time zone? Could you use UTC? That would take away the DST issues. If not, what do you want it to do in cases of ambiguity or non-existence (e.g. at 12.30am before each of the transitions).
Adding a number of days to a JodaTime Instant
[ "", "java", "datetime", "jodatime", "" ]
I'm having some trouble getting my cache to work the way I want. **The problem:** The process of retrieving the requested data is very time consuming. If using standard ASP.NET caching some users will take the "hit" of retrieving the data. This is not acceptable. **The solution?:** It is not super important that the data is 100% current. I would like to serve old invalidated data while updating the cached data in another thread making the new data available for future requests. I reckon that the data needs to be persisted in some way in order to be able to serve the first user after application restart without that user taking the "hit". I've made a solution which does somewhat of the above, but I'm wondering if there is a "best practice" way or of there is a caching framework out there already supporting this behaviour?
I created my own solution with a Dictionary/Hashtable in memory as a duplicate of the actual cache. When a method call came in requesting the object from cache and it wasn't there but was present in memory, the memory stored object was returned and fired a new thread to update the object in both memory and the cache using a delegate method.
There are tools that do this, for example Microsofts ISA Server (may be a bit expensive / overkill). You can cache it in memory using Enterprise Libary Caching. Let your users read from Cache, and have other pages that update the Cache, these other pages should be called as regularly as you need to keep the data upto date.
ASP.NET Persistent Caching ("Lazy loading"-style?)
[ "", "c#", "asp.net", "caching", "" ]
How can I setup expires headers in PHP + Apache? I'm currently using an auto\_prepend to serve resources gzipped but I'd also like to maximise the HTTP cache. How can I set these up?
There are two ways to do this. The first is to specify the header in your php code. This is great if you want to programatically adjust the expiry time. For example a wiki could set a longer expires time for a page which is not edited very often. ``` header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // 1 hour ``` Your second choice is to create an **.htaccess** file or modify your httpd config. In a shared hosting environment, modifying your .htaccess file is quite common. In order to do this, you need to know if your server supports **mod\_expires**, **mod\_headers** or both. The easiest way is simply trial and error, but some Apache servers are configured to let you view this information via the /server-info page. If your server has both mod\_expires and mod\_headers, and you want to set the expiry on static resources, try putting this in your .htaccess file: ``` # Turn on Expires and set default to 0 ExpiresActive On ExpiresDefault A0 # Set up caching on media files for 1 year (forever?) <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$"> ExpiresDefault A29030400 Header append Cache-Control "public" </FilesMatch> ``` For other combinations and more examples see: <http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html>
This Apache module might be of help: <http://httpd.apache.org/docs/2.0/mod/mod_expires.html>
Setup HTTP expires headers using PHP and Apache
[ "", "php", "performance", "apache", "http", "" ]
How to set column header text for specific column in Datagridview C#
there is **HeaderText** property in Column object, you can find the column and set its HeaderText after initializing grid or do it in windows form designer via designer for DataGrid. ``` public Form1() { InitializeComponent(); grid.Columns[0].HeaderText = "First Column"; //.............. } ``` More details are [here](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.columns.aspx) at MSDN. More details about DataGrid are [here](http://msdn.microsoft.com/en-us/library/e0ywh3cz.aspx).
For info, if you are binding to a class, you can do this in your type via `DisplayNameAttribute`: ``` [DisplayName("Access key")] public string AccessKey { get {...} set {...} } ``` Now the header-text on auto-generated columns will be "Access key".
How to set column header text for specific column in Datagridview C#
[ "", "c#", ".net", "winforms", "datagridview", "" ]
Hi I'm currently trying to post an xml file to an external server, but I'm getting a response back that the headers are incorrect. The server I'm posting requires some headers and I'm wondering if they're in the correct format or if there are any other "standard" headers that need to be included? My code is: ``` <?php function httpsPost($Url, $xml_data, $headers) { // Initialisation $ch=curl_init(); // Set parameters curl_setopt($ch, CURLOPT_FORBID_REUSE, 1); curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_URL, $Url); // Return a variable instead of posting it directly curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch,CURLOPT_USERPWD,"username:password"); // Active the POST method curl_setopt($ch, CURLOPT_POST, 1) ; // Request curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // execute the connexion $result = curl_exec($ch); // Close it curl_close($ch); return $result; } $headers[0]="BATCH_TYPE: XML_SINGLE"; $headers[1]="BATCH_COUNT: 1"; $headers[2]="VENDOR_ID: 53906"; $request_file = "./post_this.xml"; $fh = fopen($request_file, 'r'); $xml_data = fread($fh, filesize($request_file)); fclose($fh); $url = 'http://www.example.com/test.php'; $Response = httpsPost($url, $xml_data, $headers); echo $Response; ?> ```
I've done a bunch of research on this one, but I don't have any definitive answer. I'll go out on a limb and say that I think the problem is that your headers are using underscores instead of dashes. I can't think of any standard HTTP header that uses underscores. This is perfectly legal per the [HTTP 1.1 specification](http://www.w3.org/Protocols/rfc2616/rfc2616.html). According to RFC 2616: ``` message-header = field-name ":" [ field-value ] field-name = token token = 1*<any CHAR except CTLs or separators> separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT ``` If it's an option, I suggest changing the server to expect Batch-Type, Batch-Count and Vendor-Id. If Curl is changing your header names behind your back, you should [report it as a bug](http://curl.haxx.se/docs/bugs.html).
If I use a local script as the script being posted to, the output is correct. The local script simply consists of ``` <?php phpinfo(); ?> ``` So, I guess the problem is not with your code but with the display at <http://www.xhaus.com/headers>. That site seems to replace underscores with dashes for display. Why use that url for displaying the results and not your own phpinfo-script?
PHP - HTTP Post - incorrect headers
[ "", "php", "httpwebrequest", "http-headers", "" ]
I have a file containing lots of data put in a form similar to this: ``` Group1 { Entry1 { Title1 [{Data1:Member1, Data2:Member2}] Title2 [{Data3:Member3, Data4:Member4}] } Entry2 { ... } } Group2 { DifferentEntry1 { DiffTitle1 { ... } } } ``` Thing is, I don't know how many layers of parentheses there are, and how the data is structured. I need modify the data, and delete entire 'Entry's depending on conditions involving data members before writing everything to a new file. What's the best way of reading in a file like this? Thanks!
I have something similar but written in java. It parses a file with the same basic structure with a little different syntax (no '{' and '}' only indentation like in python). It is a very simple script language. Basically it works like this: It uses a stack to keep track of the inner most block of instructions (or in your case data) and appends every new instruction to the block on the top. If it parses an instruction which expects a new block it is pushed to the stack. If a block ends it pops one element from the stack. I do not want to post the entire source because it is big and it is available on google code (lizzard-entertainment, revision 405). There is a few things you need to know. * Instruction is an abstract class and it has a block\_expected method to indicate wether the concrete instruction needs a block (like loops, etc) In your case this is unnecessary you only need to check for '{'. * Block extends Instruction. It contains a list of instructions and has an add method to add more. * indent\_level return how many spaces are preceding the instruction text. This is also unneccessary with '{}' singns. placeholder ``` BufferedReader input = null; try { input = new BufferedReader(new FileReader(inputFileName)); // Stack of instruction blocks Stack<Block> stack = new Stack<Block>(); // Push the root block stack.push(this.topLevelBlock); String line = null; Instruction prev = new Noop(); while ((line = input.readLine()) != null) { // Difference between the indentation of the previous and this line // You do not need this you will be using {} to specify block boundaries int level = indent_level(line) - stack.size(); // Parse the line (returns an instruction object) Instruction inst = Instruction.parse(line.trim().split(" +")); // If the previous instruction expects a block (for example repeat) if (prev.block_expected()) { if (level != 1) { // TODO handle error continue; } // Push the previous instruction and add the current instruction stack.push((Block)(prev)); stack.peek().add(inst); } else { if (level > 0) { // TODO handle error continue; } else if (level < 0) { // Pop the stack at the end of blocks for (int i = 0; i < -level; ++i) stack.pop(); } stack.peek().add(inst); } prev = inst; } } finally { if (input != null) input.close(); } ```
The data structure basically seems to be a dict where they keys are strings and the value is either a string or another dict of the same type, so I'd recommend maybe pulling it into that sort of python structure, eg: ``` {'group1': {'Entry2': {}, 'Entry1': {'Title1':{'Data4': 'Member4', 'Data1': 'Member1','Data3': 'Member3', 'Data2': 'Member2'}, 'Title2': {}}} ``` At the top level of the file you would create a blank dict, and then for each line you read, you use the identifier as a key, and then when you see a { you create the value for that key as a dict. When you see Key:Value, then instead of creating that key as a dict, you just insert the value normally. When you see a } you have to 'go back up' to the previous dict you were working on and go back to filling that in. I'd think this whole parser to put the file into a python structure like this could be done in one fairly short recursive function that just called itself to fill in each sub-dict when it saw a { and then returned to its caller upon seeing }
Parsing an unknown data structure in python
[ "", "python", "parsing", "data-structures", "" ]
The following code is a simplified version of what I use for event dispatching. The essential point is that there is a static\_cast<T\*> on the argument of a template functor and another class makes sure that the argument passed to the functor is what the static\_cast casts to. ``` struct AbstractArg { virtual ~AbstractArg() { } }; struct AbstractFunctor { virtual void operator()(AbstractArg*) const = 0; virtual ~AbstractFunctor() { } }; namespace evil { template<typename ArgT> struct CastingFunctor : AbstractFunctor { void operator()(AbstractArg* aarg) const { ArgT* arg = static_cast<ArgT*>(arg); // Danger! // ... do stuff with it } }; } // namespace evil class TypeidManager { public: typedef std::map<std::string, AbstractFunctor*> map_type; void dispatch(AbstractArg* arg) const { map_type::const_iterator it = typeid_map.find(std::string(typeid(*arg).name())); if (it != typeid_map.end()) { AbstractFunctor* pFunctor = it->second; (*pFunctor)(arg); } }; template<typename ArgT> void register_func( void (*fun_ptr)(ArgT*)) { typeid_map.insert(std::make_pair(std::string(typeid(ArgT).name()), new evil::CastingFunctor<ArgT>)); } private: map_type typeid_map; }; ``` Is there a name for this pattern? Thanks!
This isn't an anti-pattern, it's a really useful technique often used with type erasure.
I think it is an anti-pattern, not a pattern. Normally the things you want to feed to the functors via the typeid\_map construct would come from a common inheritance hierarchy and you would use dynamic polymorphism (= virtual methods) instead. Basically you have reinvented virtual method table lookup (in a very inefficient manner).
Is there a pattern which names managing evil static_casts
[ "", "c++", "design-patterns", "" ]
I have anchor link with both href and `onclick` events specified. The `onclick` sets `location.href` to server URL and href to a other link. When the link is clicked the href event gets called always but `onclick` event gets called only once (that is only for one anchor link). If I debug JavaScript it works properly that it calls both href and `onclick`. What can be the problem?
Try ``` <a href="whatever.html" onclick='window.location.href="http://whereverelse";return false;'>linky</a> ``` just to explain: returning false in this case prevents the default action. Why would you want to do this though?
It sounds like you want the link to call a page that runs server-side code (such as PHP) and then direct the browser to another location. That's typically done by having the server-side script send a redirect response with the second URL.
Href and onclick issue in anchor link
[ "", "javascript", "dom-events", "" ]
Why doesn't C# have local static variables like C? I miss that!!
You can simulate it using a delegate... Here is my sample code: ``` public Func<int> Increment() { int num = 0; return new Func<int>(() => { return num++; }); } ``` You can call it like this: ``` Func<int> inc = Increment(); inc(); ```
Because they screwed up, and left out a useful feature to suit themselves. All the arguments about how you should code, and what's smart, and you should reconsider your way of life, are pompous defensive excuses. Sure, C# is pure, and whatchamacallit-oriented. That's why they auto-generate persistent locals for lambda functions. It's all so complicated. I feel so dumb. Loop scope static is useful and important in many cases. Short, real answer, is you have to move local statics into class scope and live with class namespace pollution in C#. Take your complaint to city hall.
Why doesn't C# support local static variables like C does?
[ "", "c#", "static", "" ]
I've got a query that looks a bit like this: ``` select records.id, contacts.name + ' (' + contacts.organization + ')' as contact, from records left join contacts on records.contact = contacts.contactid ``` Problem is - `contacts.organization` is frequently empty, and I get contacts like "John Smith ()". Is there a way to only concatenate the organization if it's non-empty?
Use a CASE statement ``` SELECT records.id, CASE contacts.organization WHEN '' THEN contacts.name ELSE contacts.name + ' (' + contacts.organization + ')' END as Contact FROM records LEFT JOIN contacts ON records.contact = contacts.contactid ``` You could modify it to also check for NULL values, but I do not believe you have that issue because if you had a NULL in your contacts.organization, your entire result field would be null instead of blank.
Not sure if this is the best way to do it: ``` CASE contacts.organization WHEN '' THEN '' ELSE '(' + contacts.organzation + ')' END ```
Conditionals in transact-sql select column lists
[ "", "sql", "t-sql", "" ]
We're deploying an application on a semi-embedded device that has memory constraints. Looking to save whatever we can we are analysing heap dumps of the app and attacking the biggest consumers. We use Spring 2.5 together with Spring DM 1.1 and we notice that some of our bundles with more complex Spring contexts are using up quite a bit of memory since Spring seems to keep around the entire object graph containing all the BeanDefinitions that were parsed from the XML. I would assume that most of this is unnecessary once the app has been initialized and everything is injected. Are there configuration options for Spring that allow one to control this behaviour? Run in some low memory mode? Throw away all unnecessary things? Trade computation time for size?
I had team members have a deeper look at this and had some interesting results. Spring in its default configuration is very much not interested in being especially conservative in its memory usage. There are 2 basic aspects that can be tweaked for significant gains: * The first is a non-exposed property inside the Spring `OsgiBundleXmlApplicationContext` that you can override if you extend from that class and override the `customizeBeanFactory` method. We did it like this: ``` @Override protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) { super.customizeBeanFactory(beanFactory); String cacheBeanMetadataSysProp = System.getProperty(CACHE_BEAN_METADATA, "true"); if (cacheBeanMetadataSysProp != null && cacheBeanMetadataSysProp.equalsIgnoreCase("false")) { beanFactory.setCacheBeanMetadata(false); } else if (cacheBeanMetadataSysProp != null && cacheBeanMetadataSysProp.equalsIgnoreCase("true")) { beanFactory.setCacheBeanMetadata(true); } } ``` Setting the "setCacheBeanMetadata" property to `false` causes the `BeanDefinitions` (basically the programmatic mirror of your XML based configuration) to be discarded after initialization. * The second change - that we currently have a prototype for - is a patch for the Spring source code to do lazy initialization of collections. It turns out that many internal Spring objects that represent Beans and all their properties have a lot of members that are initialised to HashMaps and other collections by default but are very rarely filled with data. Changing the Spring framework to initialize these lazily will save another significant amount of memory but it is a much more invasive change.
You can save *some* memory with a BeanFactory - see [3.8.1. BeanFactory or ApplicationContext](http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#context-introduction-ctx-vs-beanfactory): > As the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended that it be used in preference to the BeanFactory, except for a few limited situations such as in an Applet, where memory consumption might be critical and a few extra kilobytes might make a difference.
How can I configure Spring to save as much memory as possible?
[ "", "java", "spring", "memory", "heap-memory", "applicationcontext", "" ]
A few days ago, [you helped me to find out an algorithm for generating random strength values in an online game (thx especially John Rasch)](https://stackoverflow.com/questions/921570/generate-random-player-strengths-in-a-pyramid-structure-php). ``` function getRandomStrength($quality) { $rand = mt_rand()/mt_getrandmax(); $value = round(pow(M_E, ($rand - 1.033) / -0.45), 1); return $value; } ``` This function generates values between 1.1 and 9.9. Now I want to adjust this function so that it gives me values of the same probability but in another interval, e.g. 1.5 to 8.0. It would be perfect if you could achieve this with additional parameters. It would be great if you could help me. Thanks in advance!
The values 1.033 and -0.45 in the original code are the magic numbers that provide the scale 1.1 - 9.9. You should get the same results if you pass in 1.1 and 9.9 as the parameters `$low` and `$high` in the following code. ``` function getRandomStrength($low, $high) { // TODO: validate the input $ln_low = log( $low, M_E ); $ln_high = log( $high, M_E ); $scale = $ln_high - $ln_low; $rand = ( mt_rand() / mt_getrandmax() ) * $scale + $ln_low; $value = round( pow( M_E, $rand), 1 ); return $value; } ``` You should be able to pass in any range for `$low` and `$high` and get a logarithmic distribution in that range. (I'll leave range validity checking to you, but 0 < `$low` < `$high` should be true.) This works by back calculating the linear scale necessary to generate the logarithmic scale in the provided range. If I want my log scale to be 1.1 - 9.9, for example, I take the natural log of each of those values, giving me 0.0953 - 2.2925. I then generate a random number in this *linear* range, and raise `e` to the random power to convert it back to the log range.
One way would just be to scale the values: ``` function getRandomStrength($quality,$min,$max) { $rand = mt_rand()/mt_getrandmax(); $value = round(pow(M_E, ($rand - 1.033) / -0.45), 1); $value = $value - 1.1 $value = $value * ((max-min) / 8.8) $value = $value + $min return $value; } ```
Adjust algorithm for generating random strength values
[ "", "php", "algorithm", "random", "statistics", "" ]
``` class A { public: int i; }; A *a = new A(); ``` How to get the address of `a->i`? I tried `&a->i` and also `&(a->i)` but those generate compile time errors: "left of '.i' must have class/struct/union type"
You have not provided the same code you tried to compile. Always **copy and paste**. The tells in your code are that you don't have a syntactically correct class declaration or variable declaration, and that your error message talks about ".i" when you've claimed you've only used `a->i`. Here's working code: ``` #include <stdio.h> class A { public: int i; }; int main() { A* a = new A(); int* i = &a->i; printf("a: %p\na->i: %p\n", a, i); return 0; } ``` Ultimately, the syntax you *say* you tried for getting the address of the member was correct. The syntax the error message says you tried was `a.i`. That doesn't work, and for the reason the error message gave. The variable `a` is not a class, struct, or union type. Rather, it's a *pointer* to one of those types. You need to dereference the pointer to get at the member. When I run it, I get this: ``` $ ./a.out a: 40748 a->i: 40748 ``` The addresses are the same because `A` is a simple class, so this output is to be expected. The first member is frequently placed at the very start of a class's memory. Add a second member variable to the class and get its address; you should see different values then.
In c++: ``` class A { public: // note colon after public int i; }; // note semicolon after bracket A *a = new A(); // note *a not a* ``` to print: ``` cout << ios::hex << &a->i << endl; ``` For me this seems to work ok.
In C++, how to get the address in which the value of a class instance's field is stored?
[ "", "c++", "pointers", "" ]
Lately, I have taken to the pattern of having a lot of diagnostic logging in parts of my code, that makes use of lambda expressions/anonymous delegates like so: ``` MyEventManager.LogVerbose( LogCategory.SomeCategory, () => String.Format(msg_string, GetParam1(), GetParam2(), GetParam3() ); ``` Notice that the second argument to LogVerbose is a lambda expression which evaluates to a string. The reason for this is that if verbose logging is not actually enabled, LogVerbose should exit having done as little work as possible, in order to minimize performance impact. The construction of the error message string may, in some cases, take time or resources, and if the lambda expression is never evaluated, that performance penalty will not be incurred. I'm wondering if littering the type system with so many anonymous delegates like this will have some unforeseen consequence for application performance, or if there are any other strategies I should consider.
It should be fine. In particular, if your anonymous function doesn't capture anything, it is cached as a static field (because it can be). If you capture "`this`" then you'll end up creating new delegate instances, but they're not expensive. If you capture local variables, that will involve instantiating a nested type - but I'd only worry about this if you saw it actually becoming a problem. As ever with optimisation, focus on readability first, measure the performance, and then profile it to find out where you need to concentrate your efforts.
Whilst I don't actually know for sure the answer to the question, I think its worth considering that a drive to a more functional style of programming in C# would be seriously undermined if there were any suggestion that there would some kind of limit on the use of such expressions.
Is it possible to have too many anonymous delegates?
[ "", "c#", ".net", "performance", "logging", "" ]
Using regular expressions in C#, is there any way to find and remove duplicate words or symbols in a string containing a variety of words and symbols? **Ex.** **Initial string of words:** "I like the environment. The environment is good." **Desired string:** "I like the environment. is good" **Duplicates removed:** "the", "environment", "."
As said by others, you need more than a regex to keep track of words: ``` var words = new HashSet<string>(); string text = "I like the environment. The environment is good."; text = Regex.Replace(text, "\\w+", m => words.Add(m.Value.ToUpperInvariant()) ? m.Value : String.Empty); ```
This seems to work for me ``` (\b\S+\b)(?=.*\1) ``` Matches like so ``` apple apple orange orange red blue green orange green blue pirates ninjas cowboys ninjas pirates ```
Regular expression to find and remove duplicate words
[ "", "c#", "regex", "string", "" ]
I have to make a graphical user interface application using the language of my choice. The application will run on Windows XP. It will be some sort of a complex windows form application. I think and as per most suggestions, C# will be the best to use. The tree structure on the left of the GUI will populate after reading from a configuration file which will be a binary file . (but initially I can work with a simple ASCII file to test my code.). The application will accept some inputs from the user through this GUI and will write the back to the same config file and will reflect the changes in the tree structure or the labels or any other pertaining field on the form. There will be 3 tabs and 3 corresponding config files for each of the tabs. I need some help designing the application for now. I am planning to make a host application (main application) and use the 3 tab controls as plugins. Is this workable ? If so can you please guide me on this. I mean how do I make 3 plugins in C# and how do I write the interfaces so that the main application knows which plugin to load and when to load it ? Will there be a separate “Plugin” folder under my project folder ? I hope you got my point though this is too little of an information for you to begin with. Also there are some .cpp files already existing in the project. These files along with some .h files contain some important definitions and constants in them. These need to be integrated with my C# application. I have no clue how to do that but I am sure that it is possible by compiling the .cpp code in a .dll and then exposing the compiled .dll to my C# application. Please let me know if you need some more information for the top level design. Thanks, Viren
To implement a plugin interface manually, you will need a method something like this. I've left some TODOs in, where you would want to enhance the error handling and/or make the implementation a little more case specific. ``` public List<T> LoadPlugin<T>(string directory) { Type interfaceType = typeof(T); List<T> implementations = new List<T>(); //TODO: perform checks to ensure type is valid foreach (var file in System.IO.Directory.GetFiles(directory)) { //TODO: add proper file handling here and limit files to check //try/catch added in place of ensure files are not .dll try { foreach (var type in System.Reflection.Assembly.LoadFile(file).GetTypes()) { if (interfaceType.IsAssignableFrom(type) && interfaceType != type) { //found class that implements interface //TODO: perform additional checks to ensure any //requirements not specified in interface //ex: ensure type is a class, check for default constructor, etc T instance = (T)Activator.CreateInstance(type); implementations.Add(instance); } } } catch { } } return implementations; } ``` Example to call: ``` List<IPlugin> plugins = LoadPlugin<IPlugin>(path); ``` As for the c++ part of your question. There are few different ways you could approach this, though the correct choice depends on your specific situation. You can make a clr compliant .dll in c++, which your c# project could reference and call like any other .dll it references. Additionally, you could use [P/Invoke](http://msdn.microsoft.com/en-us/magazine/cc164123.aspx) to call into a native .dll.
One of the easiest plugin concepts I have ever used was certainly the [Managed Extensibility Framework](http://www.codeplex.com/MEF) which will be part of .NET 4 (afaik). Unfortunately it is not yet finished and only a preview is available which may differ from the final version. That being said, we used MEF Preview 3 for a uni project and it worked without problems and it certainly made the whole plugin stuff a lot easier.
Plugin based application in C#
[ "", "c#", "plugins", "" ]
This is a question I ran into about expanding on an element's JavaScript onchange event. I have several select elements that conditionally will have one onchange event attached to each of them (when they change to specific values, it hides/unhides certain elements). I want to conditionally add or append to another onchange event so they set a global variable if they do change without modifying or disabling the previous function already attached to them. Is there a way to "append" an additional function or add more functionality onto the already existing one? Here is what I believe an example would be like: ``` <select id="selectbox1"> <option>...</option> <option>...</option> </select> if (<certain conditions>) { document.getElementById("selectbox1").onchange = function () { //hides elements to reduce clutter on a web form ... } } .... if (<other conditions>) { document.getElementById("selectbox1").onchange = function2 () { //set global variable to false } } ``` Alternatively I'd like to simply add the 1-liner "set global variable to false" to the original function.
You can cheat by simply having a composite function that calls the other functions. ``` document.getElementById("selectbox1").onchange = function() { function1(); function2(); } ``` You can also use the observer pattern, described in the book [*Pro JavaScript Design Patterns*](http://jsdesignpatterns.com/). I have an example of its use in an article ([here](http://codecube.net/2009/06/mvc-pattern-with-javascript/)). ``` //– publisher class — function Publisher() { this.subscribers = []; }; Publisher.prototype.deliver = function(data) { this.subscribers.forEach(function(fn) { fn(data); }); }; //– subscribe method to all existing objects Function.prototype.subscribe = function(publisher) { var that = this; var alreadyExists = publisher.subscribers.some(function(el) { if (el === that) { return; } }); if (!alreadyExists) { publisher.subscribers.push(this); } return this; }; ```
You want to look at the `addEventListener()` and `attachEvent()` functions (for Mozilla-based browsers and IE respectively). Take a look at the docs for [addEventListener()](https://developer.mozilla.org/en/DOM/element.addEventListener) and [attachEvent()](http://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx). ``` var el = document.getElementById("selectbox1"); try { //For IE el.attachEvent("onchange", function(){ code here.. }); } catch(e) { //For FF, Opera, Safari etc el.addEventListener("change", function(){ code here.. }, false); } ``` You can add multiple listeners to each element, therefore more than one function can be called when the event fires.
How to expand an onchange event with JavaScript
[ "", "javascript", "html", "onchange", "" ]
I am often facing design patterns, and I find most articles explaining them a bit hard to understand, especially since I don't speak English fluently. I would very much appreciate if someone could explain simply and in basic English the following design patterns: Builder, Prototype, Bridge, Composite, Decorator, Facade, Flyweight, Proxy and Observer. Or if you have any links to good resources, I'm willing to spend the time to try to understand it.
I highly, highly, HIGHLY recommend the [Gang of Four](http://en.wikipedia.org/wiki/Gang_of_Four_(software)) Book. It is such a good lookup tool for design patterns, although it may be difficult to read if you're not fluent in English. Here is a list of the design patterns with examples for PHP, you may want to have a look at this: <http://www.fluffycat.com/PHP-Design-Patterns/>
I would recommend taking a look at [Head First Design Patterns](http://oreilly.com/catalog/9780596007126/) as it is a very approachable design patterns book. There are quite a few [sample pages](http://oreilly.com/catalog/9780596007126/preview.html) on the O'Reilly website so you can get a good idea of what it's like.
A simple explanation of common design patterns for non-native English speakers
[ "", "php", "design-patterns", "oop", "" ]
``` String[] a = c.toArray(new String[0]); ``` First: Do I need type cast here? (I think we should write like `(String[])c.toArray();` BUT I have seen it as just `c.toArray()` without using type cast. Is this valid? Second: Also why we write `new String[0]`?
The type cast is usually only needed if you're using pre-generics Java. If you look at the docs for `Collection.toArray(T[])` you'll see that it knows that the type of the array which is returned is the same as the type of array passed in. So, you can write: ``` List<String> list = new ArrayList<String>(); list.add("Foo"); String[] array = list.toArray(new String[0]); ``` You pass in the array to tell the collection what result type you want, which may not be the same as the type in the collection. For example, if you have a `List<OutputStream>` you may want to convert that to an `Object[]`, a `Stream[]` or a `ByteArrayOutputStream[]` - obviously the latter is only going to work if every element actually *is* a `ByteArrayOutputStream`. It also means that if you already have an array of the right type and size, the contents can be copied into that instead of creating a new array. A previous version of this answer was inaccurate, by the way - if you use the overload which doesn't take any parameters, you *always* get back an `Object[]` which can't be cast: ``` List<String> list = new ArrayList<String>(); list.add("Foo"); // toArray doesn't know the type of array to create // due to type erasure Object[] array = list.toArray(); // This cast will fail at execution time String[] stringArray = (String[]) arrray; ``` EDIT: I've just noticed this is also mentioned in erdemoo's answer, but it can't hurt to have it here too :)
if you are using list.toArray(), it will return you Object array. Casting to String array will throw exception even if elements stored in list are String type. if you are using list.toArray(Object[] a), it will store elements in list to "a" array. If the elements inside the list are String and you give String array then it will store elements inside String array, if given array is not large enough to store elements inside the list, then it will expand given list.
Should we use type cast for the object.toArray()?
[ "", "java", "arrays", "list", "" ]
Does anyone have any advice on which method is better when caching data in a C# ASP.net application? I am currently using a combination of two approaches, with some data (List, dictionaries, the usual domain-specific information) being put directly into the cache and boxed when needed, and some data being kept inside a globaldata class, and retrieved through that class (i.e. the GlobalData class is cached, and it's properties are the actual data). Is either approach preferable? I get the feeling that caching each item separately would be more sensible from a concurrency point of view, however it creates a lot more work in the long run with more functions that purely deal with getting data out of a cache location in a Utility class. Suggestions would be appreciated.
Ed, I assume those lists and dictionaries contain almost static data with low chances of expiration. Then there's data that gets frequent hits but also changes more frequently, so you're caching it using the HttpRuntime cache. Now, you should think of all that data and all of the dependencies between diferent types. If you logically find that the HttpRuntime cached data depends somehow on your GlobalData items, you should move that into the cache and set up the appropriate dependencies in there so you'll benefit of the "cascading expiration". Even if you do use your custom caching mechanism, you'd still have to provide all the synchronization, so you won't save on that by avoiding the other. If you need (preordered) lists of items with a really low frequency change, you can still do that by using the HttpRuntime cache. So you could just cache a dictionary and either use it to list your items or to index and access by your custom key.
Generally the cache's performance is so much better than the underlying source (e.g. a DB) that the performance of the cache is not a problem. The main goal is rather to get as high cache-hit ratio as possible (unless you are developing at really large scale because then it pays off to optimize the cache as well). To achieve this I usually try to make it as straight forward as possible for the developer to use cache (so that we don't miss any chances of cache-hits just because the developer is too lazy to use the cache). In some projects we've use a modified version of a CacheHandler available in Microsoft's Enterprise Library. With CacheHandler (which uses [Policy Injection](http://msdn.microsoft.com/en-us/library/cc309507.aspx)) you can easily make a method "cacheable" by just adding an attribute to it. For instance this: ``` [CacheHandler(0, 30, 0)] public Object GetData(Object input) { } ``` would make all calls to that method cached for 30 minutes. All invocations gets a unique cache-key based on the input data and method name so if you call the method twice with different input it doesn't get cached but if you call it >1 times within the timout interval with the same input then the method only gets executed once. Our modified version looks like this: ``` using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Remoting.Contexts; using System.Text; using System.Web; using System.Web.Caching; using System.Web.UI; using Microsoft.Practices.EnterpriseLibrary.Common.Configuration; using Microsoft.Practices.Unity.InterceptionExtension; namespace Middleware.Cache { /// <summary> /// An <see cref="ICallHandler"/> that implements caching of the return values of /// methods. This handler stores the return value in the ASP.NET cache or the Items object of the current request. /// </summary> [ConfigurationElementType(typeof (CacheHandler)), Synchronization] public class CacheHandler : ICallHandler { /// <summary> /// The default expiration time for the cached entries: 5 minutes /// </summary> public static readonly TimeSpan DefaultExpirationTime = new TimeSpan(0, 5, 0); private readonly object cachedData; private readonly DefaultCacheKeyGenerator keyGenerator; private readonly bool storeOnlyForThisRequest = true; private TimeSpan expirationTime; private GetNextHandlerDelegate getNext; private IMethodInvocation input; public CacheHandler(TimeSpan expirationTime, bool storeOnlyForThisRequest) { keyGenerator = new DefaultCacheKeyGenerator(); this.expirationTime = expirationTime; this.storeOnlyForThisRequest = storeOnlyForThisRequest; } /// <summary> /// This constructor is used when we wrap cached data in a CacheHandler so that /// we can reload the object after it has been removed from the cache. /// </summary> /// <param name="expirationTime"></param> /// <param name="storeOnlyForThisRequest"></param> /// <param name="input"></param> /// <param name="getNext"></param> /// <param name="cachedData"></param> public CacheHandler(TimeSpan expirationTime, bool storeOnlyForThisRequest, IMethodInvocation input, GetNextHandlerDelegate getNext, object cachedData) : this(expirationTime, storeOnlyForThisRequest) { this.input = input; this.getNext = getNext; this.cachedData = cachedData; } /// <summary> /// Gets or sets the expiration time for cache data. /// </summary> /// <value>The expiration time.</value> public TimeSpan ExpirationTime { get { return expirationTime; } set { expirationTime = value; } } #region ICallHandler Members /// <summary> /// Implements the caching behavior of this handler. /// </summary> /// <param name="input"><see cref="IMethodInvocation"/> object describing the current call.</param> /// <param name="getNext">delegate used to get the next handler in the current pipeline.</param> /// <returns>Return value from target method, or cached result if previous inputs have been seen.</returns> public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext) { lock (input.MethodBase) { this.input = input; this.getNext = getNext; return loadUsingCache(); } } public int Order { get { return 0; } set { } } #endregion private IMethodReturn loadUsingCache() { //We need to synchronize calls to the CacheHandler on method level //to prevent duplicate calls to methods that could be cached. lock (input.MethodBase) { if (TargetMethodReturnsVoid(input) || HttpContext.Current == null) { return getNext()(input, getNext); } var inputs = new object[input.Inputs.Count]; for (int i = 0; i < inputs.Length; ++i) { inputs[i] = input.Inputs[i]; } string cacheKey = keyGenerator.CreateCacheKey(input.MethodBase, inputs); object cachedResult = getCachedResult(cacheKey); if (cachedResult == null) { var stopWatch = Stopwatch.StartNew(); var realReturn = getNext()(input, getNext); stopWatch.Stop(); if (realReturn.Exception == null && realReturn.ReturnValue != null) { AddToCache(cacheKey, realReturn.ReturnValue); } return realReturn; } var cachedReturn = input.CreateMethodReturn(cachedResult, input.Arguments); return cachedReturn; } } private object getCachedResult(string cacheKey) { //When the method uses input that is not serializable //we cannot create a cache key and can therefore not //cache the data. if (cacheKey == null) { return null; } object cachedValue = !storeOnlyForThisRequest ? HttpRuntime.Cache.Get(cacheKey) : HttpContext.Current.Items[cacheKey]; var cachedValueCast = cachedValue as CacheHandler; if (cachedValueCast != null) { //This is an object that is reloaded when it is being removed. //It is therefore wrapped in a CacheHandler-object and we must //unwrap it before returning it. return cachedValueCast.cachedData; } return cachedValue; } private static bool TargetMethodReturnsVoid(IMethodInvocation input) { var targetMethod = input.MethodBase as MethodInfo; return targetMethod != null && targetMethod.ReturnType == typeof (void); } private void AddToCache(string key, object valueToCache) { if (key == null) { //When the method uses input that is not serializable //we cannot create a cache key and can therefore not //cache the data. return; } if (!storeOnlyForThisRequest) { HttpRuntime.Cache.Insert( key, valueToCache, null, System.Web.Caching.Cache.NoAbsoluteExpiration, expirationTime, CacheItemPriority.Normal, null); } else { HttpContext.Current.Items[key] = valueToCache; } } } /// <summary> /// This interface describes classes that can be used to generate cache key strings /// for the <see cref="CacheHandler"/>. /// </summary> public interface ICacheKeyGenerator { /// <summary> /// Creates a cache key for the given method and set of input arguments. /// </summary> /// <param name="method">Method being called.</param> /// <param name="inputs">Input arguments.</param> /// <returns>A (hopefully) unique string to be used as a cache key.</returns> string CreateCacheKey(MethodBase method, object[] inputs); } /// <summary> /// The default <see cref="ICacheKeyGenerator"/> used by the <see cref="CacheHandler"/>. /// </summary> public class DefaultCacheKeyGenerator : ICacheKeyGenerator { private readonly LosFormatter serializer = new LosFormatter(false, ""); #region ICacheKeyGenerator Members /// <summary> /// Create a cache key for the given method and set of input arguments. /// </summary> /// <param name="method">Method being called.</param> /// <param name="inputs">Input arguments.</param> /// <returns>A (hopefully) unique string to be used as a cache key.</returns> public string CreateCacheKey(MethodBase method, params object[] inputs) { try { var sb = new StringBuilder(); if (method.DeclaringType != null) { sb.Append(method.DeclaringType.FullName); } sb.Append(':'); sb.Append(method.Name); TextWriter writer = new StringWriter(sb); if (inputs != null) { foreach (var input in inputs) { sb.Append(':'); if (input != null) { //Diffrerent instances of DateTime which represents the same value //sometimes serialize differently due to some internal variables which are different. //We therefore serialize it using Ticks instead. instead. var inputDateTime = input as DateTime?; if (inputDateTime.HasValue) { sb.Append(inputDateTime.Value.Ticks); } else { //Serialize the input and write it to the key StringBuilder. serializer.Serialize(writer, input); } } } } return sb.ToString(); } catch { //Something went wrong when generating the key (probably an input-value was not serializble. //Return a null key. return null; } } #endregion } } ``` Microsoft deserves most credit for this code. We've only added stuff like caching at request level instead of across requests (more useful than you might think) and fixed some bugs (e.g. equal DateTime-objects serializing to different values).
Caching best practices - Single object or multiple entries?
[ "", "c#", "asp.net", "caching", "" ]
**Problem:** to see when computer makes approximation in mathematical calculations when I use Python **Example of the problem:** My old teacher once said the following statement ``` You cannot never calculate 200! with your computer. ``` I am not completely sure whether it is true or not nowadays. It seems that it is, since I get a lot zeros for it from a [Python script](https://stackoverflow.com/questions/1041348/unable-to-make-a-factorial-function-in-python). **How can you see when your Python code makes approximations?**
Python use [arbitrary-precision arithmetic](http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic) to calculate with integers, so it can exactly calculate 200!. For real numbers (so-called [*floating-point*](http://en.wikipedia.org/wiki/Floating-point)), Python does not use an exact representation. It uses a binary representation called [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754), which is essentially scientific notation, except in base 2 instead of base 10. Thus, any real number that cannot be exactly represented in base 2 with 53 bits of precision, Python cannot produce an exact result. For example, 0.1 (in base 10) is an infinite decimal in base 2, 0.0001100110011..., so it cannot be exactly represented. Hence, if you enter on a Python prompt: ``` >>> 0.1 0.10000000000000001 ``` The result you get back is different, since has been converted from decimal to binary (with 53 bits of precision), back to decimal. As a consequence, you get things like this: ``` >>> 0.1 + 0.2 == 0.3 False ``` For a good (but long) read, see [What Every Programmer Should Know About Floating-Point Arithmetic](http://docs.sun.com/source/806-3568/ncg_goldberg.html).
Python has unbounded **integer** sizes in the form of a **long** type. That is to say, if it is a whole number, the limit on the size of the number is restricted by the memory available to Python. When you compute a large number such as 200! and you see an L on the end of it, that means Python has automatically cast the int to a *long*, because an int was not large enough to hold that number. See section 6.4 of [this page](http://docs.python.org/library/stdtypes.html) for more information.
Unable to see Python's approximations in mathematical calculations
[ "", "python", "" ]
Playing around with Python - tkInter - Entry widget - when I use validatecommand (below), the check happens the first time the string > Max, but when I continue to enter text the check steps - there's no delete or insert after the first time? Any advice? (outside of not building a desktop app via python) --- ``` #!/usr/bin/env python from Tkinter import * class MyEntry(Entry): def __init__(self, master, maxchars): Entry.__init__(self, master, validate = "key", validatecommand=self.validatecommand) self.MAX = maxchars def validatecommand(self, *args): if len(self.get()) >= self.MAX: self.delete(0,3) self.insert(0, "no") return True if __name__ == '__main__': tkmain = Tk() e = MyEntry(tkmain, 5) e.grid() tkmain.mainloop() ```
[From the Tk man](http://www.tcl.tk/man/tcl8.4/TkCmd/entry.htm#M30): > The validate option will also set itself to none when you edit the entry widget from within either the validateCommand or the invalidCommand. Such editions will override the one that was being validated. If you wish to edit the entry widget (for example set it to {}) during validation and still have the validate option set, you should include the command > > after idle {%W config -validate %v} don't know how to translate that to python.
Here is a code sample that will limit the input to 5 characters: ``` import Tkinter as tk master = tk.Tk() def callback(): print e.get() def val(i): print "validating" print i if int(i) > 4: print "False" return False return True vcmd = (master.register(val), '%i') e = tk.Entry(master, validate="key", validatecommand=vcmd) e.pack() b = tk.Button(master, text="OK", command=lambda: callback()) b.pack() tk.mainloop() ``` I threw in a bunch of print statements so you can sort of see what it's doing in the console. Here are the other substitutions you can pass: ``` %d Type of action: 1 for insert, 0 for delete, or -1 for focus, forced or textvariable validation. %i Index of char string to be inserted/deleted, if any, otherwise -1. %P The value of the entry if the edit is allowed. If you are config- uring the entry widget to have a new textvariable, this will be the value of that textvariable. %s The current value of entry prior to editing. %S The text string being inserted/deleted, if any, {} otherwise. %v The type of validation currently set. %V The type of validation that triggered the callback (key, focusin, focusout, forced). %W The name of the entry widget. ```
Python tkInter Entry fun
[ "", "python", "tkinter", "" ]
The next function in MySQL `MD5( 'secret' )` generates *5ebe2294ecd0e0f08eab7690d2a6ee69* I would like to have a Java function to generate the same output. But ``` public static String md5( String source ) { try { MessageDigest md = MessageDigest.getInstance( "MD5" ); byte[] bytes = md.digest( source.getBytes("UTF-8") ); return getString( bytes ); } catch( Exception e ) { e.printStackTrace(); return null; } } private static String getString( byte[] bytes ) { StringBuffer sb = new StringBuffer(); for( int i=0; i<bytes.length; i++ ) { byte b = bytes[ i ]; sb.append( ( int )( 0x00FF & b ) ); if( i+1 <bytes.length ) { sb.append( "-" ); } } return sb.toString(); } ``` generates ``` 94-190-34-148-236-208-224-240-142-171-118-144-210-166-238-105 ```
Try encoding in base 16. Just to get you started... 94 in base 16 is 5E. \*\*Edit:\*\*Try changing your getString method: ``` private static String getString( byte[] bytes ) { StringBuffer sb = new StringBuffer(); for( int i=0; i<bytes.length; i++ ) { byte b = bytes[ i ]; String hex = Integer.toHexString((int) 0x00FF & b); if (hex.length() == 1) { sb.append("0"); } sb.append( hex ); } return sb.toString(); } ```
replace ``` sb.append( ( int )( 0x00FF & b ) ); if( i+1 <bytes.length ) { sb.append( "-" ); } ``` by ``` String hex = Integer.toHexString((int) 0x00FF & b); if (hex.length == 1) sb.append("0"); sb.append( hex ); ```
MySQL MD5 and Java MD5 not equal
[ "", "java", "mysql", "cryptography", "md5", "cryptographic-hash-function", "" ]
I am creating a status board module for my project team. The status board allows the user to to set their status as in or out and they can also provide a note. I was planning on storing all the information in a single table ... and example of the data follows: ``` Date User Status Notes ------------------------------------------------------- 1/8/2009 12:00pm B.Sisko In Out to lunch 1/8/2009 8:00am B.Sisko In 1/7/2009 5:00pm B.Sisko In 1/7/2009 8:00am B.Sisko In 1/7/2009 8:00am K.Janeway In 1/5/2009 8:00am K.Janeway In 1/1/2009 8:00am J.Picard Out Vacation ``` I would like to query the data and return the most recent status for each user, in this case, my query would return the following results: ``` Date User Status Notes ------------------------------------------------------- 1/8/2009 12:00pm B.Sisko In Out to lunch 1/7/2009 8:00am K.Janeway In 1/1/2009 8:00am J.Picard Out Vacation ``` I am try to figure out the TRANSACT-SQL to make this happen? Any help would be appreciated.
Aggregate in a subquery derived table and then join to it. ``` Select Date, User, Status, Notes from [SOMETABLE] inner join ( Select max(Date) as LatestDate, [User] from [SOMETABLE] Group by User ) SubMax on [SOMETABLE].Date = SubMax.LatestDate and [SOMETABLE].User = SubMax.User ```
another way, this will scan the table only once instead of twice if you use a subquery only sql server 2005 and up ``` select Date, User, Status, Notes from ( select m.*, row_number() over (partition by user order by Date desc) as rn from [SOMETABLE] m ) m2 where m2.rn = 1; ```
Create a SQL query to retrieve most recent records
[ "", "sql", "t-sql", "derived-table", "" ]
I am attempting to receive a stream of XML events over a Java NIO channel. I am new to both NIO and StAX parsing, so I could very easily be overlooking something :) My search has led me to several SAX and StAX implementations, but they all seem to operate on InputStreams and InputSources--not NIO channels. The two closest attempts I have made have been to get the InputStream from the channel and create a PipedInputStream: ``` // method 1 PipedOutputStream out = new PipedOutputStream(); InputStream in = new PipedInputStream(out); PrintWriter writer = new PrintWriter(out); //method 2 InputStream in = channel.socket().getInputStream() //method 3 IputStream in = Channels.newInputStream(channel); ``` followed by: ``` XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance() .createXMLStreamReader(in); //... ``` When the above code is used with method 1, it blocks on the createXMLStreamReader line. When methods 2/3 are used, they immediately throw IllegalBlockingModeException (I do understand why). Maybe a new approach is needed? My goal is to have a non-blocking server select => accept character data from a client => parse it to XML events using a specific encoding => forward that event object to another thread for processing => and return to the selecting. So am I overlooking something, or is there a better approach that can be used? If so what? Thanks!
Are you sure you need to use NIO? It may not offer the relative benefits originally expected: Paul Tyma: [Kill the myth please. NIO is *not* faster than IO](http://mailinator.blogspot.com/2008/02/kill-myth-please-nio-is-not-faster-than.html) Paul Tyma: [Writing Java Multithreaded Servers - whats old is new](http://paultyma.blogspot.com/2008/03/writing-java-multithreaded-servers.html) A stack showing where inside createXMLStreamReader() it is blocking could help, but it's probably behaving as designed. If it was designed to work against InputStreams which always either (1) give the expected amount of data; (2) end; or (3) block, then it won't automatically behave in a (usually more complicated and stateful) way that can return after reading any amount of incomplete input, without lots of deep reworking.
I also started looking around, also for XMPP server use. I have been looking around and it looks like there is only one implementation which promises NIO support: Aalto <http://wiki.fasterxml.com/AaltoHome> But it seems to have released up to version 0.9.5, March 2009. So, I'm not sure how well maintained it is, but this might be a good starting point. Unless you can convince a bigger project (maybe Woodstox), to rework some of their internal classes for NIO support.
StAX parsing from Java NIO channel
[ "", "java", "xml", "nio", "stax", "" ]
I have developed an application that must be presented on exhibition as advertising. I want it to look more sexy! What tricks do you know that enhance the appearance of your applications? What are the best design effects the developer can use for its application? I am speaking about: glowing, shadows, maybe forms of buttons, beautiful animation of splash screens and so on. What is YOUR favourite effect?
I found the following examples: * **[Vista Buttons](http://blogs.msdn.com/expression/pages/creating-a-vista-style-button-template.aspx)**: * **[Innerglows](http://blogs.msdn.com/msmossyblog/archive/2008/09/15/how-to-make-innerglows-with-expression-blend.aspx)**: * **[Glass Buttons](http://blogs.conchango.com/johnrayner/archive/2006/12/22/WPF_2F00_E_3A00_-A-glass-button.aspx)**:
If you have no feeling for what looks good, then **don't** try *magic tricks* like glowing shadows or sparky gradients, it will only look like some awkward app from the late 90s. Like Chris said, effects can ruin an application as quickly as it can make one. There is no silver bullet for good design, the best tip for someone totally lost is: Less is more. Especially when it comes to colors, avoid using many different colors. Look on other good looking apps (Photoshop CS4, Adobe Reader 9, OSX Preview, etc etc) they are actually really clean. If you really want to use some wpf-powers an easy trick is opacity transitions, just keep all animations short (max 0.2 seconds). And for moving animations make sure to use acceleration and deceleration, otherwise the animation will look really weird.
Design effects in WPF (tricks to enhance app's appearance)
[ "", "c#", "wpf", "wpf-controls", "" ]
I am gettings these type of errors in a MFC VS6 project while linking the application: ``` msvcrt.lib(MSVCRT.dll) : error LNK2005: _atoi already defined in LIBC.lib(atox.obj) ``` I know what it means (a function exists in 2 different libraries); to solve it I should have to exclude one of the 2 libraries (`msvcrt.lib` or `libc.lib`). But if I do this there are all kinds of unresolved external errors. So I would like to keep using both libraries. Is there any way to tell the linker that I want to use the `_atoi` function in `libc.lib` and not in `msvcrt.lib` (or the other way around)? Any help or direction would be great.
There seems to be an option which you can use to ignore errors like this: in projectsettings > link > check 'Force file output'. This will generate the program even if there are linkerrors. The Build output gives something like this: msvcrt.lib(MSVCRT.dll) : warning LNK4006: \_atoi already defined in LIBC.lib(atox.obj); second definition ignored Of course you will need to use this option with care as it can generate an application which won't work in some cases, but here it probably doesn't do any harm (I hope). Thank you for the other replies, but that didn't seem to be an option in my particular case.
This error certainly means that you're linking two pieces of codes that have been compiled using distinct runtime libraries. MSVCRT.dll is the dynamic version, while LIBC.lib is the static one. If you do this, all hell break loose. Try finding which parts of your code use which version, and sort this out.
how to avoid "already defined error" in C++
[ "", "c++", "linker", "visual-studio-6", "" ]
With the GWT compiler, is it possible set pass in properties as arguments to the GWT compiler? I know you can pass in certain defined parameters such as -war and -style, but this is for passing in property values, such as "user.agents" or "locale". From what I can see of the documentation, the properties can only be set using from within the module descriptor. But I want to be able to control these properties externally, from my build script. I've tried looking for documentation on what arguments are supported by com.google.gwt.dev.Compile, but there doesn't appear to be any reference documentation for that class. The docs are long on how-tos, and distressingy short on detail.
The answer is no! I've asked the exact same question in the commiters newsgroup and currently there is nothing available. They are thinking about adding support of supplying an extra .gwt.xml to override/configure things externally. This would cover what I wanted to do, but if you really want a generic access to the Properties at compile time then I'm afraid this is not possible. Maybe you should create a Functional Request... let me know I'll put a start on it as well since it would be very usefull to switch on/off certain things from the compiler command line operation.
It does take arguments. An example from an ant build file I wrote: ``` <target name="compile.gwt" depends="compile"> <java failonerror="true" classname="com.google.gwt.dev.Compiler" fork="true"> <arg value="-war" /> <arg value="${webcontent.dir}" /> <arg value="-style" /> <arg value="obfuscated" /> <arg value="${module.name}" /> <jvmarg value="-Xmx256m" /> <jvmarg value="-Xss64M" /> <classpath> <path refid="project.class.path" /> <pathelement path="${gwt.home}/gwt-dev-windows.jar" /> </classpath> </java> </target> ``` I think this covers all the flags: [Debugging and Compiling - Google Web Toolkit - Google Code](http://code.google.com/webtoolkit/doc/1.6/FAQ_DebuggingAndCompiling.html) As far as whether you pass user agents, I haven't seen it, but I haven't looked, either.
Can I pass arguments (deferred binding properties) to the GWT compiler?
[ "", "java", "gwt", "gwt-compiler", "" ]
I need to obfuscate or encrypt some plain text data in my php 5.2 application. I'd prefer a solution that would have input string and output string retain the same length. This does not need to extremely strong, as there are numerous other layers of security in place. Strong would be good, but this will just keep programmers/dba/support people/etc from accidentally reading the text from within the database. key considerations * **EDIT ADD** I'd prefer a solution that would have input string and output string retain the same length. * only string text will be obfuscated/encrypted for storage in a database * the php application will need to obfuscate/encrypt the data before the database save and will need to un-obfuscate/dencrypt following the database read * this is a modification to an existing application * only some columns will need to be obfuscated/encrypted * only some rows will need to be obfuscated/encrypted, based on a Type field * there are only a few load/save points to handle * max column size is already determined for some fields, but not for others, but I'd prefer a solution to work within the existing size of the restricted fields * **EDIT, ADD** the key will be probably be a composite of some Primary key info +uneditable fields here is a sample database table and data: ``` int char(1) varchar(24) int date MyPrimaryKey RowType UserText UserNo DateChange ------------ ------- ------------------------ -------- ---------------- 1 N nothing special here 43 6/20/2009 12:11am 2 N same thing, wow! 78 6/23/2009 1:03pm 3 S fBJKg}.jkjWfF78dlg@45kjg 43 6/25/2009 6:45am 4 N same old, same old text 21 6/25/2009 8:11am ``` The application would load and display rows 1,2, and 4 normally. However it would conditionally (based on row type) handle the text in row 3 using this obfuscate/encrypt and un-obfuscate/decrypt logic. Can anyone provide obfuscate/encrypt and un-obfuscate/decrypt functions code, links, and or pointer that would help here? thanks! **EDIT** I like the simple base64 encoding idea, but is there a method that can keep the data within a fixed size. All methods listed so far have the output value larger than the input value. This will be a problem for some columns, where the user can enter in 50 characters and it is stored in a varchar(50) column.
for simple obfuscation use strtr() - Translate certain characters: [string **strtr** ( string $str , string $from , string $to )](https://www.php.net/strtr) **to encode in php:** ``` $readable='This is a special test string ABC123 ([+,-!#$%&*])'; $unreadable=strtr($readable,' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' ,'¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ' ); print $unreadable; //outputs: "ÕéêôAêôAâAôñæäêâíAõæôõAôõóêïèAÂÃIJ³´A©Ü¬­®¢¤¥¦§«Þª" ``` **to decode in php:** ``` $unreadable='ÕéêôAêôAâAôñæäêâíAõæôõAôõóêïèAÂÃIJ³´A©Ü¬­®¢¤¥¦§«Þª'; $readable=strtr($unreadable,'¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ' ,' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ' ); print $readable; //outputs: "This is a special test string ABC123 ([+,-!#$%&*])" ``` you can easily replicate this logic in the DB if necessary (without looping): [Using a Table of Numbers, by Erland Sommarskog](http://www.sommarskog.se/arrays-in-sql-2005.html#tblnum)
How about [base64 encoding](http://www.php.net/base64_encode)? We use to use that to make SMS messages in our SMS Gateway DB unreadable by the developers.
obfuscate or encrypt some plain text data in PHP
[ "", "php", "encryption", "encoding", "obfuscation", "" ]
> **Disclaimer**: I already asked [this question](https://stackoverflow.com/questions/1059580/distributed-lock-service), but without the > deployment requirement. I got an > answer that got 3 upvotes, and when I > edited the question to include the deployment requirement the answer then > became irrelevant. The reason I'm > resubmitting is because SO considers > the original question 'answered', even > though I got no meaningful upvoted > answer. I opened a [uservoice > submission](http://stackoverflow.uservoice.com/pages/1722-general/suggestions/244826-solve-the-modified-question-problem) about this problem. > The reason I reposted is so StackOverflow consider the original question answered, so it doesn't show up on the 'unanswered questions' tab. Which distributed lock service would you use? Requirements are: 1. A mutual exclusion (lock) that can be seen from different processes/machines 2. lock...release semantics 3. Automatic lock release after a certain timeout - if lock holder dies, it will automatically be freed after X seconds 4. Java implementation 5. **Easy deployment** - must not require complicated deployment beyond either Netapp, MySql or GigaSpaces. Must play well with those products (especially GigaSpaces - this is why TerraCotta was ruled out). 6. Nice to have: .Net implementation 7. If it's free: Deadlock detection / mitigation I'm not interested in answers like "it can be done over a database", or "it can be done over JavaSpaces" - I know. Relevant answers should only contain a ready, out-of-the-box, proven implementation.
Here's the outline of a GigaSpaces based answer that meets your criteria, depending on exactly what you mean in criteria 3. I work with GigaSpaces from .Net, not Java: Create a locking class with a SpaceID+SpaceRouting property IDing what is locked and a DataMember bool property Unlocked: ``` sealed public class IdLockTrans { [SpaceID] [SpaceRouting] public string ID { get; set; } [DataMember] public bool Unlocked { get; set; } public IdLockTrans(Id id) { ID = id.ID; } public IdLockTrans() { } } ``` You will use GigaSpaces' lease time for lock release after a certain timeout. This will cause GigaSpaces to remove IdLockTrans objects from the space automatically after they have been idle for the timeout period. The lack of an IdLockTrans for an ID means the ID is unlocked. Your locker class will define and initialize these class members ``` private readonly ISpaceProxy _proxy; private readonly long _leaseTime; public override bool Lock(Id id, long timeout) { bool locked; IdLockTrans lockTransTemplate = new IdLockTrans(id); // Assume that this is a new id. try { _proxy.Write(lockTransTemplate, null, _leaseTime, 0, UpdateModifiers.WriteOnly); locked = true; } catch (EntryAlreadyInSpaceException) { using (ITransaction tx = _proxy.CreateLocalTransaction()) { try { lockTransTemplate.Unlocked = true; IdLockTrans lockTrans = _proxy.Take(lockTransTemplate, tx, timeout); locked = (lockTrans != null); if (lockTrans != null) { lockTrans.Unlocked = false; _proxy.Write(lockTrans, tx, _leaseTime, 0, UpdateModifiers.WriteOnly); } tx.Commit(); } catch { tx.Abort(); throw; } } } return locked; } public override void Unlock(Id lockedId) { IdLockTrans lockTrans = new IdLockTrans(lockedId); lockTrans.Unlocked = true; try { _proxy.Update(lockTrans, null, _leaseTime, 0, UpdateModifiers.UpdateOnly); } catch (EntryNotInSpaceException) { throw new Exception("IdLockTrans for " + lockTrans.ID + " not found on Unlock. Lock time exceeded lease time."); } } ```
Your .Net implementation is very close the existing out of the box lock/unlock API provided with the Java API. See: <http://www.gigaspaces.com/docs/JavaDoc8.0/org/openspaces/core/DefaultGigaMap.html> You may found the source code for this Java class as part of the gs-openspaces-src.zip file provided with the product. Having the same with Gigaspaces .Net API should be straightfwd.
Distributed Lock Service over MySql/GigaSpaces/Netapp
[ "", "java", "mysql", "locking", "distributed", "gigaspaces", "" ]
I want to convert a hex string to a 32 bit signed integer in C++. So, for example, I have the hex string "fffefffe". The binary representation of this is 11111111111111101111111111111110. The signed integer representation of this is: -65538. How do I do this conversion in C++? This also needs to work for non-negative numbers. For example, the hex string "0000000A", which is 00000000000000000000000000001010 in binary, and 10 in decimal.
use `std::stringstream` ``` unsigned int x; std::stringstream ss; ss << std::hex << "fffefffe"; ss >> x; ``` the following example produces `-65538` as its result: ``` #include <sstream> #include <iostream> int main() { unsigned int x; std::stringstream ss; ss << std::hex << "fffefffe"; ss >> x; // output it as a signed type std::cout << static_cast<int>(x) << std::endl; } ``` In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (<http://en.cppreference.com/w/cpp/string/basic_string/stol> and <http://en.cppreference.com/w/cpp/string/basic_string/stoul>). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a `std::string` So, the simplest answer for newer code would probably look like this: ``` std::string s = "0xfffefffe"; unsigned int x = std::stoul(s, nullptr, 16); ``` --- **NOTE:** Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-). It appears that since `lexical_cast<>` is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the `boost::lexical_cast` and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine. [Boost has some stuff](http://www.boost.org/doc/libs/1_39_0/libs/conversion/lexical_cast.htm) to do this as well, which has some nice error checking capabilities as well. You can use it like this: ``` try { unsigned int x = lexical_cast<int>("0x0badc0de"); } catch(bad_lexical_cast &) { // whatever you want to do... } ``` If you don't feel like using boost, here's a light version of lexical cast which does no error checking: ``` template<typename T2, typename T1> inline T2 lexical_cast(const T1 &in) { T2 out; std::stringstream ss; ss << in; ss >> out; return out; } ``` which you can use like this: ``` // though this needs the 0x prefix so it knows it is hex unsigned int x = lexical_cast<unsigned int>("0xdeadbeef"); ```
For a method that works with both C and C++, you might want to consider using the standard library function strtol(). ``` #include <cstdlib> #include <iostream> using namespace std; int main() { string s = "abcd"; char * p; long n = strtol( s.c_str(), & p, 16 ); if ( * p != 0 ) { //my bad edit was here cout << "not a number" << endl; } else { cout << n << endl; } } ```
C++ convert hex string to signed integer
[ "", "c++", "integer", "hex", "signed", "" ]
I have a page that opens a modal dialog. After the operations done on dialog I want to refresh the opener page. But when I open the popup by using "openDialog" I cannot access to the opener by using window.opener on popup page. It appears "undefined" when I wanted to access. (I dont want to use "popup" method in this case. I want it to be a dialog by the way. using "popup" is my second plan.) What is the best practice to get rid off this issue?
[Modifying parent data from modal dialog](http://www.tek-tips.com/faqs.cfm?fid=5782) [Refresh parent window from modal child window](http://forums.devarticles.com/javascript-development-22/refresh-parent-window-from-modal-child-window-8212.html)
this was what i need that i got from the link In the parent: ``` parentVar = "set by parent"; vRv = window.showModalDialog("modalWindow.html",window.self, ""); ``` In the modal: ``` dialogArguments.parentVar = "set by modal"; ``` PS: Dont forget to set reference to opener with "window.self"
How to find modal dialog opener from javascript?
[ "", "javascript", "popup", "opendialog", "" ]
**Major Edit:** I misread the article! The comment was in regards to the finalize method of the the class not the finally block :). Apologies. I was just reading that you should not close or dispose a database connection within a finally block but the article did not explain why. I can not seem to find a clear explanation as to why you would not want to do this. [Here is the article](http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx)
If you look around, closing the connection in the finally block is one of the recommended ways of doing it. The article you were looking at probably recommended having a 'using' statement around the code that used the connection. ``` using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = connection.CreateCommand(); command.CommandText = "select * from someTable"; // Execute the query here...put it in a datatable/dataset } ``` The 'using' statement will ensure the Connection object gets disposed immediately after it's needed rather than waiting for the Garbage Collector to dispose of it.
I have to disagree that you should not close or dispose of a database connection within a finally block. Letting an unhandled (or even handled for that matter) exception leave open connections can take down a database pretty quickly if it has a lot of activity. Closing a database connection is the defacto example of why to use the finally statement, IMHO. Of course, the using statement is my preferred method, which is maybe what the original author was going for. **Edit to the Major Edit:** That makes sense now. You wouldn't want to leave closing your database connection up to the garbage collector.
Why Not Close a Database Connection in a Finally Block
[ "", "c#", ".net", "sql-server", "database", "" ]
I was surfing the web, as usual and I wanted to take a look at [Bing](http://www.bing.com/)'s source code because I was curious and wanted to know what they were using to make their image fade in. I was surprised by what could only be qualified by the following line : **Holy wall of text!** And it made me wonder if there is any advantage to obfuscate your (X)HTML, CSS and JavaScript like this? To reduce the size of the file perhaps? --- Edit : After looking around, I realized this was a pretty common practice. Never looked at it from a minification point of view before!
They are not obfuscating. They are [minifying](http://developer.yahoo.com/yui/compressor/) in order to reduce the bandwidth used by the millions of requests they see each day. > The goal of JavaScript and CSS > minification is always to preserve the > operational qualities of the code > while reducing its overall byte > footprint (both in raw terms and after > gzipping, as most JavaScript and CSS > served from production web servers is > gzipped as part of the HTTP protocol). You might also be interested in reading the Yahoo! User Interface blog post titled ["Minification v. Obfuscation"](http://yuiblog.com/blog/2006/03/06/minification-v-obfuscation/).
2 main reasons to obfuscate your code: * Reduce the total size of the file (like you mentioned) If you replace a function called 'CallThisFunctionAndReturnAnArray' with 'C' - you've saved a lot of characters in your file. * Protect intellectual property - while if this is realistic is definite debatable, this is common justification for doing so. You can get around this with good tools, or if you are just really smart.
Why does Bing obfuscate their JavaScript?
[ "", "javascript", "html", "css", "obfuscation", "bing", "" ]
What would i need to put in the `SortIP` function to make the custom sort function sort the array by the last digit of the IP number. This doesn't work. ``` function SortIP(a, b) { return a[0][3] - b[0][3]; } LAN = new Array ( ["ADSL Router", [192, 168, 0, 1]], ["Gary's Mac", [192, 168, 0, 15]], ["Network Switch", [192, 168, 0, 2]], ["Production Email", [192, 168, 0, 60]] ); LAN.sort(SortIP); ``` expected array order: 1. ADSL Router: 192.168.0.1 2. Network Switch: 192.168.0.2 3. Gary's Mac: 192.168.0.15 4. Production Email: 192.168.0.60
You're almost there just replace `return a[0][3] - b[0][3];` with `return a[1][3] - b[1][3];` and you're done. Why? Because the IP is the second (Index=1) cell of each array.
You’re comparing the wrong values. Try this: ``` function SortIP(a, b) { return a[1][3] - b[1][3]; } ```
Creating a custom array within an array sort function in Javascript
[ "", "javascript", "arrays", "sorting", "" ]
I have to do enhancements to an existing C++ project with above 100k lines of code. My question is How and where to start with such projects ? The problem increases further if the code is not well documented. Are there any automated tools for studying code flow with large projects? Thanx,
There's a book for you: [Working Effectively with Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) It's not about tools, but about various approaches, processes and techniques you can use to better understand and make changes to the code. It is even written from a mostly C++ perspective.
Use Source Control before you touch anything!
How to start modification with big projects
[ "", "c++", "projects", "legacy-code", "" ]
I'm coding a webservice on python that uses an Oracle database. I have cx\_Oracle installed and working but I'm having some problems when I run my python code as CGI using Apache. For example the following code works perfectly at the command line: ``` #!/usr/bin/python import os import cx_Oracle import defs as df os.putenv('ORACLE_HOME', '/oracledb/10.2.0/') os.putenv('LD_LIBRARY_PATH', '/oracledb/10.2.0/lib') con = cx_Oracle.Connection(df.DB_USER, df.DB_PASS, df.DB_SID) print con ``` But when I run it as CGI I get a "cx\_Oracle.InterfaceError: Unable to acquire Oracle environment handle" at the apache error log. I searched the Net and everybody says that I have to set the `ORACLE_HOME` and `LD_LIBRARY_PATH` environment variables. Somehow the CGI script cannot access this environment variables even when I define them using `os.putenv` as you can see at the code. What I'm I doing wrong? Thanks!
I've managed to solve the problem. Somehow the user and group that apache was using didn't have access to the environment variables. I solved the problem by changing the user and group that apache was using to a user that I was certain to have access to this variables. It's strange (and frustrating) that it's so difficult to set this variables using Python. Thanks to everyone that answered my question!
This is working for me: ``` os.putenv('ORACLE_HOME', '/oracle/client/v10.2.0.3-64bit') os.putenv('LD_LIBRARY_PATH', '/oracle/client/v10.2.0.3-64bit/lib') os.environ['ORACLE_HOME'] = '/oracle/client/v10.2.0.3-64bit' os.environ['LD_LIBRARY_PATH'] = '/oracle/client/v10.2.0.3-64bit/lib' ``` Mind that first `putenv`, then update `environ`.
Python + CGI script cannot access environment variables
[ "", "python", "apache", "cgi", "cx-oracle", "" ]
> **Possible Duplicate:** > [LINQ to SQL: Return anonymous type?](https://stackoverflow.com/questions/534690/linq-to-sql-return-anonymous-type) I have a standard LINQ to SQL query, which returns the data as an anonymous type (containing about 6 columns of data of various datatypes). I would like to make this returned object available to other parts of the program, either by returning it to the method-caller, or by assigning it to a property of the object containing the method. How can I do this given that it is an anonymous type ("var")? EDIT - Here is the code: ``` using (ormDataContext context = new ormDataContext(connStr)) { var electionInfo = from t1 in context.elections join t2 in context.election_status on t1.statusID equals t2.statusID select new { t1, t2 }; } ```
Make the anonymous type into a class... ``` public class Person { public Person() { } public String Name { get; set; } public DateTime DOB { get; set; } } Person p = from person in db.People where person.Id = 1 select new Person { Name = person.Name, DOB = person.DateOfBirth } ```
You cannot type any method in C# to be the explicit type of an anonymous types. They cannot be "named" so to speak and hence cannot appear in metadata signatures. If you really want to return a value which is an anonymous type there are 2 options 1. Have the return type of the method be System.Object. You can then do evil casting hacks to get a typed value in another method. This is **very** fragile and I don't recommend it. 2. Use a generic method and a type inference trick to get the return type correct. This would require a very interesting signature definition for your approach. Anonymous types were not really meant to be passed around in this fashion. At the point you need to pass them around between your functions in this manner, you're better off explicitly defining a type.
How to return anonymous type from c# method that uses LINQ to SQL
[ "", "c#", "linq", "linq-to-sql", "anonymous-types", "" ]
How can i send mails through the php script?? I am trying to do somthing like this: ``` for($k=0;$k<=$x->length-1;$k++) { for($l=0;$l<=$j-1;$l++) { if($y->item($k)->nodeValue==$JobNoArr[$l] && $AcceptanceDateArr[$l]=='0000-00-00') { //echo $v->item($k)->nodeValue ; $email = $v->item($k)->nodeValue . ","; $to = $email; $subject = "My subject"; $txt = "Hello world!"; $headers = "From: webmaster@example.com" . "\r\n" . "CC: someother.valid@email.adr"; mail($to,$subject,$txt,$headers); } } } ``` Please help me in this issue. Best Zeeshan
I strongly advise against sending mail using PHP's `mail()` function. Composing valid emails and delivering them successfully is trickier than it seems at first glance. There is encoding, putting parts together, validation & sanitation, error reporting (more than `bool mail(...)`), support for authentication and on and on ... The `mail()` function does not offer any of these things. Try [SwiftMailer](http://swiftmailer.org) or similar. You can configure it to use PHP's `mail()` function and so much more. I highly recommend it.
You're trying too much all at once. Try going one step at a time. First send a simple email, with hard-coded parameters to get that working, then troubleshoot it within the context of your nested loops.
How to send mails through php script?
[ "", "php", "email", "" ]
I Have the following function. ``` function ChangeDasPanel(controllerPath, postParams) { $.post(controllerPath, postParams, function(returnValue) { $('#DasSpace').hide("slide", { direction: "right" }, 1000, function() { $('#DasSpace').contents().remove(); $('#DasSpace').append(returnValue).css("display", "block"); $('#DasSpace').show("slide", { direction: "right" }, 1000); }); }); }; ``` But I want to be able to call it like this ``` ChangeDasPanel("../Home/Test", {} ,function (){ //do some stuff on callback } ``` How can I implement support for callbacks in my function?
``` function ChangeDasPanel(controllerPath, postParams, f) { $.get( controllerPath, postParams, function(returnValue) { var $DasSpace = $('#DasSpace'); $DasSpace.hide( "slide", { direction: "right" }, 1000, function() { $DasSpace.contents().remove(); $DasSpace.append(returnValue).css("display", "block"); $DasSpace.show("slide", { direction: "right" }, 1000); } ); if (typeof f == "function") f(); else alert('meh'); } ); }; ``` You can pass functions like any other object in JavaScript. Passing in a callback function is straight-forward, you even do it yourself in the `$.post()` call. You can decide whether you want to have your callback called as part of the `$.post()` callback or on its own.
You know that global variables and functions are evil, so why not put your's into the jQuery namespace: ``` $.extend({ myFunc : function(someArg, callbackFnk){ var url = "http://example.com?q=" + someArg; $.getJSON(url, function(data){ // now we are calling our own callback function if(typeof callbackFnk == 'function'){ callbackFnk.call(this, data); } }); } }); $.myFunc(args, function(){ // now my function is not hardcoded // in the plugin itself }); ``` Read this post to get a better understanding: [Creating callback functions in jQuery](http://jquery-howto.blogspot.com/2009/11/create-callback-functions-for-your.html)
How do I write a jquery function that accepts a callback as a parameter
[ "", "javascript", "jquery", "function", "callback", "" ]
I have created an Excel document using OpenXml SDK 2.0, now I have to style It, but I can`t. I don't know how to paint the background color or change the font size in different cells. My code to create a cell is: ``` private static Cell CreateTextCell(string header, string text, UInt32Value index) { Cell c = new Cell(); c.DataType = CellValues.InlineString; c.CellReference = header + index; InlineString inlineString = new InlineString(); DocumentFormat.OpenXml.Spreadsheet.Text t = new DocumentFormat.OpenXml.Spreadsheet.Text(); t.Text = text; inlineString.AppendChild(t); c.AppendChild(inlineString); return c; } ```
Note: OpenXML 2.0 SDK is currently in CTP and is not licensed for production use until Office2010. My general methodoloy to deal with OpenXML SDK is to create a blank document and a document with just the features you'd like to learn how to implement (like background color) and use the SDK's OpenXmlDiff to see what changes need to be made to implement the feature. If you are creating a document from scratch, you can use DocumentReflector to generate the code for the default Stylesheet object and then add the styles you need. Starting with the default: ``` new Stylesheet( new Fonts( new Font( new FontSize() { Val = 10D }, new Color() { Theme = (UInt32Value)1U }, new FontName() { Val = "Arial" }, new FontFamilyNumbering() { Val = 2 }) ) { Count = (UInt32Value)1U }, new Fills( new Fill( new PatternFill() { PatternType = PatternValues.None }), new Fill( new PatternFill() { PatternType = PatternValues.Gray125 }) ) { Count = (UInt32Value)2U }, new Borders(... ... ... new CellFormats( new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }) { Count = (UInt32Value)1U }, ... ``` I've added a new Font of size 12 and a new Fill with red background (Indexed value 64), and added new CellFormats that reference the index of the new Font and Fill. (Make sure to update the Counts too) ``` new Stylesheet( new Fonts( new Font( new FontSize() { Val = 10D }, new Color() { Theme = (UInt32Value)1U }, new FontName() { Val = "Arial" }, new FontFamilyNumbering() { Val = 2 }), new Font( new FontSize() { Val = 12D }, new Color() { Theme = (UInt32Value)1U }, new FontName() { Val = "Arial" }, new FontFamilyNumbering() { Val = 2 }) ) { Count = (UInt32Value)2U }, new Fills( new Fill( new PatternFill() { PatternType = PatternValues.None }), new Fill( new PatternFill() { PatternType = PatternValues.Gray125 }), new Fill( new PatternFill() { PatternType = PatternValues.Solid, ForegroundColor = new ForegroundColor() { Rgb = "FFFF0000" }, BackgroundColor = new BackgroundColor() { Indexed = 64 } }) ) { Count = (UInt32Value)3U }, new Borders( new Border( new LeftBorder(), new RightBorder(), new TopBorder(), new BottomBorder(), new DiagonalBorder()) ) { Count = (UInt32Value)1U }, new CellStyleFormats( new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U } ) { Count = (UInt32Value)1U }, new CellFormats( new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }, new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)1U, FillId = (UInt32Value)0U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U }, new CellFormat() { NumberFormatId = (UInt32Value)0U, FontId = (UInt32Value)0U, FillId = (UInt32Value)2U, BorderId = (UInt32Value)0U, FormatId = (UInt32Value)0U } ) { Count = (UInt32Value)3U }, new CellStyles( new CellStyle() { Name = "Normal", FormatId = (UInt32Value)0U, BuiltinId = (UInt32Value)0U } ) { Count = (UInt32Value)1U }, new DifferentialFormats() { Count = (UInt32Value)0U }, new TableStyles() { Count = (UInt32Value)0U, DefaultTableStyle = "TableStyleMedium9", DefaultPivotStyle = "PivotStyleLight16" }); ``` Then, in code, I apply the CellStyle index to the cells I want to format: (There was already data in cells A2 and A3. Cell A2 gets the larger size, A3 gets red background) ``` SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>(); sheetData.Descendants<Row>().Where(r => r.RowIndex == 2U).First().Descendants<Cell>().First().StyleIndex = 1U; sheetData.Descendants<Row>().Where(r => r.RowIndex == 3U).First().Descendants<Cell>().First().StyleIndex = 2U; ```
Many thanks for this article. After a lot of struggling (and Googling), I finally managed to create a *very* easy-to-use C# class, which takes a DataSet and a Filename, and creates an Office 2007 .xlsx containing the DataSet's data. Suddenly, the process of adding a function to your application to "Export to Excel" becomes as easy as... ``` DataSet ds = CreateSampleData(); // Your code here ! string excelFilename = "C:\\Sample.xlsx"; CreateExcelFile.CreateExcelDocument(ds, excelFilename); ``` I've posted the full source code, plus an example of using it, on the following website. It's a Visual Studio 2008 C# WinForms application, but you can let Visual Studio upgrade this project, if you're running VS2010. Enjoy. <http://www.mikesknowledgebase.com/pages/CSharp/ExportToExcel.htm>
Creating Excel document with OpenXml sdk 2.0
[ "", "c#", "excel", "openxml", "spreadsheetml", "" ]
I have an object for which I'd like to track the number of threads that reference it. In general, when any method on the object is called I can check a thread local boolean value to determine whether the count has been updated for the current thread. But this doesn't help me if the user say, uses boost::bind to bind my object to a boost::function and uses that to start a boost::thread. The new thread will have a reference to my object, and may hold on to it for an indefinite period of time before calling any of its methods, thus leading to a stale count. I could write my own wrapper around boost::thread to handle this, but that doesn't help if the user boost::bind's an object *that contains* my object (I can't specialize based on the presence of a member type -- at least I don't know of any way to do that) and uses that to start a boost::thread. Is there any way to do this? The only means I can think of requires too much work from users -- I provide a wrapper around boost::thread that calls a special hook method on the object being passed in provided it exists, and users add the special hook method to any class that contains my object. Edit: For the sake of this question we can assume I control the means to make new threads. So I can wrap boost::thread for example and expect that users will use my wrapped version, and not have to worry about users simultaneously using pthreads, etc. Edit2: One can also assume that I have some means of thread local storage available, through `__thread` or `boost::thread_specific_ptr`. It's not in the current standard, but hopefully will be soon.
In general, this is hard. The question of "who has a reference to me?" is not generally solvable in C++. It may be worth looking at the bigger picture of the specific problem(s) you are trying to solve, and seeing if there is a better way. There are a few things I can come up with that can get you partway there, but none of them are quite what you want. You can establish the concept of "the owning thread" for an object, and REJECT operations from any other thread, a la Qt GUI elements. (Note that trying to do things thread-safely from threads other than the owner won't actually give you thread-safety, since if the owner isn't checked it can collide with other threads.) This at least gives your users fail-fast behavior. You can encourage reference counting by having the user-visible objects being lightweight references to the implementation object itself [and by documenting this!]. But determined users can work around this. And you can combine these two-- i.e. you can have the notion of thread ownership for each *reference*, and then have the object become aware of who owns the references. This could be very powerful, but not really idiot-proof. You can start restricting what users can and cannot do with the object, but I don't think covering more than the obvious sources of unintentional error is worthwhile. Should you be declaring operator& private, so people can't take pointers to your objects? Should you be preventing people from dynamically allocating your object? It depends on your users to some degree, but keep in mind you can't prevent *references* to objects, so eventually playing whack-a-mole will drive you insane. So, back to my original suggestion: re-analyze the big picture if possible.
Usually you cannot do this programmatically. Unfortuately, the way to go is to design your program in such a way that you can prove (i.e. convince yourself) that certain objects are shared, and others are thread private. The current C++ standard does not even have the notion of a thread, so there is no standard portable notion of thread local storage, in particular.
Detecting when an object is passed to a new thread in C++?
[ "", "c++", "multithreading", "boost", "hook", "reference-counting", "" ]
I submitted 5 jobs to an [ExecutorCompletionService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html), but it *seems* like the jobs are executed in sequence. The ExecutorService that is passed to the constructor of [ExecutorCompletionService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorCompletionService.html) is created using newCacheThreadPool form. Am I doing anything wrong ? **UPDATE** Each job is basically doing a database query & some calculation. The code for the ExecutorCompletionService is lifted as-is off the javadoc. I just replaced the Callables with my own custom Callable implementations.
The `ExecutorCompletionService` has *nothing* to do with how jobs are executed, it's simply a convenient way of retrieving the results. `Executors.newCachedThreadPool` by default executes tasks in separate threads, which *can* be parallel, given that: * tasks are independent, and don't e.g. synchronize on the same object inside; * you have multiple hardware CPU threads. The last point deserves an explanation. Although there are no guarantees, in practice the Sun JVM favours the currently executing thread so it's never swapped out in favour of another one. That means that your 5 tasks might end up being executed serially due to the JVM implementation and not having e.g. a multi-core machine.
I assume you meant [Executors.newCachedThreadPool()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()). If so, execution should be parallelized as you expect.
Are tasks parallelized when executed via an ExecutorCompletionService?
[ "", "java", "multithreading", "concurrency", "" ]
Basically I am looking for a win32 method to invoke in C# to set the focus to a children of an unmanaged application. But first I need to find the child control's handle which is the problem. Any useful win32 functions to solve this?
There is a library which supports enumerating and searching window handles, which is available at <http://mwinapi.sourceforge.net/> Just so that you do not have to reinvent the wheel every time ;) Start with ``` SystemWindow.AllToplevelWindows ``` and then just dig your way down (looking at class names, process names, titles, dialog IDs, whatever).
Use [FindWindowEx](http://msdn.microsoft.com/en-us/library/ms633500.aspx) to find the Handle of the Window you're looking for. Once you have that handle, use [EnumChildWindows](http://msdn.microsoft.com/en-us/library/ms633494(VS.85).aspx) to find the correct child you need. There's too much code involved for me to quickly write up a sample, but there's enough on the web to help. From Pinvoke.net: <http://www.pinvoke.net/default.aspx/user32/EnumChildWindows.html>
How to find a child of a parent unmanaged win32 app
[ "", "c#", ".net", "winapi", "unmanaged", "" ]
I have a `TextBoxD1.Text` and I want to convert it to an `int` to store it in a database. How can I do this?
Try this: ``` int x = Int32.Parse(TextBoxD1.Text); ``` or better yet: ``` int x = 0; Int32.TryParse(TextBoxD1.Text, out x); ``` Also, since [`Int32.TryParse`](http://msdn.microsoft.com/en-us/library/f02979c7.aspx) returns a `bool` you can use its return value to make decisions about the results of the parsing attempt: ``` int x = 0; if (Int32.TryParse(TextBoxD1.Text, out x)) { // you know that the parsing attempt // was successful } ``` If you are curious, the difference between `Parse` and `TryParse` is best summed up like this: > The TryParse method is like the Parse > method, except the TryParse method > does not throw an exception if the > conversion fails. It eliminates the > need to use exception handling to test > for a FormatException in the event > that s is invalid and cannot be > successfully parsed. - [MSDN](http://msdn.microsoft.com/en-us/library/f02979c7.aspx)
``` Convert.ToInt32( TextBoxD1.Text ); ``` Use this if you feel confident that the contents of the text box is a valid `int`. A safer option is ``` int val = 0; Int32.TryParse( TextBoxD1.Text, out val ); ``` This will provide you with some default value you can use. `Int32.TryParse` also returns a Boolean value indicating whether it was able to parse or not, so you can even use it as the condition of an `if` statement. ``` if( Int32.TryParse( TextBoxD1.Text, out val ){ DoSomething(..); } else { HandleBadInput(..); } ```
How can I convert String to Int?
[ "", "c#", ".net", "string", "int", "type-conversion", "" ]
I'm trying to create a program that takes a text file of c++ code and outputs another file with that code, minus any comments that it contains. Assuming that rFile and wFile are defined as follows: ``` ifstream rFile; // File stream object for read only ofstream wFile; // File stream object for write only rFile.open("input.txt", ios::in); wFile.open("output.txt", ios::out); ``` My first thought was simply go through the text and do the equivalent of pen-up(logo reference) when a (slightly improved) peek() identifies /\* and pen down when it sees \*/. Of course after seeing // it would "pen-up" until it reaches \n. The problem with this approach is that the output.txt doesn't include any of the original spaces or newlines. This was the code (I didn't even try removing comments at this stage): ``` while (!rFile.eof()) { rFile>>first; //first is a char wFile<<first; } ``` So then I tried getting each line of code separately with getline() and then adding an endl to the wFile. It works so far, but makes things so much more complicated, less elegant and the code less readable. So, I'm wondering if anyone out there has any pointers for me. (no pun intended!) N.B. This is part of a larger homework assignment that I've been given and I'm limited to using only C++ functions and not C ones.
**UPDATE:** Someone else mentioned this, but I think [`get`](http://en.cppreference.com/w/cpp/io/basic_istream/get) is probably a better function to use, than ">>". **Original post:** The solution is to read the input character-by-character, rather than using `getline()`. You can read the characters in using ">>", and output them using "<<". That way you don't have to use "endl" at all. The line terminator and space characters will be read in as individual characters. When you see the start of a comment, you can then just stop outputting characters until you eat the appropriate comment terminator. You also need to make sure to treat "\r\n" as a single terminator when processing the end of a "//" token.
I would use the istreambuf\_iterator: This allows you to iterate through the file one character at a time. This also allows you to remove the processing logic from the looping logic the takes you through the file. ``` #include <iterator> #include <iostream> #include <algorithm> class CommentFilter { public: CommentFilter(std::ostream& output) :m_commentOn(false) ,m_output(output) {} // For each character we find call this method void operator()(char c) const { // Check for a change in the comment state. (ie PenDown) // Leaving this for you to do. // Now print the stuff you want. if (!m_commentOn) { // If the commentOn is true then we don't print. // Otherwise we do. m_output << c; } } private: bool m_commentOn; std::ostream& m_output; }; int main() { CommentFilter filter(std::cout); // The istreambuf_iterator allows you to iterate through a stream one obejct at a time. // In this case we define the object to be a char. // // So for each obejct (char) we find we call the functor filter with that object. // This means filer must have a method so that it can be called like this filter('a') // To-Do this we define the operator() see-above. std::for_each( std::istreambuf_iterator<char>(std::cin), std::istreambuf_iterator<char>(), filter ); } ```
a C++ program to remove comments
[ "", "c++", "parsing", "" ]
In my company, I've seen several approaches for notifying a user when their input is invalid (our validation is generally done when the user clicks some form of a "Submit" button). Here are the most common approaches I've seen: * Using the [ErrorProvider](http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider.aspx) class to communicate which controls contain invalid input. (*this is my current preference because the validation can be done in one shot and the user can easily identify which controls contain the invalid input.*) * Validating the input in all of the controls and compiling a list of messages to display to the user. Once the validation routine has completed, display all "invalid input" messages to the user at once (via a MessageBox). * Validating the input in each control sequentially and notifying the user once a piece of invalid data is found (via a MessageBox). (*I'm not a fan of this approach because if Control\_A and Control\_B both contain invalid data, the user will have to attempt to submit the data twice in order to see both validation messages.*) What do you think is the best way to go about effectively/efficiently notifying users of invalid input?
Using [IDataError](http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx), you can combine the two first approaches, since it both allows you to provide an error for individual controls, but also an aggregate error message for the entire view. In some cases, you may have validation logic that depends on the *combination* of several different input values, so only binding validation to each control would be too prohibitive. On the other hand, you still want to be able to provide an error message for each control in the many cases where this makes sense. IDataError allows you to do both. The most common UI implementation is to have a visual cue (such as a blinking icon) next to each invalid control. Popping up a modal dialog (Message Box) each time the user does something invalid is a very effective way of annoying the user - they lose context and have to spend time clicking on the 'OK' button to make the dialog go away.
We check all the controls when the user press OK. We mark each invalid value with a special colour and list all the errors in a message box.
What are the common practices for notifying a user of invalid input?
[ "", "c#", "winforms", "validation", "user-input", "" ]
Because of memory constrains, I have to store some pairs of values in an array with 6 bits/pair (3 bits/value). The problem comes when I want to access this array as a normal one, based on the index of the pair. The array looks like this ``` |--byte 0 | --byte 1 | --byte 2 |00000011 | 11112222 | 22333333 ... and so on, the pattern repeats. |------|-------|--------|------| pair 0 pair 1 pair 2 pair 3 => 4 pairs / 3 bytes ``` You can see that sometimes (for indexes divisible by 1 and 2) 2 bytes are required to extract the values. I made a function that given an index, returns the first value from the pair (3 bits) and the other one (also 3 bits). ``` void GetPair(char *array, int index, int &value1, int &value2) { int groupIndex = index >> 2; // Divide by 4 to get the index of the group of 3 bytes (with 4 pairs) // We use 16 bits starting with the first byte from the group for indexes divisible by 0 and 1, // 16 bits starting with the second byte when divisible by 2 and 3 short int value = *(short int *)(array + groupIndex + ((index & 0x02) >> 1)); switch(index & 0x03) { // index % 4 case 0: { // extract first 3 bits value1 = (value & 0xE000) >> 13; // extract the next 3 bits value2 = (value & 0x1C00) >> 10; break; } case 1: { value1 = (value & 0x380) >> 7; value2 = (value & 0x70) >> 4; break; } case 2: { value1 = (value & 0xE00) >> 9; value2 = (value & 0x1C0) >> 6; break; } case 3: { value1 = (value & 0x38) >> 2; value2 = value & 0x7; break; } } ``` Now my question is: *Is there any faster method to extract these values?* I made a test and when using 2 bytes/pair (1 byte/value) it takes about 6 seconds to access all pairs (53 in total) 100 million times. When using the compact array, it takes about 22 seconds :( (probably because it needs to compute all those masks and bit shifts). I tried to explain as clearly as i could... forgive me if not.
How about this? It eliminates memory accesses for the masks and shift values. (Of course, the (non-portable) assumption is that char is 8 bit and short is 16 bit. It is also assumed that index \* 6 does not overflow `int`.) ``` void GetPair(char *array, int index, int &value1, int &value2) { unsigned shift = 10 - index * 6 % 8; unsigned short data = (*(unsigned short *)(array + index * 6 / 8) >> shift) & 0x3f; value2 = data & 7; value1 = data >> 3; } ``` There might be a penalty for reading a short crossing a 16 bit boundary, though. There used to be such issues way back when I was still keeping track of such things. If that is the case, it would probably be better to read a 32 bit value starting at a 16 bit boundary and adjust the shifts and masks accordingly.
This is a classic case of trading off speed for memory efficiency. I assume that you are working in an environment where memory is scarce and you need to shove many, many items into this array, otherwise this probably isn't worth your time. You can eliminate the switch statement by using a lookup table to find the correct shift and mask values. ``` short int shift1[4] = { 13, 7, 9, 2 }; short int shift2[4] = { 10, 4, 6, 0 }; short int mask1[4] = { 0xe000, 0x0380, 0x0e00, 0x38 }; short int mask2[4] = { 0x1c00, 0x0700, 0x1c, 0x07 }; int index = value % 4; /* you're not saving any time by using bitwise AND but you are making your code less readable */ value1 = (value & mask1[index]) >> shift1; value2 = (value & mask2[index]) >> shift2; ``` The idea is that you eliminate any branching. However each path is so short that it just may not matter. In my testing (gcc on a PowerPC) there was barely any difference. However, the memory bandwidth on this machine is slow enough that both versions are faster than just using direct array accesses and 1 byte per value.
Array of pairs of 3 bit elements
[ "", "c++", "optimization", "memory", "" ]
In C# .NET 2.0, I have a WinForms ComboBox with ComboBoxStyle DropDownList. However, the drop down appears whenever the user clicks anywhere on the combo box. Instead, I'd like to have it only open when the user explicitly clicks on the drop down button. When the user clicks on the rest of the combo box, I'd like to just assign it the keyboard focus so he or she can use some keyboard commands on the selected item. What's the best way to do this?
After some help from the other answers, I arrived at this quick solution: ``` public class MyComboBox : ComboBox { public MyComboBox() { FlatStyle = FlatStyle.Popup; DropDownStyle = ComboBoxStyle.DropDownList; } protected override void WndProc(ref Message m) { if (m.Msg == 0x0201 /* WM_LBUTTONDOWN */ || m.Msg == 0x0203 /* WM_LBUTTONDBLCLK */) { int x = m.LParam.ToInt32() & 0xFFFF; if (x >= Width - SystemInformation.VerticalScrollBarWidth) base.WndProc(ref m); else { Focus(); Invalidate(); } } else base.WndProc(ref m); } } ```
You have two issues to consider. The first is rather simple: determine whether the dropdown should be opened or closed. This code can do that: ``` void comboBox1_MouseClick(object sender, MouseEventArgs e) { ComboBox combo = sender as ComboBox; int left = combo.Width - (SystemInformation.HorizontalScrollBarThumbWidth + SystemInformation.HorizontalResizeBorderThickness); if (e.X >= left) { // They did click the button, so let it happen. } else { // They didn't click the button, so prevent the dropdown. } } ``` The second issue is more significant -- actually preventing the dropdown from appearing. The simplest approach is: ``` comboBox1.DropDownStyle = ComboBoxStyle.DropDown; ``` But, that allows typing into the box, which you may not want. I spent about 15 minutes looking at options, and it appears that to prevent the dropdown from appearing and simultaneously prevent the user from typing into the dropdown, you would need to subclass the control. That way, you can override OnMouseClick(), and only call the base.OnMouseClick() when they did click on button. It would look something like this (untested): ``` public class CustomComboBox : ComboBox { protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); int left = this.Width - (SystemInformation.HorizontalScrollBarThumbWidth + SystemInformation.HorizontalResizeBorderThickness); if (e.X >= left) { // They did click the button, so let it happen. base.OnMouseClick(e); } else { // They didn't click the button, so prevent the dropdown. // Just do nothing. } } } ```
How can I force a DropDownList style ComboBox to only open when the user clicks the drop-down button?
[ "", "c#", "winforms", ".net-2.0", "combobox", "" ]
I have a Java project in Eclipse with ~10 packages and ~10 class files per package. Is there a way to determine total lines of code for the whole project from within Eclipse? I am familiar with other tools (e.g., Code Analyzer, wc, etc.) but I want to know if there is a way to do this within Eclipse (or get confirmation that there is no way to do it).
Here's a good metrics plugin that displays number of lines of code and much more: <http://metrics.sourceforge.net/> It says it requires Eclipse 3.1, although I imagine they mean 3.1+ Here's another metrics plugin that's been tested on Ganymede: <http://eclipse-metrics.sourceforge.net>
`Search` > `File Search` Check the `Regular expression` box. Use this expression: > \n[\s]\* Select whatever file types (`*.java`, `*.xml`, etc..) and working sets are appropriate for you.
Counting Line Numbers in Eclipse
[ "", "java", "eclipse", "" ]
I have the need to relatively quickly be able to determine if a set of files on a user's machine has been processed before by my application. The app in question uploads the files for the user to a server, and if the files have been uploaded before, it skips the upload. My plan so far has been to hash the files and then store the results along with an identifier of how they were uploaded to the server. The problem I think I'm going to run into is that storing this data could become quite cumbersome due to the length of the hashes. I'm expecting around 30-40 files right now but that could double or (hypothetically) even triple. Would this be possible to store using a Dictionary, with the hashes as the key and the server information as the value? I would then have that Dictionary stored in the App's Properties.Settings.Default object. Is that feasible to store with that system or will I run into some sort of problem there? Note that due to the nature of the application, there is *no* chance of two users ever having the same set of data, so I don't need to compare uploads between users. Additionally, what would the performance be like for this type of operation? Users are expected to have at least a Pentium-M 1.5 GHz processor with 1 GB of RAM.
I probably wouldn't put the dictionary into the app.config file, although I guess you could, depending on the server information. I'd probably just put it in a text file on its own unless you found that to be more of a problem for some reason. It feels like it's more data *for* the application than configuration *of* the application. Performance shouldn't be an issue at all - dictionaries are designed to still be efficient with *millions* of entries, let alone the tens or hundreds you're talking about.
In reference to getting the hash values, I thought I'd mention this... Using a hash value is good, so long as you get the same result each time without fail. I've read somewhere that .GetHashCode() isn't the same between different versions of .NET, so if you're planning on saving the hash in a persistent state, I'd avoid .GetHashCode(). If it is all done at once, then .GetHashCode() is ideal for comparing if things are the same. If you need to persist the hash there are hashing classes available in .NET. I'm admittedly not an expert with this, but I think SHA1 has a hashing method.
Quickly determining if a set of files are identical in C#?
[ "", "c#", "performance", "hash", "settings", "" ]
I've noticed substantial pain over this constructor (even here on Stack Overflow). People use it even though the documentation clearly states: > *The results of this constructor can be somewhat unpredictable* > <http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(double)> I've even seen a [JSR-13](http://jcp.org/en/jsr/detail?id=13) being [APPROVED](http://jcp.org/en/jsr/results?id=2758) with a recommendation stating: > *Existing specifications that might be deprecated: We propose deprecating the BigDecimal(double) constructor, which currently gives results that are different to the Double.toString() method.* Despite all this, the constructor has not yet been deprecated. I'd love to hear any views on this.
Deprecation is deprecated. Parts of APIs are only marked deprecated in exceptional cases. So, run FindBugs as part of your build process. FindBugs has a detector PlugIn API and is also open source (LGPL, IIRC).
Considering the behavior of [`BigDecimal(double)`](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html#BigDecimal(double)) is correct, in my opinion, I'm not too sure it really would be such a problem. I wouldn't exactly agree with the wording of the documentation in the `BigDecimal(double)` constructor: > The results of this constructor can be > somewhat **unpredictable**. One might > assume that writing `new > BigDecimal(0.1)` in Java creates a > `BigDecimal` which is exactly equal to > `0.1` (an unscaled value of `1`, with a scale of `1`), but it is actually equal > to > `0.1000000000000000055511151231257827021181583404541015625`. (Emphasis added.) Rather than saying *unpredictable*, I think the wording should be **unexpected**, and even so, this would be unexpected behavior for those who are not aware of the limitations of representation of decimal numbers with [floating point values](http://en.wikipedia.org/wiki/Floating_point). As long as one keeps in mind that floating point values cannot represent all decimal values with precision, the value returned by using `BigDecimal(0.1)` being `0.1000000000000000055511151231257827021181583404541015625` actually makes sense. If the `BigDecimal` object instantiated by the `BigDecimal(double)` constructor is consistent, then I would argue that the result is predictable. My guess as to why the `BigDecimal(double)` constructor is not being deprecated is because the behavior can be considered correct, and as long as one knows how floating point representations work, the behavior of the constructor is not too surprising.
Why is the Bigdecimal(double d) construction still around?
[ "", "java", "api", "bigdecimal", "" ]
Because of transitive dependencies, my wars are getting populated by xml-apis, xerces jars. I tried following the instructions on the reference page for maven-war-plugin but it is not working. ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <packagingExcludes>WEB-INF/lib/xalan-2.6.0.jar,WEB-INF/lib/xercesImpl-2.6.2.jar,WEB-INF/lib/xml-apis-1.0.b2.jar,WEB-INF/lib/xmlParserAPIs-2.6.2.jar</packagingExcludes> <webXml>${basedir}/src/main/webapp/WEB-INF/web.xml</webXml> <warName>project1</warName> <warSourceDirectory>src/main/webapp</warSourceDirectory> </configuration> </plugin> ``` What am I doing wrong ? If it matters, I discovered that the maven-war-plugin I'm using is at version 2.1-alpha-1
You can mark these dependencies as provided: ``` <dependency> <groupId>xerces</groupId> <artifactId>xerces</artifactId> <version>2.4.0</version> <scope>provided</scope> </dependency> ``` This way the maven will add them to the compilation classpath, but will not package them. It is assumed they exist in your servlet container. See more about maven scopes [here](http://maven.apache.org/pom.html#Dependencies) under "scope" **Edit** If you want to remove classes added via transitive dependencies you can exclude them from the dependency like this: ``` <dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> ``` (taken from [this answer](https://stackoverflow.com/questions/816858/maven-remove-a-single-transitive-dependency/816896#816896)) See more [here](http://maven.apache.org/guides/introduction/introduction-to-optional-and-excludes-dependencies.html)
I fixed it. Rereading the reference with a bit more care, I discovered that the element **packagingExcludes** should be **warSourceExcludes**.
How to exclude jars generated by maven war plugin?
[ "", "java", "maven-2", "" ]
We are attempting to only make available certain functions to be run based on what request address is. I was wondering how we could do this: ``` if(condition1) { $(document).ready(function() { ... ... // condition1's function }); } else if(condition2) { $(document).ready(function() { ... ... // condition2's function }); else if... ``` I was wondering what a good pattern would work for this? since we have all of our functions in one file.
It depends on what your conditions are like... If they're all of a similar format you could do something like ``` array = [ ["page1", page1func], ["page2", page2func], ... ] for(i=0; i<array.length; ++i) { item = array[i]; if(pageName == item[0]) $(document).ready(item[1]); } ```
I like [Nick's answer](https://stackoverflow.com/questions/1049745/javascript-functions/1049827#1049827) the best, but I might take a hash table approach, assuming the 'request address' is a known fixed value: ``` var request_addresses = { 'request_address_1': requestAddress1Func, 'request_address_2': requestAddress2Func }; $(document).ready(request_addresses[the_request_address]); ``` Of course, `request_addresses` could look like this as well: ``` var request_addresses = { 'request_address_1': function () { /* $(document).ready() tasks for request_address_1 */ }, 'request_address_2': function () { /* $(document).ready() tasks for request_address_2 */ } }; ```
Javascript functions
[ "", "javascript", "design-patterns", "" ]
I'm developing Swing application, and everything works fine usually. But I have an GUI issue. When I run the application, and for example minimize some other window, my application is still working, but the central part of `JFrame` is invisible or hidden. After finishing some part of program logic the GUI repaints and is visible again. This will continue until the program finishes running. Is there any API for preventing this behavior, or some class for forcing the GUI visible, or maybe to add some progress bar? If someone need this information I'm testing this on Windows Vista, with java 1.6.
It sounds to me like you are doing some sort of slow IO or calculations that are causing your GUI to become unresponsive. What you need to do is do the long running processes in another thread. The standard way of doing that is with a [`SwingWorker`](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html) class. The [Java tutorials](http://java.sun.com/docs/books/tutorial/uiswing/concurrency/) have some great resources and tutorials on how to properly use the `SwingWorker`. [Here](https://stackoverflow.com/questions/977740/swing-cant-get-jbutton-to-update-repaint-not-working) and [here](https://stackoverflow.com/questions/940913/how-to-prevent-swing-gui-locking-up-during-a-background-task) is a link to another question that I believe may be similar. This behavior you are seeing is a result of your long running process blocking the thread that the GUI uses to repaint itself. Thus, while your task is performing, the GUI is unable to repaint your `JFrame` and it becomes unresponsive.
Just like jinguy says you are most likely doing a task that takes a long time to complete and needs to be put in a background thread. Have a look at the Java Sun [Concurrency in Swing](http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html) Tutorial for more information on how to do this correctly.
Swing application problem
[ "", "java", "swing", "swingworker", "" ]
I noticed that JavaScript's `new Date()` function is very smart in accepting dates in several formats. ``` Xmas95 = new Date("25 Dec, 1995 23:15:00") Xmas95 = new Date("2009 06 12,12:52:39") Xmas95 = new Date("20 09 2006,12:52:39") ``` I could not find documentation anywhere showing all the valid string formats while calling `new Date()` function. This is for converting a string to a date. If we look at the opposite side, that is, converting a date object to a string, until now I was under the impression that JavaScript doesn't have a built-in API to format a date object into a string. > **Editor's note:** The following approach is the asker's attempt that worked on a particular browser but does *not* work in general; **see the answers on this page** to see some actual solutions. Today, I played with the `toString()` method on the date object and surprisingly it serves the purpose of formatting date to strings. ``` var d1 = new Date(); d1.toString('yyyy-MM-dd'); //Returns "2009-06-29" in Internet Explorer, but not Firefox or Chrome d1.toString('dddd, MMMM ,yyyy') //Returns "Monday, June 29,2009" in Internet Explorer, but not Firefox or Chrome ``` Also here I couldn't find any documentation on all the ways we can format the date object into a string. Where is the documentation which lists the format specifiers supported by the `Date()` object?
I love *[10 ways to format time and date using JavaScript](https://www.webdevelopersnotes.com/10-ways-to-format-time-and-date-using-javascript)* and *[Working with Dates](http://www.elated.com/articles/working-with-dates/)*. Basically, you have three methods and you have to combine the strings for yourself: ``` getDate() // Returns the date getMonth() // Returns the month getFullYear() // Returns the year ``` Example: ``` var d = new Date(); var curr_date = d.getDate(); var curr_month = d.getMonth() + 1; //Months are zero based var curr_year = d.getFullYear(); console.log(curr_date + "-" + curr_month + "-" + curr_year); ```
**[Moment.js](http://momentjs.com)** It is a (lightweight)\* JavaScript date library for parsing, manipulating, and formatting dates. ``` var a = moment([2010, 1, 14, 15, 25, 50, 125]); a.format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm" a.format("ddd, hA"); // "Sun, 3PM" ``` *(\*) lightweight meaning 9.3KB minified + gzipped in the smallest possible setup (feb 2014)*
Where can I find documentation on formatting a date in JavaScript?
[ "", "javascript", "date", "datetime-format", "date-format", "time-format", "" ]
My server time is in GMT, and I do the following whenever someone comes online. ``` // Set a default timezone $defaultTimeZone = 'America/Toronto'; // load the user, if they are online... $onlineUser = new user(); if (isset($_SESSION['user_id'])) { if ($onlineUser->loadUser($_SESSION['user_id'])) { $defaultTimeZone = $onlineUser->timeZone; } } // set time zones date_default_timezone_set($defaultTimeZone); $db->query("SET SESSION time_zone = '".$defaultTimeZone."'"); ``` So, my problem is this... whenever someone does something it stores the date/time in the users local time... causing me a whole wack of issues. All I want is for everything to be stored in GMT, but have the users see & interact with the data in their local time zone. **EDIT:** Here is how I am updating the users status: ``` public function updateStatus() { global $db, $common, $config; // update the user record $data = array( 'date_last_active' => new Zend_Db_Expr('NOW()') ); $db->update('users', $data, 'user_id='.$this->userId); } ``` Here is my function to turn a date stamp into seconds... ``` public function dateTimeToUnixTime($dateString) { if (strlen($dateString) < 10) { return ""; } $parseDateTime = split(" ", $dateString); $parseDate = split("-", $parseDateTime[0]); if (isset($parseDateTime[1])) { $parseTime = split(":", $parseDateTime[1]); } else { $parseTime = split(":", "00:00:00"); } return mktime($parseTime[0], $parseTime[1], $parseTime[2], $parseDate[1], $parseDate[2], $parseDate[0]); } ``` And finally, how I am comparing the dates: ``` $date = $oUser->dateLastActive; $lastSeen = abs($common->dateTimeToUnixTime(date('Y-m-d H:i:s')) - $common->dateTimeToUnixTime($date)); if ($lastSeen < 300 ) { echo "<font size='1' color='green'><strong>Online</strong></font>"; } if ($lastSeen >= 300) { echo "<font size='1' color='black'><strong>Offline</strong></font>"; } ```
The trick here is to know what column type `date_last_active` is. I've had enough experience with `TIMESTAMP` and `DATETIME` to know that one translates (and honors) the MySQL time\_zone session variable, the other doesn't. ``` mysql> SET SESSION time_zone = 'America/New_York'; Query OK, 0 rows affected (0.00 sec) mysql> create table timetest ( dt datetime NULL, ts timestamp NOT NULL DEFAULT 0 ); Query OK, 0 rows affected (0.06 sec) mysql> INSERT INTO timetest ( dt, ts ) VALUES ( UTC_TIMESTAMP(), UTC_TIMESTAMP() ); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO timetest ( dt, ts ) VALUES ( NOW(), NOW() ); Query OK, 1 row affected (0.00 sec) mysql> SELECT * FROM timetest; +---------------------+---------------------+ | dt | ts | +---------------------+---------------------+ | 2009-06-27 17:53:51 | 2009-06-27 17:53:51 | | 2009-06-27 13:53:54 | 2009-06-27 13:53:54 | +---------------------+---------------------+ 2 rows in set (0.00 sec) mysql> set session time_zone='UTC'; Query OK, 0 rows affected (0.00 sec) mysql> SELECT * FROM timetest; +---------------------+---------------------+ | dt | ts | +---------------------+---------------------+ | 2009-06-27 17:53:51 | 2009-06-27 21:53:51 | | 2009-06-27 13:53:54 | 2009-06-27 17:53:54 | +---------------------+---------------------+ 2 rows in set (0.00 sec) ``` So, here is what I do: * When inserting into the database, use UTC in PHP and in MySQL. In `my.cnf` I have: `time_zone=UTC` to avoid any issues in MySQL, and in PHP I `date_default_timezone_set('UTC')`. * Use `UTC_TIMESTAMP()` instead of `NOW()` - one is UTC, one uses the local (session) time zone. If you're following the first point, above, use UTC\_TIMESTAMP(). * When selecting to display to the user, `set time_zone='`*local\_time\_zone*`'` before displaying anything. * If you have to display stuff, then update, make sure to bracket your calls with the appropriate timezone changes in PHP and MySQL. Hopefully that's enough to figure out how to approach this. Let me know if you have further questions.
I think Mysql's NOW() function stores the current time zone, which is definitely a hassle, I would check out CONVERT\_TZ(dt,from\_tz,to\_tz), this could solve your issue, also I believe php's time() returns server time, you could store this instead. the only drawback is you'd either have to convert the returned value to a datetime/timestamp compatible value, or store it as a varchar. the drawback to using convert\_tz is you could end up with some ugly queries, and you'd have to figure out the current time zone every time you used it.
Having Timezone problems with PHP and MySQL
[ "", "php", "mysql", "timezone", "" ]
I have 2 files namely: 1. *uploading.php* 2. *emaillinks.php* both include a file *inc.php* which has all the include files and initiate database connection. a variable is declared in file *uploading.php*, i wanted to know how can i access it in *emaillinks.php*, i cant include *uploading.php* in *emaillinks.php*. I want to avoid cookies because data is big and always different. what is the best option to make it accessible by emaillinks.php? Thank You.
Depending on what it is, you could put it into the database or into the [session](http://php.net/session_start) (`$_SESSION`)
If you can't include you'll need to go with session variables or cookies.
accessing values globally
[ "", "php", "" ]
Am currently working on an application that requires users to submit posts and comments which is displayed on the site. As we all know that user input can't be trusted so i used htmlspecialchars($string,ENT\_QUOTES) to process user's posts and comments. Now, i want some certain html tags ignored. such as `<b><br />` and a few more tags. How can i do it so that htmlspecialchars ignores some tags while it filters the others.
**solution a)** use strip\_tags insted of htmlspecialchars, and whitelist the needed tags. **better solution b)** Use bbcodes, and give aliases to the wanted tags, e.g: [b]bold[/b]
It is **very, very difficult** to allow only some HTML tags without allowing any possibility of script injection or the like. I would actually recommend avoiding this and using something that generates HTML such as [this UBB code parser](http://www.phpclasses.org/browse/package/818.html) (or similar). Or even [Markdown](http://daringfireball.net/projects/markdown/) (with HTML option turned off). That gives no scope for attackers to hit your site, which is very important if it is public-facing. If you allow even some HTML through, chances are that a determined attacker will find a way round it.
User Input filtering in PHP
[ "", "php", "blogs", "user-input", "textinput", "htmlspecialchars", "" ]
How can I create a new `Exception` different from the pre-made types? ``` public class InvalidBankFeeAmountException extends Exception{ public InvalidBankFeeAmountException(String message){ super(message); } } ``` It will show the warning for the **InvalidBankFeeAmountException** which is written in the first line.
All you need to do is create a new `class` and have it `extend Exception`. If you want an `Exception` that is unchecked, you need to `extend RuntimeException`. **Note**: A checked `Exception` is one that requires you to either surround the `Exception` in a `try`/`catch` block or have a '`throws`' clause on the method declaration. (like `IOException`) Unchecked `Exceptions` may be thrown just like checked `Exceptions`, but you aren't required to explicitly handle them in any way (`IndexOutOfBoundsException`). For example: ``` public class MyNewException extends RuntimeException { public MyNewException(){ super(); } public MyNewException(String message){ super(message); } } ```
just extend either * `Exception`, if you want your exception to be checked (i.e: required in a throws clause) * `RuntimeException`, if you want your exception to be unchecked.
How can I write custom Exceptions?
[ "", "java", "exception", "" ]
I need to parse a log in the following format: ``` ===== Item 5483/14800 ===== This is the item title Info: some note ===== Item 5483/14800 (Update 1/3) ===== This is the item title Info: some other note ===== Item 5483/14800 (Update 2/3) ===== This is the item title Info: some more notes ===== Item 5483/14800 (Update 3/3) ===== This is the item title Info: some other note Test finished. Result Foo. Time 12 secunds. Stats: CPU 0.5 MEM 5.3 ===== Item 5484/14800 ===== This is this items title Info: some note Test finished. Result Bar. Time 4 secunds. Stats: CPU 0.9 MEM 4.7 ===== Item 5485/14800 ===== This is the title of this item Info: some note Test finished. Result FooBar. Time 7 secunds. Stats: CPU 2.5 MEM 2.8 ``` I only need to extract each item's title (next line after ===== Item 5484/14800 =====) and the result. So i need to keep only the line with the item title and the result for that title and discard everything else. The issue is that sometimes a item has notes (maxim 3) and sometimes the result is displayed without additional notes so this makes it tricky. Any help would be appreciated. I'm doing the parser in python but don't need the actual code but some pointing in how could i achive this? LE: The result I'm looking for is to discard everything else and get something like: ``` ('This is the item title','Foo') then ('This is this items title','Bar') ```
``` 1) Loop through every line in the log a)If line matches appropriate Regex: Display/Store Next Line as the item title. Look for the next line containing "Result XXXX." and parse out that result for including in the result set. ``` EDIT: added a bit more now that I see the result you're looking for.
I know you didn't ask for real code but this is too great an opportunity for a generator-based text muncher to pass up: ``` # data is a multiline string containing your log, but this # function could be easily rewritten to accept a file handle. def get_stats(data): title = "" grab_title = False for line in data.split('\n'): if line.startswith("====="): grab_title = True elif grab_title: grab_title = False title = line elif line.startswith("Test finished."): start = line.index("Result") + 7 end = line.index("Time") - 2 yield (title, line[start:end]) for d in get_stats(data): print d # Returns: # ('This is the item title', 'Foo') # ('This is this items title', 'Bar') # ('This is the title of this item', 'FooBar') ``` Hopefully this is straightforward enough. Do ask if you have questions on how exactly the above works.
How would I go about parsing the following log?
[ "", "python", "parsing", "" ]
If I have a method that operates exclusively on a reference type variable (e.g. a datatable) and modifies it, is there any need to return that variable from the method?? For example, the following method goes through a datatable and trims all the values within it and then returns the datatable to the caller: ``` private DataTable TrimAllDataInDataTable(DataTable dt) { foreach (DataRow row in dt.Rows) { foreach (DataColumn dc in dt.Columns) { row[dc] = row[dc].ToString().Trim(); } } return dt; } ``` Would it be better if this method returns void? Seems pretty pointless to return it (?), but do you think that it reads better if it returns the object after operating on it (like it does at the moment)??
To me, when a method returns a reference type, I expect it to be a new object. I'd pick making it return void. A question: is there any reason for this method to not be a member of the `DataTable` class? I think that `DataTable.TrimAllData()` would work even better
Personally, I'd return void. The method name lets developers know that you are going to modify values in the DataTable, and returning the DataTable doesn't give any benefit whilst it may introduce the ambiguity that you are cloning the table before processing it.
If a method performs operations on a reference type is there any need to return it?
[ "", "c#", "" ]
I was looking at the jQuery UI code, and I found that every file starts with a construct like this: ``` jQuery.ui || (function($) { ``` My question is: why is there a semicolon before `jQuery`, and why is the logical OR being done?
> why is there a semicolon before jQuery? The semi-colon is there to ensure safe file concatenation. (libraries and library components are frequently packed into a single file) > why is the logical OR being done? The self-invoking anonymous function on the right hand-side will only run if the left-hand-side of the statement evaluates to a falsey value. So if **`jQuery.ui`** already exists on the page then the function will not run. It only runs when **`jQuery.ui`** does not yet exist.
I'm guessing the `;` is to ensure that javascript packers won't mess up the line, but that's the best I have. The logical or is there to make sure that `jQuery.ui` doesn't get declared twice. JavaScript does short circuit, so it won't evaluate the right hand side of the `||` if the left hand side evaluates to something that is [truthey](http://www.protonfish.com/jslang.shtml) *(thanks [JP](http://www.protonfish.com/jslang.shtml)!)*. Bonus syntax deciphering, that $ that's passed in to the anonymous function is the reference to jQuery. I had to scroll all the way down the page before that one clicked :-) So, here's a broken down version of the line above ``` ; // extra semi colon to ensure correct concatenation and minifying jQuery.ui // check if the variable called jQuery.ui is truthey || // OR if jQuery.ui isn't defined (function($) {...})(jQuery); // define and execute an anonymous function // passing in the conflict safe jQuery // as the parameter called $ ```
What is the consequence of this bit of javascript?
[ "", "javascript", "jquery", "jquery-ui", "" ]
I have 2 Message driven beans. 2 Activation Specs for these beans. I have one Message bus and both the activation specs are configured to this one bus. I have 2 different queues and one queue connection factory configured for that one Message bus. Now, I would write my code to send a message to one of the queues at runtime after determining the queue. However, both my MDBs receive the same message. How is this configuration done in general? Do I always configure 1 Queue -> 1 Queue Connection Factory -> 1 Message Bus -> 1 MDB? Is it all a one-to-one relationship? Oh, I forgot to mention this: I am using Websphere Application Server v6.1
In general the concept is that: 1. a message is sent(Queue)/published(Topic) to a destination (Queue/Topic) 2. the ActivationSpec listens to messages at a particular destintation (Queue/Topic) 3. ActivationSpec : Destination is a 1:1 relationship 4. A bean (MDB which is a consumer) is configured to listen to an ActivationSpec. What this means is that in effect the bean is linked to a destination with a layer of indirection provided by the activationSpec. Where does the bus come in - SIBus is the messaging infrastructure that makes all this possible. Destinations are hosted on the bus. Coming to the question - the ActivationSpec would be configured to listen to a destination on the bus to which messages would be sent. The connection factory decides the bus to which message would be sent. As long as the destination name is unique and targetted to a specific queue (JMS Queue is linked to destination on the bus) one message would only be received by one ActivationSpec. how many destinations (under SIBus link in WAS admin console) have been created on the bus ? Could you check/validate if the configuration is correct? to answer your questions - "Is it one bus per activation spec and one queue connection factory per queue." - the answer is NO. 1. Bus is the underlying infrastructure that can host "n" destinations. One ActivationSpec listens to one destination. 2. With queue connection factory is a factory (J2EE factory pattern) for creating queues.
I suspect the configuration you have is not set up the way you think it is. We use the same configuration your described, with many MDB's (with a queue and activation spec), a single factory and message bus and everything works as expected. To get the behaviour you are seeing is not actually possible unless you either send the same message to both queues, or have defined a topic instead of a queue. I am pretty sure that even if both MDB's are reading from the same queue, only one will get the message, since a queue only supports point to point messaging. What you have described is topic based behaviour.
Message Driven Beans - Single Bus, Multiple Activation Specs
[ "", "java", "jakarta-ee", "message-queue", "message-driven-bean", "" ]
I have a application written in wxPython which I want to make multilingual. Our options are 1. using gettext <http://docs.python.org/library/gettext.html> 2. seprating out all UI text to a messages.py file, and using it to translate text I am very much inclined towards 2nd and I see no benefit in going gettext way, using 2nd way i can have all my messages at one place not in code, so If i need to change a message, code need not be changed, in case of gettext i may have confusing msg-constants as I will be just wrapping the orginal msg instead of converting it to a constant in messages.py basically instead of ``` wx.MessageBox(_("Hi stackoverflow!")) ``` I think ``` wx.MessageBox(messages.GREET_SO) ``` is better, so is there any advantage in gettext way and disadvantage 2nd way? and is there a 3rd way? edit: also gettext languages files seems to be too tied to code, and what happens if i want two messages same in english but different in french e.g. suppose french has more subtle translation for different scnerarios for english one is ok experience: I have already gone 2nd way, and i must say every application should try to extract UI text from code, it gives a chance to refactor, see where UI is creeping into model and where UI text can be improved, gettext in comparison is mechanic, doesn't gives any input for coder, and i think would be more difficult to maintain. and while creating a name for text e.g. PRINT\_PROGRESS\_MSG, gives a chance to see that at many places, same msg is being used slightly differently and can be merged into a single name, which later on will help when i need to change msg only once. Conclusion: I am still not sure of any advantage to use gettext and am using my own messages file. but I have selected the answer which at least explained few points why gettext can be beneficial. The final solution IMO is which takes the best from both ways i.e my own message identifier wrapped by gettext e.g ``` wx.MessageBox(_("GREET_SO")) ```
Gettext is the way to go, in your example you can also use gettext to "avoid storing the translations in the code": ``` wx.MessageBox(messages.GREET_SO) ``` might be the same with gettext as: ``` wx.MessageBox(_("GREET_SO")) or wx.MessageBox(_("messages.GREET_SO")) ``` Gettext is pretty much the standard for multilingual applications, and I'm pretty sure you'll benefit from using it in the future. Example, you can use Poedit (or other similar app) to assign translations to your collaborators or contributors and later on flag one or several messages as not properly translated. Also if there are missing / extra entries poedit will warn you. Don't fool yourself, gettext is the only proven reliable way to maintain translations.
There are some advantages of gettext: 1. One of the biggest advantages is: when using poedit to do the translations you can benefit from the translation database. Basically poedit ca scan your harddisk and find already translated files and will make suggestions when you translate your file. 2. When you give the code to other people to translate they might already know the gettext way of translating, while you have to explain them your way of translating. 3. You have the text in the context of the code, so it should be easier to translate, when you see the code around the translation 4. Consider text like: `print _('%d files of %d files selected') % (num, numTotal)` and even more complicated situations. Here it really helps having the code around ...
Making a wxPython application multilingual
[ "", "python", "internationalization", "multilingual", "gettext", "" ]
I'm trying to convert `std::string` to `float/double`. I tried: ``` std::string num = "0.6"; double temp = (double)atof(num.c_str()); ``` But it always returns zero. Any other ways?
``` std::string num = "0.6"; double temp = ::atof(num.c_str()); ``` Does it for me, it is a valid C++ syntax to convert a string to a double. You can do it with the stringstream or boost::lexical\_cast but those come with a performance penalty. --- Ahaha you have a Qt project ... ``` QString winOpacity("0.6"); double temp = winOpacity.toDouble(); ``` Extra note: If the input data is a `const char*`, `QByteArray::toDouble` will be faster.
The Standard Library (C++11) offers the desired functionality with [`std::stod`](http://www.cplusplus.com/reference/string/stod/) : ``` std::string s = "0.6" std::wstring ws = "0.7" double d = std::stod(s); double dw = std::stod(ws); ``` Generally for most other basic types, see [`<string>`](http://www.cplusplus.com/reference/string/). There are some new features for C strings, too. See [`<stdlib.h>`](http://www.cplusplus.com/reference/cstdlib/)
Why can't I convert a std::string to double using atof?
[ "", "c++", "" ]
Netscape fails to read a lot of jQuery written. What steps do you take to overcome these, and how much of the market do netscape users take up?
Steps I would take: 1. Let it fail 2. Wait for Netscape users to notice they are using a long dead browser with security holes in it The market share for Netscape is as close to zero as makes no matter.
Umm, 0%? Having said that, I have to admit that jquery fails on a lot of sites while prototype works, in my ancient Konqueror 3.5.10, so maybe there's a pattern here.
Getting jQuery to work with Netscape 7 and 8
[ "", "javascript", "jquery", "browser", "conflict", "netscape", "" ]
In order to work with decimal data types, I have to do this with variable initialization: ``` decimal aValue = 50.0M; ``` What does the M part stand for?
It means it's a decimal literal, as others have said. However, the origins are probably not those suggested elsewhere in this answer. From the [C# Annotated Standard](https://rads.stackoverflow.com/amzn/click/com/0123725119) (the ECMA version, not the MS version): > The `decimal` suffix is M/m since D/d > was already taken by `double`. > Although it has been suggested that M > stands for money, Peter Golde recalls > that M was chosen simply as the next > best letter in `decimal`. A similar annotation mentions that early versions of C# included "Y" and "S" for `byte` and `short` literals respectively. They were dropped on the grounds of not being useful very often.
From C# specifications: ``` var f = 0f; // float var d = 0d; // double var m = 0m; // decimal (money) var u = 0u; // unsigned int var l = 0l; // long var ul = 0ul; // unsigned long ``` Note that you can use an uppercase or lowercase notation.
What does the M stand for in C# Decimal literal notation?
[ "", "c#", "decimal", "literals", "" ]
I want to know what this looks like. I don't have any ideas about ZendFramework, and that makes me sad. :( If any one knows of a site which is built in ZendFramework, or has any other experience with it, please do let me know your thoughts.
I've been looking for an up-to-date best-practice and feature-filled Zend Framework based application to be able to base things on myself, to little effect thus far. I did come across a decent small version of that though last week - <http://www.dodoapp.com/> It's a fairly simple ajax-enabled todo-list, with member self-registration, login and admin back-end, but no openId or major use of ACLs and so on that I'd love to have more live examples of. <http://www.dodoapp.com/> has at least been updated to use Zend\_Application and the source code is downloadable.
I believe zend does! Here <http://framework.zend.com/about/casestudies> Also [magento](http://www.magentocommerce.com/) is a notable application of the zend framework **Update:** Just found another post that you might find helpful. A more extensive list of zend framework based projects: <http://devzone.zend.com/article/2060>
Does any one have an example of a website build in ZendFrameWork?
[ "", "php", "zend-framework", "" ]
Excerpt from code ``` PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sch.tab1 where col1 like lower ( 'ABZ' ) "); preparedStatement.executeQuery(); ``` The above code executes successfully. But when i try to execute this ``` PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sch.tab1 where col1 like lower ( ? ) "); preparedStatement.setString ( myValue ); preparedStatement.executeQuery(); ``` It throws an exception."*STRING TO BE PREPARED CONTAINS INVALID USE OF PARAMETER MARKERS*" What could be the problem here? --- ***Answer found, see the comments***
I think Carlos is on to something. Try ``` SELECT * FROM sch.tab1 where col1 like lower ( '' + ? ) ``` or whatever passes for string concatenation operator in your version of SQL. Forcing a string context might get you past the error. May require extra parentheses.
I *suspect* the problem is that you can't apply functions directly to parameters. Is there any particular reason why you want the lower casing to be performed at the database rather than in your code? (I can think of some potential reasons, admittedly.) Unless you really need to do this, I'd just change the SQL to: ``` SELECT * FROM sch.tab1 where col1 like ? ``` and call `toLower()` in Java, preferably specifying the appropriate locale in which to perform the lower-casing.
Query does not work with a parameter marker with preparedStatement
[ "", "java", "jdbc", "prepared-statement", "" ]
I am trying to compare two text files and output the first string in the comparison file that does not match but am having difficulty since I am very new to python. Can anybody please give me a sample way to use this module. When I try something like: ``` result = difflib.SequenceMatcher(None, testFile, comparisonFile) ``` I get an error saying object of type 'file' has no len.
For starters, you need to pass strings to difflib.SequenceMatcher, not files: ``` # Like so difflib.SequenceMatcher(None, str1, str2) # Or just read the files in difflib.SequenceMatcher(None, file1.read(), file2.read()) ``` That'll fix your error. To get the first non-matching string, see the [difflib documentation.](http://docs.python.org/library/difflib.html)
Here is a quick example of comparing the contents of two files using Python difflib... ``` import difflib file1 = "myFile1.txt" file2 = "myFile2.txt" diff = difflib.ndiff(open(file1).readlines(),open(file2).readlines()) print ''.join(diff), ```
Comparing two .txt files using difflib in Python
[ "", "python", "difflib", "" ]
In an application I will have between about 3000 and 30000 strings. After creation (read from files unordered) there will not be many strings that will be added often (but there WILL be sometimes!). Deletion of strings will also not happen often. Comparing a string with the ones stored will occur frequently. What kind of structure can I use best, a hashtable, a tree (Red-Black, Splay,....) or just on ordered list (maybe a StringArray?) ? (Additional remark : a link to a good C# implementation would be appreciated as well)
It sounds like you simply need a hashtable. The [`HashSet<T>`](http://msdn.microsoft.com/en-us/library/bb359438.aspx) would thus seem to be the ideal choice. (You don't seem to require keys, but `Dictionary<T>` would be the right option if you did, of course.) Here's a summary of the time complexities of the different operations on a `HashSet<T>` of size `n`. They're partially based off the fact that the type uses an array as the backing data structure. * **Insertion:** Typically `O(1)`, but potentially `O(n)` if the array needs to be resized. * **Deletion:** `O(1)` * **Exists (Contains):** `O(1)` (given ideal hashtable buckets) Someone correct me if any of these are wrong please. They are just my best guesses from what I know of the implementation/hashtables in general.
[HashSet](http://msdn.microsoft.com/en-us/library/bb359438.aspx) is very good for fast insertion and search speeds. Add, Remove and Contains are O(1). Edit- Add assumes the array does not need to be resized. If that's the case as Noldorin has stated it is O(n). I used HashSet on a recent VB 6 (I didn't write it) to .NET 3.5 upgrade project where I was iterating round a collection that had child items and each child item could appear in more than one parent item. The application processed a list of items I wanted to send to an API that charges a lot of money per call. I basically used the HashSet to keep track items I'd already sent to prevent us incurring an unnecessary charge. As the process was invoked several times (it is basically a batch job with multiple commands), I serialized the HashSet between invocations. This worked very well- I had a requirement to reuse as much as the existing code as possible as this had been thoroughly tested. The HashSet certainly performed very fast.
Efficient insertion and search of strings
[ "", "c#", "search", "" ]
I'd like to generate a number of objects (in C++) based on the amount/number the user enters. Now I've somewhere heard that it has to be done using pointer tricks, creating a pointer to an array of the Object type required, and then dynamically increasing the size of array ( at runtime ). Isn't there a workaround of directly using names like Object1, Object2..... ObjectX instead of having Classname \*Object[] and then using the array index to get the object ? In either case, it'd be great if someone could clarify on the issue. Thanks !
So far no-one has explained why your thinking is flawed. C++ is a compiled language, and it goes to great lengths to turn the source program into efficient machine code. For this reason, the names you give variables are available to the program only at compile time, when you turn it from source into an executable file. Afterwards, when you want to create objects dynamically, those kinds of information are no longer available. The program only knows about the machine addresses where operands to machine instructions are located.
If you want dynamically-sized array, then use std::vector. You won't be able to resize a built-in array. If you want to be able to get an object by string name, then you should use std::map, it has an indexer: ``` std::map<string, Classname> myMap; myMap["Object1"] = Classname(); Classname newClassname = myMap["Object1"]; ```
How to generate C++ Dynamic Objects names?
[ "", "c++", "arrays", "dynamic", "pointers", "object", "" ]
I am trying to figure out the exact meaning of the words `Covariance` and `Contravariance` from several articles online and questions on StackOverflow, and from what I can understand, it's only **another word for polymorphism**. Am I correct with the above statement? Or have I got it wrong ?
It's certainly related to polymorphism. I wouldn't say they're just "another word" for polymorphism though - they're about very specific situations, where you can treat one type as if it were another type *in a certain context*. For instance, with normal polymorphism you can treat any reference to a `Banana` as a reference to a `Fruit` - but that doesn't mean you can substitute `Fruit` *every* time you see the type `Banana`. For example, a `List<Banana>` can't be treated as a `List<Fruit>` because `list.Add(new Apple())` is valid for `List<Fruit>` but not for `List<Banana>`. Covariance allows a "bigger" (less specific) type to be substituted in an API where the original type is *only* used in an "output" position (e.g. as a return value). Contravariance allows a "smaller" (more specific) type to be substituted in an API where the original type is *only* used in an "input" position. It's hard to go into all the details in a single SO post (although hopefully someone else will do a better job than this!). Eric Lippert has an excellent [series of blog posts](https://ericlippert.com/category/covariance-and-contravariance/) about it.
Thanks for all the shout-outs, guys. Jon and Rasmus's answers are fine, I would just add a quick technical note. When speaking casually and informally, yes, people use "covariance" and "contravariance" to refer to a specific kind of polymorphism. That is, the kind of polymorphism where you treat a sequence of spiders as though it were a sequence of animals. Were we to get all computer-sciency and try to make more technical definitions, then I probably would not say that covariance and contravariance are "a kind of polymorphism". I would approach a more technical definition like this: First, I'd note that there are two possible kinds of polymorphism in C# that you might be talking about, and it is important to not confuse them. The first kind is traditionally called "ad hoc polymorphism", and that's the polymorphism where you have a method M(Animal x), and you pass spiders and giraffes and wallabies to it, and the method uniformly treats its passed-in arguments the same way by using the commonalities guaranteed by the Animal base class. The second kind is traditionally called "parametric polymorphism", or "generic polymorphism". That's the ability to make a generic method `M<T>(T t)` and then have a bunch of code in the method that again, treats the argument uniformly based on commonalities guaranteed by the constraints on T. I think you're talking about the first kind of polymorphism. But my point is just that we can define polymorphism as the ability of a programming language to *treat different things uniformly based on a known commonality.* (For example, a known base type, or known implemented interface.) Covariance and contravariance is the ability of a programming language to *take advantage of commonalities between generic types deduced from known commonalities of their type arguments.*
C# : Is Variance (Covariance / Contravariance) another word for Polymorphism?
[ "", "c#", "polymorphism", "covariance", "contravariance", "variance", "" ]
I have a datagridview and a combobox which get populated randomly with data. However, the new data is never displayed automatically. Someone mentioned the idea of invalidating the control to force the application to redraw it and thus iterate through the contents and populate the control with the new data. Does anyone know which is the best method for implementing auto-updating controls in windows forms applications? help greatly appreciated, regards.
If you use a BindingSource, the BindingSource.ResetBindings method might help you.
I suppose you use databinding ? You use databinding on custom objects ? in that case, your classes have to implement the INotifyPropertyChanged interface.
C# Win Forms Auto-Updating Controls
[ "", "c#", "winforms", "datagridview", "combobox", "auto-update", "" ]
I have to monitor a serial port and process its data. As a test program I was using select for just one port. The run function is as follows: ``` void <ProtocolClass>::run() { int fd = mPort->GetFileDescriptor(); fd_set readfs; int maxfd=1; int res; FD_ZERO(&readfs); FD_SET(fd,&readfs); struct timeval Timeout; Timeout.tv_usec=0; Timeout.tv_sec=3; //BYTE ack_message_frame[ACKNOWLEDGE_FRAME_SIZE]; while(true) { usleep(10); res=select(maxfd,&readfs,NULL,NULL,NULL); if(res<0) perror("\nselect failed"); else if( res==0) puts("TIMEOUT"); else if(FD_ISSET(fd,&readfs)) {//IF INPUT RECEIVED qDebug("************RECEIVED DATA****************"); FlushBuf(); qDebug("\nReading data into a read buffer"); int bytes_read=mPort->ReadPort(mBuf,1000); mFrameReceived=false; for(int i=0;i<bytes_read;i++) { qDebug("%x",mBuf[i]); } //if complete frame has been received, write the acknowledge message frame to the port. if(bytes_read>0) { qDebug("\nAbout to Process Received bytes"); ProcessReceivedBytes(mBuf,bytes_read); qDebug("\n Processed Received bytes"); if(mFrameReceived) { int no_bytes=mPort->WritePort(mAcknowledgeMessage,ACKNOWLEDGE_FRAME_SIZE); }//if frame received }//if bytes read > 0 } //if input received }//end while } ``` But the problem is it doesn't seemed to work as nothing happens. Can somebody suggest the correct way to do it. I want to use select per thread. Is this feasible. Can you give me a sample code to do it. I have searched the net but the examples are very basic involving just the main function. There are no C++ specific examples. I am using Qt threads by the way. Thanks
i think i know what's the problem. ``` FD_ZERO(&readfs); FD_SET(fd,&readfs); ``` The above lines should be inside the while loop. Because, select call will reset the 'fd' bit position in the readFs structure. So, the next time when select is called, it does know what while file descriptors to poll, as all are reset here. The correction suggested by stefaanv should also be included
First thing I noticed: maxfds must be fd + 1. Would this help?
Select() not Working in thread
[ "", "c++", "multithreading", "" ]
I'm looking for a nice tight regex solution to this problem. I'm looking to reformat an UNC into a Uri Problem: UNC directory needs to be reformatted into a Uri **\\server\d$\x\y\z\AAA** needs to look like: **<http://server/z/AAA>**
I think a replace is easier to write and understand than Regex in this case. Given: ``` string input = "\\\\server\\d$\\x\\y\\z\\AAA"; ``` You can do a double replace: ``` string output = String.Format("http:{0}", input.Replace("\\d$\\x\\y", String.Empty).Replace("\\", "/")); ```
.Net framework supports a class called [System.Uri](http://msdn.microsoft.com/en-us/library/txt7706a.aspx) which can do the conversion. It is simpler and handles the escape cases. It handles both UNC, local paths to Uri format. C#: ``` Console.WriteLine((new System.Uri("C:\Temp\Test.xml")).AbsoluteUri); ``` PowerShell: ``` (New-Object System.Uri 'C:\Temp\Test.xml').AbsoluteUri ``` Output: ``` file:///C:/Temp/Test.xml ```
Regular Expressions ~ convert UNC to URL
[ "", "c#", "regex", "uri", "unc", "" ]
On Oracle 9i, why does the following produce the result 'abc' ``` select 'abc ' || (select txt from (select 'xyz' as txt from dual where 1=2)) from dual ``` while this produces 'abc xyz': ``` select 'abc ' || (select txt from (select count(*), 'xyz' as txt from dual where 1=2)) from dual ``` Why does adding count(\*) to the subquery result in different behavior? Should the predicate **`where 1=2`** preclude any results in the subquery?
``` select count(*) from dual where 1=2 ``` returns 0. That is, a row with the value zero.
It's returning the count of everything in the subquery, which is correctly 0. Using aggregate functions always (and correctly) behaves this way and is part of the SQL standard.
Why does adding count(*) to a select statement force a row to exist in a subquery?
[ "", "sql", "oracle", "subquery", "" ]
I just tryed the standard way for adding CToolbar to a dialog on the new CMFCToolBar. But it doesn't work. Befor I dip into the new implementation, I want to know if it actually possible?
I'm not sure what you mean by "the standard way", but you can certainly do it programatically: ``` // In MyDlg.h class CMyDlg : public CDialog { ... CMFCToolBar m_ToolBar; ... }; // In MyDlg.cpp BOOL CMyDlg::OnInitDialog() { ... if( m_ToolBar.Create( this, AFX_DEFAULT_TOOLBAR_STYLE, 100 ) ) { m_ToolBar.SetPaneStyle( m_ToolBar.GetPaneStyle() & ~(CBRS_GRIPPER | CBRS_SIZE_DYNAMIC | CBRS_BORDER_ANY) ); m_ToolBar.InsertButton( CMFCToolBarButton( ID_APP_ABOUT, -1, _T("About") ) ); m_ToolBar.InsertButton( CMFCToolBarButton( ID_APP_EXIT, -1, _T("Exit") ) ); CSize sizeToolBar = m_ToolBar.CalcFixedLayout( FALSE, TRUE ); m_ToolBar.SetWindowPos( NULL, 0, 0, sizeToolBar.cx, sizeToolBar.cy, SWP_NOACTIVATE | SWP_NOZORDER ); } ... } ```
If you only have to deal with dialog-only commands the trick is to set SetRouteCommandsViaFrame to FALSE. Then the owner (usually the dialog) will be used for commands instead of the main frame.
Is it possible to add CMFCToolBar to a dialog?
[ "", "c++", "visual-c++", "mfc", "mfc-feature-pack", "" ]
So I have some settings that are of the **user** scope, but for some reason, they are not being saved to the .exe.config file. I do the following: ``` Properties.Settings.Default.Email = "new@value.com"; Properties.Settings.Default.Save(); ``` Yet I look at the settings file in the debug folder and it is still the default that I set in visual studio. Am I doing this wrong?
User settings are specific to the user, so they wouldn't get saved back to the .exe.config file, which is system wide. From the docs of `LocalSettingsProvider`: > Application-scoped settings and the > default user-scoped settings are > stored in a file named > application.exe.config, which is > created in the same directory as the > executable file. Application > configuration settings are read-only. > Specific user data is stored in a file > named `username.config`, stored under > the user's home directory. So for a UserSettingsTest application just run from VS under the debugger (hence the vshost bit) I ended up with a path of: ``` C:\Users\Jon\AppData\Local\UserSettingsTest \UserSettingsTest.vshost.e_Url_pdqoppugkz1vaawbhwkkcu5ibxpi2fgu \1.0.0.0\user.config ```
If you have your Assembly info set to automatically generate any version numbers (1.0.\*), then every time you debug your app the version number will be different, and so will be creating a new file every time. If this is the case you will need to perform an upgrade on the settings file: ``` Properties.Settings.Default.Upgrade() ``` You can also set a setting of `NeedsUpgrading` to `true` by default and set it to false after performing an upgrade so that end users who are not changing version numbers every time the app is started will not be Upgrading all the time
Why are my application settings not getting persisted?
[ "", "c#", ".net", "application-settings", "" ]
I have the following ugly if statement that is part of a class that is pulled from an IOC container: ``` protected virtual void ExecuteSourceControlGet(IBuildMetaData buildMetaData, IPackageTree componentTree) { if ((buildMetaData.RepositoryElementList != null) && (buildMetaData.RepositoryElementList.Count > 0)) { componentTree.DeleteWorkingDirectory(); foreach (var repositoryElement in buildMetaData.RepositoryElementList) { repositoryElement.PrepareRepository(componentTree, get).Export(); } } if((buildMetaData.ExportList != null) && (buildMetaData.ExportList.Count > 0)) { var initialise = true; foreach (var sourceControl in buildMetaData.ExportList) { log.InfoFormat("\nHorn is fetching {0}.\n\n".ToUpper(), sourceControl.Url); get.From(sourceControl).ExportTo(componentTree, sourceControl.ExportPath, initialise); initialise = false; } } log.InfoFormat("\nHorn is fetching {0}.\n\n".ToUpper(), buildMetaData.SourceControl.Url); get.From(buildMetaData.SourceControl).ExportTo(componentTree); } ``` My normal approach to eliminating if statements is to create a subclass for each condition. What is different about this example is: 1. The class that has this method is pulled from the IOC container. 2. I might want the logic in between the 2 if statements to run or not at all. Any advice greatly welcomed.
How about using two *extract methods*, and invert the if's to be guards: ``` protected virtual void ExecuteSourceControlGet(IBuildMetaData buildMetaData, IPackageTree componentTree) { ExecuteRepositoryElementList(buildMetaData.RepositoryElementList, componentTree); ExecuteExportList(buildMetaData.ExportList, componentTree); log.InfoFormat("\nHorn is fetching {0}.\n\n".ToUpper(), buildMetaData.SourceControl.Url); get.From(buildMetaData.SourceControl).ExportTo(componentTree); } private void ExecuteRepositoryElementList(RepositoryElementList repositoryElements, IPackageTree componentTree) { // Guard: No elements if (repositoryElements == null || repositoryElements.Count == 0) return; componentTree.DeleteWorkingDirectory(); foreach (var repositoryElement in repositoryElements) { repositoryElement.PrepareRepository(componentTree, get).Export(); } } private void ExecuteExportList(ExportList exportList, IPackageTree componentTree) { // Guard: No elements if(exportList == null || exportList.Count == 0) return; var initialise = true; foreach (var sourceControl in exportList) { log.InfoFormat("\nHorn is fetching {0}.\n\n".ToUpper(), sourceControl.Url); get.From(sourceControl).ExportTo(componentTree, sourceControl.ExportPath, initialise); initialise = false; } } ``` BTW: The two methods must be fixed with the correct type of **IBuildMetaData.RepositoryElementList** and **IBuildMetaData.ExportList**.
I'm not really sure why you'd want to eliminate the if statements - and using inheritance for it seems over the top. You might want to create an extension method for the repeated collection code: ``` public static bool HasElements<T>(this ICollection<T> collection) { return collection != null && collection.Count != 0; } ``` This lets you change the conditions to: ``` if (buildMetaData.RepositoryElementList.HasElements()) ``` and ``` if (buildMetaData.ExportList.HasElements()) ``` which is slightly simpler IMO. If there ends up being any more logic you might also want to separate the two blocks into different methods. Other than that, I wouldn't worry. Oh, and another extension method which won't help if you need to care whether or not you have elements, but will help if you just want to do a null-safe `foreach`: ``` public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source) { return source ?? Enumerable.Empty<T>(); } ``` (Not that it saves very much over using the null coalescing operator inline, admittedly...)
How can I clean up this ugly if statement?
[ "", "c#", ".net", "" ]
This seems to be a trivial question but I got hung on it for a few hours now (maybe too much Java killed my C++ braincells). I have created a class that has the following constructor (i.e. no default constructor) ``` VACaptureSource::VACaptureSource( std::string inputType, std::string inputLocation ) { if( type == "" || location == "" ) { throw std::invalid_argument("Empty type or location in VACaptureSource()"); } type = inputType; location = inputLocation; // Open the given media source using the appropriate OpenCV function. if( type.compare("image") ) { frame = cvLoadImage( location.c_str() ); if( !frame ) { throw std::runtime_error("error opening file"); } } else { throw std::invalid_argument("Unknown input type in VACaptureSource()"); } ``` } When I want to create an instance, I use ``` // Create input data object try { VACaptureSource input = VACaptureSource("image", "/home/cuneyt/workspace/testmedia/face_images/jhumpa_1.jpg"); } catch( invalid_argument& ia ) { cerr << "FD Error: " << ia.what() << endl; usage(argv[0]); } catch( runtime_error& re ) { cerr << "FD Error: " << re.what() << endl; usage(argv[0]); } ``` However, in this case the instance is local to this block and I can't refer to it anywhere else. On the other hand, I can't say ``` VACAptureSource input; ``` at the beginning of the program since there's no default constructor. What is the correct way to do this? Thanks!
What about using a pointer (or some RAII version thereof)? ``` VACaptureSource* input = NULL; try { input = new VACaptureSource(...); } catch(...) { //error handling } //And, of course, at the end of the program delete input; ```
why do you need to refer to it outside the `try` block? Instead of ``` try { VACaptureSource input = VACaptureSource("image", "/home/cuneyt/workspace/testmedia/face_images/jhumpa_1.jpg"); } //catch.... //do stuff with input ``` you could move everything into the try block: ``` try { VACaptureSource input = VACaptureSource("image", "/home/cuneyt/workspace/testmedia/face_images/jhumpa_1.jpg"); //do stuff with input } //catch.... ``` or you could factor it out into a separate function, which is called from the try block: ``` void doStuff(VACaptureSource& input){ //do stuff with input } try { VACaptureSource input = VACaptureSource("image", "/home/cuneyt/workspace/testmedia/face_images/jhumpa_1.jpg"); doStuff(input); } //catch.... ``` The last one even gives you the nice bonus of separating the construction from use, which places nicely into unit tests where you might want the function to work on a mock object instead.
Correct way to initialize an object with exception throwing constructor
[ "", "c++", "exception", "constructor", "" ]
I have a form with 4 dropdowns on it. The default selected option in all the dropdowns is "Please Select". I want to use Jquery to make sure all dropdowns have a value before the page is submitted, but my code only works on the first one. Does anyone have a way that I can check all of the dropdowns at once? ``` function doconfirm() { if ($('select').val() == '') { alert("Please Select All Fields"); } } ``` I'm sure I am missing something but I cant figure it out. Thanks
``` function doconfirm() { if ($('select').each(function() { if($(this).val() == '') { alert("Please Select All Fields"); return(false); } }); } ```
A slight variation on @mgroves' approach, this *explicitly* tests for at least one selected option, and alerts on the first select that doesn't have one. If there is any advantage to this approach, it is better readability (especially since the use of .val() is somewhat ambiguous for this purpose): ``` function doconfirm() { if($('select').each(function() { if(!$(this).find('option:selected').length) { alert("Please Select All Fields"); return(false); } }); } ```
Select not Selected
[ "", "javascript", "jquery", "" ]
Consider and client server scenario and you got two options: 1. You can include Server's Public Key in Client and perform the exchange. 2. You can use Diffie Hellman KeyExchange Algorithm to handshake and then exchange the key. Which one is more secure way? also if public key will come from store say from Client CA store? would it be more secure instead of binding it in Client app? The deployment will be done via an installer, verifying the version on each run.
Don't. If you need to solve this kind of problem in production code, have an expert do it. There are so many subtle pitfalls in cryptography that chances are you will come a cropper.
With (only) DH key exchange, the client has no way to know that it is really the server he is talking to. So the conversation would be secure from eavesdroppers, but someone could pretend to be the server and compromise the client.
Public key or Diffie-Hellman Key Exchange Algorithm
[ "", "c++", "wcf", "security", "client-server", "public-key", "" ]
Code example: ``` private void comboBox_SelectedIndexChanged(object sender, EventArgs e) { if(some condition) { comboBox.Text = "new string" } } ``` My problem is that the comboBox text always shows the selected index's string value and not the new string. Is the a way round this?
This code should work... ``` public Form1() { InitializeComponent(); comboBox1.Items.AddRange(new String[] { "Item1", "Item2", "Item3" }); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { String text = "You selected: " + comboBox1.Text; BeginInvoke(new Action(() => comboBox1.Text = text)); } ``` Hope it helps... **:)**
You should reset the `SelectedIndex` property to -1 when setting the `Text` property.
How do I Change comboBox.Text inside a comboBox.SelectedIndexChanged event?
[ "", "c#", "combobox", "selectedindexchanged", "" ]
I'm a pretty young developer, and still in the emulation phase of my career. I have read a lot about some topics like concurrency, and using unit of work to allow your business layer to control persistence transactions. I have even implemented some painful, but functional code that implements these topics. But I have not really ever seen a real world example of a truly elegant implementation. I don't have a lot of good TDD, pattern focused role models around me, so I'm forced to look at the outside world for guidance. So, I'm looking for some stellar examples of open source enterprise app domain models. Preferably written in c#, but other languages would be fine as well as long as they are good examples of clean elegant domain model solutions. Some of the things I would really like to see are elegant solutions for Concurrency, Business Rules and Object Validation, Transactions / Unit of Work, and semi transparent logging mechanisms. I'm also curious to see what some of the real world best practices are for exception handling in domain model code. I know I could just start tearing into some open source projects at random, and try to decipher the good from the bad, but I was hoping the expert community here would have some good ideas of projects to look at to stream line the effort. Thanks for your time. ## Edit I'm not really interested in frameworks that make design and construction easier. My choice of framework, or whether to use a framework is a necessary consideration, but is entirely separate from my question here. Unless those frameworks are themselves open source, and very good examples to dig through. What I am looking for is a project that 'got it right', solving a real world problem with code that is flexible, and easily maintainable, so that I can see with my own eyes, and understand an example of how it should be done that is not a trivial 50 line tutorial example.
I liked lot the architecture of oxite cms at <http://www.codeplex.com/oxite>. I learned lot from that project. I use nhibernate for data access instead of linq2sql and it works good for me. Of course its not a large scale project but its a perfect start. CSLA does not follow the DDD paradigm. The above book ".NET Domain-Driven Design with C#" by Tim McCarthy (Wrox Press)" is really good one. The best book for understanding DDD is [Domain-Driven Design: Tackling Complexity in the Heart of Software](https://rads.stackoverflow.com/amzn/click/com/0321125215) by Eric Evans. This book is the "bible" of good DDD design. Beyond that many resources can be found on <http://dddcommunity.org/>. There you can find more videos and articles from DDD experts including Eric Evans and there is a sample application of good DDD design but unfortunately its in java :(
You could check out [nopCommerce](http://nopcommerce.codeplex.com/) i used it to try it work really nice and it has a good implemantation of DDD and BO, quite generic and fast, the install pattern is olso a classic so if you aiming a web apps you could check this out too.
What are some good open source c# examples of quality domain models
[ "", "c#", "open-source", "concurrency", "business-objects", "" ]
I think I am stupid. I searched now for 15 minutes, and found several different solutions for scrolling on datagrids, but none seems to work for me. I am using WPF with .NET 3.5 and the WPF Toolkit DataGrid. My grid gets updated when my observable collection changes, works perfectly. Now, my DataGrid is located inside a normal Grid and scrollbars appear if the DataGrid gets too big. Also fine... And now comes the 1.000.000 $ question: How do I get the datagrid to scroll to the last row? There is: * no AutoScroll Property * no CurrentRowSelected Index * a CurrentCell, but no Collection I could use for CurrentCell = AllCells.Last Any ideas? I feel really stupid, and it seems strange that this question is so hard. What am I missing?
;) ``` if (mainDataGrid.Items.Count > 0) { var border = VisualTreeHelper.GetChild(mainDataGrid, 0) as Decorator; if (border != null) { var scroll = border.Child as ScrollViewer; if (scroll != null) scroll.ScrollToEnd(); } } ```
You should use the datagrid method ``` datagrid.ScrollIntoView(itemInRow); ``` or ``` datagrid.ScrollIntoView(itemInRow, column); ``` this way provides no messing around finding the scroll viewer etc.
How to autoscroll on WPF datagrid
[ "", "c#", "wpf", "datagrid", "" ]