Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
In Jesse Liberty's Learning C# book, he says > "Objects of one type can be converted into objects of another type. > This is called casting." If you investigate the IL generated from the code below, you can clearly see that the casted assignment isn't doing the same thing as the converted assignment. In the former, you can see the boxing/unboxing occurring; in the latter you can see a call to a convert method. I know in the end it may be just a silly semantic difference--but is casting just another word for converting. I don't mean to be snarky, but I'm not interested in anyone's gut feeling on this--opinions don't count here! Can anyone point to a definitive reference that confirms or denies if casting and converting are the same thing? ``` object x; int y; x = 4; y = ( int )x; y = Convert.ToInt32( x ); ``` Thank you rp Note added after Matt's comment about explicit/implicit: I don't think implicit/explicit is the difference. In the code I posted, the change is explicit in both cases. An implicit conversion is what occurs when you assign a short to an int. Note to Sklivvz: I wanted confirmation that my suspicion of the looseness of Jesse Liberty's (otherwise usually lucid and clear) language was correct. I thought that Jesse Liberty was being a little loose with his language. I understand that casting is routed in object hierarchy--i.e., you can't cast from an integer to a string but you could cast from custom exception derived from System.Exception to a System.Exception. It's interesting, though, that when you do try to cast from an int to a string the compiler tells you that it couldn't "convert" the value. Maybe Jesse is more correct than I thought!
The simple answer is: it depends. For value types, casting will involve genuinely converting it to a different type. For instance: ``` float f = 1.5f; int i = (int) f; // Conversion ``` When the casting expression unboxes, the result (assuming it works) is *usually* just a copy of what was in the box, with the same type. There are exceptions, however - you can unbox from a boxed int to an enum (with an underlying type of int) and vice versa; likewise you can unbox from a boxed int to a Nullable<int>. When the casting expression is from one reference type to another and no user-defined conversion is involved, there's no conversion as far as the object itself is concerned - only the type of the *reference* "changes" - and that's really only the way that the value is regarded, rather than the reference itself (which will be the same bits as before). For example: ``` object o = "hello"; string x = (string) o; // No data is "converted"; x and o refer to the same object ``` When user-defined conversions get involved, this *usually* entails returning a different object/value. For example, you could define a conversion to string for your own type - and this would certainly not be the same data as your own object. (It might be an existing string referred to from your object already, of course.) In my experience user-defined conversions usually exist between value types rather than reference types, so this is rarely an issue. All of these count as conversions in terms of the specification - but they don't all count as converting an *object* into an *object* of a different type. I suspect this is a case of Jesse Liberty being loose with terminology - I've noticed that in Programming C# 3.0, which I've just been reading. Does that cover everything?
Absolutely not! Convert tries to get you an Int32 via "any means possible". Cast does nothing of the sort. With cast you are telling the compiler to treat the object as Int, without conversion. You should always use cast when you know (by design) that the object is an Int32 or another class that has an casting operator to Int32 (like float, for example). Convert should be used with String, or with other classes. Try this ``` static void Main(string[] args) { long l = long.MaxValue; Console.WriteLine(l); byte b = (byte) l; Console.WriteLine(b); b = Convert.ToByte(l); Console.WriteLine(b); } ``` Result: > 9223372036854775807 > > 255 > > Unhandled Exception: > > System.OverflowException: Value is > greater than Byte.MaxValue or less > than Byte.MinValue at > System.Convert.ToByte (Int64 value) > [0x00000] at Test.Main > (System.String[] args) [0x00019] in > /home/marco/develop/test/Exceptions.cs:15
Is casting the same thing as converting?
[ "", "c#", "clr", "casting", "" ]
I have a set of XSDs from which I generate data access classes, stored procedures and more. What I don't have is a way to generate database table from these - is there a tool that will generate the DDL statements for me? This is not the same as [Create DB table from dataset table](https://stackoverflow.com/questions/16443/create-db-table-from-dataset-table), as I do not have dataset tables, but XSDs.
Commercial Product: Altova's [XML Spy](http://www.altova.com/features_sql.html). Note that there's no general solution to this. An XSD can easily describe something that does not map to a relational database. While you can try to "automate" this, your XSD's must be designed with a relational database in mind, or it won't work out well. If the XSD's have features that don't map well you'll have to (1) design a mapping of some kind and then (2) write your own application to translate the XSD's into DDL. Been there, done that. Work for hire -- no open source available.
There is a command-line tool called [XSD2DB](http://xsd2db.sourceforge.net/), that generates database from xsd-files, available at sourceforge.
How can I create database tables from XSD files?
[ "", ".net", "sql", "database", "xsd", "code-generation", "" ]
I've just started writing unit tests for a legacy code module with large physical dependencies using the #include directive. I've been dealing with them a few ways that felt overly tedious (providing empty headers to break long #include dependency lists, and using #define to prevent classes from being compiled) and was looking for some better strategies for handling these problems. I've been frequently running into the problem of duplicating almost every header file with a blank version in order to separate the class I'm testing in it's entirety, and then writing substantial stub/mock/fake code for objects that will need to be replaced since they're now undefined. Anyone know some better practices?
The depression in the responses is overwhelming... But don't fear, we've got [the holy book to exorcise the demons of legacy C++ code](https://rads.stackoverflow.com/amzn/click/com/0131177052). Seriously just buy the book if you are in line for more than a week of jousting with legacy C++ code. Turn to page 127: **The case of the horrible include dependencies.** (Now I am not even within miles of Michael Feathers but here as-short-as-I-could-manage answer..) **Problem**: In C++ if a classA needs to know about ClassB, Class B's declaration is straight-lifted / textually included in the ClassA's source file. And since we programmers love to take it to the wrong extreme, a file can recursively include a zillion others transitively. Builds take years.. but hey atleast it builds.. we can wait. Now to say 'instantiating ClassA under a test harness is difficult' is an understatement. (Quoting MF's example - Scheduler is our poster problem child with deps galore.) ``` #include "TestHarness.h" #include "Scheduler.h" TEST(create, Scheduler) // your fave C++ test framework macro { Scheduler scheduler("fred"); } ``` This will bring out the includes dragon with a flurry of build errors. **Blow#1 Patience-n-Persistence**: Take on each include one at a time and decide if we really need that dependency. Let's assume SchedulerDisplay is one of them, whose displayEntry method is called in Scheduler's ctor. **Blow#2 Fake-it-till-you-make-it** (Thanks RonJ): ``` #include "TestHarness.h" #include "Scheduler.h" void SchedulerDisplay::displayEntry(const string& entryDescription) {} TEST(create, Scheduler) { Scheduler scheduler("fred"); } ``` And pop goes the dependency and all its transitive includes. You can also reuse the Fake methods by encapsulating it in a Fakes.h file to be included in your test files. **Blow#3 Practice**: It may not be always that simple.. but you get the idea. After the first few duels, the process of breaking deps will get easy-n-mechanical **Caveats** (Did I mention there are caveats? :) * We need a separate build for test cases in this file ; we can have only 1 definition for the SchedulerDisplay::displayEntry method in a program. So create a separate program for scheduler tests. * We aren't breaking any dependencies in the program, so we are not making the code cleaner. * You need to maintain those fakes as long as we need the tests. * Your sense of aesthetics may be offended for a while.. just bite your lip and 'bear with us for a better tomorrow' Use this technique for a very huge class with severe dependency issues. Don't use often or lightly.. **Use this as a starting point for deeper refactorings.** Over time this testing program can be taken behind the barn as you extract more classes (WITH their own tests). For more.. please do read the book. Invaluable. Fight on bro!
Since you're testing legacy code I'm assuming you can't refactor said code to have less dependencies (e.g. by using the [pimpl idiom](http://www.gotw.ca/gotw/028.htm)) That leaves you with little options I'm afraid. Every header that was included for a type or function will need a mock object for that type or function for everything to compile, there's little you can do...
C++ Unit Testing Legacy Code: How to handle #include?
[ "", "c++", "unit-testing", "legacy", "" ]
I doubt it can be done portably, but are there any solutions out there? I think it could be done by creating an alternate stack and reseting SP,BP, and IP on function entry, and having yield save IP and restore SP+BP. Destructors and exception safety seem tricky but solvable. Has it been done? Is it impossible?
Yes it **can be done** without a problem. All you need is a little assembly code to move the call stack to a newly allocated stack on the heap. I would **look at the [boost::coroutine](http://www.boost.org/doc/libs/1_53_0/libs/coroutine/doc/html/index.html) library**. The one thing that you should watch out for is a stack overflow. On most operating systems overflowing the stack will cause a segfault because virtual memory page is not mapped. However if you allocate the stack on the heap you don't get any guarantee. Just keep that in mind.
On POSIX, you can use makecontext()/swapcontext() routines to portably switch execution contexts. On Windows, you can use the fiber API. Otherwise, all you need is a bit of glue assembly code that switches the machine context. I have implemented coroutines both with ASM (for AMD64) and with swapcontext(); neither is very hard.
How do you implement Coroutines in C++
[ "", "c++", "coroutine", "c++17", "" ]
The original query looks like this (MySQL): ``` SELECT * FROM books WHERE title LIKE "%text%" OR description LIKE "%text%" ORDER BY date ``` Would it be possible to rewrite it (without unions or procedures), so that result will look like this: * list of books where title matches query ordered by date, followed by: * list of books where description matches query ordered by date So basically just give a higher priority to matching titles over descriptions.
In sql server I would do the following: ``` select * from books where title like '%text%' or description like '%text%' order by case when title like '%text%' then 1 else 2 end, date ``` I'm not sure if you can include columns in ORDER BY in mysql that aren't in the SELECT, but that's the principle I'd use. Otherwise, just include the derived column in the SELECT as well.
``` select * from books where title like "%text%" or description like "%text%" order by date, case when title like "%text%" then 0 else 1 end ```
Is it possible to build following SQL query
[ "", "sql", "mysql", "database", "" ]
I'm having a problem writing Norwegian characters into an XML file using C#. I have a string variable containing some Norwegian text (with letters like æøå). I'm writing the XML using an XmlTextWriter, writing the contents to a MemoryStream like this: ``` MemoryStream stream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.GetEncoding("ISO-8859-1")); xmlTextWriter.Formatting = Formatting.Indented; xmlTextWriter.WriteStartDocument(); //Start doc ``` Then I add my Norwegian text like this: ``` xmlTextWriter.WriteCData(myNorwegianText); ``` Then I write the file to disk like this: ``` FileStream myFile = new FileStream(myPath, FileMode.Create); StreamWriter sw = new StreamWriter(myFile); stream.Position = 0; StreamReader sr = new StreamReader(stream); string content = sr.ReadToEnd(); sw.Write(content); sw.Flush(); myFile.Flush(); myFile.Close(); ``` Now the problem is that in the file on this, all the Norwegian characters look funny. I'm probably doing the above in some stupid way. Any suggestions on how to fix it?
Why are you writing the XML first to a MemoryStream and then writing that to the actual file stream? That's pretty inefficient. If you write directly to the FileStream it should work. If you still want to do the double write, for whatever reason, do one of two things. Either 1. Make sure that the StreamReader and StreamWriter objects you use *all* use the *same* encoding as the one you used with the XmlWriter (not just the StreamWriter, like someone else suggested), or 2. Don't use StreamReader/StreamWriter. Instead just copy the stream at the byte level using a simple byte[] and Stream.Read/Write. This is going to be, btw, a lot more efficient anyway.
Both your StreamWriter and your StreamReader are using UTF-8, because you're not specifying the encoding. That's why things are getting corrupted. As tomasr said, using a FileStream to start with would be simpler - but also MemoryStream has the handy "WriteTo" method which lets you copy it to a FileStream very easily. I hope you've got a using statement in your real code, by the way - you don't want to leave your file handle open if something goes wrong while you're writing to it. Jon
Writing XML files using XmlTextWriter with ISO-8859-1 encoding
[ "", "c#", ".net", "xml", "encoding", "iso-8859-1", "" ]
The code that I want to write is like this: ``` void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff } } catch (MyException ex) { // Do the right thing for this exception. } } ``` I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use? Here is a more fleshed out example of periodically checking: ``` Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>(); void ThrowOnThread(Thread thread, Exception ex) { // the exception passed in is going to be handed off to another thread, // so it needs to be thread safe. lock (exceptionDictionary) { exceptionDictionary[thread] = ex; } } void ExceptionCheck() { lock (exceptionDictionary) { Exception ex; if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex)) throw ex; } } void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } } void MethodOnThreadB() { try { for (;;) { // Do stuff ExceptionCheck(); } } catch (MyException ex) { // Do the right thing for this exception. } } ```
This is NOT a good idea [This article talks about ruby's timeout library.](http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html) which throws exceptions across threads. It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads. In a nutshell, what can (and does) happen is this: ThreadA: ``` At some random time, throw an exception on thread B: ``` ThreadB: ``` try { //do stuff } finally { CloseResourceOne(); // ThreadA's exception gets thrown NOW, in the middle // of our finally block and resource two NEVER gets closed. // Obviously this is BAD, and the only way to stop is to NOT throw // exceptions across threads CloseResourceTwo(); } ``` Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads. You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem. However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that.
There are enough problems with exceptions that can be thrown on threads by other mechanisms, like aborting threads and the likes, that you should find another way of doing it. An exception is a mechanism used to signal that a process has experienced something exceptional that it cannot deal with. You should try to avoid writing the code so that an exception is used to signal that *something else* has experienced something exceptional. That other thread will most likely not know how to handle the exception *in all cases where it could be thrown by your code*. In short, you should find some other mechanism for aborting your threads than using exceptions. Use event objects or similar to tell a thread to abort its processing, that's the best way.
Is there a good method in C# for throwing an exception on a given thread
[ "", "c#", "multithreading", "exception", "" ]
I just installed Ganymede and am exploring an old project in it. All of my JSPs are giving me weird validation errors. I'm seeing stuff like - ``` Syntax error on token "}", delete this token Syntax error on token "catch", Identifier expected Syntax error, insert "Finally" to complete TryStatement ``` I'm doing best practice stuff here, no scriplets or anything, so I think that Eclipse is incorrectly applying a Java class validator to my JSPs. Any idea on how to stop that from happening? Under Options/Editors/File Associations I have the following for JSPs: ``` JSP Editor (default) Web Page Editor Text Editor CSS JSP Editor ``` Am I missing something? Also I think this is correct, but just in case it's not, here is my page directive - ``` <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> ```
I have just downloaded Ganymede 3.4.2 and added WTP 3.0.4 to it and this error has gone for me.
I actually found out what my problem was through the [eclipse webtools usergroup](http://www.eclipse.org/newsportal/article.php?id=17447&group=eclipse.webtools#17447). The issue for me was the use of the Spring form custom tag library. If you self-close the tag... ``` <form:errors path="*" /> ``` ...then you get the goofy JSP validation error. If you close the tag as if there was body content... ``` <form:errors path="*"></form:errors> ``` Then the error goes away. I need to follow-up with a bug for the Ganymede team.
Eclipse Ganymede not validating JSPs properly
[ "", "java", "eclipse", "validation", "jsp", "ganymede", "" ]
Is there a way to create an html link using h:outputLink, other JSF tag or code to create a non faces request (HTTP GET) with request parameters? For example I have the following navigation-rule ``` <navigation-rule> <navigation-case> <from-outcome>showMessage</from-outcome> <to-view-id>/showMessage.jsf</to-view-id> <redirect/> </navigation-case> </navigation-rule> ``` In my page I would like to output the following html code: ``` <a href="/showMessage.jsf?msg=23">click to see the message</a> ``` I could just write the html code in the page, but I want to use the navigation rule in order to have all the urls defined in a single configurable file.
This is an interesting idea. I'd be curious to know how it pans out in practice. **Getting the navigation rules** Navigation is handled by the [NavigationHandler](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/application/NavigationHandler.html). Getting hold of the NavigationHandler isn't difficult, but the API does not expose the rules it uses. As I see it, you can: 1. parse faces-config.xml on initialization and store the rules in the application context (*easy*) 2. implement your own NavigationHandler that ignores the rules in faces-config.xml or supplements them with your own rules file and exposes its ruleset somehow (*workable, but takes a bit of work*) 3. mock your own [FacesContext](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/FacesContext.html) and pass it to the existing navigation handler (*really difficult to make two FacesContext object coexist in same thread and extremely inefficient*) Now, you have another problem too. Where are you going to keep the mappings to look up the views? Hard-code them in the beans? **Using the navigation rules** Off hand, I can think of two ways you could construct parameter-containing URLs from the back-end. Both involve defining a bean of some kind. ``` <managed-bean> <managed-bean-name>navBean</managed-bean-name> <managed-bean-class>foo.NavBean</managed-bean-class> <managed-bean-scope>application</managed-bean-scope> </managed-bean> ``` Source: ``` package foo; import java.io.IOException; import java.io.Serializable; import java.net.URLEncoder; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; public class NavBean implements Serializable { private String getView() { String viewId = "/showMessage.faces"; // or look this up somewhere return viewId; } /** * Regular link to page */ public String getUrlLink() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); String navUrl = context.getExternalContext().encodeActionURL( extContext.getRequestContextPath() + viewId); return navUrl; } /** * Just some value */ public String getValue() { return "" + System.currentTimeMillis(); } /** * Invoked by action */ public String invokeRedirect() { FacesContext context = FacesContext.getCurrentInstance(); ExternalContext extContext = context.getExternalContext(); String viewId = getView(); try { String charEncoding = extContext.getRequestCharacterEncoding(); String name = URLEncoder.encode("foo", charEncoding); String value = URLEncoder.encode(getValue(), charEncoding); viewId = extContext.getRequestContextPath() + viewId + '?' + name + "=" + value; String urlLink = context.getExternalContext().encodeActionURL( viewId); extContext.redirect(urlLink); } catch (IOException e) { extContext.log(getClass().getName() + ".invokeRedirect", e); } return null; } } ``` **GET** For a GET request, you can use the UIParameters to set the values and let the renderer build the parameter list. ``` <h:outputLink value="#{navBean.urlLink}"> <f:param name="foo" value="#{navBean.value}" /> <h:outputText value="get" /> </h:outputLink> ``` **POST** If you want to set the URL to a view during a POST action, you can do it using a redirect in an action (invoked by a button or commandLink). ``` <h:commandLink id="myCommandLink" action="#{navBean.invokeRedirect}"> <h:outputText value="post" /> </h:commandLink> ``` **Notes** Note that [ExternalContext.encodeActionURL](http://java.sun.com/javaee/javaserverfaces/1.1_01/docs/api/javax/faces/context/ExternalContext.html#encodeActionURL(java.lang.String)) is used to encode the string. This is good practice for producing code that is portable across contexts (portlets, etcetera). You would use *encodeResourceURL* if you were encoding a link to an image or download file.
Tried using PrettyFaces? It's an open-source JSF extension designed specifically to make bookmarkable JSF pages / JSF with GET requests possible. [PrettyFaces - SEO, Dynamic Parameters, Bookmarks and Navigation for JSF / JSF2](http://ocpsoft.com/prettyfaces "PrettyFaces - SEO, Dynamic Parameters, Bookmarks and Navigation for JSF / JSF2")
How to create a GET request with parameters, using JSF and navigation-rules?
[ "", "java", "jsf", "redirect", "navigation", "" ]
I have a SQL table with news stories and Unix timestamps. I'd like to only keep the 50 newest stories. How would I write an SQL statement to delete any amount of older stories?
I ended up using two queries since MySQL5 doesn't yet support LIMIT's in subqueries ``` SELECT unixTime FROM entries ORDER BY unixTime DESC LIMIT 49, 1; DELETE FROM entries WHERE unixTime < $sqlResult; ```
Blockquote ``` delete from table where id not in ( select id from table order by id desc limit 50 ) ``` You select the ids of the data you don't want to delete, and the you delete everything NOT IN these value...
Delete all but the 50 newest rows
[ "", "mysql", "sql", "" ]
My [Google-fu](https://english.stackexchange.com/questions/19967/what-does-google-fu-mean) has failed me. In Python, are the following two tests for equality equivalent? ``` n = 5 # Test one. if n == 5: print 'Yay!' # Test two. if n is 5: print 'Yay!' ``` Does this hold true for objects where you would be comparing instances (a `list` say)? Okay, so this kind of answers my question: ``` L = [] L.append(1) if L == [1]: print 'Yay!' # Holds true, but... if L is [1]: print 'Yay!' # Doesn't. ``` So `==` tests value where `is` tests to see if they are the same object?
`is` will return `True` if two variables point to the same object (in memory), `==` if the objects referred to by the variables are equal. ``` >>> a = [1, 2, 3] >>> b = a >>> b is a True >>> b == a True # Make a new copy of list `a` via the slice operator, # and assign it to variable `b` >>> b = a[:] >>> b is a False >>> b == a True ``` In your case, the second test only works because Python caches small integer objects, which is an implementation detail. For larger integers, this does not work: ``` >>> 1000 is 10**3 False >>> 1000 == 10**3 True ``` The same holds true for string literals: ``` >>> "a" is "a" True >>> "aa" is "a" * 2 True >>> x = "a" >>> "aa" is x * 2 False >>> "aa" is intern(x*2) True ``` Please see [this question](https://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none) as well.
There is a simple rule of thumb to tell you when to use `==` or `is`. * `==` is for *value equality*. Use it when you would like to know if two objects have the same value. * `is` is for *reference equality*. Use it when you would like to know if two references refer to the same object. In general, when you are comparing something to a simple type, you are usually checking for *value equality*, so you should use `==`. For example, the intention of your example is probably to check whether x has a value equal to 2 (`==`), not whether `x` is literally referring to the same object as 2. --- Something else to note: because of the way the CPython reference implementation works, you'll get unexpected and inconsistent results if you mistakenly use `is` to compare for reference equality on integers: ``` >>> a = 500 >>> b = 500 >>> a == b True >>> a is b False ``` That's pretty much what we expected: `a` and `b` have the same value, but are distinct entities. But what about this? ``` >>> c = 200 >>> d = 200 >>> c == d True >>> c is d True ``` This is inconsistent with the earlier result. What's going on here? It turns out the reference implementation of Python caches integer objects in the range -5..256 as singleton instances for performance reasons. Here's an example demonstrating this: ``` >>> for i in range(250, 260): a = i; print "%i: %s" % (i, a is int(str(i))); ... 250: True 251: True 252: True 253: True 254: True 255: True 256: True 257: False 258: False 259: False ``` This is another obvious reason not to use `is`: the behavior is left up to implementations when you're erroneously using it for value equality.
Is there a difference between "==" and "is"?
[ "", "python", "reference", "equality", "semantics", "" ]
Is there an easy way to programmatically determine the number of lines within a text file?
**Seriously belated edit: If you're using .NET 4.0 or later** The `File` class has a new [`ReadLines`](http://msdn.microsoft.com/en-us/library/dd383503.aspx) method which lazily enumerates lines rather than greedily reading them all into an array like `ReadAllLines`. So now you can have both efficiency and conciseness with: ``` var lineCount = File.ReadLines(@"C:\file.txt").Count(); ``` --- **Original Answer** If you're not too bothered about efficiency, you can simply write: ``` var lineCount = File.ReadAllLines(@"C:\file.txt").Length; ``` For a more efficient method you could do: ``` var lineCount = 0; using (var reader = File.OpenText(@"C:\file.txt")) { while (reader.ReadLine() != null) { lineCount++; } } ``` **Edit: In response to questions about efficiency** The reason I said the second was more efficient was regarding memory usage, not necessarily speed. The first one loads the entire contents of the file into an array which means it must allocate at least as much memory as the size of the file. The second merely loops one line at a time so it never has to allocate more than one line's worth of memory at a time. This isn't that important for small files, but for larger files it could be an issue (if you try and find the number of lines in a 4GB file on a 32-bit system, for example, where there simply isn't enough user-mode address space to allocate an array this large). In terms of speed I wouldn't expect there to be a lot in it. It's possible that ReadAllLines has some internal optimisations, but on the other hand it may have to allocate a massive chunk of memory. I'd guess that ReadAllLines might be faster for small files, but significantly slower for large files; though the only way to tell would be to measure it with a Stopwatch or code profiler.
The easiest: ``` int lines = File.ReadAllLines("myfile").Length; ```
Determine the number of lines within a text file
[ "", "c#", "input", "text-files", "" ]
I understand that the function is not allowed to change the state of the object, but I thought I read somewhere that the compiler was allowed to assume that if the function was called with the same arguments, it would return the same value and thus could reuse a cached value if it was available. e.g. ``` class object { int get_value(int n) const { ... } ... object x; int a = x.get_value(1); ... int b = x.get_value(1); ``` then the compiler could optimize the second call away and either use the value in a register or simply do `b = a;` Is this true?
`const` is about program semantics and not about implementation details. You should mark a member function `const` when it does not change the visible state of the object, and should be callable on an object that is itself `const`. Within a `const` member function on a class `X`, the type of `this` is `X const *`: pointer to constant `X` object. Thus all member variables are effectively `const` within that member function (except `mutable` ones). If you have a `const` object, you can only call `const` member functions on it. You can use `mutable` to indicate that a member variable may change even within a `const` member function. This is typically used to identify variables used for caching results, or for variables that don't affect the actual observable state such as mutexes (you still need to lock the mutex in the `const` member functions) or use counters. ``` class X { int data; mutable boost::mutex m; public: void set_data(int i) { boost::lock_guard<boost::mutex> lk(m); data=i; } int get_data() const // we want to be able to get the data on a const object { boost::lock_guard<boost::mutex> lk(m); // this requires m to be non-const return data; } }; ``` If you hold the data by pointer rather than directly (including smart pointers such as `std::auto_ptr` or `boost::shared_ptr`) then the pointer becomes `const` in a `const` member function, but not the pointed-to data, so you can modify the pointed-to data. As for caching: in general the compiler cannot do this because the state might change between calls (especially in my multi-threaded example with the mutex). However, if the definition is inline then the compiler can pull the code into the calling function and optimize what it can see there. This might result in the function *effectively* only being called once. The next version of the [C++ Standard (C++0x)](http://www.open-std.org/jtc1/sc22/wg21/) will have a new keyword `constexpr`. Functions tagged `constexpr` return a constant value, so the results can be cached. There are limits on what you can do in such a function (in order that the compiler can verify this fact).
No. A const method is a method that doesn't change the state of the object (i.e. its fields), but you can't assume that given the same input, return value of a const method is determined. In other words, `const` keyword does NOT imply that the function is one-to-one. For instance a method that returns the current time is a const method but its return value changes between calls.
What are the semantics of a const member function?
[ "", "c++", "methods", "constants", "" ]
Can I expose a class from another .net namespace as a class in my namespace? I use a class - antlr.collections.AST - as the return type for a function belonging to a class in my namespace; as a result, the user has to have ``` using antlr.collections; using myNamespace; ``` at the top of their files in order to use my function. Can I make myNamespace.AST an alias for antlr.collections.AST, such that the user only has to have ``` using myNamespace; ``` at the top of their files?
Bear in mind that the consumers of your code won't actually *need* to have using statements. Those are there to make their lives easier, so they don't have to type antlr.collections.Foo and antlr.collections.Bar all over their source. The bigger "impact" (if indeed there really is a severe one) is that the consumer of your code will need a hard reference to the assembly where antlr.collections is defined. However, if that's documented up front, I honestly don't see it being that big of a problem. It's no different than the consumer of a SubSonic-generated DAL needing references both to the generated DAL assembly and the original SubSonic assembly. (And, quite possibly, using statements as well.) Dependencies are what they are. There's a reason classes are broken into namespaces -- primarily for organization and to reduce naming conflicts. Not knowing what classes are in the namespace you mention, I don't know how likely such a conflict actually is in your scenario ... But attempting to move the class from one namespace to another, or to hide the fact that such is needed by deriving a blank class from it, is probably not the best idea. It won't kill the consumers of your class to have another reference and using statement.
How about deriving a class using the same name in the new namespace? I meant: ``` namespace MyForms { class Class1 : Some.Other.Namespace.Class1 { // ... } } ```
can I expose a class from another .net namespace as a class in my namespace?
[ "", "c#", ".net", "namespaces", "" ]
I'm just wondering what the optimal solution is here. Say I have a normalized database. The primary key of the whole system is a varchar. What I'm wondering is should I relate this varchar to an int for normalization or leave it? It's simpler to leave as a varchar, but it might be more optimal For instance I can have ``` People ====================== name varchar(10) DoB DateTime Height int Phone_Number ====================== name varchar(10) number varchar(15) ``` Or I could have ``` People ====================== id int Identity name varchar(10) DoB DateTime Height int Phone_Number ====================== id int number varchar(15) ``` Add several other one-to-many relationships of course. What do you all think? Which is better and why?
Can you really use names as primary keys? Isn't there a high risk of several people with the same name? If you really are so lucky that your name attribute can be used as primary key, then - by all means - use that. Often, though, you will have to make something up, like a customer\_id, etc. And finally: "NAME" is a reserved word in at least one DBMS, so consider using something else, e.g. fullname.
I believe that the majority of people who have developed any significant sized real world database applications will tell you that surrogate keys are the only realistic solution. I know the academic community will disagree but that is the difference between theoretical purity and practicality. Any reasonable sized query that has to do joins between tables that use non-surrogate keys where some tables have composite primary keys quickly becomes unmaintainable.
SQL Server normalization tactic: varchar vs int Identity
[ "", "sql", "sql-server", "database-design", "optimization", "normalization", "" ]
How unique is the php session id? I got the impression from various things that I've read that I should not rely on two users never getting the same sessionid. Isn't it a GUID?
Session\_id can indeed be duplicated, but the probability is very low. If you have a website with a fair traffic, it may happens once in you web site life, and will just annoy one user for one session. This is not worth to care about unless you expect to build a very high traffic website or a service for the bank industry.
It's not very unique as shipped. In the default configuration it's the result of a hash of various things including the result of gettimeofday (which isn't terribly unique), but if you're worried, you should configure it to draw some entropy from /dev/urandom, like so ``` ini_set("session.entropy_file", "/dev/urandom"); ini_set("session.entropy_length", "512"); ``` search for "php\_session\_create\_id" in [the code](https://github.com/php/php-src/blob/34792280bcd2210784ba574d52fc3619cc06160d/ext/session/session.c#L279) for the actual algorithm they're using. Edited to add: There's a DFA random-number generator seeded by the pid, mixed with the time in usecs. It's not a firm uniqueness condition [especially from a security perspective](http://seclists.org/vuln-dev/2001/Jul/33). Use the entropy config above. **Update:** > As of PHP 5.4.0 session.entropy\_file defaults to /dev/urandom or > /dev/arandom if it is available. In PHP 5.3.0 this directive is left > empty by default. [PHP Manual](http://www.php.net/manual/en/session.configuration.php#ini.session.entropy-file)
How unique is the php session id
[ "", "php", "session", "guid", "" ]
is it possible to extend vim functionality via custom extension (preferably, written in Python)? What I need ideally is custom command when in command mode. E.g. ESC :do\_this :do\_that
vim supports scripting in python (and in perl as well, I think). You just have to make sure that the vim distribution you are using has been compiled with python support. If you are using a Linux system, you can download the source and then compile it with ``` ./configure --enable-pythoninterp make sudo make install ``` Inside vim, you can type ``` :version ``` to list the available features; if it has python support, you should see a '+python' somewhere (a '-python' otherwise). Then, to check the usage of the python module, you can type ``` :help python ``` P.S: if you're going to compile the vim sources, make sure to check the available configure options, you might need to specify --with-python-config-dir as well. P.P.S: to create a "custom command in command mode" (if I understand correctly what you mean), you can create a function "MyFunction" in a vim script (using python or the vim scripting language) and then invoke it with ``` :Call MyFunction() ``` Check ``` :help user-functions ``` for details
Yes it is. There are several extensions on <http://www.vim.org/scripts/index.php> It can be done with python as well if the support for python is compiled in. Article about it: <http://www.techrepublic.com/article/extending-vim-with-python/> Google is our friend. HTH
Vim extension (via Python)?
[ "", "python", "vim", "" ]
How can I make this work? ``` switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } ``` I don't want to use the name since string comparing for types is just awfull and can be subject to change.
``` System.Type propertyType = typeof(Boolean); System.TypeCode typeCode = Type.GetTypeCode(propertyType); switch (typeCode) { case TypeCode.Boolean: //doStuff break; case TypeCode.String: //doOtherStuff break; default: break; } ``` You can use an hybrid approach for TypeCode.Object where you dynamic if with typeof. This is very fast because for the first part - the switch - the compiler can decide based on a lookup table.
You can't. What you can do is create a mapping between Types and a delegate using a dictionary: ``` var TypeMapping = new Dictionary<Type, Action<string>>(){ {typeof(string), (x)=>Console.WriteLine("string")}, {typeof(bool), (x)=>Console.WriteLine("bool")} }; string s = "my string"; TypeMapping[s.GetType()]("foo"); TypeMapping[true.GetType()]("true"); ```
Switch over PropertyType
[ "", "c#", "switch-statement", "" ]
I need to present the user with a matrix of which one column is editable. What is the most appropriate control to use? I can't use a ListView because you can only edit the first column (the label) and that's no good to me. Is the DataGridView the way to go, or are there third party alternative components that do a better job?
DataGridView is the best choice as it is free and comes with .NET WinForms 2.0. You can define editable columns or read-only. Plus you can customize the appearance if required.
DataGridView is good. If you prefer a prettier interface, [Telerik controls](http://www.telerik.com/products/winforms/overview.aspx) are better.
Editable data grid for C# WinForms
[ "", "c#", "winforms", "user-interface", "editing", "" ]
I know in php you can embed variables inside variables, like: ``` <? $var1 = "I\'m including {$var2} in this variable.."; ?> ``` But I was wondering how, and if it was possible to include a function inside a variable. I know I could just write: ``` <?php $var1 = "I\'m including "; $var1 .= somefunc(); $var1 = " in this variable.."; ?> ``` But what if I have a long variable for output, and I don't want to do this every time, or I want to use multiple functions: ``` <?php $var1 = <<<EOF <html lang="en"> <head> <title>AAAHHHHH</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> There is <b>alot</b> of text and html here... but I want some <i>functions</i>! -somefunc() doesn't work -{somefunc()} doesn't work -$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string -more non-working: ${somefunc()} </body> </html> EOF; ?> ``` Or I want dynamic changes in that load of code: ``` <? function somefunc($stuff) { $output = "my bold text <b>{$stuff}</b>."; return $output; } $var1 = <<<EOF <html lang="en"> <head> <title>AAAHHHHH</title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> </head> <body> somefunc("is awesome!") somefunc("is actually not so awesome..") because somefunc("won\'t work due to my problem.") </body> </html> EOF; ?> ``` Well?
Function calls within strings are supported since PHP5 by having a variable containing the name of the function to call: ``` <? function somefunc($stuff) { $output = "<b>{$stuff}</b>"; return $output; } $somefunc='somefunc'; echo "foo {$somefunc("bar")} baz"; ?> ``` will output "`foo <b>bar</b> baz`". I find it easier however (and this works in PHP4) to either just call the function outside of the string: ``` <? echo "foo " . somefunc("bar") . " baz"; ?> ``` or assign to a temporary variable: ``` <? $bar = somefunc("bar"); echo "foo {$bar} baz"; ?> ```
`"bla bla bla".function("blub")." and on it goes"`
In PHP is it possible to use a function inside a variable
[ "", "php", "html", "variables", "function", "" ]
I'm writing a pretty straightforward `e-commerce app` in **asp.net**, do I need to use transactions in my stored procedures? Read/Write ratio is about 9:1
Many people ask - do I need transactions? Why do I need them? When to use them? The answer is simple: use them all the time, unless you have a very good reason not to (for instance, don't use atomic transactions for "long running activities" between businesses). The default should always be yes. You are in doubt? - use transactions. Why are transactions beneficial? They help you deal with crashes, failures, data consistency, error handling, they help you write simpler code etc. And the list of benefits will continue to grow with time. Here is some more info from <http://blogs.msdn.com/florinlazar/>
Remember in SQL Server all single statement CRUD operations are in an implicit transaction by default. You just need to turn on explict transactions (BEGIN TRAN) if you need to make multiple statements act as an atomic unit.
Do I really need to use transactions in stored procedures? [MSSQL 2005]
[ "", "sql", "asp.net", "sql-server", "e-commerce", "" ]
The method signature of a Java `main`method is: ``` public static void main(String[] args) { ... } ``` Is there a reason why this method must be static?
The method is static because otherwise there would be ambiguity: which constructor should be called? Especially if your class looks like this: ``` public class JavaClass{ protected JavaClass(int x){} public void main(String[] args){ } } ``` Should the JVM call `new JavaClass(int)`? What should it pass for `x`? If not, should the JVM instantiate `JavaClass` without running any constructor method? I think it shouldn't, because that will special-case your entire class - sometimes you have an instance that hasn't been initialized, and you have to check for it in every method that could be called. There are just too many edge cases and ambiguities for it to make sense for the JVM to have to instantiate a class before the entry point is called. That's why `main` is static. I have no idea why `main` is always marked `public` though.
This is just convention. In fact, even the name main(), and the arguments passed in are purely convention. Java 21 introduced [alternative conventions](https://openjdk.org/jeps/445) as a preview feature; you can omit the `String[]` parameter, the `public` modifier, and even the `static` modifier. If you omit the `static` modifier, an instance of the class will be created before the invocation, which requires that the class has a non-private zero-parameter constructor. The default constructor created by the compiler if no constructor has been declared, is sufficient. When you run java.exe (or javaw.exe on Windows), what is really happening is a couple of Java Native Interface (JNI) calls. These calls load the DLL that is really the JVM (that's right - java.exe is NOT the JVM). JNI is the tool that we use when we have to bridge the virtual machine world, and the world of C, C++, etc... The reverse is also true - it is not possible (at least to my knowledge) to actually get a JVM running without using JNI. Basically, java.exe is a super simple C application that parses the command line, creates a new String array in the JVM to hold those arguments, parses out the class name that you specified as containing main(), uses JNI calls to find the main() method itself, then invokes the main() method, passing in the newly created string array as a parameter. This is very, very much like what you do when you use reflection from Java - it just uses confusingly named native function calls instead. It would be perfectly legal for you to write your own version of java.exe (the source is distributed with the JDK) and have it do something entirely different. In fact, that's exactly what we do with all of our Java-based apps. Each of our Java apps has its own launcher. We primarily do this so we get our own icon and process name, but it has come in handy in other situations where we want to do something besides the regular main() call to get things going (For example, in one case we are doing COM interoperability, and we actually pass a COM handle into main() instead of a string array). So, long and short: the reason it is static is b/c that's convenient. The reason it's called 'main' is that it had to be something, and main() is what they did in the old days of C (and in those days, the name of the function *was* important). I suppose that java.exe could have allowed you to just specify a fully qualified main method name, instead of just the class (java com.mycompany.Foo.someSpecialMain) - but that just makes it harder on IDEs to auto-detect the 'launchable' classes in a project.
Why is the Java main method static?
[ "", "java", "static", "program-entry-point", "" ]
I am a totally blind programmer who would like to learn Python. Unfortunately the fact that code blocks are represented with different levels of indentation is a major stumbling block. I was wondering if there were any tools available that would allow me to write code using braces or some other code block delimiter and then convert that format into a properly indented representation that the Python interpreter could use?
There's a solution to your problem that is distributed with python itself. `pindent.py`, it's located in the Tools\Scripts directory in a windows install (my path to it is C:\Python25\Tools\Scripts), it looks like you'd have to [grab it from svn.python.org](https://svn.python.org/projects/python/trunk/Tools/scripts/pindent.py) if you are running on Linux or OSX. It adds comments when blocks are closed, or can properly indent code if comments are put in. Here's an example of the code outputted by pindent with the command: `pindent.py -c myfile.py` ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar ``` Where the original `myfile.py` was: ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 else: print 'oops!' ``` You can also use `pindent.py -r` to insert the correct indentation based on comments (read the header of pindent.py for details), this should allow you to code in python without worrying about indentation. For example, running `pindent.py -r myfile.py` will convert the following code in `myfile.py` into the same properly indented (and also commented) code as produced by the `pindent.py -c` example above: ``` def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar ``` I'd be interested to learn what solution you end up using, if you require any further assistance, please comment on this post and I'll try to help.
I personally doubt that there currently is at the moment, as a lot of the Python afficionados love the fact that Python is this way, whitespace delimited. I've never actually thought about that as an accessibility issue however. Maybe it's something to put forward as a bug report to Python? I'd assume that you use a screen reader here however for the output? So the tabs would seem "invisible" to you? With a Braille output, it might be easier to read, but I can understand exactly how confusing this could be. In fact, this is very interesting to me. I wish that I knew enough to be able to write an app that will do this for you. I think it's definately something that I'll put in a bug report for, unless you've already done so yourself, or want to. Edit: Also, as [noted](https://stackoverflow.com/questions/118643#118656) by [John Millikin](https://stackoverflow.com/users/3560/john-millikin) There is also [PyBraces](http://timhatch.com/projects/pybraces/) Which might be a viable solution to you, and may be possible to be hacked together dependant on your coding skills to be exactly what you need (and I hope that if that's the case, you release it out for others like yourself to use) Edit 2: I've just [reported this](http://bugs.python.org/issue3942) to the python bug tracker
Is there a way to convert indentation in Python code to braces?
[ "", "python", "" ]
Does beautiful soup work with iron python? If so with which version of iron python? How easy is it to distribute a windows desktop app on .net 2.0 using iron python (mostly c# calling some python code for parsing html)?
I was asking myself this same question and after struggling to follow advice here and elsewhere to get IronPython and BeautifulSoup to play nicely with my existing code I decided to go looking for an alternative native .NET solution. BeautifulSoup is a wonderful bit of code and at first it didn't look like there was anything comparable available for .NET, but then I found the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack) and if anything I think I've actually gained some maintainability over BeautifulSoup. It takes clean or crufty HTML and produces a elegant XML DOM from it that can be queried via XPath. With a couple lines of code you can even get back a raw XDocument and then [craft your queries in LINQ to XML](http://vijay.screamingpens.com/archive/2008/05/26/linq-amp-lambda-part-3-html-agility-pack-to-linq.aspx). Honestly, if web scraping is your goal, this is about the cleanest solution you are likely to find. **Edit** Here is a simple (read: not robust at all) example that parses out the US House of Representatives holiday schedule: ``` using System; using System.Collections.Generic; using HtmlAgilityPack; namespace GovParsingTest { class Program { static void Main(string[] args) { HtmlWeb hw = new HtmlWeb(); string url = @"http://www.house.gov/house/House_Calendar.shtml"; HtmlDocument doc = hw.Load(url); HtmlNode docNode = doc.DocumentNode; HtmlNode div = docNode.SelectSingleNode("//div[@id='primary']"); HtmlNodeCollection tableRows = div.SelectNodes(".//tr"); foreach (HtmlNode row in tableRows) { HtmlNodeCollection cells = row.SelectNodes(".//td"); HtmlNode dateNode = cells[0]; HtmlNode eventNode = cells[1]; while (eventNode.HasChildNodes) { eventNode = eventNode.FirstChild; } Console.WriteLine(dateNode.InnerText); Console.WriteLine(eventNode.InnerText); Console.WriteLine(); } //Console.WriteLine(div.InnerHtml); Console.ReadKey(); } } } ```
I've tested and used BeautifulSoup with both IPy 1.1 and 2.0 (forget which beta, but this was a few months back). Leave a comment if you are still having trouble and I'll dig out my test code and post it.
Iron python, beautiful soup, win32 app
[ "", ".net", "python", "ironpython", "" ]
I am building a physics simulation engine and editor in Windows. I want to build the editor part using Qt and I want to run the engine using SDL with OpenGL. My first idea was to build the editor using only Qt and share as much code with the engine (the resource manager, the renderer, the maths). But, I would also like to be able to run the simulation inside the editor. **This means I also have to share the simulation code which uses SDL threads.** So, my question is this: Is there a way to have an the render OpenGL to a Qt window by using SDL? I have read on the web that it might be possible to supply SDL with a window handle in which to render. Anybody has experience dong that? Also, the threaded part of the simulator might pose a problem since it uses SDL threads.
While you might get it to work like first answer suggest you will likely run into problems due to threading. There is no simple solutions when it comes to threading, and here you would have SDL Qt and OpenGL mainloop interacting. Not fun. The easiest and sanest solution would be to decouple both parts. So that SDL and Qt run in separate processes and have them use some kind of messaging to communicate (I'd recommend d-bus here ). You can have SDL render into borderless window and your editor sends commands via messages.
This is a simplification of what I do in my project. You can use it just like an ordinary widget, but as you need, you can using it's m\_Screen object to draw to the SDL surface and it'll show in the widget :) ``` #include "SDL.h" #include <QWidget> class SDLVideo : public QWidget { Q_OBJECT public: SDLVideo(QWidget *parent = 0, Qt::WindowFlags f = 0) : QWidget(parent, f), m_Screen(0){ setAttribute(Qt::WA_PaintOnScreen); setUpdatesEnabled(false); // Set the new video mode with the new window size char variable[64]; snprintf(variable, sizeof(variable), "SDL_WINDOWID=0x%lx", winId()); putenv(variable); SDL_InitSubSystem(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE); // initialize default Video if((SDL_Init(SDL_INIT_VIDEO) == -1)) { std:cerr << "Could not initialize SDL: " << SDL_GetError() << std::endl; } m_Screen = SDL_SetVideoMode(640, 480, 8, SDL_HWSURFACE | SDL_DOUBLEBUF); if (m_Screen == 0) { std::cerr << "Couldn't set video mode: " << SDL_GetError() << std::endl; } } virtual ~SDLVideo() { if(SDL_WasInit(SDL_INIT_VIDEO) != 0) { SDL_QuitSubSystem(SDL_INIT_VIDEO); m_Screen = 0; } } private: SDL_Surface *m_Screen; }; ``` Hope this helps Note: It usually makes sense to set both the min and max size of this widget to the SDL surface size.
How do I use Qt and SDL together?
[ "", "c++", "winapi", "qt", "sdl", "" ]
In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity? My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. * Do I have to choose between performance and data integrity? * If so, is in general better to go one way or is it particular to the case? * Are there other alternatives?
[RichQ's answer](https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734) is a reasonable technique, if you're using an array, vector, etc. If you're using a collection that isn't indexed by ordinal values... or think you *might need to* at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated `begin()`/`end()` methods: ``` class Blah { public: typedef std::vector<mydata> mydata_collection; typedef myDataCollection::const_iterator mydata_const_iterator; // ... mydata_const_iterator data_begin() const { return myPreciousData.begin(); } mydata_const_iterator data_end() const { return myPreciousData.end(); } private: mydata_collection myPreciousData; }; ``` ...which you can then use in the normal fashion: ``` Blah blah; for (Blah::mydata_const_iterator itr = blah.data_begin(); itr != blah.data_end(); ++itr) { // ... } ```
Many times the caller wants access just to iterate over the collection. Take a page out of Ruby's book and make the iteration a private aspect of your class. ``` #include <algorithm> #include <boost/function.hpp> class Blah { public: void for_each_data(const std::function<void(const mydata&)>& f) const { std::for_each(myPreciousData.begin(), myPreciousData.end(), f); } private: typedef std::vector<mydata> mydata_collection; mydata_collection myPreciousData; }; ``` With this approach you're not exposing anything about your internals, i.e. that you even *have* a collection.
Efficient alternatives for exposing a Collection
[ "", "c++", "performance", "collections", "data-integrity", "" ]
I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons. In the RenderContent call in the Webpart I've got some code to add event handlers: ``` ArrayList nextPages = new ArrayList(); //populate nextPages .... AfterPageRepeater.DataSource = nextPages; AfterPageRepeater.DataBind(); foreach (Control oRepeaterControl in AfterPageRepeater.Controls) { if (oRepeaterControl is RepeaterItem) { if (oRepeaterControl.HasControls()) { foreach (Control oControl in oRepeaterControl.Controls) { if (oControl is LinkButton) { ((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click); } } } } } ``` The function PageNavigateButton\_Click is never called however. I can see it being added as an event handler in the debugger however. Any ideas? I'm stumped how to do this.
By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad(): ``` protected override void OnLoad(EventArge e) { base.OnLoad(e); EnsureChildControls(); var linkButtons = from c in AfterPageRepeater.Controls .OfType<RepeaterItem>() where c.HasControls() select c into ris from lb in ris.OfType<LinkButton>() select lb; foreach(var linkButton in linkButtons) { linkButton.Click += PageNavigateButton_Click } } ```
Have you tried assigning the CommandName and CommandArgument properties to each button as you iterate through? The Repeater control supports the ItemCommand event, which is an event that will be raised when a control with the CommandName property is hit. From there it is easy enough to process because the CommandName and CommandArgument values are passed into the event and are readily accessible.
ASP.NET - Add Event Handler to LinkButton inside of Repeater in a RenderContent call
[ "", "c#", "asp.net", "sharepoint", "web-parts", "" ]
Suppose there are two scripts Requester.php and Provider.php, and Requester requires processing from Provider and makes an http request to it (Provider.php?data="data"). In this situation, Provider quickly finds the answer, but to maintain the system must perform various updates throughout the database. Is there a way to immediately return the value to Requester, and then continue processing in Provider. Psuedo Code ``` Provider.php { $answer = getAnswer($_GET['data']); echo $answer; //SIGNAL TO REQUESTER THAT WE ARE FINISHED processDBUpdates(); return; } ```
You basically want to signal the end of 1 process (return to the original `Requester.php`) and spawn a new process (finish `Provider.php`). There is probably a more elegant way to pull this off, but I've managed this a couple different ways. All of them basically result in exec-ing a command in order to shell off the second process. adding the following `> /dev/null 2>&1 &` to the end of your command will allow it to run in the background without inhibiting the actual execution of your current script Something like the following may work for you: ``` exec("wget -O - \"$url\" > /dev/null 2>&1 &"); ``` -- though you could do it as a command line PHP process as well. You could also save the information that needs to be processed and handle the remaining processing on a cron job that re-creates the same sort of functionality without the need to exec.
You can flush the output buffer with the flush() command. Read the comments in the [PHP manual](http://se.php.net/manual/en/function.flush.php) for more info
PHP: How to return information to a waiting script and continue processing
[ "", "php", "" ]
I am using Oracle SQL (in SQLDeveloper, so I don't have access to SQLPLUS commands such as COLUMN) to execute a query that looks something like this: ``` select assigner_staff_id as staff_id, active_flag, assign_date, complete_date, mod_date from work where assigner_staff_id = '2096'; ``` The results it give me look something like this: ``` STAFF_ID ACTIVE_FLAG ASSIGN_DATE COMPLETE_DATE MOD_DATE ---------------------- ----------- ------------------------- ------------------------- ------------------------- 2096 F 25-SEP-08 27-SEP-08 27-SEP-08 02.27.30.642959000 PM 2096 F 25-SEP-08 25-SEP-08 25-SEP-08 01.41.02.517321000 AM 2 rows selected ``` This can very easily produce a very wide and unwieldy textual report when I'm trying to paste the results as a nicely formatted quick-n-dirty text block into an e-mail or problem report, etc. What's the best way to get rid of all tha extra white space in the output columns when I'm using just plain-vanilla Oracle SQL? So far all my web searches haven't turned up much, as all the web search results are showing me how to do it using formatting commands like COLUMN in SQLPLUS (which I don't have).
What are you using to get the results? The output you pasted looks like it's coming from SQL\*PLUS. It may be that whatever tool you are using to generate the results has some method of modifying the output. By default Oracle outputs columns based upon the width of the title or the width of the column data which ever is wider. If you want make columns smaller you will need to either rename them or convert them to text and use substr() to make the defaults smaller. ``` select substr(assigner_staff_id, 8) as staff_id, active_flag as Flag, to_char(assign_date, 'DD/MM/YY'), to_char(complete_date, 'DD/MM/YY'), mod_date from work where assigner_staff_id = '2096'; ```
In your statement, you can specify the type of output you're looking for: ``` select /*csv*/ col1, col2 from table; select /*Delimited*/ col1, col2 from table; ``` there are other formats available such as xml, html, text, loader, etc. You can change the formatting of these particular options under tools > preferences > Database > Utilities > Export Be sure to choose Run Script rather than Run Statement. \* this is for Oracle SQL Developer v3.2
How to format Oracle SQL text-only select output
[ "", "sql", "oracle", "formatting", "" ]
My goal here is to create a very simple template language. At the moment, I'm working on replacing a variable with a value, like this: This input: > The Web Should produce this output: > The Web This Is A Test Variable I've got it working. But looking at my code, I'm running multiple identical regexes on the same strings -- that just offends my sense of efficiency. There's got to be a better, more Pythonic way. (It's the two "while" loops that really offend.) This does pass the unit tests, so if this is silly premature optimization, tell me -- I'm willing to let this go. There may be dozens of these variable definitions and uses in a document, but not hundreds. But I suspect there's obvious (to other people) ways of improving this, and I'm curious what the StackOverflow crowd will come up with. ``` def stripMatchedQuotes(item): MatchedSingleQuotes = re.compile(r"'(.*)'", re.LOCALE) MatchedDoubleQuotes = re.compile(r'"(.*)"', re.LOCALE) item = MatchedSingleQuotes.sub(r'\1', item, 1) item = MatchedDoubleQuotes.sub(r'\1', item, 1) return item def processVariables(item): VariableDefinition = re.compile(r'<%(.*?)=(.*?)%>', re.LOCALE) VariableUse = re.compile(r'<%(.*?)%>', re.LOCALE) Variables={} while VariableDefinition.search(item): VarName, VarDef = VariableDefinition.search(item).groups() VarName = stripMatchedQuotes(VarName).upper().strip() VarDef = stripMatchedQuotes(VarDef.strip()) Variables[VarName] = VarDef item = VariableDefinition.sub('', item, 1) while VariableUse.search(item): VarName = stripMatchedQuotes(VariableUse.search(item).group(1).upper()).strip() item = VariableUse.sub(Variables[VarName], item, 1) return item ```
The first thing that may improve things is to move the re.compile outside the function. The compilation is cached, but there is a speed hit in checking this to see if its compiled. Another possibility is to use a single regex as below: ``` MatchedQuotes = re.compile(r"(['\"])(.*)\1", re.LOCALE) item = MatchedQuotes.sub(r'\2', item, 1) ``` Finally, you can combine this into the regex in processVariables. Taking [Torsten Marek's](https://stackoverflow.com/questions/146607/im-using-python-regexes-in-a-criminally-inefficient-manner#146683) suggestion to use a function for re.sub, this improves and simplifies things dramatically. ``` VariableDefinition = re.compile(r'<%(["\']?)(.*?)\1=(["\']?)(.*?)\3%>', re.LOCALE) VarRepl = re.compile(r'<%(["\']?)(.*?)\1%>', re.LOCALE) def processVariables(item): vars = {} def findVars(m): vars[m.group(2).upper()] = m.group(4) return "" item = VariableDefinition.sub(findVars, item) return VarRepl.sub(lambda m: vars[m.group(2).upper()], item) print processVariables('<%"TITLE"="This Is A Test Variable"%>The Web <%"TITLE"%>') ``` Here are my timings for 100000 runs: ``` Original : 13.637 Global regexes : 12.771 Single regex : 9.095 Final version : 1.846 ``` [Edit] Add missing non-greedy specifier [Edit2] Added .upper() calls so case insensitive like original version
[`sub`](http://docs.python.org/lib/node46.html) can take a callable as it's argument rather than a simple string. Using that, you can replace all variables with one function call: ``` >>> import re >>> var_matcher = re.compile(r'<%(.*?)%>', re.LOCALE) >>> string = '<%"TITLE"%> <%"SHMITLE"%>' >>> values = {'"TITLE"': "I am a title.", '"SHMITLE"': "And I am a shmitle."} >>> var_matcher.sub(lambda m: vars[m.group(1)], string) 'I am a title. And I am a shmitle. ``` Follow eduffy.myopenid.com's advice and keep the compiled regexes around. The same recipe can be applied to the first loop, only there you need to store the value of the variable first, and always return `""` as replacement.
I'm using Python regexes in a criminally inefficient manner
[ "", "regex", "algorithm", "optimization", "python", "" ]
I need to convert a (possibly) null terminated array of ascii bytes to a string in C# and the fastest way I've found to do it is by using my UnsafeAsciiBytesToString method shown below. This method uses the String.String(sbyte\*) constructor which contains a warning in it's remarks: "The value parameter is assumed to point to an array representing a string encoded using the default ANSI code page (that is, the encoding method specified by Encoding.Default). Note: **\* Because the default ANSI code page is system-dependent, the string created by this constructor from identical signed byte arrays may differ on different systems. \*** ... **\* If the specified array is not null-terminated, the behavior of this constructor is system dependent. For example, such a situation might cause an access violation. \*** " Now, I'm positive that the way the string is encoded will never change... but the default codepage on the system that my app is running on might change. So, is there any reason that I shouldn't run screaming from using String.String(sbyte\*) for this purpose? ``` using System; using System.Text; namespace FastAsciiBytesToString { static class StringEx { public static string AsciiBytesToString(this byte[] buffer, int offset, int maxLength) { int maxIndex = offset + maxLength; for( int i = offset; i < maxIndex; i++ ) { /// Skip non-nulls. if( buffer[i] != 0 ) continue; /// First null we find, return the string. return Encoding.ASCII.GetString(buffer, offset, i - offset); } /// Terminating null not found. Convert the entire section from offset to maxLength. return Encoding.ASCII.GetString(buffer, offset, maxLength); } public static string UnsafeAsciiBytesToString(this byte[] buffer, int offset) { string result = null; unsafe { fixed( byte* pAscii = &buffer[offset] ) { result = new String((sbyte*)pAscii); } } return result; } } class Program { static void Main(string[] args) { byte[] asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c', 0, 0, 0 }; string result = asciiBytes.AsciiBytesToString(3, 6); Console.WriteLine("AsciiBytesToString Result: \"{0}\"", result); result = asciiBytes.UnsafeAsciiBytesToString(3); Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result); /// Non-null terminated test. asciiBytes = new byte[]{ 0, 0, 0, (byte)'a', (byte)'b', (byte)'c' }; result = asciiBytes.UnsafeAsciiBytesToString(3); Console.WriteLine("UnsafeAsciiBytesToString Result: \"{0}\"", result); Console.ReadLine(); } } } ```
Any reason not to use the `String(sbyte*, int, int)` constructor? If you've worked out which portion of the buffer you need, the rest should be simple: ``` public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length) { unsafe { fixed (byte* pAscii = buffer) { return new String((sbyte*)pAscii, offset, length); } } } ``` If you need to look first: ``` public static string UnsafeAsciiBytesToString(byte[] buffer, int offset) { int end = offset; while (end < buffer.Length && buffer[end] != 0) { end++; } unsafe { fixed (byte* pAscii = buffer) { return new String((sbyte*)pAscii, offset, end - offset); } } } ``` If this truly is an ASCII string (i.e. all bytes are less than 128) then the codepage problem shouldn't be an issue unless you've got a *particularly* strange default codepage which isn't based on ASCII. Out of interest, have you actually profiled your application to make sure that this is really the bottleneck? Do you definitely need the absolute fastest conversion, instead of one which is more readable (e.g. using Encoding.GetString for the appropriate encoding)?
Oneliner (assuming the buffer actually contains ONE well formatted null terminated string): ``` String MyString = Encoding.ASCII.GetString(MyByteBuffer).TrimEnd((Char)0); ```
Fastest way to convert a possibly-null-terminated ascii byte[] to a string?
[ "", "c#", ".net", "string", "ascii", "" ]
Why is it wrong to use `std::auto_ptr<>` with standard containers?
The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. `std::auto_ptr` does not fulfill this requirement. Take for example this code: ``` class X { }; std::vector<std::auto_ptr<X> > vecX; vecX.push_back(new X); std::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL. ``` To overcome this limitation, you should use the [`std::unique_ptr`](http://msdn.microsoft.com/en-us/library/ee410601.aspx), [`std::shared_ptr`](http://msdn.microsoft.com/en-us/library/bb982026.aspx) or [`std::weak_ptr`](http://msdn.microsoft.com/en-us/library/bb982126.aspx) smart pointers or the boost equivalents if you don't have C++11. [Here is the boost library documentation for these smart pointers.](http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/smart_ptr.htm)
The **copy semantics** of `auto_ptr` are not compatible with the containers. Specifically, copying one `auto_ptr` to another does not create two equal objects since one has lost its ownership of the pointer. More specifically, copying an `auto_ptr` causes one of the copies to let go of the pointer. Which of these remains in the container is not defined. Therefore, you can randomly lose access to pointers if you store `auto_ptrs` in the containers.
Why is it wrong to use std::auto_ptr<> with standard containers?
[ "", "c++", "stl", "raii", "auto-ptr", "c++-faq", "" ]
What is the easiest cross platform widget toolkit? I'm looking for one that minimally covers Windows, OSX, and Linux with a C or C++ interface.
I don't know of any I've personally used with a C API, but [wxWidgets](http://www.wxwidgets.org/) is C++. It runs on Windows, Linux, and Mac OS X. And if you're looking for easy, [wxPython](http://www.wxpython.org/) is a Python wrapper around wxWidgets and it is pretty easy to use.
I really like Qt. Have been working with it in several projects now. Although the project, I am currently working on, will be released for windows only, some of our developers code under Mac OS X using the gcc. And using different compilers and environments is an extra benefit for locating errors & bugs. I forgot to mention that Qt has a really good documentation including lots of practical examples that help for a quick start.
Easiest cross platform widget toolkit?
[ "", "c++", "c", "cross-platform", "gui-toolkit", "" ]
I am looking for a tool that can take a unit test, like ``` IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); ``` and generate, automatically, the corresponding stub class and interface ``` interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } ``` I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?
What you appear to need is a parser for your language (Java), and a name and type resolver. ("Symbol table builder"). After parsing the source text, a compiler usually has a name resolver, that tries to record the definition of names and their corresponding types, and a type checker, that verifies that each expression has a valid type. Normally the name/type resolver complains when it can't find a definition. What you want it to do is to find the "undefined" thing that is causing the problem, and infer a type for it. For ``` IPerson p = new Person(); ``` the name resolver knows that "Person" and "IPerson" aren't defined. If it were ``` Foo p = new Bar(); ``` there would be no clue that you wanted an interface, just that Foo is some kind of abstract parent of Bar (e.g., a class or an interface). So the decision as which is it must be known to the tool ("whenever you find such a construct, assume Foo is an interface ..."). You could use a heuristic: IFoo and Foo means IFoo should be an interface, and somewhere somebody has to define Foo as a class realizing that interface. Once the tool has made this decision, it would need to update its symbol tables so that it can move on to other statements: For ``` p.Name = "Sklivvz"; ``` given that p must be an Interface (by the previous inference), then Name must be a field member, and it appears its type is String from the assignment. With that, the statement: ``` Assert.AreEqual("Sklivvz", p.Name); ``` names and types resolve without further issue. The content of the IFoo and Foo entities is sort of up to you; you didn't have to use get and set but that's personal taste. This won't work so well when you have multiple entities in the same statement: ``` x = p.a + p.b ; ``` We know a and b are likely fields, but you can't guess what numeric type if indeed they are numeric, or if they are strings (this is legal for strings in Java, dunno about C#). For C++ you don't even know what "+" means; it might be an operator on the Bar class. So what you have to do is collect *constraints*, e.g., "a is some indefinite number or string", etc. and as the tool collects evidence, it narrows the set of possible constraints. (This works like those word problems: "Joe has seven sons. Jeff is taller than Sam. Harry can't hide behind Sam. ... who is Jeff's twin?" where you have to collect the evidence and remove the impossibilities). You also have to worry about the case where you end up with a contradiction. You could rule out p.a+p.b case, but then you can't write your unit tests with impunity. There are standard constraint solvers out there if you want impunity. (What a concept). OK, we have the ideas, now, can this be done in a practical way? The first part of this requires a parser and a bendable name and type resolver. You need a constraint solver or at least a "defined value flows to undefined value" operation (trivial constraint solver). Our [DMS Software Reengineering Toolkit](http://www.semanticdesigns.com/Products/DMS/DMSToolkit.html) with its [Java Front End](http://www.semanticdesigns.com/Products/FrontEnds/JavaFrontEnd.html) could probably do this. DMS is a tool builder's tool, for people that want to build tools that process computer langauges in arbitrary ways. (Think of "computing with program fragments rather than numbers"). DMS provides general purpose parsing machinery, and can build an tree for whatever front end it is given (e.g., Java, and there's a C# front end). The reason I chose Java is that our Java front end has all that name and type resolution machinery, and it is provided in source form so it can be bent. If you stuck to the trivial constraint solver, you could probably bend the Java name resolver to figure out the types. DMS will let you assemble trees that correspond to code fragments, and coalesce them into larger ones; as your tool collected facts for the symbol table, it could build the primitive trees. Somewhere, you have to decide you are done. How many unit tests the tool have to see before it knows the entire interface? (I guess it eats all the ones you provide?). Once complete, it assembles the fragments for the various members and build an AST for an interface; DMS can use its prettyprinter to convert that AST back into source code like you've shown. I suggest Java here because our Java front end has name and type resolution. Our C# front end does not. This is a "mere" matter of ambition; somebody has to write one, but that's quite a lot of work (at least it was for Java and I can't imagine C# is really different). But the idea works fine in principle using DMS. You could do this with some other infrastructure that gave you access to a parser and an a bendable name and type resolver. That might not be so easy to get for C#; I suspect MS may give you a parser, and access to name and type resolution, but not any way to change that. Maybe Mono is the answer? You still need a was to generate code fragments and assemble them. You might try to do this by string hacking; my (long) experience with gluing program bits together is that if you do it with strings you eventually make a mess of it. You really want pieces that represent code fragments of known type, that can only be combined in ways the grammar allows; DMS does that thus no mess.
Its amazing how no one really gave anything towards what you were asking. I dont know the answer, but I will give my thoughts on it. If I were to attempt to write something like this myself I would probably see about a resharper plugin. The reason I say that is because as you stated, resharper can do it, but in individual steps. So I would write something that went line by line and applied the appropriate resharper creation methods chained together. Now by no means do I even know how to do this, as I have never built anything for resharper, but that is what I would try to do. It makes logical sense that it could be done. And if you do write up some code, PLEASE post it, as I could find that usefull as well, being able to generate the entire skeleton in one step. Very useful.
Generating classes automatically from unit tests?
[ "", "c#", "unit-testing", "code-generation", "" ]
I am building a small website for fun/learning using a fairly standard Web/Service/Data Access layered design. To save me from constantly having to create instances of my service layer/data access layer classes, I have made the methods in them all static. I shouldn't get concurrency issues as they use local variables etc and do not share any resources (things are simple enough for this at the moment). As far as I can see the only trade-off for this is that I am not really following a true OO approach, but then again it keeps the code much cleaner. Is there any reason this would not be a viable approach? What sort of problems might arise later on? Would it be better to have a "factory" class that can return me instances of the service and data layer classes as needed?
Disadvantages: * You will be unable to write unit tests as you will be unable to write mock data access/business logic objects to test against. * You will have concurrency problems as different threads try to access the static code at the same time - or if you use synchronized static methods you will end up with threads queuing up to use the static methods. * You will not be able to use instance variables, which will become a restriction as the code becomes more complex. * It will be more difficult to replace elements of the business or data access layers if you need to. * If you intend to write your application in this manner you would be better off using a language designed to work in this way, such as PHP. You would be better off going for non-static business/data access layer classes by either: * Using the singleton pattern (creating a single instance of each class and sharing them among threads)... * Or creating instances of the classes in each thread as and when they are needed. Keep in mind that each user/session connected to your application will be running in it's own thread - so your web application is inherently multi-threaded.
You know those rides at the amusement park where they say "please keep your hands and feet inside the ride at all times"? It turns out the ride is a lot more fun if you don't. The only real trade-off is that you're not really following a true keeping-your-hands-and-feet-inside-the-ride-at-all-times approach. The point is this -- there is a reason you should follow a "true OO approach", just as there's a reason to keep your hands and feet inside the ride -- it's great fun until you start bleeding everywhere.
Static layers in a java web application
[ "", "java", "data-access-layer", "business-logic-layer", "" ]
I want to get the size of an http:/.../file before I download it. The file can be a webpage, image, or a media file. Can this be done with HTTP headers? How do I download just the file HTTP header?
Yes, assuming the HTTP server you're talking to supports/allows this: ``` public long GetFileSize(string url) { long result = -1; System.Net.WebRequest req = System.Net.WebRequest.Create(url); req.Method = "HEAD"; using (System.Net.WebResponse resp = req.GetResponse()) { if (long.TryParse(resp.Headers.Get("Content-Length"), out long ContentLength)) { result = ContentLength; } } return result; } ``` If using the HEAD method is not allowed, or the Content-Length header is not present in the server reply, the only way to determine the size of the content on the server is to download it. Since this is not particularly reliable, most servers will include this information.
> Can this be done with HTTP headers? Yes, this is the way to go. *If* the information is provided, it's in the header as the `Content-Length`. Note, however, that this is not necessarily the case. Downloading only the header can be done using a `HEAD` request instead of `GET`. Maybe the following code helps: ``` HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://example.com/"); req.Method = "HEAD"; long len; using(HttpWebResponse resp = (HttpWebResponse)(req.GetResponse())) { len = resp.ContentLength; } ``` Notice the property for the content length on the `HttpWebResponse` object – no need to parse the `Content-Length` header manually.
How to get the file size from http headers
[ "", "c#", "http", "download", "http-headers", "" ]
Is there a built in dll that will give me a list of links from a string. I want to send in a string with valid html and have it parse all the links. I seem to remember there being something built into either .net or an unmanaged library. I found a couple open source projects that looked promising but I thought there was a built in module. If not I may have to use one of those. I just didn't want an external dependency at this point if it wasn't necessary.
[SubSonic.Sugar.Web.ScrapeLinks](http://web.archive.org/web/20090510122547/http://subsonichelp.com/html/d4d577b3-5089-17a2-c667-db50ad3c9ff9.htm) seems to do part of what you want, however it grabs the html from a url, rather than from a string. You can check out their implementation [here](https://github.com/subsonic/SubSonic-2.0/blob/master/SubSonic/Sugar/Web.cs).
I'm not aware of anything built in and from your question it's a little bit ambiguous what you're looking for exactly. Do you want the entire anchor tag, or just the URL from the href attribute? If you have well-formed XHtml, you might be able to get away with using an XmlReader and an XPath query to find all the anchor tags (`<a>`) and then hit the href attribute for the address. Since that's unlikely, you're probably better off using RegEx to pull down what you want. Using RegEx, you could do something like: ``` List<Uri> findUris(string message) { string anchorPattern = "<a[\\s]+[^>]*?href[\\s]?=[\\s\\\"\']+(?<href>.*?)[\\\"\\']+.*?>(?<fileName>[^<]+|.*?)?<\\/a>"; MatchCollection matches = Regex.Matches(message, anchorPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled); if (matches.Count > 0) { List<Uri> uris = new List<Uri>(); foreach (Match m in matches) { string url = m.Groups["url"].Value; Uri testUri = null; if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out testUri)) { uris.Add(testUri); } } return uris; } return null; } ``` Note that I'd want to check the href to make sure that the address actually makes sense as a valid Uri. You can eliminate that if you aren't actually going to be pursuing the link anywhere.
Parse HTML links using C#
[ "", "c#", ".net", "html", "" ]
I'm trying to match elements with a name that is `'container1$container2$chkChecked'`, using a regex of `'.+\$chkChecked'`, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?
my guess, by your use of quotes, is you did something like ``` re = new RegExp('.+\$chkChecked'); ``` which won't work because js takes advantage of the \ in its string interpretation as an escape so it never makes it into the regex interpreter instead you want ``` re = new RegExp('.+\\$chkChecked'); ```
try ``` string.match( /[$]chkChecked$/ ) ``` alternatively, you could try ``` string.match( /[^a-zA-Z0-9]chkChecked/ ) ``` ( Also, make sure your using `//` around your regex, otherwise you might be matching using string literals. Not obvious tho without a larger code snippet )
JavaScript RegEx Elements Match
[ "", "javascript", "regex", "" ]
I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, experiences or better alternatives?
I apply logging with AOP using Castle Windsor DynamicProxies. I was already using Castle for it's IoC container, so using it for AOP was the path of least resistence for me. If you want more info let me know, I'm in the process of tidying the code up for releasing it as a blog post Edit Ok, here's the basic Intercepter code, faily basic but it does everything I need. There are two intercepters, one logs everyhing and the other allows you to define method names to allow for more fine grained logging. This solution is faily dependant on Castle Windsor **Abstract Base class** ``` namespace Tools.CastleWindsor.Interceptors { using System; using System.Text; using Castle.Core.Interceptor; using Castle.Core.Logging; public abstract class AbstractLoggingInterceptor : IInterceptor { protected readonly ILoggerFactory logFactory; protected AbstractLoggingInterceptor(ILoggerFactory logFactory) { this.logFactory = logFactory; } public virtual void Intercept(IInvocation invocation) { ILogger logger = logFactory.Create(invocation.TargetType); try { StringBuilder sb = null; if (logger.IsDebugEnabled) { sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(".{0}(", invocation.Method); for (int i = 0; i < invocation.Arguments.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(invocation.Arguments[i]); } sb.Append(")"); logger.Debug(sb.ToString()); } invocation.Proceed(); if (logger.IsDebugEnabled && invocation.ReturnValue != null) { logger.Debug("Result of " + sb + " is: " + invocation.ReturnValue); } } catch (Exception e) { logger.Error(string.Empty, e); throw; } } } } ``` **Full Logging Implemnetation** ``` namespace Tools.CastleWindsor.Interceptors { using Castle.Core.Logging; public class LoggingInterceptor : AbstractLoggingInterceptor { public LoggingInterceptor(ILoggerFactory logFactory) : base(logFactory) { } } } ``` **Method logging** ``` namespace Tools.CastleWindsor.Interceptors { using Castle.Core.Interceptor; using Castle.Core.Logging; using System.Linq; public class MethodLoggingInterceptor : AbstractLoggingInterceptor { private readonly string[] methodNames; public MethodLoggingInterceptor(string[] methodNames, ILoggerFactory logFactory) : base(logFactory) { this.methodNames = methodNames; } public override void Intercept(IInvocation invocation) { if ( methodNames.Contains(invocation.Method.Name) ) base.Intercept(invocation); } } } ```
+1 on postsharp. Have been using for several things (including some attempts on adding preconditions and postconditions to C# code) and don't know how I'd make it without it...
PostSharp - il weaving - thoughts
[ "", "c#", "visual-studio", "logging", "aop", "postsharp", "" ]
I'm looking for a suite of plugins that can help me finally switch over to vim full-time. Right now I'm using Komodo with some good success, but their vim bindings have enough little errors that I'm tired of it. What I do love in Komodo, though, is the code completion. So, here's what I'm looking for (ordered by importance). * Code completion, meaning: the ability to code complete modules/functions/etc. in *any* module that's on the pythonpath, **not just system modules**. Bonus points for showing docstrings when completing. * Jump-to a class definition. I'm guessing CTAGS will do this, so how do you all manage automatically updating your tags files? * Project type management for managing buffers: ideally the ability to grep for a filename in a directory structure to open it. Bonus for showing an index of class definitions while a buffer is open. * Bzr integration. Not super important, since most of it I can just drop to the shell to do.
[Here you can find some info](http://www.sontek.net/python-with-a-modular-ide-vim) about this. It covers code completion, having a list of classes and functions in open files. I haven't got around to do a full configuration for vim, since I don't use Python primarily, but I have the same interests in transforming vim in a better Python IDE. **Edit:** The original site is down, so found it [saved on the web archive](https://web.archive.org/web/20110106042207/http://sontek.net/python-with-a-modular-ide-vim).
And I write another plugin: <https://github.com/klen/python-mode> Old (now its more powerful) screencast here: <https://www.youtube.com/watch?v=67OZNp9Z0CQ>
Has anyone found a good set of python plugins for vim -- specifically module completion?
[ "", "python", "vim", "code-completion", "" ]
I've got many assemblies/projects in the same c#/.net solution. A setting needs to be saved by people using the web application gui, and then a console app and some test projects need to access the same file. Where should I put the file and how to access it? I've tried using "AppDomain.CurrentDomain.BaseDirectory" but that ends up being different for my assemblies. Also the "System.Reflection.Assembly.Get\*Assembly.Location" fail to give me what I need. Maybe this isn't something I should but in a file, but rather the database? But it feels so complicated doing that for a few lines of configuration.
Personally, I would be leveraging the database because the alternative is either a configuration headache or is more trouble than it's worth. You *could* configure each application to point to the same file, but that becomes problematic if you want to move the file. Or you could write a service to manage the file and expose that to clients, but at this point you may as well just use the DB.
Put the file in ``` Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "[Company Name]\[Application Suite]"); ```
Letting several assemblies access the same text file
[ "", "c#", ".net", "file", "file-io", "filesystems", "" ]
So I've decided to try to solve my physics homework by writing some python scripts to solve problems for me. One problem that I'm running into is that significant figures don't always seem to come out properly. For example this handles significant figures properly: ``` from decimal import Decimal >>> Decimal('1.0') + Decimal('2.0') Decimal("3.0") ``` But this doesn't: ``` >>> Decimal('1.00') / Decimal('3.00') Decimal("0.3333333333333333333333333333") ``` So two questions: 1. Am I right that this isn't the expected amount of significant digits, or do I need to brush up on significant digit math? 2. Is there any way to do this without having to set the decimal precision manually? Granted, I'm sure I can use numpy to do this, but I just want to know if there's a way to do this with the decimal module out of curiosity.
Changing the decimal working precision to 2 digits is *not* a good idea, unless you absolutely only are going to perform a single operation. You should always perform calculations at higher precision than the level of significance, and only round the final result. If you perform a long sequence of calculations and round to the number of significant digits at each step, errors will accumulate. The decimal module doesn't know whether any particular operation is one in a long sequence, or the final result, so it assumes that it shouldn't round more than necessary. Ideally it would use infinite precision, but that is too expensive so the Python developers settled for 28 digits. Once you've arrived at the final result, what you probably want is quantize: ``` >>> (Decimal('1.00') / Decimal('3.00')).quantize(Decimal("0.001")) Decimal("0.333") ``` You have to keep track of significance manually. If you want automatic significance tracking, you should use interval arithmetic. There are some libraries available for Python, including [pyinterval](http://pyinterval.googlecode.com/) and [mpmath](http://code.google.com/p/mpmath/) (which supports arbitrary precision). It is also straightforward to implement interval arithmetic with the decimal library, since it supports directed rounding. You may also want to read the [Decimal Arithmetic FAQ: Is the decimal arithmetic ‘significance’ arithmetic?](http://speleotrove.com/decimal/decifaq4.html#signif)
Decimals won't throw away decimal places like that. If you really want to limit precision to 2 d.p. then try ``` decimal.getcontext().prec=2 ``` EDIT: You can alternatively call quantize() every time you multiply or divide (addition and subtraction will preserve the 2 dps).
Significant figures in the decimal module
[ "", "python", "floating-point", "decimal", "physics", "significance", "" ]
Microsoft WPF? Adobe AIR/Flex? Adobe Flash? Curl programming language? How does AJAX fit in? Given a server written in C++ .NET.
The answer does depend really on what your application actually does and your platform requirements. If its a regular web application like gmail and you want it to work on lots of browsers and platforms; then I'd recommend a combination of HTML, CSS and [GWT](http://code.google.com/webtoolkit/) as this means your application code is all Java, its very easy to refactor modularise and maintain, there's a ton of Java programmers out there and the IDEs for Java are awesome (IntelliJ or eclipse etc). You can then use browser plugins like Siverlight or Flex if and when they make sense (e.g. like [Google finance](http://finance.google.com/finance) uses Flash for interactive graphs). If your application is highly graphical like a Visio type of thing or needs to embed Microsoft Office or something; you might wanna look at Silverlight/Flex/AIR particularly if you can kinda dictate the browser versions and platforms for an internal application. Though with client side there's no clear single answer (just look at the comments on this thread :) there are many options (Java Applets/Swing/JavaFX, Ajax, GWT, Air/Flex, Silverlight/.Net etc) which all have strengths and weaknesses. My recommendation for the communication between the client and your C++ server would be to expose your C++ application as a set of RESTful resources - then at any point in time you can easily write other kinds of clients in any language technology or framework.
Using WPF you can build desktop and then almost 1:1 port it to silverlight and target the web
Best technology for developing an app that runs on DESKTOP and in BROWSER?
[ "", "c++", "client", "distributed", "" ]
What is the best way to disable the warnings generated via `_CRT_SECURE_NO_DEPRECATE` that allows them to be reinstated with ease and will work across Visual Studio versions?
If you don't want to pollute your source code (after all this warning presents only with Microsoft compiler), add `_CRT_SECURE_NO_WARNINGS` symbol to your project settings via "Project"->"Properties"->"Configuration properties"->"C/C++"->"Preprocessor"->"Preprocessor definitions". Also you can define it just before you include a header file which generates this warning. You should add something like this ``` #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif ``` And just a small remark, make sure you understand what this warning stands for, and maybe, if you don't intend to use other compilers than MSVC, consider using safer version of functions i.e. strcpy\_s instead of strcpy.
You could disable the warnings temporarily in places where they appear by using ``` #pragma warning(push) #pragma warning(disable: warning-code) //4996 for _CRT_SECURE_NO_WARNINGS equivalent // deprecated code here #pragma warning(pop) ``` so you don't disable all warnings, which can be harmful at times.
Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE
[ "", "c++", "visual-studio", "visual-c++", "" ]
Say I have the following C++: ``` char *p = new char[cb]; SOME_STRUCT *pSS = (SOME_STRUCT *) p; delete pSS; ``` Is this safe according to the C++ standard? Do I need to cast back to a `char*` and then use `delete[]`? I know it'll work in most C++ compilers, because it's plain-ordinary-data, with no destructors. Is it guaranteed to be safe?
It's not guaranteed to be safe. Here's a relevant link in the C++ FAQ lite: [16.13] Can I drop the `[]` when deleting array of some built-in type (`char`, `int`, etc.)? [http://www.parashift.com/c++-faq-lite/freestore-mgmt.html#faq-16.13](https://isocpp.org/wiki/faq/freestore-mgmt#delete-array-built-ins)
No, it's undefined behaviour - a compiler could plausibly do something different, and as the C++ FAQ entry that [thudbang](https://stackoverflow.com/questions/70880/deleting-a-buffer-through-a-different-type-of-pointer#70905) linked to says, `operator delete[]` might be overloaded to do something different to `operator delete`. You can sometimes get away with it, but it's also good practice to get into the habit of matching delete[] with new[] for the cases where you can't.
deleting a buffer through a different type of pointer?
[ "", "c++", "pointers", "memory-management", "" ]
Let me first say, we validate every field on the server side, so this a question about client-side usability. What is the conventional wisdom on *exactly when* to validate and format html form input fields using javascript? As an example, we have a phone number field. We allow numbers, spaces, parentheses, and hyphens. We want the field to have ten digits. Also, we want the field to look like (123) 456-7890, even if the user doesn't type it that way. It seems like we can * Validate and format it when the user exits the field. * Validate and format on every character entered. * Intercept keystrokes and prevent the user from entering characters that are wrong. * Some combination of the above (e.g. format on entry and validate on exit, prevent on entry and format on exit, etc.) * [**Added**] Wait and do all the validation and formatting when the user clicks submit. I've seen it done all of these ways, but I can't find information about what is best (or even generally accepted) from a usability perspective, and more importantly, why. [**Edit**: Some clarification] We are absolutely not enforcing any format standards. When I say format, I mean we'll use javascript to rewrite things so they look nice. If the user types 1234567890, we'll change it to (123) 456-7890. There are no "formatting rules" that can fail. I distinguish this from validation because if they don't type enough numbers, we have to make them fix it. I guess I should rephrase the question as "what is the conventional wisdom on exactly when to validate and exactly when to format...? Good info in the answers so far! **EDIT**: I'm accepting my own answer below in the hopes that others will find the link as helpful as I did.
By far the best answer so far was not an answer but a comment (see above.) I'm adding it as an answer in case anyone misses it in the comment. See the following article on A List Apart. [Inline Validation in Web Forms by Luke Wroblewski](http://www.alistapart.com/articles/inline-validation-in-web-forms/)
> Validate and format it when the user exits the field. Yes. Provide noninvasive feedback to the user if validation or formatting rules fail. By noninasive I mean don't popup an alert or modal dialog box, thereby forcing the user to click something. Rather dynamically display a message adjacent or underneath the field where validation or formatting failed. > Validate and format on every character entered. No. I think that hinders usability. Instead provide the user with a tooltip or some other hint as to what the formatting rules are or validation rules are. E.g. for a "required" field the practically ubiquitious asterisk, and for fields with formatting tell the user up front what the expected format is. > Intercept keystrokes and prevent the user from entering characters that are wrong. If you are going to prevent the user from entering invalid characters, tell the user why you just blocked their input, noninvasively. Also,do not steal focus of the field. So for me the general principles are: 1. Inform the user up front about your validation and formatting rules. 2. Do not assume the user is sighted, so keep web accessiblity and screen readers in mind. (Unless you are developing a web site that has a limited target audience such as an Intranet.) 3. Provide the user with noninvasive feedback, meaning do not make the user click on an alert box or modal dialog upon each failure. 4. Make it obvious which input box failed validation or formatting rules, and tell the user why their input failed. 5. Do not steal the mouse/pointer focus, when providing feedback. 6. Keep tab order in mind, so that when keyboard oriented users complete a field, they can hit tab and go to the next logical input/selection field.
What Event to Trigger Javascript Form Field Validation and Formatting?
[ "", "javascript", "validation", "usability", "" ]
I have an application that is causing a lot of headaches. It's a .NET app connecting to SQL Server 2005 via a web service. The program has grid that is filled by a long running stored procedure that is prone to timing out. In the case when it does time out and a SqlException is thrown, there is no execption handling to close the connection. What are the actual consequences of this condition? I think that the framework or SQL Server probably takes care of it one way or another but am not sure. **Addition** The program always works well in the morning, but after an hour or so of use it basically stops working. The issue isn't that I don't know how to code the connection properly. I need to know if these symptoms could be casued by the unclosed connections. It is kind of a big deal to change the production code and I would like to know that it is at least possible for this to be the issue. **Conclusion** I engineered this failure to occur on hundreds of simultaneous connections. Never was I able reproduce the failure condition in the application environment. Marked best practices answer as correct. Thanks everyone.
Since a SqlConnection closes while disposing i usually use this syntax ``` using (SqlConnection conn = new SqlConnection()) { // SqlCode here } ```
There is a connection limit; if your app crashes frequently and does not close the connections automatically, new connection requests will be denied. That said, connections do time out after a while if they're not closed.
What are the consequences of not closing database connection after an error?
[ "", ".net", "sql", "sql-server", "sql-server-2005", "web-services", "" ]
what is an efficient way to get a certain time for the next day in Java? Let's say I want the long for tomorrow 03:30:00. Setting Calendar fields and Date formatting are obvious. Better or smarter ideas, thanks for sharing them! Okami
I take the brute force approach ``` // make it now Calendar dateCal = Calendar.getInstance(); // make it tomorrow dateCal.add(Calendar.DAY_OF_YEAR, 1); // Now set it to the time you want dateCal.set(Calendar.HOUR_OF_DAY, hours); dateCal.set(Calendar.MINUTE, minutes); dateCal.set(Calendar.SECOND, seconds); dateCal.set(Calendar.MILLISECOND, 0); return dateCal.getTime(); ```
I'm curious to hear what other people have to say about this one. My own experience is that taking shortcuts (i.e., "better or smarter ideas") with `Date`s almost always lands you in trouble. Heck, just using `java.util.Date` is asking for trouble. Added: Many have recommended [Joda Time](http://joda-time.sourceforge.net/) in other Date-related threads.
Get the time of tomorrow xx:xx
[ "", "java", "date", "" ]
Does anybody know of a method for creating custom Performance Counters using ordinary unmanaged Visual C++? I know that it can be done easily using managed C++, but I need to do it using an unmanaged Windows service. I also know that you can retrieve performance counter data, but I need to create some custom counters and increment them during the applications runtime.
See here: <http://msdn.microsoft.com/en-us/library/aa371925.aspx> It is not really hard, but a bit tedious as the API involves extensive usage of self-referential, variable-length structures and has to employ some IPC mechanism to obtain the data from the monitored process.
The support for adding C++ performance counters changed in Vista and beyond. The Performance DLL approach suggested in another answer still works, but the new technique described [here](https://msdn.microsoft.com/en-us/library/aa965334(v=vs.85).aspx) is easier to use. In this approach you write a manifest that describes your counters, run CTRPP, a tool that generates code from your manifest. Compile and link this code with your application, and add a call to initialize the process (it starts a background thread), and add code to update the counters as necessary. The details of publishing the counters are handled by the background thread running the generated code. You also need to run lodctr /m:[manifest file] to register your counters before they can be used. This must be run as an admin. BTW: Another program, unlodctr reverse the effect of lodctr and must be used if you make any changes to your counters because there is no "replace" operation, only delete the old, then install the new. <RANT>Documentation for all the above is just plain awful. For example lodctr was completely reworked for Vista, but the doc in MSDN is all for the XP version and no longer applies. If you visit MSDN please use the "This documentation is not helpful" button liberally and maybe Microsoft will get the message.</RANT>
Creating Custom Performance Counters in Visual C++
[ "", "c++", "visual-c++", "performancecounter", "" ]
I am searching for a good system for PHP, which does UnitTesting, Subversion, Coding Standards. I would love to hear your suggestions and which one is the best and why. I will be running it on a debian server so anything which runs on mac or windows servers would be out of the question.
I second Hudson for CI and PHP. I have written a tutorial on setting it up if you are interested. Edit: My tutorial is out of date. I highly recommend: <http://jenkins-php.org/>
We have played with Xinc, but we stuck with phpUnderControl for now. It seemed a bit more mature, when we evaluated the different solutions. phpug came with the obvious support for phpUnit, also generates docs (phpDocumentor) uses xdebug code coverage and project mess detection and even checks on CS (through phpcs). As for phpUnit, you can now even run [phpt](http://qa.php.net/phpt_details.php)-style tests with it which makes it for some people easier to write tests. And even though phpug adds CruiseControl and Java to the game it hasn't been much of a hassle for us. Not as much as I assumed anyway. :) I mean, that's the advantage with a Java-based service. (Assuming you have the JDK) You just download and run it. That easy. I am not familiar with Java on Debian, but last time I checked it wasn't an issue. As for commercial solutions I know a bunch of PHP shops that use [Bamboo](http://www.atlassian.com/software/bamboo/) (along with the complete Atlassian suite).
Alternative to phpUnderControl - is it the best?
[ "", "php", "version-control", "continuous-integration", "" ]
I am working on a very large scale computing library that is using STL heavily. The library is being built using MSVC2003 and it is using its STL implementation. I am looking for an alternative STL implementation that would help the library lower its memory requirements and increase its performance. It is not possible to switch to a newer version of MSVC for the moment. I would like some feedback on real world usage not based on benchmarks if possible. EDIT: To make it a little clearer, for example some STL implementation (like STLSoft) are proposing specific optimizations for string concatenation; these might sounds small in impact but they can lead to large improvements. STLPort is another good example where they clearly state their goal: having the fastest STL implementation around, there is the stdlib++, etc ... all of these can be good candidates but I have no time to test them all, i require some community help on that.
[STLPort](http://stlport.org/). Haven't measured memory usage differences, but it's definitely quicker (yes, real world usage).
I question your basic premise, that you can not switch to a newer version of MSVC. I don't think you're going to get lower memory and increased performance "for free" by downloading a new STL. Or at least, if you did, you would probably have to do as many code fixes as if you were to just update to the latest MSVC. Long term, there's no question you want to update... Do it now, and you **might** get lucky and get some of that memory and performance for free. The only thing I can think to suggest to you along the lines of what you say you're looking for would be to try the Intel compiler, which I've had both good (performance!) and bad (quirky, sometimes!) experience with. Other than that, find your own memory and performance problems, and write custom containers and algorithms. STL is awesome, but it's not a panacea for fixing all problems in all cases. Domain knowledge is your best ally.
What is the STL implementation with the lowest memory footprint?
[ "", "c++", "optimization", "stl", "" ]
I am working on a legacy project in `VC++/Win32/MFC`. Recently it became a requirement that the application work on a **tablet pc**, and this ushered in a host of new issues. I have been able to work with, and around these issues, **but am left with one wherein I could use some expert suggestions.** I have a particular bug that is induced by the "lift" of the stylus off of the active surface. Basically the mouse cursor disappears and then reappears when you "press" it back onto the screen. It makes sense that this is unaccounted for in the application. you can't **lift** the cursor on a desktop pc. So what I am looking for is a good overview on what happens (in terms of windows messages, etc.) when the lift occurs. Does this translate to just focus changes and mouseover events? My bug seems to also involve cursor changes (may not be lift related though). Certainly the unexpected "lift" is breaking the state of the application's tool processing. **So the tangible questions are:** 1. What happens when a stylus "lift" occurs? A press? 2. What API calls can be used to detect this? Does it just translate into standard messages with flags/values set? 3. Whats a good way to test/emulate this when your development pc is a desktop? Am I just flying blind here? (I only have periodic access to a tablet pc) 4. What represents correct behavior or best practice for tablet stylus awareness? Thanks for your consideration, ee
As a tablet user I can answer a few of your questions. First: > You cannot very easily keep a "keyboard focus" on a window when the stylus has to trail out of the focused window to push a key on the virtual keyboard. Most of the virtual keyboards I've used (The windows tablet input panel and one under ubuntu) allow the program they are typing in to keep "keyboard focus." > What happens when a stylus "lift" occurs? A press? Under Windows, the pressure value drops, but outside of that, there is no event. (I don't know about linux.) > What API calls can be used to detect this? Does it just translate into standard messages with flags/values set? As mentioned above, if you can get the pressure value, you can use that. > Whats a good way to test/emulate this when your development pc is a desktop? Am I just flying blind here? (I only have periodic access to a tablet pc) When the stylus is placed down elsewhere, the global coordinates of the pointer change, so, you can emulate the sudden pointer move with anything that allows you to change the global pointer values. (The Robot class in Java makes this fairly easy.) > What represents correct behavior or best practice for tablet stylus awareness? I'd recommend you read what Microsoft has to say, the MSDN website has a number of excellent articles. (<http://msdn.microsoft.com/en-us/library/ms704849(VS.85).aspx>) I'll point out that the size of the buttons on your applications makes a HUGE difference. Hope this was of help.
@Greg - A clarification, this is a laptop pc with integrated tablet and stylus built in. the device has no dedicated keyboard (it is a virtual one on the touchscreen) and is not a wacom input device. Sorry for the confusion. It appears that there is an [SDK](http://www.microsoft.com/downloads/details.aspx?FamilyId=B46D4B83-A821-40BC-AA85-C9EE3D6E9699&displaylang=en#RelatedLinks) for the Microsoft Windows XP Tablet PC Edition that may have the ability to get special details such as pressure. However, I know that there has to be some level of standard compatibility with existing non-tablet-aware applications. I guess I can try to get Spy++ installed on the tablet and try and filter down to specific messages/events.
What happens when the stylus "lifts" on a tablet PC?
[ "", "c++", "windows", "events", "tablet-pc", "stylus-pen", "" ]
Everyone has accidentally forgotten the `WHERE` clause on a `DELETE` query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical. What if, in place of actual `DELETE` queries, the application and maintenance scripts did something like: ``` UPDATE foo SET to_be_deleted=1 WHERE blah = 50; ``` And then a cron job was set to go through and actually delete everything with the flag? The downside would be that pretty much every other query would need to have `WHERE to_be_deleted != 1` appended to it, but the upside would be that you'd never mistakenly lose data again. You could see "2,349,325 rows affected" and say, "Hmm, looks like I forgot the `WHERE` clause," and reset the flags. You could even make the to\_be\_deleted field a `DATE` column, so the cron job would check to see if a row's time had come yet. Also, you could remove `DELETE` permission from the production database user, so even if someone managed to inject some SQL into your site, they wouldn't be able to remove anything. So, my question is: Is this a good idea, or are there pitfalls I'm not seeing?
That is fine if you want to do that, but it seems like a lot of work. How many people are manually changing the database? It should be very few, especially if your users have an app to work with. When I work on the production db I put EVERYTHING I do in a transaction so if I mess up I can rollback. Just having a standard practice like that for me has helped me. I don't see anything really wrong with that though other than ever single point of data manipulation in each applicaiton will have to be aware of this functionality and not just the data it wants.
This would be fine as long as your appliction does not require that the data is immediately deleted since you have to wait for the next interval of the cron job. I think a better solution and the more common practice is to use a development server and a production server. If your development database gets blown out, simply reload it. No harm done. If you're testing code on your production database, you deserve anything bad that happens.
Database safety: Intermediary "to_be_deleted" column/table?
[ "", "sql", "database", "" ]
In JavaScript, you can use [Lazy Function Definitions](http://peter.michaux.ca/article/3556) to optimize the 2nd - Nth call to a function by performing the **expensive** one-time operations only on the first call to the function. I'd like to do the same sort of thing in PHP 5, but redefining a function is not allowed, nor is overloading a function. Effectively what I'd like to do is like the following, only optimized so the 2nd - Nth calls (say 25-100) don't need to re-check if they are the first call. ``` $called = false; function foo($param_1){ global $called; if($called == false){ doExpensiveStuff($param_1); $called = true; } echo '<b>'.$param_1.'</b>'; } ``` PS I've thought about using an include\_once() or require\_once() as the first line in the function to execute the external code just once, but I've heard that these too are expensive. Any Ideas? or is there a better way to tackle this?
Use a local static var: ``` function foo() { static $called = false; if ($called == false) { $called = true; expensive_stuff(); } } ``` Avoid using a global for this. It clutters the global namespace and makes the function less encapsulated. If other places besides the innards of the function need to know if it's been called, then it'd be worth it to put this function inside a class like Alan Storm indicated.
Have you actually profiled this code? I'm doubtful that an extra boolean test is going to have any measurable impact on page rendering time.
Lazy Function Definition in PHP - is it possible?
[ "", "php", "design-patterns", "optimization", "" ]
I haven't kept up lately with the C++ world. Exactly where do things stand these days regarding the standard? Is TR1 adopted? Is there a TR2? How do these relate to C++0x? Are the subsumed? Has a decision been reached on threading yet?
You can find an extensive article about the upcoming C++0x on [wikipedia](http://en.wikipedia.org/wiki/C%2B%2B0x) and the current state of C++ evolution [here](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2705.html). It is also worth giving a look at the current GNU implementation in [gcc](http://www.gnu.org/software/gcc/gcc-4.4/cxx0x_status.html)
I'd recommend you to visit <http://www.open-std.org/jtc1/sc22/wg21/>
State of C++ Standard
[ "", "c++", "standards", "" ]
The title is pretty much self explanatory. Given two dates what is the best way of finding the number of week days using PHP? Week days being Monday to Friday. For instance, how would I find out that there are 10 week days in between `31/08/2008` and `13/09/2008`?
``` $datefrom = strtotime($datefrom, 0); $dateto = strtotime($dateto, 0); $difference = $dateto - $datefrom; $days_difference = floor($difference / 86400); $weeks_difference = floor($days_difference / 7); // Complete weeks $first_day = date("w", $datefrom); $days_remainder = floor($days_difference % 7); $odd_days = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder? if ($odd_days > 7) { // Sunday $days_remainder--; } if ($odd_days > 6) { // Saturday $days_remainder--; } $datediff = ($weeks_difference * 5) + $days_remainder; ``` From here: <http://www.addedbytes.com/php/php-datediff-function/>
If you are creating an invoicing system, you have to think about the bank holidays, Easter, etc. It is not simple to compute it. The best solution I have ever seen is to pregenerate a table with days and its type to SQL database (row per day = 365 rows per year) and then perform simple count query with proper selection (WHERE clause). You can find this solution fully described in *Joe Celko's Thinking in Sets: Auxiliary, Temporal, and Virtual Tables in SQL*
Given two dates what is the best way of finding the number of weekdays in PHP?
[ "", "php", "date", "" ]
Is there any good tool for working on Dabtabase apart from Toad which requires license and DBVisualiser not supportive
Try fabForce Database Designer; it is GPL too. <http://fabforce.net/dbdesigner4/>
i'd recommend oracle SQLdeveloper. it has all the functionality you need for developing and maintanice
Is there any good tool for working on Database apart from Toad which requires license and DBVisualiser not supportive
[ "", "sql", "database", "" ]
I know this would be easy with position:fixed, but unfortanately I'm stuck with supporting IE 6. How can I do this? I would rather use CSS to be clean, but if I have to use Javascript, that's not the end of the world. In my current implementation I have a "floating footer" that floats above the main content area and is positioned with Javascript. The implementation I have right now is not particular elegant even with the Javascript, so my questions are: 1. Is there a way to do this without Javascript? 2. If I have to use Javascript, are there any "nice" solutions to this floating footer problem? By "nice" I mean something that will work across browsers, doesn't overload the browser's resources (since it will have to recalculate often), and is elegant/easy to use (i.e. it would be nice to write something like `new FloatingFooter("floatingDiv")`). I'm going to guess there is no super easy solution that has everything above, but something I can build off of would be great. Finally, just a more general question. I know this problem is a big pain to solve, so what are other UI alternatives rather than having footer content at the bottom of every page? On my particular site, I use it to show transitions between steps. Are there other ways I could do this?
This may work for you. It works on IE6 and Firefox 2.0.0.17 for me. Give it a shot. I made the footer's height very tall, just for effect. You would obviously change it to what you need. I hope this works for you. ``` <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <title>Liquid Footer</title> <style type="text/css"> .footer { background-color: #cdcdcd; height: 180px; text-align: center; font-size:10px; color:#CC0000; font-family:Verdana; padding-top: 10px; width: 100%; position:fixed; left: 0px; bottom: 0px; } </style> <!--[if lte IE 6]> <style type="text/css"> body {height:100%; overflow-y:auto;} html {overflow-x:auto; overflow-y:hidden;} * html .footer {position:absolute;} </style> <![endif]--> </head> <body> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> This is to expand the content on the page<br> <div class="footer">-- This is your liquid footer --</div> </body> </html> ```
if you do want to not use the conditional comments, so that you can put the css in a separate file, use `!important`. Something like this: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <style> html { overflow-x: auto; overflow-y: scroll !important; overflow-y: hidden; /* ie6 value b/c !important ignored */ } body { padding:0; margin:0; height: 100%; overflow-y: hidden !important; overflow-y: scroll; /* ie6 value b/c !important ignored */ } #bottom { background-color:#ddd; position: fixed !important; position: absolute; /* ie6 value b/c !important ignored */ width: 100%; bottom: 0px; z-index: 5; height:100px; } #content { font-size: 50px; } </style> </head> <body> <div id="bottom"> keep this text in the viewport at all times </div> <div id="content"> Let's create enough content to force scroll bar to appear. Then we can ensure this works when content overflows. One quick way to do this is to give this text a large font and throw on some extra line breaks. <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <br/><br/><br/><br/><br/><br/><br/><br/> </div> </body> </html> ```
How do I get a floating footer to stick to the bottom of the viewport in IE 6?
[ "", "javascript", "css", "internet-explorer-6", "sticky-footer", "" ]
``` public class Test { public static void main(String[] args) { } } class Outer { void aMethod() { class MethodLocalInner { void bMethod() { System.out.println("Inside method-local bMethod"); } } } } ``` Can someone tell me how to print the message from `bMethod`?
You can only instantiate `MethodLocalInner` within `aMethod`. So do ``` void aMethod() { class MethodLocalInner { void bMethod() { System.out.println("Inside method-local bMethod"); } } MethodLocalInner foo = new MethodLocalInner(); // Default Constructor foo.bMethod(); } ```
Within the method *aMethod* after the declaration of the class *MethodLocalInner* you could for instance do the following call: ``` new MethodLocalInner().bMethod(); ```
Method Local Inner Class
[ "", "java", "inner-classes", "method-invocation", "" ]
I need to read selected files, matching on the file name, from a remote zip archive using Python. I don't want to save the full zip to a temporary file (it's not that large, so I can handle everything in memory). I've already written the code and it works, and I'm answering this myself so I can search for it later. But since evidence suggests that I'm one of the dumber participants on Stackoverflow, I'm sure there's room for improvement.
Here's how I did it (grabbing all files ending in ".ranks"): ``` import urllib2, cStringIO, zipfile try: remotezip = urllib2.urlopen(url) zipinmemory = cStringIO.StringIO(remotezip.read()) zip = zipfile.ZipFile(zipinmemory) for fn in zip.namelist(): if fn.endswith(".ranks"): ranks_data = zip.read(fn) for line in ranks_data.split("\n"): # do something with each line except urllib2.HTTPError: # handle exception ```
Thanks Marcel for your question and answer (I had the same problem in a different context and encountered the same difficulty with file-like objects not really being file-like)! Just as an update: For Python 3.0, your code needs to be modified slightly: ``` import urllib.request, io, zipfile try: remotezip = urllib.request.urlopen(url) zipinmemory = io.BytesIO(remotezip.read()) zip = zipfile.ZipFile(zipinmemory) for fn in zip.namelist(): if fn.endswith(".ranks"): ranks_data = zip.read(fn) for line in ranks_data.split("\n"): # do something with each line except urllib.request.HTTPError: # handle exception ```
How do I read selected files from a remote Zip archive over HTTP using Python?
[ "", "python", "http", "zip", "" ]
How to set all the values in a `std::map` to the same value, without using a loop iterating over each value?
Using a loop *is* by far the simplest method. In fact, it’s a one-liner:[C++17] ``` for (auto& [_, v] : mymap) v = value; ``` Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use `std::fill`. To use them anyway (pre-C++20), we need to write adapters — in the case of `std::fill`, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do *not* advise using it as-is. Use a library (such as [Boost.Iterator](https://www.boost.org/doc/libs/1_74_0/libs/iterator/doc/function_output_iterator.html)) for a more general, production-strength implementation. ``` template <typename M> struct value_iter : std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type> { using base_type = std::iterator<std::bidirectional_iterator_tag, typename M::mapped_type>; using underlying = typename M::iterator; using typename base_type::value_type; using typename base_type::reference; value_iter(underlying i) : i(i) {} value_iter& operator++() { ++i; return *this; } value_iter operator++(int) { auto copy = *this; i++; return copy; } reference operator*() { return i->second; } bool operator ==(value_iter other) const { return i == other.i; } bool operator !=(value_iter other) const { return i != other.i; } private: underlying i; }; template <typename M> auto value_begin(M& map) { return value_iter<M>(map.begin()); } template <typename M> auto value_end(M& map) { return value_iter<M>(map.end()); } ``` With this, we can use `std::fill`: ``` std::fill(value_begin(mymap), value_end(mymap), value); ```
I encountered the same problem but found that the range returned by boost::adaptors::values is mutable, so it can then be used with normal algorithms such as std::fill. ``` #include <boost/range/adaptor/map.hpp> auto my_values = boost::adaptors::values(my_map); std::fill(my_values.begin(), my_values.end(), 123); ```
Setting all values in a std::map
[ "", "c++", "stl", "" ]
A couple of days ago, I read a blog entry (<http://ayende.com/Blog/archive/2008/09/08/Implementing-generic-natural-language-DSL.aspx>) where the author discuss the idea of a generic natural language DSL parser using .NET. The brilliant part of his idea, in my opinion, is that the text is parsed and matched against classes using the same name as the sentences. Taking as an example, the following lines: ``` Create user user1 with email test@email.com and password test Log user1 in Take user1 to category t-shirts Make user1 add item Flower T-Shirt to cart Take user1 to checkout ``` Would get converted using a collection of "known" objects, that takes the result of parsing. Some example objects would be (using Java for my example): ``` public class CreateUser { private final String user; private String email; private String password; public CreateUser(String user) { this.user = user; } public void withEmail(String email) { this.email = email; } public String andPassword(String password) { this.password = password; } } ``` So, when processing the first sentence, CreateUser class would be a match (obviously because it's a concatenation of "create user") and, since it takes a parameter on the constructor, the parser would take "user1" as being the user parameter. After that, the parser would identify that the next part, "with email" also matches a method name, and since that method takes a parameter, it would parse "test@email.com" as being the email parameter. I think you get the idea by now, right? One quite clear application of that, at least for me, would be to allow application testers create "testing scripts" in natural language and then parse the sentences into classes that uses JUnit to check for app behaviors. I'd like to hear ideas, tips and opinions on tools or resource that could code such parser using Java. Better yet if we could avoid using complex lexers, or frameworks like ANTLR, which I think maybe would be using a hammer to kill a fly. More than that, if anyone is up to start an open source project for that, I would definitely be interested.
Considering the complexity of lexing and parsing, I don't know if I'd want to code all that by hand. **[ANTLR](http://www.antlr.org/) isn't that hard to pickup and I think it is worthing looking into based on your problem.** If you use a parse grammar to build and abstract syntax tree from the input, its pretty easy to then process that AST with a tree grammar. The tree grammar could easily handle executing the process you described. You'll find ANTLR in many places including Eclipse, Groovy, and Grails for a start. [The Definitive ANTLR Reference](https://rads.stackoverflow.com/amzn/click/com/0978739256) even makes it fairly straightforward to get up to speed on the basic fairly quickly. I had a project that had to handle some user generated query text earlier this year. I started down a path to manually process it, but it quickly became overwhelming. I took a couple days to get up the speed on ANTLR and had an initial version of my grammar and processor running in a few days. Subsequent changes and adjustments to the requirements would have killed any custom version, but required relatively little effort to adjust once I had the ANTLR grammars up and running. Good luck!
You might want to consider [Xtext](http://wiki.eclipse.org/Xtext), which internally uses ANTLR and does some nice things like auto-generating an editor for your DSL.
What would the best tool to create a natural DSL in Java?
[ "", "java", "dsl", "nlp", "parsing", "" ]
While refactoring some old code I have stripped out a number of public methods that should actually of been statics as they a) don't operate on any member data or call any other member functions and b) because they might prove useful elsewhere. This led me to think about the best way to group 'helper' functions together. The Java/C# way would be to use a class of static functions with a private constructor, e.g.: ``` class Helper { private: Helper() { } public: static int HelperFunc1(); static int HelperFunc2(); }; ``` However, being C++ you could also use a namespace: ``` namespace Helper { int HelperFunc1(); int HelperFunc2(); } ``` In most cases I think I would prefer the namespace approach but I wanted to know what the pros and cons of each approach are. If used the class approach for example, would there be any overheads?
Overhead is not an issue, namespaces have some advantages though * You can reopen a namespace in another header, grouping things more logically while keeping compile dependencies low * You can use namespace aliasing to your advantage (debug/release, platform specific helpers, ....) e.g. I've done stuff like ``` namespace LittleEndianHelper { void Function(); } namespace BigEndianHelper { void Function(); } #if powerpc namespace Helper = BigEndianHelper; #elif intel namespace Helper = LittleEndianHelper; #endif ```
A case where one might use `class` (or `struct`) over `namespace` is when one needs a type, for example: ``` struct C { static int f() { return 33; } }; namespace N { int f() { return 9; } } template<typename T> int foo() { return T::f(); } int main() { int ret = foo<C>(); //ret += foo<N>(); // compile error: N is a namespace return ret; } ```
'Helper' functions in C++
[ "", "c++", "class", "namespaces", "" ]
I would like to encrypt strings which could potentially only be about three or four characters but run to about twenty characters. A hashing function ([md5](http://www.php.net/md5), [sha1](http://www.php.net/sha1), [crypt](http://www.php.net/crypt) etc) is not suitable as I would like to be able to decrypt the information as well. The [mcrypt](http://au.php.net/mcrypt) extension has a thoroughly daunting array of possibilities. Does anyone have any ideas about the best way to safely encrypt short strings and *why*? Does anyone have any links to any material introducing a casual programmer to practical encryption scenarios?
I highly recommend the suggestions of **Chris Kite**. Without knowing more about what you're doing, why, and the threats you anticipate needing to protect against AES-128 is likely sufficient. The ability to use symmetric encryption is great for a standalone app that will be both the decryptor and encryptor of data. As both **Chris Kite** and **Arachnid** said, due to the small size of your data it's advised that you pad the data and use a random Initialization Vector. > **Update:** As for why.... if the data is small enough, and the IV can be predicted, it's possible to brute force the plain-text by generating cipher-text for every combination of plain-text with the known IV and matching it up to the captured cipher-text. In short, this is how rainbow tables work. Now if you're going to encrypt on one server and decrypt on another I'd go with the suggestions of **pdavis**. By using an asymmetric method you're able to separate the encryption keys from the decryption keys. This way if the server that encrypts data is compromised, the attacker is still unable to decrypt the data. If you're able to, it'd help the community to know more about your use case for the encryption. As I mentioned above, having a proper understanding of plausible threats is key when evaluating security controls.
I like to use GnuPG for anything that needs to be encrypted on a server and then possibly decrypted either on the server or on another server (which is usually my case). This allows for an extra level of security since in my scenario the encrypting server doesn't have the key to decrypt the data. It also allows for easier manual decryption. There are a few good wrappers available for various languages (another advantage), one for PHP is [GnuPGP PHP Class](http://www.austintech.com/2003/06/11/gnupg-php-class/).
What is the best way to encrypt a very short string in PHP?
[ "", "php", "encryption", "" ]
Events are synchronous in C#. I have this application where my main form starts a thread with a loop in it that listens to a stream. When something comes along on the stream an event is fired from the loop to the main form. If the main form is slow or shows a messagebox or something the loop will be suspended. What is the best way around this? By using a callback and invoke on the main form?
Hmmm, I've used different scenarios that depended on what I needed at the time. I believe the BeginInvoke would probably be the easiest to code since you're almost there. Either way you should be using Invoke already, so just changing to BeginInvoke. Using a callback on a separate thread will accomplish the same thing (as long as you use the threadpool to queue up the callback) as using BeginInvoke.
Since you're using a form, the easier way is to use the [BackgroundWorker](https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker) component. > The BackgroundWorker class allows you > to run an operation on a separate, > dedicated thread. Time-consuming > operations like downloads and database > transactions can cause your user > interface (UI) to seem as though it > has stopped responding while they are > running. When you want a responsive UI > and you are faced with long delays > associated with such operations, the > BackgroundWorker class provides a > convenient solution.
Best way to make events asynchronous in C#
[ "", "c#", "events", "asynchronous", "" ]
What is the difference between `==` and `===`? * How exactly does the loosely `==` comparison work? * How exactly does the strict `===` comparison work? What would be some useful examples?
## Difference between `==` and `===` The difference between the loosely `==` equal operator and the strict `===` identical operator is exactly explained in the [manual](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison): Comparison Operators | Example | Name | Result | | --- | --- | --- | | $a == $b | Equal | TRUE if $a is equal to $b after type juggling. | | $a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. | --- ## Loosely `==` equal comparison If you are using the `==` operator, or any other comparison operator which uses loosely comparison such as `!=`, `<>` or `==`, you always have to look at the **context** to see what, where and why something gets converted to understand what is going on. ## Converting rules * [Converting to boolean](http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting) * [Converting to integer](http://php.net/manual/en/language.types.integer.php#language.types.integer.casting) * [Converting to float](http://php.net/manual/en/language.types.float.php#language.types.float.casting) * [Converting to string](http://php.net/manual/en/language.types.string.php#language.types.string.casting) * [Converting to array](http://php.net/manual/en/language.types.array.php#language.types.array.casting) * [Converting to object](http://php.net/manual/en/language.types.object.php#language.types.object.casting) * [Converting to resource](http://php.net/manual/en/language.types.resource.php#language.types.resource.casting) * [Converting to NULL](http://php.net/manual/en/language.types.null.php#language.types.null.casting) ## Type comparison table As reference and example you can see the comparison table in the [manual](http://php.net/manual/en/types.comparisons.php#types.comparisions-loose): | | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | "" | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | TRUE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | TRUE | FALSE | TRUE | | 1 | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | 0 | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | TRUE | FALSE | TRUE | TRUE | | -1 | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | | "1" | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | "0" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | | "-1" | TRUE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | | NULL | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | TRUE | | array() | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | TRUE | FALSE | FALSE | | "php" | TRUE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | | "" | FALSE | TRUE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | TRUE | ## Strict `===` identical comparison If you are using the `===` operator, or any other comparison operator which uses strict comparison such as `!==` or `===`, then you can always be sure that the types won't *magically* change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value. ## Type comparison table As reference and example you can see the comparison table in the [manual](http://php.net/manual/en/types.comparisons.php#type.comparisons-strict): Strict comparisons with `===` | | TRUE | FALSE | 1 | 0 | -1 | "1" | "0" | "-1" | NULL | array() | "php" | "" | | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | | TRUE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | 1 | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | 0 | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | -1 | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | "1" | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | | "0" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | FALSE | | "-1" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | FALSE | | NULL | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | FALSE | | array() | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | FALSE | | "php" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | FALSE | | "" | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | FALSE | TRUE | > **Editor's note** - This was properly quoted previously, but is more readable as a markdown table. This is not plagiarism
The operator == casts between two different types if they are different, while the === operator performs a 'typesafe comparison'. That means that it will only return true if both operands have the same type and the same value. Examples: ``` 1 === 1: true 1 == 1: true 1 === "1": false // 1 is an integer, "1" is a string 1 == "1": true // "1" gets casted to an integer, which is 1 "foo" === "foo": true // both operands are strings and have the same value ``` **Warning**: two instances of the same class with equivalent members do NOT match the `===` operator. Example: ``` $a = new stdClass(); $a->foo = "bar"; $b = clone $a; var_dump($a === $b); // bool(false) ```
How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
[ "", "php", "operators", "" ]
In an application where users can belong to multiple groups, I'm currently storing their groups in a column called `groups` as a binary. Every four bytes is a 32 bit integer which is the `GroupID`. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually find out if they contain that group. Another method was to use a unicode string, where each character is the integer denoting a group, and this makes searching easy, but is a bit of a fudge. Another method is to create a separate table, linking users to groups. One column called `UserID` and another called `GroupID`. Which of these ways would be the best to do it? Or is there a better way?
You have a many-to-many relationship between users and groups. This calls for a separate table to combine users with groups: ``` User: (UserId[PrimaryKey], UserName etc.) Group: (GroupId[PrimaryKey], GroupName etc.) UserInGroup: (UserId[ForeignKey], GroupId[ForeignKey]) ``` To find all users in a given group, you just say: ``` select * from User join UserInGroup on UserId Where GroupId=<the GroupId you want> ``` Rule of thumb: If you feel like you need to encode multiple values in the same field, you probably need a foreign key to a separate table. Your tricks with byte-blocks or Unicode chars are just clever tricks to encode multiple values in one field. Database design should not use clever tricks - save that for application code ;-)
I'd definitely go for the separate table - certainly the best relational view of data. If you have indexes on both UserID and GroupID you have a quick way of getting users per group and groups per user.
What is the best way to add users to multiple groups in a database?
[ "", "sql", "database", "" ]
I have a large codebase, and I'd like to refactor the package structure so that classes which interact heavily go in the same package. It seems that it should be possible to create a tool that could look at the interactions between classes, and then group together those classes that interact heavily. These groupings might then suggest a good hierarchy for packages. Does such a tool exist? (open source is preferred).
Structure Analysis for Java is an Eclipse plugin that does some dependency analysis: <http://stan4j.com/>
Structure101 is another product that can analyze the structure of your code and do dependency and what-if analysis. <http://www.headwaysoftware.com/products/structure101/index.php>
Is there a tool that will look at my Java code, and suggest a good package structure?
[ "", "java", "refactoring", "" ]
Phantom References serve for post-mortem operations. The Java specification states that a **phantom referenced object** will not be deallocated until the phantom-reference itself is cleaned. My question is: What purpose does this feature (object not deallocated) serve? (The only idea i came up with, is to allow native code to do post-mortem cleanup on the object, but it isn't much convincing).
The only good use-case I can think of, that would prevent deallocation, is one where some kind of JNI-implemented asynchronous data source is writing into the referenced object, and must be told to stand down - to stop writing into the object - before the memory is recycled. If prior deallocation were allowed, a simple forgot-to-dispose() bug could result in memory corruption. This is one of the cases where finalize() would have been used in the past, and probably drove some of its quirks.
Edit, since I've misunderstand the question first: Quoted from here <http://www.memorymanagement.org/glossary/p.html>: > The Java specification says that the > phantom reference is not cleared when > the reference object is enqueued, but > actually, there's no way in the > language to tell whether that has been > done or not. In some implementations, > JNI weak global references are weaker > than phantom references, and provide a > way to access phantom reachable > objects. But I found no other references which would say the same.
Phantom Referenced Objects
[ "", "java", "finalize", "phantom-reference", "" ]
I've started refactoring some legacy code recently and came across two functions for drawing a coordinate grid, the problem is that these functions differ only in orthogonal variables they treat, something like that ``` void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int x = x0; x < x1; x += step) { MoveToEx(dc, x, y0, NULL); LineTo(dc, x, y1); } } void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int y = y0; y < y1; y += step) { MoveToEx(dc, x0, y, NULL); LineTo(dc, x1, y); } } ``` So if I decide to add some fancy stuff, like antialiasing or merely change drawing pencil or whatever I'll have to put the same code in both of them and it's code duplication and it's bad we all know why. My question is how would you rewrite these two functions into a single one to avoid this problem?
Drawing a line is simply joining two points, and drawing a scaling incrementing (x0,y0) and(x1,y1) in a particular direction, through X, and/or through Y. This boils down to, in the scale case, which direction(s) stepping occurs (maybe both directions for fun). ``` template< int XIncrement, YIncrement > struct DrawScale { void operator()(HDC dc, int step, int x0, int x1, int y0, int y1) { const int deltaX = XIncrement*step; const int deltaY = YIncrement*step; const int ymax = y1; const int xmax = x1; while( x0 < xmax && y0 < ymax ) { MoveToEx(dc, x0, y0, NULL); LineTo(dc, x1, y1); x0 += deltaX; x1 += deltaX; y0 += deltaY; y1 += deltaY; } } }; typedef DrawScale< 1, 0 > DrawScaleX; typedef DrawScale< 0, 1 > DrawScaleY; ``` The template will do its job: at compile time the compiler will remove all the null statements i.e. deltaX or deltaY is 0 regarding which function is called and half of the code goes away in each functor. You can add you anti-alias, pencil stuff inside this uniq function and get the code properly generated generated by the compiler. This is cut and paste on steroids ;-) -- ppi
Why you just do not extract the body of the for cycle into a separate function? Then you can do the funny stuff in the extracted function. ``` void DrawScaleX(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int x = x0; x < x1; x += step) { DrawScale(dc, x, y0, x, y1); } } void DrawScaleY(HDC dc, int step, int x0, int x1, int y0, int y1) { for(int y = y0; y < y1; y += step) { DrawScale(dc, x0, y, x1, y); } } private void DrawScale(HDC dc, int x0, int y0, int x1, int y1) { //Add funny stuff here MoveToEx(dc, x0, y0, NULL); LineTo(dc, x1, y1); //Add funny stuff here } ```
Orthogonal variables code duplication problem
[ "", "c++", "code-duplication", "" ]
Sometimes my c++ program crashes in debug mode, and what I got is a message box saying that an assertion failed in some of the internal memory management routines (accessing unallocated memory etc.). But I don't know where that was called from, because I didn't get any stack trace. How do I get a stack trace or at least see where it fails in my code (instead of library/ built-in routines)?
If you have a crash, you can get information about where the crash happened whether you have a debug or a release build. And you can see the call stack even if you are on a computer that does not have the source code. To do this you need to use the PDB file that was built with your EXE. Put the PDB file inside the same directory as the EXE that crashed. Note: Even if you have the same source code, building twice and using the first EXE and the second PDB won't work. You need to use the exact PDB that was built with your EXE. Then attach a debugger to the process that crashed. Example: windbg or VS. Then simply checkout your call stack, while also having your threads window open. You will have to select the thread that crashed and check on the callstack for that thread. Each thread has a different call stack. If you already have your VS debugger attached, it will automatically go to the source code that is causing the crash for you. If the crash is happening inside a library you are using that you don't have the PDB for. There is nothing you can do.
If you run the debug version on a machine with VS, it should offer to bring it up and let you see the stack trace. The problem is that the real problem is not on the call stack any more. If you free a pointer twice, that can result in this problem somewhere else unrelated to the program (the next time anything accesses the heap datastructures) I wrote this blog on some tips for getting the problem to show up in the call stack so you can figure out what is going on. <http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/02/06/6-_2200_Pointers_2200_-on-Debugging-Unmanaged-Code.aspx> The best tip is to use the gflags utility to make pointer issues cause immediate problems.
How to get a stack trace when C++ program crashes? (using msvc8/2005)
[ "", "c++", "debugging", "visual-studio-2005", "stack-trace", "" ]
``` public static Logger getLogger() { final Throwable t = new Throwable(); final StackTraceElement methodCaller = t.getStackTrace()[1]; final Logger logger = Logger.getLogger(methodCaller.getClassName()); logger.setLevel(ResourceManager.LOGLEVEL); return logger; } ``` This method would return a logger that knows the class it's logging for. Any ideas against it? Many years later: <https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java>
I guess it adds a lot of overhead for every class. Every class has to be 'looked up'. You create new Throwable objects to do that... These throwables don't come for free.
The [MethodHandles](https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.html) class (as of Java 7) includes a [Lookup](https://docs.oracle.com/javase/7/docs/api/java/lang/invoke/MethodHandles.Lookup.html) class that, from a static context, can find and return the name of the current class. Consider the following example: ``` import java.lang.invoke.MethodHandles; public class Main { private static final Class clazz = MethodHandles.lookup().lookupClass(); private static final String CLASSNAME = clazz.getSimpleName(); public static void main( String args[] ) { System.out.println( CLASSNAME ); } } ``` When run this produces: ``` Main ``` For a logger, you could use: ``` private static Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getSimpleName()); ```
Java logger that automatically determines caller's class name
[ "", "java", "logging", "stack-trace", "" ]
I have an Asset object that has a property AssignedSoftware, which is a collection. I want to make sure that the same piece of Software is not assigned to an Asset more than once. In Add method I check to see if the Software already exist, and if it does, I want to throw an exception. Is there a standard .NET exception that I should be throwing? Or does best practices dictate I create my own custom exception?
From the Class Library design guidelines for errors (<http://msdn.microsoft.com/en-us/library/8ey5ey87(VS.71).aspx>): > In most cases, use the predefined exception types. Only define new exception types for programmatic scenarios, where you expect users of your class library to catch exceptions of this new type and perform a programmatic action based on the exception type itself. This is in lieu of parsing the exception string, which would negatively impact performance and maintenance. > > ... > > Throw an ArgumentException or create an exception derived from this class if invalid parameters are passed or detected. > > Throw the InvalidOperationException exception if a call to a property set accessor or method is not appropriate given the object's current state. This seems like an "Object state invalid" scenario to me, so I'd pick InvalidOperationException over ArgumentException: The parameters are valid, but not at this point in the objects life.
Why has `InvalidOperationException` been accepted as the answer?! It should be an `ArgumentException`?! `InvalidOperationException` should be used if the object having the method/property called against it is not able to cope with the request due to uninit'ed state etc. The problem here is **not the object being Added to, but the object being passed to the object (it's a dupe).** Think about it, if this Add call never took place, would the object still function as normal, YES! This should be an **ArgumentException**.
What is the correct .NET exception to throw when try to insert a duplicate object into a collection?
[ "", "c#", "exception", "collections", "" ]
I'm searching a small **Java** based RSS/Feed Generator, something like the [FeedCreator.class.php](http://www.bitfolge.de/rsscreator-en.html) library, any suggestions?, thanks!
There's the Rome framework as well <http://rometools.github.io/rome/> Does RSS and Atom
How about [jRSS](http://jrss.sourceforge.net/)? It looks promising -- supports generating RSS 2 and is relatively small.
Do you know a good Java RSS/Feed Generator?
[ "", "java", "rss", "generator", "feed", "" ]
My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a `URLConnection`. How can I specify this?
This should do the trick: ``` URL url = new URL(yourUrlHere); Proxy proxy = new Proxy(Proxy.Type.DIRECT, new InetSocketAddress( InetAddress.getByAddress( new byte[]{your, ip, interface, here}), yourTcpPortHere)); URLConnection conn = url.openConnection(proxy); ``` And you are done. Dont forget to handle exceptions nicely and off course change the values to suit your scenario. Ah and I omitted the import statements
Using the Apache commons HttpClient I have also found the following to work (removed try/catch for clarity): ``` HostConfiguration hostConfiguration = new HostConfiguration(); byte b[] = new byte[4]; b[0] = new Integer(192).byteValue(); b[1] = new Integer(168).byteValue(); b[2] = new Integer(1).byteValue(); b[3] = new Integer(11).byteValue(); hostConfiguration.setLocalAddress(InetAddress.getByAddress(b)); HttpClient client = new HttpClient(); client.setHostConfiguration(hostConfiguration); GetMethod method = new GetMethod("http://remoteserver/"); method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); System.out.println(new String(responseBody));"); ``` However, I still wonder what would happen if the gateway of the IP is down (192.168.1.11 in this case). Will the next gateway be tried or will it fail?
How can I specify the local address on a java.net.URLConnection?
[ "", "java", "tomcat", "ip", "urlconnection", "" ]
I believe strongly in using unit-tests as part of building large multi-platform applications. We currently are planning on having our unit-tests within a separate project. This has the benefit of keeping our code base clean. I think, however, that this would separate the test code from the implementation of the unit. What do you think of this approach and are there any tools like JUnit for c++ applications?
There are many Test Unit frameforks for C++. CppUnit is certainly not the one I would choose (at least in its stable version 1.x, as it lacks many tests, and requires a lot of redundant lines of codes). So far, my preferred framework is [CxxTest](http://cxxtest.sf.net/), and I plan on evaluating [Fructose](http://fructose.sourceforge.net/) some day. Any way, there are a few "papers" that evaluate C++ TU frameworks : * [*Exploring the C++ Unit Testing Framework Jungle*](http://gamesfromwithin.com/exploring-the-c-unit-testing-framework-jungle), By Noel Llopis * [an article in Overload Journal #78](http://accu.org/index.php/journals/c211/)
That's a reasonable approach. I've had very good results both with [UnitTest++](http://unittest-cpp.sourceforge.net/) and [Boost.Test](http://www.boost.org/doc/libs/1_36_0/libs/test/doc/html/index.html) I've looked at CppUnit, but to me, it felt more like a translation of the JUnit stuff than something aimed at C++. **Update:** These days I prefer using [Catch](https://github.com/philsquared/Catch). I found it to be effective and simple to use.
How do you implement unit-testing in large scale C++ projects?
[ "", "c++", "unit-testing", "coding-style", "" ]
If i have lots of directory names either as literal strings or contained in variables, what is the easiest way of combining these to make a complete path? I know of ``` Path.Combine ``` but this only takes 2 string parameters, i need a solution that can take any number number of directory parameters. e.g: ``` string folder1 = "foo"; string folder2 = "bar"; CreateAPath("C:", folder1, folder2, folder1, folder1, folder2, "MyFile.txt") ``` Any ideas? Does C# support unlimited args in methods?
> Does C# support unlimited args in methods? Yes, have a look at the params keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested): ``` string CombinePaths(params string[] parts) { string result = String.Empty; foreach (string s in parts) { result = Path.Combine(result, s); } return result; } ```
LINQ to the rescue again. The [Aggregate](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate) extension function can be used to accomplish what you want. Consider this example: ``` string[] ary = new string[] { "c:\\", "Windows", "System" }; string path = ary.Aggregate((aggregation, val) => Path.Combine(aggregation, val)); Console.WriteLine(path); //outputs c:\Windows\System ```
Building a directory string from component parts in C#
[ "", "c#", "filesystems", "string-building", "" ]
How can I find the 2nd, 3rd, ... nth maximum value of a column?
You could sort the column into descending format and then just obtain the value from the nth row. EDIT:: Updated as per comment request. ***WARNING*** completely untested! ``` SELECT DOB FROM (SELECT DOB FROM USERS ORDER BY DOB DESC) WHERE ROWID = 6 ``` Something like the above should work for Oracle ... you might have to get the syntax right first!
Consider the following Employee table with a single column for salary. ``` +------+ | Sal | +------+ | 3500 | | 2500 | | 2500 | | 5500 | | 7500 | +------+ ``` The following query will return the Nth Maximum element. ``` select SAL from EMPLOYEE E1 where (N - 1) = (select count(distinct(SAL)) from EMPLOYEE E2 where E2.SAL > E1.SAL ) ``` For eg. when the second maximum value is required, ``` select SAL from EMPLOYEE E1 where (2 - 1) = (select count(distinct(SAL)) from EMPLOYEE E2 where E2.SAL > E1.SAL ) ``` ``` +------+ | Sal | +------+ | 5500 | +------+ ```
Query to find nᵗʰ max value of a column
[ "", "sql", "database", "" ]
I've seen a number of postgresql modules for python like pygresql, pypgsql, psyco. Most of them are Python DB API 2.0 compliant, some are not being actively developed anymore. Which module do you recommend? Why?
psycopg2 seems to be the most popular. I've never had any trouble with it. There's actually a pure Python interface for PostgreSQL too, called [bpgsql](http://barryp.org/software/bpgsql/). I wouldn't recommend it over psycopg2, but it's recently become capable enough to support Django and is useful if you can't compile C modules.
I suggest Psycopg over Psycopg2 since the first one seems a bit more sable. At least in my experience. I have an application running 24/7 and sometimes I was getting random memory crashes (double free or corruption errors) from Psycopg2. Nothing I could have debug fast or easily since it's not a Python error but a C error. I just switched over to Pyscopg and I did not get any crashes after that. Also, as said in an other post, [bpgsql](http://barryp.org/software/bpgsql/) seems a very good alternative. It's stable and easy to use since you don't need to compile it. The only bad side is that library is not threadsafe. Pygresql seems nice, there's a more direct way to query the database with this library. But I don't know how stable this one is though.
Python PostgreSQL modules. Which is best?
[ "", "python", "postgresql", "module", "" ]
So I'm programming along in a nice, up to date, object oriented fashion. I regularly make use of the various aspects of OOP that PHP implements but I am wondering when might I need to use closures. Any experts out there that can shed some light on when it would be useful to implement closures?
PHP will support closures natively in 5.3. A closure is good when you want a local function that's only used for some small, specific purpose. The [RFC for closures](http://wiki.php.net/rfc/closures) gives a good example: ``` function replace_spaces ($text) { $replacement = function ($matches) { return str_replace ($matches[1], ' ', '&nbsp;').' '; }; return preg_replace_callback ('/( +) /', $replacement, $text); } ``` This lets you define the `replacement` function locally inside `replace_spaces()`, so that it's not: **1)** cluttering up the global namespace **2)** making people three years down the line wonder why there's a function defined globally that's only used inside one other function It keeps things organized. Notice how the function itself has no name, it's simply defined and assigned as a reference to `$replacement`. But remember, you have to wait for PHP 5.3 :)
When you will need a function in the future which performs a task that you have decided upon now. For example, if you read a config file and one of the parameters tells you that the `hash_method` for your algorithm is `multiply` rather than `square`, you can create a closure that will be used wherever you need to hash something. The closure can be created in (for example) `config_parser()`; it creates a function called `do_hash_method()` using variables local to `config_parser()` (from the config file). Whenever `do_hash_method()` is called, it has access to variables in the local scope of`config_parser()` even though it's not being called in that scope. A hopefully good hypothetical example: ``` function config_parser() { // Do some code here // $hash_method is in config_parser() local scope $hash_method = 'multiply'; if ($hashing_enabled) { function do_hash_method($var) { // $hash_method is from the parent's local scope if ($hash_method == 'multiply') return $var * $var; else return $var ^ $var; } } } function hashme($val) { // do_hash_method still knows about $hash_method // even though it's not in the local scope anymore $val = do_hash_method($val) } ```
Closures in PHP... what, precisely, are they and when would you need to use them?
[ "", "php", "oop", "closures", "" ]
Inspired by another question asking about the missing `Zip` function: Why is there no `ForEach` extension method on the `IEnumerable` interface? Or anywhere? The only class that gets a `ForEach` method is `List<>`. Is there a reason why it's missing, maybe performance?
There is already a `foreach` statement included in the language that does the job most of the time. I'd hate to see the following: ``` list.ForEach( item => { item.DoSomething(); } ); ``` Instead of: ``` foreach(Item item in list) { item.DoSomething(); } ``` The latter is clearer and easier to read **in most situations**, although maybe a bit longer to type. However, I must admit I changed my stance on that issue; a `ForEach()` extension method would indeed be useful in some situations. Here are the major differences between the statement and the method: * Type checking: foreach is done at runtime, `ForEach()` is at compile time (Big Plus!) * The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething); * ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion. Those are all great points made by many people here and I can see why people are missing the function. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration.
ForEach method was added before LINQ. If you add ForEach extension, it will never be called for List instances because of extension methods constraints. I think the reason it was not added is to not interference with existing one. However, if you really miss this little nice function, you can roll out your own version ``` public static void ForEach<T>( this IEnumerable<T> source, Action<T> action) { foreach (T element in source) action(element); } ```
Why is there no ForEach extension method on IEnumerable?
[ "", "c#", ".net", "vb.net", "extension-methods", "" ]
Greetings, I'm trying to find either a free .NET library or a command-line executable that lets me convert M4A files to either MP3s or WMA files. Please help :).
Found it! <http://pieter.wigleven.com/it/archives/3> There may be other solutions, but this is gold for what I was looking for. P.S. I've written [a .NET DLL](https://github.com/AlexeyMK/M4A-to-MP3--.net-) which handles this behind-the-scenes. It's pretty terrible code, but it gets the job done.
This is simple if you know the right tools: ``` ffmpeg -i infile.m4a tmp.wav lame tmp.wav outfile.mp3 ``` Here a batch version (sorry Linux/Mac only): ``` #!/bin/bash n=0 maxjobs=3 for i in *.m4a ; do ffmpeg -i "$i" "$TMP/${i%m4a}wav" (lame "$TMP/${i%m4a}wav" "${i%m4a}mp3" ; rm "$TMP/${i%m4a}wav") & # limit jobs if (( $(($((++n)) % $maxjobs)) == 0 )) ; then wait fi done ```
How do I convert an M4A file to an MP3 or WMA file programmatically?
[ "", "c#", ".net", "mp3", "" ]
I'm talking about an action game with no upper score limit and no way to verify the score on the server by replaying moves etc. What I really need is the strongest encryption possible in Flash/PHP, and a way to prevent people calling the PHP page other than through my Flash file. I have tried some simple methods in the past of making multiple calls for a single score and completing a checksum / fibonacci sequence etc, and also obfuscating the SWF with Amayeta SWF Encrypt, but they were all hacked eventually. Thanks to StackOverflow responses I have now found some more info from Adobe - <http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_12.html> and <https://github.com/mikechambers/as3corelib> - which I think I can use for the encryption. Not sure this will get me around CheatEngine though. I need to know the best solutions for both AS2 and AS3, if they are different. The main problems seem to be things like TamperData and LiveHTTP headers, but I understand there are more advanced hacking tools as well - like CheatEngine (thanks Mark Webster)
This is a classic problem with Internet games and contests. Your Flash code works with users to decide a score for a game. But users aren't trusted, and the Flash code runs on the user's computer. You're SOL. There is nothing you can do to prevent an attacker from forging high scores: * Flash is even easier to reverse engineer than you might think it is, since the bytecodes are well documented and describe a high-level language (Actionscript) --- when you publish a Flash game, you're publishing your source code, whether you know it or not. * Attackers control the runtime memory of the Flash interpreter, so that anyone who knows how to use a programmable debugger can alter any variable (including the current score) at any time, or alter the program itself. The simplest possible attack against your system is to run the HTTP traffic for the game through a proxy, catch the high-score save, and replay it with a higher score. You can try to block this attack by binding each high score save to a single instance of the game, for instance by sending an encrypted token to the client at game startup, which might look like: ``` hex-encoding( AES(secret-key-stored-only-on-server, timestamp, user-id, random-number)) ``` (You could also use a session cookie to the same effect). The game code echoes this token back to the server with the high-score save. But an attacker can still just launch the game again, get a token, and then immediately paste that token into a replayed high-score save. So next you feed not only a token or session cookie, but also a high-score-encrypting session key. This will be a 128 bit AES key, itself encrypted with a key hardcoded into the Flash game: ``` hex-encoding( AES(key-hardcoded-in-flash-game, random-128-bit-key)) ``` Now before the game posts the high score, it decrypts the high-score-encrypting-session key, which it can do because you hardcoded the high-score-encrypting-session-key-decrypting-key into the Flash binary. You encrypt the high score with this decrypted key, along with the SHA1 hash of the high score: ``` hex-encoding( AES(random-128-bit-key-from-above, high-score, SHA1(high-score))) ``` The PHP code on the server checks the token to make sure the request came from a valid game instance, then decrypts the encrypted high score, checking to make sure the high-score matches the SHA1 of the high-score (if you skip this step, decryption will simply produce random, likely very high, high scores). So now the attacker decompiles your Flash code and quickly finds the AES code, which sticks out like a sore thumb, although even if it didn't it'd be tracked down in 15 minutes with a memory search and a tracer ("I know my score for this game is 666, so let's find 666 in memory, then catch any operation that touches that value --- oh look, the high score encryption code!"). With the session key, the attacker doesn't even have to run the Flash code; she grabs a game launch token and a session key and can send back an arbitrary high score. You're now at the point where most developers just give up --- give or take a couple months of messing with attackers by: * Scrambling the AES keys with XOR operations * Replacing key byte arrays with functions that calculate the key * Scattering fake key encryptions and high score postings throughout the binary. This is all mostly a waste of time. It goes without saying, SSL isn't going to help you either; SSL can't protect you when one of the two SSL endpoints is evil. Here are some things that can actually reduce high score fraud: * Require a login to play the game, have the login produce a session cookie, and don't allow multiple outstanding game launches on the same session, or multiple concurrent sessions for the same user. * Reject high scores from game sessions that last less than the shortest real games ever played (for a more sophisticated approach, try "quarantining" high scores for game sessions that last less than 2 standard deviations below the mean game duration). Make sure you're tracking game durations serverside. * Reject or quarantine high scores from logins that have only played the game once or twice, so that attackers have to produce a "paper trail" of reasonable looking game play for each login they create. * "Heartbeat" scores during game play, so that your server sees the score growth over the lifetime of one game play. Reject high scores that don't follow reasonable score curves (for instance, jumping from 0 to 999999). * "Snapshot" game state during game play (for instance, amount of ammunition, position in the level, etc), which you can later reconcile against recorded interim scores. You don't even have to have a way to detect anomalies in this data to start with; you just have to collect it, and then you can go back and analyze it if things look fishy. * Disable the account of any user who fails one of your security checks (for instance, by ever submitting an encrypted high score that fails validation). Remember though that you're only deterring high score fraud here. There's *nothing* you can do to prevent if. If there's money on the line in your game, someone is going to defeat any system you come up with. The objective isn't to *stop* this attack; it's to make the attack more expensive than just getting really good at the game and beating it.
You may be asking the wrong question. You seem focused on the methods people are using to game their way up the high score list, but blocking specific methods only goes so far. I have no experience with TamperData, so I can't speak to that. The question you should be asking is: "How can I verify that submitted scores are valid and authentic?" The specific way to do that is game-dependent. For very simple puzzle games, you might send over the score along with the specific starting state and the sequence of moves that resulted in the end state, and then re-run the game on the server side using the same moves. Confirm that the stated score is the same as the computed score and only accept the score if they match.
What is the best way to stop people hacking the PHP-based highscore table of a Flash game
[ "", "php", "actionscript-3", "security", "actionscript", "actionscript-2", "" ]
How do I authenticate against AD using Python + LDAP. I'm currently using the python-ldap library and all it is producing is tears. I can't even bind to perform a simple query: ``` import sys import ldap Server = "ldap://my-ldap-server" DN, Secret, un = sys.argv[1:4] Base = "dc=mydomain,dc=co,dc=uk" Scope = ldap.SCOPE_SUBTREE Filter = "(&(objectClass=user)(sAMAccountName="+un+"))" Attrs = ["displayName"] l = ldap.initialize(Server) l.protocol_version = 3 print l.simple_bind_s(DN, Secret) r = l.search(Base, Scope, Filter, Attrs) Type,user = l.result(r,60) Name,Attrs = user[0] if hasattr(Attrs, 'has_key') and Attrs.has_key('displayName'): displayName = Attrs['displayName'][0] print displayName sys.exit() ``` Running this with `myusername@mydomain.co.uk password username` gives me one of two errors: `Invalid Credentials` - When I mistype or intentionally use wrong credentials it fails to authenticate. > ldap.INVALID\_CREDENTIALS: {'info': '80090308: LdapErr: DSID-0C090334, comment: AcceptSecurityContext error, data 52e, vece', 'desc': 'Invalid credentials'} Or > ldap.OPERATIONS\_ERROR: {'info': '00000000: LdapErr: DSID-0C090627, comment: In order to perform this operation a successful bind must be completed on the connection., data 0, vece', 'desc': 'Operations error'} What am I missing out to bind properly? I am getting the same errors on fedora and windows.
I was missing ``` l.set_option(ldap.OPT_REFERRALS, 0) ``` From the init.
If you are open to using pywin32, you can use Win32 calls from Python. This is what we do in our CherryPy web server: ``` import win32security token = win32security.LogonUser( username, domain, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) authenticated = bool(token) ```
Authenticating against active directory using python + ldap
[ "", "python", "authentication", "active-directory", "ldap", "" ]
I'm used to working with PHP but lately I've been working with Java and I'm having a headache trying to figure this out. I want to save this representation in Java: ``` Array ( ["col_name_1"] => Array ( 1 => ["col_value_1"], 2 => ["col_value_2"], ... , n => ["col_value_n"] ), ["col_name_n"] => Array ( 1 => ["col_value_1"], 2 => ["col_value_2"], ... , n => ["col_value_n"] ) ) ``` Is there a clean way (i.e. no dirty code) to save this thing in Java? Note; I would like to use Strings as array indexes (in the first dimension) and I don't know the definite size of the arrays..
You can use a Map and a List (these both are interfaces implemented in more than one way for you to choose the most adequate in your case). For more information check the tutorials for [Map](http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html) and [List](http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html) and maybe you should start with the [Collections](http://java.sun.com/docs/books/tutorial/collections/) tutorial. An example: ``` import java.util.*; public class Foo { public static void main(String[] args) { Map<String, List<String>> m = new HashMap<String, List<String>>(); List<String> l = new LinkedList<String>(); l.add("col_value_1"); l.add("col_value_2"); //and so on m.put("col_name_1",l); //repeat for the rest of the colnames //then, to get it you do List<String> rl = m.get("col_name_1"); } } ```
Try using a `Map<String, List<String>>`. This will allow you to use Strings as keys / indices into the outer map and get a result being a list of Strings as values. You'll probably want to use a `HashMap` for the outer map and `ArrayList`'s for the inner lists. If you want some clean code that is similar to the PHP you gave to initialize it, you can do something like this: ``` Map<String, List<String>> columns = new HashMap<String, List<String>>() {{ put("col_name_1", Arrays.asList("col_val_1", "col_val_2", "col_val_n")); put("col_name_2", Arrays.asList("col_val_1", "col_val_2", "col_val_n")); put("col_name_n", Arrays.asList("col_val_1", "col_val_2", "col_val_n")); }}; ```
Java: Arrays & Vectors
[ "", "java", "arrays", "data-structures", "hashmap", "" ]
Any ideas how to determine the number of active threads currently running in an [`ExecutorService`](https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/ExecutorService.html)?
Use a [ThreadPoolExecutor](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html) implementation and call [getActiveCount()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html#getActiveCount()) on it: ``` int getActiveCount() // Returns the approximate number of threads that are actively executing tasks. ``` The ExecutorService interface does not provide a method for that, it depends on the implementation.
Assuming `pool` is the name of the ExecutorService instance: ``` if (pool instanceof ThreadPoolExecutor) { System.out.println( "Pool size is now " + ((ThreadPoolExecutor) pool).getActiveCount() ); } ```
Active threads in ExecutorService
[ "", "java", "multithreading", "concurrency", "" ]
What is the best way to start developing Windows Mobile Professional applications in Python? Is there a reasonable SDK including an emulator? Is it even possible without doing excessive amount of underlaying Windows API calls for UI for instance?
If the IronPython and .Net Compact Framework teams work together, Visual Studio may one day support Python for Windows Mobile development out-of-the-box. Unfortunately, [this feature request has been sitting on their issue tracker for ages](http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=9191)...
(I used to write customer apps for Windows Mobile.) Forget about python. Even if it's technically possible: * your app will be big (you'll have to bundle the whole python runtime with your app) * your app will use lots of memory (python is a memory hog, relative to C/C++) * your app will be slow * you wont find any documentation or discussion groups to help you when you (inevitably) encounter problems Go with C/C++ (or C#). Visual Studio 2005/2008 have decent tools for those (SDK for winmo built-in, debugging on the emulator or device connected through USB), the best documentation is for those technologies plus there are active forums/discussion groups/mailing lists where you can ask for help.
Windows Mobile development in Python
[ "", "python", "windows-mobile", "" ]
I've been doing some work with the JAX-RS reference implementation (Jersey). I know of at least two other frameworks (Restlet & Apache CXF). My question is: Has anyone done some comparison between those frameworks and if so, which framework would you recommend and why?
FWIW we're using Jersey as its packed full of features (e.g. WADL, implicit views, XML/JSON/Atom support) has a large and vibrant developer community behind it and has great [spring integration](http://www.javakaffee.de/blog/2008/04/21/jersey-spring-integration-mostly-complete/). If you use JBoss/SEAM you might find RESTeasy integrates a little better - but if you use Spring for Dependency Injection then Jersey seems the easiest, most popular, active and functional implementation.
[Restlet](http://www.restlet.org) has an extensive list of extensions for Spring, WADL, XML, JSON as well and many more, including an extension for JAX-RS API. It is also the sole framework [available in six consistent editions](http://www.restlet.org/downloads/testing): * Java SE * Java EE * Google Web Toolkit * Google AppEngine * Android * OSGi environments Its main benefits are: * fully symmetric client and server API when JAX-RS was designed for server-side processing * connectors for other protocols than HTTP (mapping to HTTP semantics) when JAX-RS is HTTP only * much broader feature scope including full URI routing control via the Restlet API (but can integrate with Servlet if needed) * full provision for NIO support The JAX-RS API can be a good choice if you are restricted to JCP approved APIs (then don't use Spring or any extension of the JAX-RS projects like Jersey and RESTeasy!), but otherwise Restlet is the most mature framework (initially released in 2005) and will give you, in its 2.0 version, all the benefits of annotations combined with a powerful and extensible class-oriented framework. For a longer [list of features, please check this page](http://restlet.com/products/restlet-framework/#features). Best regards, Jerome Louvel Restlet ~ Founder and Lead developer ~ <http://www.restlet.org>
JAX-RS Frameworks
[ "", "java", "rest", "jax-rs", "" ]
I've been wondering, is there a performance difference between using named functions and anonymous functions in Javascript? ``` for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() { // do something }; } ``` vs ``` function myEventHandler() { // do something } for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = myEventHandler; } ``` The first is tidier since it doesn't clutter up your code with rarely-used functions, but does it matter that you're re-declaring that function multiple times?
The performance problem here is the cost of creating a new function object at each iteration of the loop and not the fact that you use an anonymous function: ``` for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = function() { // do something }; } ``` You are creating a thousand distinct function objects even though they have the same body of code and no binding to the lexical scope ([closure](http://www.google.com/search?q=javascript+closure)). The following seems faster, on the other hand, because it simply assigns the *same* function reference to the array elements throughout the loop: ``` function myEventHandler() { // do something } for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = myEventHandler; } ``` If you were to create the anonymous function before entering the loop, then only assign references to it to the array elements while inside the loop, you will find that there is no performance or semantic difference whatsoever when compared to the named function version: ``` var handler = function() { // do something }; for (var i = 0; i < 1000; ++i) { myObjects[i].onMyEvent = handler; } ``` In short, there is no observable performance cost to using anonymous over named functions. As an aside, it may appear from above that there is no difference between: ``` function myEventHandler() { /* ... */ } ``` and: ``` var myEventHandler = function() { /* ... */ } ``` The former is a *function declaration* whereas the latter is a variable assignment to an anonymous function. Although they may appear to have the same effect, JavaScript does treat them slightly differently. To understand the difference, I recommend reading, “[JavaScript function declaration ambiguity](http://www.dustindiaz.com/javascript-function-declaration-ambiguity/)”. The actual execution time for any approach is largely going to be dictated by the browser's implementation of the compiler and runtime. For a complete comparison of modern browser performance, visit [the JS Perf site](http://jsperf.com/named-or-anonymous-functions/12)
Here's my test code: ``` var dummyVar; function test1() { for (var i = 0; i < 1000000; ++i) { dummyVar = myFunc; } } function test2() { for (var i = 0; i < 1000000; ++i) { dummyVar = function() { var x = 0; x++; }; } } function myFunc() { var x = 0; x++; } document.onclick = function() { var start = new Date(); test1(); var mid = new Date(); test2(); var end = new Date(); alert ("Test 1: " + (mid - start) + "\n Test 2: " + (end - mid)); } ``` The results: Test 1: 142ms Test 2: 1983ms It appears that the JS engine doesn't recognise that it's the same function in Test2 and compiles it each time.
Does use of anonymous functions affect performance?
[ "", "javascript", "performance", "optimization", "" ]
I'm trying to store an xml serialized object in a cookie, but i get an error like this: ``` A potentially dangerous Request.Cookies value was detected from the client (KundeContextCookie="<?xml version="1.0" ...") ``` I know the problem from similiar cases when you try to store something that looks like javascript code in a form input field. What is the best practise here? Is there a way (like the form problem i described) to supress this warning from the asp.net framework, or should i JSON serialize instead or perhaps should i binary serialize it? What is common practise when storing serialized data in a cookie? EDIT: Thanks for the feedback. The reason i want to store more data in the cookie than the ID is because the object i really need takes about 2 seconds to retreive from a service i have no control over. I made a lightweight object 'KundeContext' to hold a few of the properties from the full object, but these are used 90% of the time. This way i only have to call the slow service on 10% of my pages. If i only stored the Id i would still have to call the service on almost all my pages. I could store all the strings and ints seperately but the object has other lightweight objects like 'contactinformation' and 'address' that would be tedious to manually store for each of their properties.
I wouldn't store data in XML in the cookie - there is a limit on cookie size for starters (used to be 4K for *all* headers including the cookie). Pick a less verbose encoding strategy such as delimiters instead e.g. a|b|c or separate cookie values. Delimited encoding makes it especially easy and fast to decode the values. The error you see is ASP.NET complaining that the headers look like an XSS attack.
Storing serialized data in a cookie is a very, very bad idea. Since users have complete control over cookie data, it's just too easy for them to use this mechanism to feed you malicious data. In other words: *any* weakness in your deserialization code becomes instantly exploitable (or at least a way to crash something). Instead, only keep the simplest identifier possible in your cookies, of a type of which the format can easily be validated (for example, a GUID). Then, store your serialized data server-side (in a database, XML file on the filesystem, or whatever) and retrieve it using that identifier. Edit: also, in this scenario, make sure that your identifier is random enough to make it infeasible for users to guess each other's identifiers, and impersonate each other by simply changing their own identifier a bit. Again, GUIDs (or ASP.NET session identifiers) work very well for this purpose. Second edit after scenario clarification by question owner: why use your own cookies at all in this case? If you keep a reference to either the original object or your lightweight object in the session state (Session object), ASP.NET will take care of all implementation details for you in a pretty efficient way.
Storing xml data in a cookie
[ "", "c#", "asp.net", "serialization", "cookies", "" ]
I want to run javascript/Python/Ruby inside my application. I have an application that creates process automatically based on user's definition. The process is generated in C#. I want to enable advanced users to inject script in predefined locations. Those scripts should be run from the C# process. For example, the created process will have some activities and in the middle the script should be run and then the process continues as before. Is there a mechanism to run those scripts from C#?
Basically, you have two problems: how to define point of injections in your generated code, and how to run python / ruby / whatev scripts from there. Depending on how you generate the process, one possible solution would be to add a function to each possible point of injection. The function would check, whether the user has associated any scripts with given points, and if so, runs the script by invoking [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython) / [IronRuby](http://www.ironruby.net/) (with optionally given parameters). Disadvantages include: limited accessibility from the scripts to the created process (basically, only variables passed as parameters could be accessed); as well as implementation limits (IronPython's current version omits several basic system functions).
Look into IronPython and IronRuby -- these will allow you to easily interoperate with C#.
Running scripts inside C#
[ "", "c#", "scripting", "" ]
On a file path field, I want to capture the directory path like: ``` textbox1.Text = directory path ``` Anyone?
Well I am using VS 2008 SP1. This all I need: ``` private void button1_Click(object sender, EventArgs e) { FolderBrowserDialog profilePath = new FolderBrowserDialog(); if (profilePath.ShowDialog() == DialogResult.OK) { profilePathTextBox.Text = profilePath.SelectedPath; } else { profilePathTextBox.Text = "Please Specify The Profile Path"; } } ```
There is a FolderBrowserDialog class that you can use if you want the user to select a folder. <http://msdn.microsoft.com/en-us/library/system.windows.forms.folderbrowserdialog.aspx> ``` DialogResult result = folderBrowserDialog1.ShowDialog(); if (result.Equals(get_DialogResult().OK)) { textbox1.Text = folderBrowserDialog1.get_SelectedPath(); } ``` If all you want is to get the direcotory from a full path, you can do this: ``` textbox1.Text = Path.GetDirectoryName(@"c:\windows\temp\myfile.txt"); ``` This will set the Text-property to "c:\windows\temp\"
OpenFileDialog. How about "Specify Directory Dialog"?
[ "", "c#", "directory", "openfiledialog", "" ]
Let me start off with a bit of background. This morning one of our users reported that Testuff's setup file has been reported as infected with a virus by the CA antivirus. Confident that this was a false positive, I looked on the web and found that users of another program (SpyBot) have reported the same problem. A now, for the actual question. Assuming the antivirus is looking for a specific binary signature in the file, I'd like to find the matching sequences in both files and hopefully find a way to tweak the setup script to prevent that sequence from appearing. I tried the following in Python, but it's been running for a long time now and I was wondering if there was a better or faster way. ``` from difflib import SequenceMatcher spybot = open("spybotsd160.exe", "rb").read() testuff = open("TestuffSetup.exe", "rb").read() s = SequenceMatcher(None, spybot, testuff) print s.find_longest_match(0, len(spybot), 0, len(testuff)) ``` Is there a better library for Python or for another language that can do this? A completely different way to tackle the problem is welcome as well.
See [the longest common substring problem](http://en.wikipedia.org/wiki/Longest_common_substring_problem). I guess difflib uses the DP solution, which is certainly too slow to compare executables. You can do much better with suffix trees/arrays. Using perl [Tree::Suffix](http://search.cpan.org/~gray/Tree-Suffix-0.20/lib/Tree/Suffix.pm) might be easiest solution. Apparently it gives all common substrings in a specified length range: ``` @lcs = $tree->lcs; @lcs = $tree->lcs($min_len, $max_len); @lcs = $tree->longest_common_substrings; ```
Note that even if you did find it this way, there's no guarantee that the longest match is actually the one being looked for. Instead, you may find common initialisation code or string tables added by the same compiler for instance.
Find matching sequences in two binary files
[ "", "python", "binary", "diff", "antivirus", "" ]
Why use one over the other?
== is the identity test. It will return true if the two objects being tested are in fact the same object. `Equals()` performs an equality test, and will return true if the two objects consider themselves equal. Identity testing is faster, so you can use it when there's no need for more expensive equality tests. For example, comparing against `null` or the empty string. It's possible to overload either of these to provide different behavior -- like identity testing for `Equals()` --, but for the sake of anybody reading your code, please don't. --- Pointed out below: some types like `String` or `DateTime` provide overloads for the `==` operator that give it equality semantics. So the exact behavior will depend on the types of the objects you are comparing. --- See also: * <http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx>
@John Millikin: > Pointed out below: some value types like DateTime provide overloads for the == operator >that give it equality semantics. So the exact behavior will depend on the types of the >objects you are comparing. To elaborate: DateTime is implemented as a struct. All structs are children of System.ValueType. Since System.ValueType's children live on the stack, there is no reference pointer to the heap, and thus no way to do a reference check, you must compare objects by value only. System.ValueType overrides .Equals() and == to use a reflection based equality check, it uses reflection to compare each fields value. Because reflection is somewhat slow, if you implement your own struct, it is important to override .Equals() and add your own value checking code, as this will be much faster. Don't just call base.Equals();
== or .Equals()
[ "", "c#", "" ]
There is a [Microsoft knowledge base article](http://support.microsoft.com/?scid=194627) with sample code to open all mailboxes in a given information store. It works so far (requires a bit of [copy & pasting](http://blogs.msdn.com/jasonjoh/archive/2004/08/01/204585.aspx) on compilers newer than VC++ 6.0). At one point it calls IExchangeManageStore::GetMailboxTable with the distinguished name of the information store. For the Exchange 2007 Trial Virtual Server image it has to look like this: ``` "/o=Litware Inc/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Configuration/cn=servers/cn=DC1". ``` Using [OutlookSpy](http://www.dimastr.com/outspy/) and clicking on IMsgStore and IExchangeManageStore reveals the desired string next to "Server DN:". I want to avoid forcing the user to put this into a config file. So if OutlookSpy can do it, how can my application find out the distinguished name of the information store where the currently open mailbox is on?
Thinking there must be a pure MAPI solution, I believe I've figured out how OutlookSpy does it. The following code snippet, inserted after ``` printf("Created MAPI session\n"); ``` in the example from [KB194627](http://support.microsoft.com/kb/194627), will show the *Server DN*. ``` LPPROFSECT lpProfSect; hr = lpSess->OpenProfileSection((LPMAPIUID)pbGlobalProfileSectionGuid, NULL, 0, &lpProfSect); if(SUCCEEDED(hr)) { LPSPropValue lpPropValue; hr = HrGetOneProp(lpProfSect, PR_PROFILE_HOME_SERVER_DN, &lpPropValue); if(SUCCEEDED(hr)) { printf("Server DN: %s\n", lpPropValue->Value.lpszA); MAPIFreeBuffer(lpPropValue); } lpProfSect->Release(); } ``` **Update:** There is the function *HrGetServerDN* in the [EDK 5.5 source code](http://www.microsoft.com/downloads/details.aspx?FamilyID=36a309c3-8c55-4476-8785-cafc59a2d075&DisplayLang=en), it extracts the *Server DN* from a given session's *PR\_EMS\_AB\_HOME\_MTA*. I'll try it if the other way turns out to be unreliable.
It'll be in Active Directory, so you'd use ADSI/LDAP to look at CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=*example*,DC=*com*. Use Sysinternals' ADExplorer to have a dig around in there to find the value you're looking for.
How to find out the distinguished name of the information store to feed to IExchangeManageStore::GetMailboxTable?
[ "", "c++", "outlook", "exchange-server", "mapi", "" ]
I have a huge database with 100's of tables and stored procedures. Using SQL Server 2005, how can I get a list of stored procedures that are doing an insert or update operation on a given table.
``` select so.name, sc.text from sysobjects so inner join syscomments sc on so.id = sc.id where sc.text like '%INSERT INTO xyz%' or sc.text like '%UPDATE xyz%' ``` This will give you a list of all stored procedure contents with INSERT or UPDATE in them for a particular table (you can obviously tweak the query to suit). Also longer procedures will be broken across multiple rows in the returned recordset so you may need to do a bit of manual sifting through the results. **Edit**: Tweaked query to return SP name as well. Also, note the above query will return any UDFs as well as SPs.
`sys.sql_dependencies` has a list of entities with dependencies, including tables and columns that a sproc includes in queries. See [this post](https://stackoverflow.com/questions/69923/stored-procedures-reverse-engineering#93967) for an example of a query that gets out dependencies. The code snippet below will get a list of table/column dependencies by stored procedure ``` select sp.name as sproc_name ,t.name as table_name ,c.name as column_name from sys.sql_dependencies d join sys.objects t on t.object_id = d.referenced_major_id join sys.objects sp on sp.object_id = d.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.referenced_minor_id where sp.type = 'P' ```
List of Stored Procedure from Table
[ "", "sql", "sql-server", "stored-procedures", "" ]
My company is considering changing continuous integration servers (I won't say which one we have now, so I won't skew your responses in anyway :) ) I wondering if anybody has any recommendations? Best user experience, level of difficulty to maintain, etc... Our code is all in java, and we use ANT as a build tool.
I recently implemented a [Hudson](http://hudson-ci.org/) server. Having previously used Cruise Control, **I am very satisfied with Hudson and very impressed with its ease of setup and use.** Adding new projects is infinitely easier than it was with Cruise Control.
*Edit: We use Hudson now.* A while ago I looked into a bunch of these with the following requirements: * Java code * Ant builds * Groovy builds * Distributed builds * SCM trigger integration * http reports * smtp reports The [Continuous Integration Feature Matrix](http://confluence.public.thoughtworks.org/display/CC/CI+Feature+Matrix "CI Feature Matrix") is a great place to start. I ended up selecting [AnthillPro](http://www.anthillpro.com/html/default.html "AnthillPro") and am using it successfully, just scratching at the surface of what we can and hope to use it for.
Continuous Integration Servers
[ "", "java", "continuous-integration", "" ]
Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)? I would expect to be able to instantiate a an object of some sort, give it a template along the lines of ``` Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} ``` provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order'). I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as ``` Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} ``` and I can pass it an Object array, in my calling Java program ``` new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; ``` However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.
You can just use the Universal Expression Language itself. You need an implementation (but there are a few to choose from). After that, you need to implement three classes: ELResolver, FunctionMapper and VariableMapper. This blog post describes how to do it: [Java: using EL outside J2EE](http://illegalargumentexception.blogspot.com/2008/04/java-using-el-outside-j2ee.html).
[StringTemplate](http://www.stringtemplate.org/) is a more lightweight alternative to Velocity and Freemarker.
JSTL/JSP EL (Expression Language) in a non JSP (standalone) context
[ "", "java", "jsp", "el", "text-formatting", "" ]
Is it possible to to take a screenshot of a webpage with JavaScript and then submit that back to the server? I'm not so concerned with browser security issues. etc. as the implementation would be for [HTA](http://msdn.microsoft.com/en-us/library/ms536471(vs.85).aspx). But is it possible?
I have done this for an HTA by using an ActiveX control. It was pretty easy to build the control in VB6 to take the screenshot. I had to use the keybd\_event API call because SendKeys can't do PrintScreen. Here's the code for that: ``` Declare Sub keybd_event Lib "user32" _ (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long) Public Const CaptWindow = 2 Public Sub ScreenGrab() keybd_event &H12, 0, 0, 0 keybd_event &H2C, CaptWindow, 0, 0 keybd_event &H2C, CaptWindow, &H2, 0 keybd_event &H12, 0, &H2, 0 End Sub ``` That only gets you as far as getting the window to the clipboard. Another option, if the window you want a screenshot of is an HTA would be to just use an XMLHTTPRequest to send the DOM nodes to the server, then create the screenshots server-side.
Google is doing this in Google+ and a talented developer reverse engineered it and produced <http://html2canvas.hertzen.com/> . To work in IE you'll need a canvas support library such as <http://excanvas.sourceforge.net/>
Take a screenshot of a webpage with JavaScript?
[ "", "javascript", "hta", "webpage-screenshot", "" ]
**Problem:** Ajax suggest-search on [*n*] ingredients in recipes. That is: match recipes against multiple ingredients. For instance: `SELECT Recipes using "flower", "salt"` would produce: `"Pizza", "Bread", "Saltwater"` and so forth. **Tables:** ``` Ingredients [ IngredientsID INT [PK], IngredientsName VARCHAR ] Recipes [ RecipesID INT [PK], RecipesName VARCHAR ] IngredientsRecipes [ IngredientsRecipesID INT [PK], IngredientsID INT, RecipesID INT ] ``` **Query:** ``` SELECT Recipes.RecipesID, Recipes.RecipesName, Ingredients.IngredientsID, Ingredients.IngredientsName FROM IngredientsRecipes INNER JOIN Ingredients ON IngredientsRecipes.IngredientsID = Ingredients.IngredientsID INNER JOIN Recipes ON IngredientsRecipes.RecipesID = Recipes.RecipesID WHERE Ingredients.IngredientsName IN ('salt', 'water', 'flower') ``` I am currently constructing my query using ASP.NET C# because of the dynamic nature of the `WHERE` clause. I bites that I have to construct the query in my code-layer instead of using a stored procedure/pure SQL, which in theory should be much faster. Have you guys got any thoughts on how I would move all of the logic from my code-layer to pure SQL, or at least how I can optimize the performance of what I'm doing? I am thinking along the lines of temporary tables: **Step one**: `SELECT IngredientsID FROM Ingredients` and `INSERT INTO temp-table` **Step two**: `SELECT RecipesName FROM Recipes` joined with `IngredientsRecipes` joined with `temp-table.IngredientsID`
You have two options. If you're using SQL Server 2008 (or Oracle) you can pass in a [table value parameter](http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters). If you're using SQL Server 2005, you can use [XML to simulate this capability](http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx) If you're using something earlier than 2005, you need to concatenate the ids in a single string and create a UDF to parse them.
You could at least parametrize the where clausule to avoid SQL injection, something alike: ``` using System.Data; using System.Data.SqlClient; using System.Text; class Foo { public static void Main () { string[] parameters = {"salt", "water", "flower"}; SqlConnection connection = new SqlConnection (); SqlCommand command = connection.CreateCommand (); StringBuilder where = new StringBuilder (); for (int i = 0; i < parametes.Length; i++) { if (i != 0) where.Append (","); where.AppendFormat ("@Param{0}", i); command.Parameters.Add (new SqlParameter ("Param" + i, parameters [i])); } } } ```
SQL Server: Dynamic where-clause
[ "", "c#", "sql-server", "performance", "" ]